diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 71c24b14e0..d6f415d971 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1088,6 +1088,66 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run Game Design complete launch binding PostgreSQL component proof + if: ${{ matrix.module == 'game-design-service' }} + run: | + ./gradlew :game-design-service:integrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingServiceIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingServiceIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingServiceIntegrationTest#returnsAndRetriesThePersistedCompletePairWithoutChangingOwnerRows()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingServiceIntegrationTest#retainsTheHistoricalAttestationWhenCurrentVersionStateAdvances()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingServiceIntegrationTest#deniesCrossTenantAndSubstitutedSourceSelectorsWithoutMutatingPersistedEvidence()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingServiceIntegrationTest#deniesPersistedDescriptorWhoseBundleLacksCompleteOwnerEvidenceWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingServiceIntegrationTest#descriptorSnapshotRejectsNonRepeatableReadBeforeAnyWrite()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingServiceIntegrationTest#concurrentVersionAdvanceCannotSplitTheCompleteOwnerSnapshot()' \ + game-design-service + + - name: Capture Game Design complete launch binding PostgreSQL raw XML + if: ${{ always() && matrix.module == 'game-design-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-design-complete-launch-binding-postgresql-proof-${{ github.sha }} + path: services/game-design-service/build/test-results/integrationTest/TEST-*CompleteLaunchBindingServiceIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Run Game Design authored-source delivery PostgreSQL and physical mTLS proof + if: ${{ !cancelled() && matrix.module == 'game-design-service' }} + run: | + ./gradlew :game-design-service:integrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryIntegrationTest \ + --tests integration.net.firedevops.firemud.gamedesign.service.GameAuthoredWorldSourceDeliveryMtlsIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryIntegrationTest#freshRegistrationQueuesOneStableWorldRequestAndExactSourceRetryReusesIt()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryIntegrationTest#sourceAndDeliveryIntentRollBackTogether()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryIntegrationTest#concurrentExactDeliveriesReturnOneDurableAckAndChangedReceiptIsDenied()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryIntegrationTest#databaseRejectsDeliverySourceRebindingAndReceiptMutation()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryIntegrationTest#committedAckWithLostLocalCommitAcknowledgementRecoversFromDurableRead()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryIntegrationTest#retainedSourceAndGameRowsRemainUnchangedAcrossV41WithoutDeliveryAssociation()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryIntegrationTest#historicalFreshSourceRetryDoesNotBackfillMissingV41DeliveryClaim()' \ + --require-suite integration.net.firedevops.firemud.gamedesign.service.GameAuthoredWorldSourceDeliveryMtlsIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.GameAuthoredWorldSourceDeliveryMtlsIntegrationTest#deliversPersistedFreshSourceAndCompletedRestartRetryReturnsOriginalReceipt()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.GameAuthoredWorldSourceDeliveryMtlsIntegrationTest#lostWorldResponseLeavesPendingIntentAndExactRetryRecoversCommittedOwnerReceipt()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.GameAuthoredWorldSourceDeliveryMtlsIntegrationTest#wrongAuthenticatedWorldCallerCannotCreateOwnerRowsOrAcknowledgeDelivery()' \ + game-design-service + + - name: Capture Game Design authored-source delivery PostgreSQL and physical mTLS raw XML + if: ${{ always() && matrix.module == 'game-design-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-design-authored-source-delivery-proof-${{ github.sha }} + path: | + services/game-design-service/build/test-results/integrationTest/TEST-*GameAuthoredWorldSourceDeliveryIntegrationTest.xml + services/game-design-service/build/test-results/integrationTest/TEST-*GameAuthoredWorldSourceDeliveryMtlsIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + - name: Run Game Design authored-source read socket mTLS proof if: ${{ !cancelled() && matrix.module == 'game-design-service' }} run: | @@ -1138,6 +1198,8 @@ jobs: --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 'integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateMtlsIntegrationTest#composesPersistedGameDesignVersionOverMtlsWithWorldIdentityReadbackAndExactRetry(Path)' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.AuthoredWorldVersionStateMtlsIntegrationTest#rejectsSubstitutedCanonicalVersionBeforeWorldIdentityPersistence(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()' \ @@ -1191,6 +1253,85 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run World owner epoch CAS PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + ./gradlew :world-management-service:integrationTest \ + --tests net.firedevops.firemud.worldmanagement.WorldDesignEpochCasPostgresIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.WorldDesignEpochCasPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignEpochCasPostgresIntegrationTest#concurrentFirstZeroClaimsHaveExactlyOneWinnerForEachEpochTable()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignEpochCasPostgresIntegrationTest#concurrentExistingEpochClaimsHaveExactlyOneWinnerForEachEpochTable()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignEpochCasPostgresIntegrationTest#tupleDimensionsAndInvalidEpochsCannotChangeNeighboringRows()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignEpochCasPostgresIntegrationTest#lateScopeConflictRollsBackServiceAuthoredRowAndPriorAggregateAdvance()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignEpochCasPostgresIntegrationTest#authoredRowAggregateScopeAndLedgerShareTheOwnerTransaction()' \ + world-management-service + + - name: Capture World owner epoch CAS PostgreSQL raw XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-owner-epoch-cas-postgresql-proof-${{ github.sha }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldDesignEpochCasPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Run World complete launch binding PostgreSQL component proof + if: ${{ matrix.module == 'world-management-service' }} + run: | + ./gradlew :world-management-service:integrationTest \ + --tests net.firedevops.firemud.worldmanagement.WorldCompleteLaunchBindingIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.WorldCompleteLaunchBindingIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldCompleteLaunchBindingIntegrationTest#persistsCompletePairReadsItBackAndLeavesUnmappedRetainedRowsUntouched()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldCompleteLaunchBindingIntegrationTest#forwardV26MigrationPreservesUnmappedRetainedWorldRows()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldCompleteLaunchBindingIntegrationTest#deniesMissingOrSubstitutedSourceBeforeAnyWorldOwnerWrite()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldCompleteLaunchBindingIntegrationTest#concurrentExactAndChangedClaimsKeepOneImmutableBinding()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldCompleteLaunchBindingIntegrationTest#simultaneousExactRetriesReturnTheSameDurableReceiptAndOwnerOperation()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldCompleteLaunchBindingIntegrationTest#recoversCommittedBindingWhenOwnerCommitAcknowledgmentIsLost()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldCompleteLaunchBindingIntegrationTest#readsCurrentVersionForExactCommittedBindingAndPreservesOriginalReceipt()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldCompleteLaunchBindingIntegrationTest#deniesMixedCurrentVersionEvidenceWithoutChangingCommittedBinding()' \ + world-management-service + + - name: Capture World complete launch binding PostgreSQL raw XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-complete-launch-binding-postgresql-proof-${{ github.sha }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldCompleteLaunchBindingIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Run World authored Version identity PostgreSQL prerequisite proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + ./gradlew :world-management-service:integrationTest \ + --tests net.firedevops.firemud.worldmanagement.WorldAuthoredVersionIdentityIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.WorldAuthoredVersionIdentityIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredVersionIdentityIntegrationTest#persistsExactIdentityAndPrivateKeyWithoutContentOrLifecycleWrites()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredVersionIdentityIntegrationTest#deniesWrongGameDesignIdentitySourceNamespaceAndMissingIntakeBeforeOwnerWrites()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredVersionIdentityIntegrationTest#concurrentExactStableIdentityReturnsOneOriginalHistoricalReceipt()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredVersionIdentityIntegrationTest#conflictingUuidOrGameDesignSelectorDoesNotRewriteTheOriginalReceipt()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredVersionIdentityIntegrationTest#recoversLostCommitAcknowledgmentAndRetriesWithoutRereadingOrReminting()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredVersionIdentityIntegrationTest#forwardV27MigrationPreservesRetainedRowsWithoutInferringIdentityAssociations()' \ + world-management-service + + - name: Capture World authored Version identity PostgreSQL raw XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-authored-version-identity-postgresql-proof-${{ github.sha }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldAuthoredVersionIdentityIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + - name: Run World shared publication-fence PostgreSQL prerequisite proof if: ${{ !cancelled() && matrix.module == 'world-management-service' }} run: | @@ -1256,6 +1397,8 @@ jobs: --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeMtlsIntegrationTest#commitsFreshWorldOwnerReceiptThenReturnsExactReceiptOverAuthenticatedSocket()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeMtlsIntegrationTest#reconcilesLostSuccessAcknowledgementWithExactRetryAndCommittedReadback()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeMtlsIntegrationTest#deniesWrongWorkloadAndChangedBindingWithoutOwnerMutation()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeMtlsIntegrationTest#registeredDraftMutationDeniesGameDesignPeerWithoutAccountCommitAuthorization()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeMtlsIntegrationTest#registeredDraftMutationDeniesOtherAuthenticatedPeerBeforeOwnerMutation()' \ world-management-service - name: Upload World authored-source intake PostgreSQL socket composition results @@ -1266,6 +1409,27 @@ jobs: path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldAuthoredSourceIntakeMtlsIntegrationTest.xml if-no-files-found: warn retention-days: 7 + - name: Run World legacy generation write HTTP and PostgreSQL denial proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + ./gradlew :world-management-service:integrationTest \ + --tests 'net.firedevops.firemud.worldmanagement.WorldManagementServiceApplicationIntegrationTest.saveRuleDeniesAuthenticatedWriteWithoutCanonicalCommitAuthorization' \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.WorldManagementServiceApplicationIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldManagementServiceApplicationIntegrationTest#saveRuleDeniesAuthenticatedWriteWithoutCanonicalCommitAuthorization()' \ + world-management-service + + - name: Capture World legacy generation write HTTP PostgreSQL raw XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-generation-write-denial-postgresql-proof-${{ github.sha }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldManagementServiceApplicationIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + - name: Retain Game Design owner migration raw PostgreSQL evidence if: ${{ always() && matrix.module == 'game-design-service' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 diff --git a/design/architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md b/design/architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md index 95a103d9ff..aedcf28232 100644 --- a/design/architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md +++ b/design/architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The current implementation does not satisfy this decision. `SaveRevision` can call World Management before Game Design persists its local revision. World aggregate and scope epochs are read and then saved without the expected epoch in the database update predicate, and some mutation shapes can omit scope fencing. There is no Game Design-owned durable commit/proposal coordinator with exact base and digest binding, complete affected-scope capture, per-owner apply status, or a creator-visible synchronized read fence. Existing revision ledgers and publish digests are useful seams but do not prove this contract. +The current implementation does not fully satisfy this decision. The held-back World mutation algorithm now advances its declared aggregate and scope epochs with expected-epoch storage predicates, including conflict-safe first claims; execution and remaining limitations are recorded in the [World tracker](../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). Some mutation shapes can still omit required scope fencing. `SaveRevision` can call World Management before Game Design persists its local revision, and there is no Game Design-owned durable commit/proposal coordinator with exact base and digest binding, complete affected-scope capture, per-owner apply status, or a creator-visible synchronized read fence. The registered World write remains denied without Account commit authorization. Existing revision ledgers and publish digests do not prove the complete contract. ## Decision Record diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 2d8215c996..9f7bb2a3c7 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -40,6 +40,12 @@ The readback request binds a distinct canonical non-nil read `requestId` to the **Implementation and activation boundary:** The source repository/codec/readback is a prerequisite candidate, not a protected product creator or a live catalog handoff. Normal official-hosted authoring remains subject to the Account-owned commit-bound creator/terms gate below, which cannot be replaced by the source transaction or a caller-supplied authorization flag. No new public creation route or catalog admission is enabled before its producer, receiver, owner authorization and negative proof pass. Retained Game Session tenant keys need a separate audited, Game Design-authenticated association and Game Session's own exact retained-row readback; Account's manifest and numeric/slug similarity cannot establish it. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) owns the remaining implementation and proof. +#### Durable fresh-source delivery to World + +Game Design commits a new fresh `NEW_GAME_ROW` source operation and its World delivery intent in the same owner transaction. The intent binds the complete immutable source evidence to one separately allocated, durable World `intakeRequestId`; process restart, an exact source retry or an uncertain acknowledgement must not allocate a replacement intake identity. Retained source registration does not create this fresh delivery intent or infer a World association. The migration installs storage without backfilling retained or historical associations. Exact replay of a historical source-only operation still returns its original source receipt; an absent delivery intent neither fabricates a delivery result nor invalidates that source receipt, and its delivery remains denied until separately proved. + +Delivery uses the authenticated [World intake and readback contract](../world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association), outside the Game Design database transaction. Before acknowledging delivery, Game Design obtains independent authenticated World readback and compares the complete original public receipt and intake binding. A short local transaction retains that first complete receipt against the original intent, followed by independent durable readback; concurrent identical acknowledgements return the same stored outcome and conflicting receipts fail closed. An exact completed retry reads that outcome before contacting World. Unavailable, mismatched or ambiguous outcomes remain pending for exact retry, not terminal failure or expiry-based deletion. This is source delivery only: neither its intent nor World receipt supplies Account creator authorization, content materialization, release evidence, lifecycle readiness or admission. Normal protected creator and delivery wiring still require their own implementation and proof under the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + ### Authored-source-bound launch descriptor and exact readback The descriptor's `publishedReleaseBundleRef` uses the exact persisted [Game Design release identity](version-control.md#launch-and-attestation-read-authorization-target-state), not a reference reconstructed from its source tenant or private row identifiers. A new source-bound resolution rejects a bundle without that owner reference. This storage prerequisite does not complete the separately required release-attestation response or authorize launch. @@ -48,7 +54,21 @@ Game Design's existing immutable launch-descriptor boundary binds selector prove The committed descriptor retains those source fields and the exact resolved template, version, release bundle reference and Game Design version-state epoch, plus every other resolved launch field and the original request identity/digest. New canonical request and result digests use distinct versioned domains, fixed exhaustive field order, strict UTF-8 byte-length framing and explicit optional presence/value encoding as in [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). A digest excludes only its own derived value, not an applicable source, request or result field. Source identity, release attestation and the launch result remain independently verified evidence; none substitutes for another. -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. +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 separate representation below does not extend or reinterpret signed descriptor v1 or its digests. + +#### Separate complete release-attestation evidence + +The closed `game-design-authored-world-release-attestation/v1` evidence carries, in order, `schemaVersion=1`, `targetNamespace`, `descriptorResultDigest`, canonical `canonicalTenantId` and `canonicalVersionId`, `worldSlug`, `authoredWorldSourceOperationId`, `authoredWorldSourceEvidenceDigest`, `launchDescriptorId`, `publishedReleaseBundleRef`, `versionStateEpoch`, `publishWorkflowId`, `commitId`, `participantDigests`, `manifestHash`, `manifestSchemaVersion`, `requiredManifestAssetKeys`, `artifactDigests`, `commandDefinitions`, and `generationConfigRevision`, followed by its derived `evidenceDigest`. The exact nonblank textual `publishWorkflowId` is an opaque owner operation handle, not a UUID or a tenant selector; consumers must not parse a legacy owner key out of it or rewrite an immutable retained workflow identity. The descriptor is transported and independently verified alongside this evidence; its result digest already binds every closed request/result field, including private owner selectors, patch/remap presence and source identity. The attestation's canonical UUIDs do not authorize another owner to reuse those private selectors as local keys. + +The digest uses that versioned domain followed by field-name/value segments in the listed order, each framed by exact decimal strict-UTF-8 byte length, `:`, and bytes, as in the descriptor contract. Positive counters and schema versions use canonical decimal strings; UUIDs are canonical non-nil text. Source, descriptor, dedicated ability, manifest, artifact and outer evidence digests use `sha256:` plus 64 lowercase hexadecimal digits. Participant `contentDigest` instead preserves its existing owner format of exactly 64 lowercase hexadecimal digits without a prefix; receivers neither prefix that committed value nor accept an alternate representation. Arrays bind the segment pair `.size` and its canonical nonnegative decimal count, then every indexed field in exact retained order; there is no sorting or Unicode normalization during hashing. Object-array labels are `[].`; string-array labels are `[]`. Optional fields append `.present` and `.value`, with lowercase boolean presence and empty absent value, exactly as in the descriptor. Each participant entry binds, in order, `participantKey`, `scopeValue`, `baseVersionId` presence/value, `appliedCommitId`, `contentDigest`, `digestSchemaVersion`, and `abilitySchemaDigest` presence/value. A complete full-Version attestation has exactly the five distinct required owners in canonical order (`WORLD_MANAGEMENT`, `ENTITY_MANAGEMENT`, `GAME_LOGIC`, `AUTOMATION_SCRIPTING`, `GAME_DESIGN_CONTROL_PLANE`), exact descriptor Version scope, no patch base, successful supported-schema evidence and one identical nonblank applied commit. Only Game Logic supplies the nonblank dedicated ability-schema digest. Failed owner results are not successful attestation entries. + +Participant schemas remain their existing owner-specific supported versions: World Management `2`, Entity Management `2`, Game Logic `1`, Automation & Scripting `5`, and Game Design control plane `1`. The outer attestation's version `1` does not renumber those schemas. Each artifact entry binds, in order, `usageKey`, `artifactKind`, `immutableObjectKey`, `contentDigest`, `contentType`, and `artifactSchemaVersion`. Required usage keys and artifact entries are unique and retained in unsigned UTF-8 usage-key order; every required key selects exactly one actual-byte artifact entry. Artifact schema `1` retains the existing flat `artifacts/sha256/` object address. A proved empty manifest remains distinct from missing manifest evidence. Every command-definition string and the exact generation revision is retained. Local row IDs, private tenant keys and publication timestamps are owner storage metadata, not alternate canonical identity or authority fields in this separate schema. Neither an aggregate participant digest nor the manifest hash replaces dedicated ability or individual byte evidence. + +`GetCompleteLaunchBinding` takes the exact existing `GetLaunchDescriptorRequest` selector, echoes its separate non-nil read request ID, and returns the independently validated descriptor and separate attestation together or an error without either successful component. It authenticates the exact same-namespace Game Session or World workload before producer access. The consumer authenticates Game Design from the negotiated TLS peer before releasing its request, rejects unknown fields and missing or conflicting components, and verifies the exact request echo and both exhaustive digests. The old descriptor-only read remains explicitly narrower; it cannot be used as a fallback for this method. + +Game Design reads the exact immutable descriptor, source and release association from one dedicated read-only repeatable-read owner snapshot and checks the persisted Version UUID provenance before producing this pair. A missing, unsupported, unbound or mismatched component denies rather than synthesizing a partial attestation. Its normal authenticated producer may only return the already committed immutable release; it cannot publish, repair or resolve another release during a read. Identical read retries preserve the exact evidence bytes/digest; a different descriptor or release conflicts. World durably retains both verified components with its local lifecycle result and reads them back exactly before reporting `PREPARING`. This evidence is release integrity and provenance, not current activation authorization; current Version fences, Account authorization and World lifecycle predicates remain independent. + +**Implementation status:** The separate carrier, normal producer and World retention/consumer are in progress. Existing source-only descriptor proof, ordinary asset publication and a digest computed from a fixture are not full release-pair or deployed activation proof. Runtime activation remains denied until producer, authenticated consumer, migration, substitution, retry and readback proof executes. 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. @@ -66,9 +86,9 @@ Before reporting `PREPARING`, World verifies that exact descriptor against its r 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. +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 Game Design-owned numeric version selector, that same persisted Version row's canonical non-nil UUID `canonicalVersionId`, current lifecycle state, positive version-state epoch and derived evidence digest. The canonical UUID is owner evidence, not caller input, a World private key, or an identifier derived from the numeric selector. A missing, nil or contradictory UUID fails closed; the read never allocates or repairs it. 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. +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 Game Design-owned version selector, canonical lowercase `canonicalVersionId` UUID, 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. Every field is required; the closed response has no UUID-free fallback. 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. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 25481624eb..9ccf337872 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -8,7 +8,7 @@ This API contract is target-state canonical; implementation coverage is partial - 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` 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 has no commit-time creator authorization: its gRPC handler forwards any authenticated bearer to the mutation service, whose checks cover request shape and Draft state but not the acting account, current tenant role, or applicable Account terms authority. V24 SQL guards deny canonical-key mutations across all 16 tenant-bearing tables. The source-qualified Game Design Draft/version read is non-mutating precondition evidence, not write authorization. Current wrong-workload, cross-tenant, and commit-time authorization denial proof remains absent; see the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). +- The registered `ApplyWorldDesignMutation` RPC denies before request decoding or owner access until its [canonical Draft commit authorization](#canonical-draft-commit-authorization) is implemented. A workload peer, bearer claim or source-qualified Draft/version read cannot substitute for that authorization. Detailed current capability and proof limits belong in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). - 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. ## gRPC APIs @@ -47,7 +47,8 @@ Expected response: - `GET /ping` – basic health check returning `"pong"`. - `GET /regions?tenantId=...` – list regions for a tenant. -- `POST /generation/rules` and `GET /generation/rules?tenantId=...` – **current legacy routes**. These routes are not the supported design-time boundary: the POST path accepts only tenant access, defaults `versionId` to `1`, and does not enforce Game Design Draft/version authority. They must be removed or hard-fail closed before procedural-generation readiness is claimed. +- `POST /generation/rules` – **denied legacy write route**. After existing body parsing and tenant-access checks, the route returns HTTP `412` / `FAILED_PRECONDITION` before service dispatch because canonical Draft and Account commit authorization are absent. This is not a supported authoring boundary; detailed proof and remaining gates belong in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). +- `GET /generation/rules?tenantId=...` – **current legacy read route**. Its numeric tenant-access and pagination behavior remain unchanged; a read does not authorize a generation write. - `POST /generation/runtime-defaults` and `GET /generation/runtime-defaults?tenantId=...` – **target-only, not implemented**. These operational WMS-owned routes must remain unavailable until their authenticated tenant binding, request identity/replay, durable persistence, and failure semantics are defined and proved. The service exposes an OpenAPI specification under `/v3/api-docs` with a Swagger UI at `/swagger-ui.html` when running locally. @@ -72,6 +73,8 @@ World Management exposes design-time APIs used by Game Design to write Draft tem ### Canonical Draft commit authorization +**Current registered-write boundary:** `ApplyWorldDesignMutation` returns `FAILED_PRECONDITION` before request decoding or owner mutation because its Account commit-authorization producer and verifier are not implemented. An authenticated Game Design workload, service claim or otherwise valid-looking Draft request cannot bypass this denial. Owner-local mutation algorithm tests are not proof of an authorized exposed writer; the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) owns the remaining producer, consumer and execution gates. + For a canonical Draft write, Account supplies the current tenant-scoped designer/admin authorization for the acting account; where official-hosted creator terms apply, the applicable Account-owned party and terms currentness authority is required independently of the tenant role. Game Design carries that authorization with the exact World mutation descriptor. The descriptor and authorization must bind the acting account, canonical tenant, stable operation identity and digest, expected Draft/version, and the applicable role/terms authority. Account remains the owner of current authority and its fence under the [canonical authority contract](../../system-architecture-authentication.md#canonical-authority-tuple) and [hosted-terms contract](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party); consumers reuse the Account authority/fence protocol where supported. No new route, RPC, lease, envelope, schema, or field encoding is selected by this contract. World verifies both the authenticated Game Design producer and the Account authorization against the exact descriptor at the owner commit boundary. A source receipt, source-qualified Draft/version read, forwarded JWT, workload identity, copied role/terms state, or preflight-only check cannot authorize the mutation or replace commit-time currentness verification. The path remains automatic through Account, Game Design, and World; it has no manual authorization or migration step. Missing, stale, mismatched, unavailable, or uncertain authorization denies or aborts the owner commit, and Game Design must not report a successful cross-owner commit. Any staged data remains non-authoritative cleanup/quarantine state. Canonical World writes remain denied until this commit-time verification is implemented and proved. @@ -257,6 +260,14 @@ Fresh World content enters automatically through authenticated Game Design sourc World owns allocation and retention of its private local storage selectors. It atomically persists the association to the canonical tenant UUID and exact accepted content binding with its intake outcome, then reads back the complete original association and result before acknowledging success. Exact retries preserve the original source, descriptor, content and local association; a changed binding conflicts rather than silently selecting another tenant or release. This association does not itself prove current ACTIVE state or permit gameplay admission. +The identity prerequisite for a fresh World version is separate from accepting its content. World resolves an exact committed `NEW_GAME_ROW` source intake and obtains the persisted canonical Version UUID through the authenticated [source-qualified Game Design version-state read](../game-design-service/api-contracts.md#source-qualified-version-state-read). World allocates its own private positive version selector and atomically retains that association, the original complete source/version evidence and its owner outcome. Neither Game Design's private numeric Version selector nor a caller-supplied UUID is a World-local content lookup. The stable identity scope is `(targetNamespace, canonicalTenantId, worldSlug, canonicalVersionId)`; the Game Design private Version selector and exact original intake/source binding must remain one-to-one within that scope. A new transport read UUID is correlation only, not a new association operation. Exact retries read the original immutable association before contacting mutable upstream state, and changed source, intake, UUID or private-selector associations conflict. Independent readback checks the full original evidence and local association, including recovery after a lost commit acknowledgement. No retained World version or template is claimed by this fresh path. + +This identity receipt creates no content or lifecycle row and is not proof of materialization, current write authorization, publication, `PREPARING` or gameplay admission. Its original Version state and epoch are historical identity provenance, not reusable currentness authorization. Draft content still requires Account-authorized owner commit and the shared World publication/write fence; selecting published content additionally requires exact local content and complete release readback. The private World version selector must not replace the Game Design-owned selector used by its publication request or workflow identity. Implementation and execution limits remain in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). + +Released-content intake is a separate non-admitting owner step: World authenticates the exact same-namespace Game Session workload, reads the complete descriptor/release pair from Game Design over its verified workload channel, and matches the pair's namespace, canonical tenant, world selector and exact source operation/digest to the already committed World source intake and private association. World retains both complete original components together with that exact intake operation, receipt and private local key in one immutable owner transaction. The stable operation key is the descriptor's existing `(targetNamespace, canonicalTenantId, controlPlaneRequestId)`; a separate non-nil read UUID is transport correlation, not a second mutation identity. Missing source intake, an unproved association or a substituted descriptor/attestation denies before persistence. No local key is inferred from a Game Design numeric selector, and this step creates no template or lifecycle row. + +World independently reads back the committed pair and association before reporting this intake step successful. An exact retry returns the same retained owner operation and evidence without rereading mutable defaults or selecting a replacement release; changed request fields, result digest, attestation or source binding conflict. Owner readback recomputes both closed evidence digests and checks the complete stored pair, not just its IDs or hashes. Retained missing evidence is not synthesized. This prerequisite is not `PREPARING`: canonical lifecycle preparation additionally needs exact local published-content readback, current source/lifecycle evidence and every applicable commit-authorization guard. Existing canonical writes and runtime activation remain denied until those independent boundaries and their positive/negative proof are complete. + The source-intake prerequisite is separate from released-content acceptance: `world-authored-source-intake/v1` retains the complete closed Game Design source receipt, positive schema version, target namespace, stable `intakeRequestId`, owner-allocated operation UUID, canonical tenant UUID, world slug, source operation/evidence digest, request digest and receipt digest. World also retains its own private local tenant association internally; it does not transmit that numeric selector as a canonical identifier. Fresh allocation requires Game Design's proved `NEW_GAME_ROW` provenance and an owner-allocated selector that cannot claim existing World rows. A retained Game Design source is not proof that World has no retained content and cannot take this fresh-allocation shortcut. The request digest is SHA-256 over fixed-order UTF-8 segments with decimal byte-length `:` framing: `world-authored-source-intake-request/v1`, target namespace, intake request UUID, canonical tenant UUID, world slug, source operation UUID and source evidence digest. The owner-internal receipt digest uses the same framing over `world-authored-source-intake-receipt/v1`, target namespace, owner operation UUID, request digest, canonical tenant UUID, world slug, source operation UUID, source evidence digest and canonical decimal private local tenant key. UUIDs use canonical non-nil text, the private key is positive, and digests render as `sha256:` plus 64 lower-case hexadecimal characters. The source digest is verified against the complete original owner receipt, never accepted alone as authentication. A writable World owner transaction stores and exactly reads back the association and immutable receipt together; changed request/source/local association, absent or corrupt readback, and allocation over existing World state fail closed. This receipt is not released-content, descriptor, ACTIVE-state or admission proof. @@ -271,13 +282,13 @@ World reserves a fresh private selector durably with its canonical association. 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. +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. That evidence supplies Game Design's persisted canonical Version UUID separately from its numeric source selector; World must retain the UUID-to-private-key association from exact owner evidence, never derive it from numeric equality. For a retained complete launch binding, World also compares that UUID with the unchanged release attestation's canonical Version UUID before accepting currentness. 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). ## Initial Admission Hold Contract -Canonical preparation verifies Game Design's exact [authored-source-bound launch descriptor and its separately authenticated full release attestation](../game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback), then retains and reads back both together with the World lifecycle result before reporting `PREPARING`. World rejects either missing item and any swapped or mismatched pair, including disagreement in descriptor/source identity, canonical tenant/world scope, canonical UUID version, resolved release, or required release evidence. An exact retry returns the originally retained pair and lifecycle result; it cannot replace either item with newer owner state. The existing currentness and authorization checks still apply, and the pair and `PREPARING` result commit through the existing atomic workflow. A source selector receipt does not replace release attestation, and a private source key does not establish a World tenant association. Game Design's version-state epoch remains distinct from this owner's lifecycle epoch; descriptor recovery alone does not prove current ACTIVE eligibility. The separate attestation's wire and durable pair representation remain unspecified by the owner contract and must be settled without changing descriptor v1. +Canonical preparation verifies Game Design's exact [authored-source-bound launch descriptor and its separately authenticated full release attestation](../game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback), then retains and reads back both together with the World lifecycle result before reporting `PREPARING`. World rejects either missing item and any swapped or mismatched pair, including disagreement in descriptor/source identity, canonical tenant/world scope, canonical UUID version, resolved release, or required release evidence. An exact retry returns the originally retained pair and lifecycle result; it cannot replace either item with newer owner state. The existing currentness and authorization checks still apply, and the pair and `PREPARING` result commit through the existing atomic workflow. A source selector receipt does not replace release attestation, and a private source key does not establish a World tenant association. Game Design's version-state epoch remains distinct from this owner's lifecycle epoch; descriptor recovery alone does not prove current ACTIVE eligibility. The separate closed evidence and exact authenticated read are owned by [Game Design's release-attestation contract](../game-design-service/api-contracts.md#separate-complete-release-attestation-evidence); World must retain both components rather than extending descriptor v1 or accepting descriptor-only fallback. Producer, consumer, local retention and negative runtime proof remain activation gates. [Versioning and Runtime](../../system-architecture-versioning-runtime.md#first-open-from-never-opened-authority) owns the first-OPEN transition and its tagged prior-pointer preconditions. World owns the durable initial-admission hold and authoritative target lifecycle proof. The hold binds one stable initial-admission request/digest, the complete canonical namespace/tenant/realm/playable-namespace/scope, exact target instance/version/ACTIVE epoch, and the precondition tag with its applicable pointer/catalog versions. Private World storage selectors do not replace those identities: any association must come from exact persisted authenticated owner evidence, never numeric equality, slugs or Account's migration manifest. diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index 7f4e8a112b..6d4705a482 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -30,7 +30,9 @@ Post-bundle publish failure is likewise unresolved: target reconciliation must r Purge failure status is also not durable in the current implementation: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and then rethrows from an `@Transactional` method, so rollback can discard those markers after object deletion. The resulting durable row may remain `PURGE_IN_PROGRESS` without resumable evidence. Target recovery requires an independent durable failure/reconciliation boundary (or equivalent non-rollback record) and focused deletion/post-delete-save failure proof. -Asset repair has a separate current ordering gap: `AssetExportServiceImpl` writes the version-prefix objects and manifest before `VersionAssetArtifactServiceImpl` compares the result with the release attestation, so a mismatch may mutate live prefix keys before failing. After process loss, `PUBLISHED`/`ACTIVE` repair fails closed when the process-local selection is unavailable, but a `RETIRED` Version can currently fall through to a fresh tenant-wide selection; that drift is not exact repair proof. Pre-write away-from-published verification and durable version-scoped selection remain target-only. +The asset candidate now uses durable version-scoped byte snapshots and a frozen pre-write export candidate, with conditional content-addressed writes and exact stored-evidence recovery instead of process-local or tenant-wide reselection. Actual PostgreSQL-to-object-store component proof is recorded in the [authoring tracker](../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); it is not live asset delivery or complete publication/activation proof. The remaining lifecycle, destructive-operation and shared-fence gaps remain owned by [Asset Storage](./microservices/game-design-service/asset-storage.md#implementation-status). + +The complete launch-binding candidate exposes the unchanged source-bound descriptor plus a separately authenticated exact release attestation and adds immutable World retention against its committed source-intake association. Its component proof and remaining producer/consumer gaps are recorded in the [authoring tracker](../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) and [World tracker](../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). It does not supply local World content, current commit authorization, `PREPARING`, or runtime activation; the [Game Design owner contract](./microservices/game-design-service/api-contracts.md#separate-complete-release-attestation-evidence) remains the sole owner of the separate attestation schema. Capacity admission is also target-state only. Account's `CommitTenantCapacityAdmission` RPC and both caller integrations (Game Session and World Management) are unimplemented, as are the durable Account authority/usage ledger, the exact `capacityDelta` wire contract, the capacity-admission action-family schema and cross-language `mutationDigest/v1` golden vectors, and the reservation create/finalize/release/reconciliation lifecycle. The capacity-admission sections below are normative contracts and must not be read as evidence that these RPC, caller, ledger, schema/vector, or reservation components exist. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 21a9469e38..fdf58e82f0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -426,3 +426,13 @@ Entry format: - Context: Game Design's integration analyzer exited with code 3 without a report; repeating the exact task with `--info` still showed only the invocation and missing annotation class, not the finding. A temporary Gradle init script enabling an XML report on that same task exposed a nullable PostgreSQL read in the new composition test. - Outcome: the missing-row read now fails explicitly, and the canonical composed check passes without suppressions or reduced analyzer coverage. The report-only script was a temporary diagnostic input, not repository tooling or substitute validation. - Expected pattern: if the detailed log remains inconclusive, enable the affected task's report without changing its analysis or failure policy; fix the reported issue and rerun the normal gate. A missing annotation warning alone does not explain an analyzer failure. + +- `2026-10-05`: A successful diagnostic invocation may have skipped its analyzer + - Context: a focused Game Design SpotBugs diagnostic returned `BUILD SUCCESSFUL` without `-PfullCheck`; the task log showed `spotbugsMain SKIPPED`. Document briefly reported that as an isolated analyzer pass before checking the task state. + - Outcome: the skipped result was withdrawn, the exact task rerun with `-PfullCheck`, and its XML exposed the constructor finding behind the consolidated failure. No skipped diagnostic result was used as publication or completion proof. + - Expected pattern: preserve required check flags in diagnostic commands and inspect the actual task outcome, not just the process exit status, before attributing analyzer execution or calling a failure intermittent. + +- `2026-10-05`: Cross-service test dependencies can leak another owner's Flyway migrations + - Context: the new Game Design-to-World composition fixture added a World service test dependency. Its service JAR also supplied `db/migration`, so existing Game Design classpath-based Flyway fixtures failed on duplicate V1 migrations in CI; Docker-free local checks had skipped that setup. All eight new database cases passed, but six other required cases did not execute. + - Outcome: selecting the World dependency's standard classes-only variant preserves its implementation and transitive dependencies without its migration resources. A resolved runtime-classpath diagnostic and full affected checks pass; exact corrected-state PostgreSQL execution is still required. + - Expected pattern: for cross-service test composition, inspect resolved runtime artifacts as well as compilation. Keep owner migrations explicitly isolated and verify existing owner suites still execute; do not modify migrations or weaken fixtures to accommodate resource leakage. 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 fd876b3b91..422175ee04 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,9 +6,15 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The World complete-binding prerequisite includes an explicitly unwired source-qualified current-Version consumer and component proof. Game Design returns its already-persisted canonical Version UUID and complete immutable Version/source provenance from the same read-only snapshot; World reads back the original local pair/source before comparing the exact source, UUID, state and descriptor epoch, preserves the original result on currentness denial, and performs no lifecycle mutation. Exact `e20471d6addc25ebe1e4b3afbc4ac648e116f5de` [CI37254215948](https://github.com/benhook1013/FireMUD/actions/runs/37254215948) has independently verified raw XML for all 29 required PostgreSQL methods: six Game Design complete-binding, eight World pair/currentness, four Game Design owner-snapshot, five version/mTLS (including two identity-composition), and six World identity methods. All 29 executed without skips, failures or errors. The nine existing Game Design owner suites also executed all 63 methods cleanly. The source-built merge `41895db449bef1cd13c98cc178fe80d70caadb35` has the expected `a339` and `e204` parents and the same tree; its raw XML was independently verified. This corrects the earlier `2ceefac830e6747bd088e075d992457f678adde9` checkpoint, where six Game Design complete-binding methods were skipped after World migrations leaked into existing Game Design fixtures. The classes-only dependency repair is now proved, with no pending runtime revalidation for that repair. Earlier local full Game Design/World checks and both boot JARs passed with 709 clean unit executions, one object-store unit skip and all 148 PostgreSQL nodes skipped without Docker. The [World tracker](./world-runtime-and-movement.md#current-status) owns World identity implementation and proof limits. This does not close normal Game Logic publication, canonical World content, commit-time owner/Account fencing or launch activation. + +The authored-source delivery batch adds V41 durable delivery intent in the same transaction as fresh `NEW_GAME_ROW` source registration, followed by authenticated World intake and independent receipt readback outside the Game Design transaction. A short Game Design owner transaction retains the first complete World receipt and independently reads it back; an exact completed retry returns that immutable acknowledgement before contacting World, while an ambiguous/lost acknowledgement retains the same intake identity for exact retry. Historical source-only retries are not backfilled, and retained sources do not receive a delivery intent. Full Game Design/World checks and both boot JARs pass with 718 clean unit executions, including all nine new delivery cases; one object-store unit case and all 158 PostgreSQL methods skip locally without Docker. At exact `db03a6d2d4a4c09a45540fcad183bb4469557415`, [CI37257109313](https://github.com/benhook1013/FireMUD/actions/runs/37257109313) executes all ten new methods without skips, failures or errors: seven PostgreSQL component cases mock outbound World calls, while three composition cases use actual Game Design and World PostgreSQL owners and physical workload mTLS with synthetic persisted creation fixtures. All 29 earlier required launch/identity/version methods and 63 existing Game Design owner methods also execute cleanly. Independent raw-XML parsing/hashing and expected merge parents with an equal source tree establish exact attribution. Forward V41 generation, migration numbering, workflow validation and 230 architecture-contract tests pass. The delivery path is not registered as a worker and does not enable a public creator, Account designer/terms authorization, content materialization, lifecycle preparation or activation. The [Game Design API contract](../../architecture/microservices/game-design-service/api-contracts.md#durable-fresh-source-delivery-to-world) owns delivery semantics; the [World tracker](./world-runtime-and-movement.md#current-status) records only its local consequence. Assigned proof is settled, but aggregate CI was still active with an unrelated, not-yet-diagnosed Python failure at observer handoff; no aggregate-green claim follows. + The source-aware Unit 1B launch integration still depends on the complete Game Design release producer under `AR-1.4`, `AR-1.5` and `AR-3.2`. The owner-reference prerequisite preserves independently generated opaque release identity and exact canonical tenant/Version provenance; neither derives from private identifiers. Exact `cec29b3fcad147be44dd37b1d47381fecd0d8dac` [CI37224206898](https://github.com/benhook1013/FireMUD/actions/runs/37224206898) executed all six canonical Version and five immutable release-identity PostgreSQL methods without skips, failures or errors; aggregate CI failed elsewhere. These cases supersede the earlier missing source fixtures and overlong schema-name failure below, not the missing whole-release producer. Game Logic's required full-version manifest/provenance and dedicated ability-schema evidence remain unavailable, so no complete source-qualified release or successful launch may be manufactured. Retained World content still needs its own audited association; private key equality or Account's manifest is not World authority. Initial launch and admission remain denied until the complete owner and authenticated consumer proof executes. -The ordinary-asset producer replaces tenant-wide selection and process-local recovery with V37 owner-qualified Draft mappings and immutable actual-byte snapshots, including a proved empty set. V38 freezes complete ordered artifact/manifest candidate evidence before external writes; conditional content-addressed export verifies exact bytes, type and length, while ambiguity remains PENDING. Checked artifact epoch CAS and immutable release readback do not authorize shared-object deletion or complete Version lifecycle/purge fencing. Exact `9789b12fc892d7187dc9268312d4a96010924345` [CI37233813567](https://github.com/benhook1013/FireMUD/actions/runs/37233813567) executed all 15 required asset and five release-identity PostgreSQL cases cleanly, superseding the earlier insert/fixture failures. Its two publication transaction failures exposed diagnostic overflow; forward V39 losslessly widens generated release/descriptor revisions and terminal diagnostics, with retained-row and exact failed-retry cases awaiting corrected PostgreSQL execution. V40 preserves the dedicated Game Logic ability digest in publish-attempt evidence, including NULL absence, separately from aggregate content. The corrected five-service check and five boot JARs pass locally: 475 Game Design and 1193 Automation unit cases execute cleanly; other service results are reused. All 93 Game Design PostgreSQL/composition and 88 Automation integration cases skip locally without Docker. Historical actual-MinIO exporter proof uses synthetic snapshot/candidate fixtures; the new PostgreSQL-to-real-MinIO composition case is separately required but not yet executed. Mocked S3, compiled or skipped tests are not provider/database execution. Public authenticated Draft/creator ingress, the normal rule/ability and derived-artifact producers, complete descriptor/release and World binding, Version/global reachability/purge fences, fresh image/deployment and approved live public delivery remain open; no runtime activation is authorized. The [asset-storage owner](../../architecture/microservices/game-design-service/asset-storage.md) owns the target contract. +The ordinary-asset producer replaces tenant-wide selection and process-local recovery with V37 owner-qualified Draft mappings and immutable actual-byte snapshots, including a proved empty set. V38 freezes complete ordered artifact/manifest candidate evidence before external writes; conditional content-addressed export verifies exact bytes, type and length, while ambiguity remains PENDING. Checked artifact epoch CAS and immutable release readback do not authorize shared-object deletion or complete Version lifecycle/purge fencing. Exact `eebc3c5426c517569f701048adcd702474512bb7` [CI37238129505](https://github.com/benhook1013/FireMUD/actions/runs/37238129505) executed all 15 required asset and five release-identity PostgreSQL cases cleanly. Its eight descriptor cases include V39 full retained-row equality and lossless long diagnostics; both previously failing publication transaction cases now pass with original failed-retry evidence preserved. The new V40 dedicated ability-carrier case exposed a separate publish-attempt INSERT returning null after persistence. The explicit returned-row repair is published at `1189b3b5631200735078b80de6dd42f72c58ca91`, with its H2 original-request/save/independent-readback test and full local Game Design check clean. At that exact head, independently parsed raw XML from [CI37240401842](https://github.com/benhook1013/FireMUD/actions/runs/37240401842) proves all five publication-transaction PostgreSQL cases executed without skips, failures or errors, including the dedicated ability-carrier case. Local Docker unavailability still skipped all 93 Game Design PostgreSQL nodes and the MinIO unit case at that checkpoint; those local skips are not counted as database proof. + +At exact `1189b3b5631200735078b80de6dd42f72c58ca91`, [source-built MinIO37240405194](https://github.com/benhook1013/FireMUD/actions/runs/37240405194) executed both the existing provider test and the new real PostgreSQL-to-MinIO composition test, each once without skips, errors or failures. This supersedes historical synthetic snapshot/candidate proof, but not fresh application images, approved public delivery or live readiness. The composed full [CI37240401842](https://github.com/benhook1013/FireMUD/actions/runs/37240401842) completed with `FAILURE`: Account Build/Test succeeded, Game Session was cancelled after its focused proof steps passed, and TCP executed 17 cases with 13 PLAY ownership-denial failures. The existing Gameplay-owned PLAY/bootstrap gap and separately routed shared Python failures remain open; none is relabeled flaky. The complete separately authenticated descriptor/release producer and World durable consumer are work in progress, not an enabled launch. Public authenticated Draft/creator ingress, normal rule/ability and derived-artifact production, synchronized owner commits, Version/global reachability/purge fences, deployment and approved public origin remain open. No runtime activation is authorized; the [asset-storage owner](../../architecture/microservices/game-design-service/asset-storage.md) owns the target contract and [Game Design](../../architecture/microservices/game-design-service/api-contracts.md#separate-complete-release-attestation-evidence) owns the new separate launch evidence. At exact `9789b12fc892d7187dc9268312d4a96010924345`, [CI37233813567](https://github.com/benhook1013/FireMUD/actions/runs/37233813567) executed all seven asset-snapshot, six export-candidate, two artifact-repository and five release-identity PostgreSQL cases with zero skips, failures or errors. Independent raw-XML parsing confirms those counts. The earlier source-built MinIO provider case at `80aefbf43b09854f472e491463f9ff2d41e4313e` passed with synthetic snapshot/candidate fixtures; it does not establish database-to-store composition. The current CI also exposed two publication transaction failures and misplaced later required-case checks after other selectors replaced their reports; aggregate CI is not green. Corrected transaction, composed PostgreSQL-to-MinIO and fresh application-image proof remain separate gates. @@ -22,7 +28,7 @@ The owner-local release association candidate now persists and reads back the ac 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. +The complete-binding candidate preserves the unchanged closed descriptor/v1 and adds a separate, exhaustive release-attestation/v1 under the [Game Design owner contract](../../architecture/microservices/game-design-service/api-contracts.md#separate-complete-release-attestation-evidence). Game Design assembles the pair from its exact persisted descriptor, canonical Game/Version source and immutable release in one read-only `REPEATABLE_READ` snapshot. The shared transport rejects partial or substituted components and authenticates the exact Game Design peer before releasing a request; the protected read admits only the exact same-namespace Game Session or World workload. World independently retains both components against its own committed source-intake association. The earlier `22b6a877a3a52cd53fb744262a9a392d08903f0e` database run exposed an overlong private Game Design fixture key; the independently random 35-character correction preserves the unchanged 36-character column. All six corrected Game Design methods and all eight later World binding/currentness methods execute cleanly at `c214e6ca4b832d70ba264eb02f47315aea2d4ae7` in CI37248504487, with exact raw-XML and tree attribution summarized above. The Game Design fixture supplies synthetic participant/manifest evidence and the World fixture mocks the external client, so these are component proofs, not the normal Game Logic producer, cross-owner publication, local World content, `PREPARING`, current commit authorization or activation. Those obligations remain open and denied. This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. 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 b0b11e9e05..3eeb8b5a4b 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,28 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The held-back World mutation algorithm now uses full-tuple, expected-epoch SQL predicates for its declared aggregate and scope advances. An absent epoch can be claimed only from zero with a conflict-safe insert; stale, negative or overflowing expected counters cannot succeed. A losing advance raises `DRAFT_WRITE_CONFLICT` inside the existing owner transaction rather than committing content under an unconditional epoch save. The focused mutation suite executed 29 cases successfully. The consolidated World check, boot JAR, formatting, static analysis, links and Markdown passed with 227 unit executions and no unit skips; all 55 PostgreSQL integration methods, including five new deterministic race, tuple-isolation and rollback cases, compiled but skipped locally without Docker. The subsequent exact-source CI execution is recorded below. This closes a local storage primitive, not complete affected-scope validation, immutable complete-input retry binding, source-qualified content materialization, synchronized Draft visibility, Account authorization, publication or lifecycle. The registered mutation remains denied. [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) remains the target contract. + +At exact source `f968b46adf12570e870b17e17fe0d4382e7078b4`, [CI37289016289](https://github.com/benhook1013/FireMUD/actions/runs/37289016289) World job `111694868974` succeeded. Root independently parsed and rehashed raw XML: all five new epoch-CAS methods executed once, passed and had zero skips, failures or errors. These prove real PostgreSQL first-claim and existing-row races, tuple isolation, rollback after a late scope conflict and rollback of authored content, both counters and ledger after an otherwise successful owner mutation. XML SHA-256 is `d779fe0a7214cba7901370cd59d0478113ed33721ca38d32d31af827bcc28eb6`. Job checkout and independently verified merge `467ca7355ef92583a74893b624bf740ca7b48205` bind exact base `071b35375b7b4c174147ed201c10dc50658b19a4` and source parents, with tree `96f74c67841d2f52a2673136308539eb6f50a667` identical to the source. The later World Gradle check also passed. Metadata-only runs `37289154141` and `37289180583` skipped build jobs and supply no execution credit. The aggregate was still active at observer closeout; complete authorization, synchronized publication, materialization, fresh-image/live and activation proof remain open. + +The canonical launch dependency is not satisfied by the existing source, Version identity and descriptor/release receipts alone: none proves that World's local topology is the released row set. The next normal content producer must compose Account-authorized authored commit, Game Design's durable synchronized coordination, source-qualified World-private Version resolution, shared write/publication fencing, complete participant digest and exact terminal published-content readback. Only then can canonical `PREPARING` atomically allocate and retain the Game Session instance UUID to World-private run association and complete runtime topology. Fresh tenant/run addressing must not be inferred from numeric equality, and the legacy hard-coded generation inputs and silently skipped topology rows cannot constitute that materialization proof. Creator authorization belongs at authored commit; later derived preparation consumes its proved immutable published result. Gameplay's separate selected-actor location reader remains unwired pending the actual fresh lifecycle/readback handoff; a run association also does not create authoritative location state. + +The registered `ApplyWorldDesignMutation` ingress denies before decoding or contacting owner services while the accepted Account commit-authorization path is absent. Handler-unit proof covers absent caller context, Game Design service claims, matching workload-peer context and malformed version input, with no mutation, digest or lifecycle service calls and no success fields. The legacy `POST /generation/rules` now preserves body parsing and tenant-access checks, then denies with HTTP `412` / `FAILED_PRECONDITION` before service dispatch; numeric `GET` behavior is unchanged. Eight controller cases cover tenant-admin and global-admin claim denial, existing designer/player/wrong-tenant rejection, malformed bodies and reads. All 223 World unit cases pass, including 27 registered-handler cases; the full World check, boot JAR, static analysis, formatting, links and Markdown pass. All 50 World PostgreSQL methods skip locally without Docker. Both new registered-handler cases executed successfully through physical mTLS with Game Design and Account certificates, comparing all 24 World row families before/after. The corrected HTTP/PostgreSQL denial case now passes on CI with its actual interceptor, parsed-token, strict `412` / error-envelope, and complete generation-rule-row preservation assertions; the focused XML and run evidence are recorded below. Matching peer context in unit tests is not a substitute for runtime execution. The [canonical Draft authorization contract](../../architecture/microservices/world-management-service/api-contracts.md#canonical-draft-commit-authorization) owns the target producer/consumer boundary. Owner-local mutation algorithms remain component-only; current tenant-role/Creator Party terms, synchronized commit, canonical content, fresh-image startup and live activation proof remain open. + +At exact `fc550d85f496426e3d9f2a07d95a6bbf043ea8e9`, independently parsed raw XML from [CI37260050177](https://github.com/benhook1013/FireMUD/actions/runs/37260050177) proves 45 selected PostgreSQL/mTLS executions: 44 passed, one HTTP denial assertion failed, and none skipped. The full five-case World intake/mTLS suite passed, including both new registered-handler denial methods. All 63 existing Game Design owner methods and its full Gradle check passed. World's full Gradle check was skipped after the HTTP failure. Merge `7c393da406ff7df359c26de87794f46f986793cb` has the expected a339/fc550 parents and identical candidate tree `49fa83b50b15ab01d73538900e8ed3a50e9eef5c`. Successful runner unit XML was unavailable, so precise unit counts remain local evidence only. This is not aggregate-green, fresh-image, complete Account authorization or activation proof. + +At exact diagnostic `3d1ac2f3dc8167d765e018ab50c202a37f9383c6`, [CI37261894806](https://github.com/benhook1013/FireMUD/actions/runs/37261894806) executed the HTTP case and proved its actual `HttpAuthProperties.isEnabled()` was false before seeding or sending the request. This identifies the test-context omission, not a production authorization defect. The fixture correction explicitly enables the canonical shared HTTP auth property and preserves the production-public `GET /ping` route; no generation-write route is public, no context is manually installed, and the actual-interceptor, token, strict `412` and complete retained-row assertions remain. The corrected local full World check and boot JAR pass with all 223 unit cases clean, while all 50 PostgreSQL methods remain Docker-skipped. The later corrected-head runner result below supplies the focused execution unavailable locally. The separate shared-MVC test executes successfully and proves the same signed admin fixture reaches `412` through the real interceptor; it does not replace the World/PostgreSQL proof. + +At exact `3e5087b9ed1cd1093883f90198146effbb128df1`, [CI37262851416](https://github.com/benhook1013/FireMUD/actions/runs/37262851416) completed World job `111613756866` and its full Gradle Checks step successfully. The published `WorldManagementServiceApplicationIntegrationTest` XML reports the dedicated `saveRuleDeniesAuthenticatedWriteWithoutCanonicalCommitAuthorization()` method executed once with zero skips, failures or errors; its HTTP log records status `412`, and the passing test asserts the error envelope and equality of the complete generation-rule rows before and after. The full application integration-suite XML was not published, so its total count is unknown; no World authored Version identity XML was available. Separately published World socket XML proves 7 executions and complete launch-binding XML proves 8 executions, all without skips, failures or errors. The verified merge `ef2a406f3bad10be0504e6922fd8f304c3f41e5c` has the expected a339/3e parents and the same tree as this source head. This focused success closes the corrected HTTP denial runtime proof; it does not establish execution counts for other uncaptured integration methods, accepted canonical Account authorization, canonical content, lifecycle wiring, fresh-image startup or live activation. + +At exact `6deee1ae2acf3835789ec5b70d86f8c37ecbbabf`, independently parsed raw XML from [CI37258266597](https://github.com/benhook1013/FireMUD/actions/runs/37258266597) proves all 39 required launch/identity/version/delivery PostgreSQL methods and 63 existing Game Design owner methods executed without skips, failures or errors. Its merge `7614cf07c450600569e377e1cabca50ebe362034` has the expected a339/6deee parents and the exact candidate tree. The World job and unit test task succeeded, but successful-job unit XML was not uploaded; the precise unit counts above are local evidence, not invented CI counts. This exact runner proof predates the new three denial runtime methods and legacy POST correction. Python validation reports the separately owned smoke callback `B023` at line 1059; General's published correction is outside this ancestry and remains a later alignment gate. No aggregate-green, full-flow or activation claim follows. + +The fresh authored-Version identity candidate adds an explicitly unwired World owner association. It authenticates the exact same-namespace Game Design caller, resolves the committed `NEW_GAME_ROW` source intake, verifies the source-owned persisted canonical Version UUID, and allocates a private World-local version key. Forward V27 retains the original complete source/version evidence against an exact intake FK; immutable unique claims and independent readback preserve the first result across retries, concurrent reads and lost commit acknowledgements. It creates no content or lifecycle row, does not reuse a Game Design numeric key as a World key, and does not infer retained associations. At exact `e20471d6addc25ebe1e4b3afbc4ac648e116f5de`, independently verified raw XML from [CI37254215948](https://github.com/benhook1013/FireMUD/actions/runs/37254215948) proves all six World identity methods, two identity-composition methods, eight World pair/currentness methods, six Game Design complete-binding methods, four Game Design owner-snapshot methods and three existing physical version-read methods executed without skips, failures or errors. The identity-composition methods use real Game Design PostgreSQL, physical mTLS and World persistence but fixture-injected source delivery. The nine existing Game Design owner suites also passed all 63 methods. This supersedes the earlier `2ceefac830e6747bd088e075d992457f678adde9` checkpoint, where six Game Design complete-binding methods were skipped due to World migrations leaking into existing Game Design fixtures; the classes-only dependency repair is now proved. Full local Game Design/World checks and both boot JARs had 709 clean unit executions, one object-store unit skip and all 148 PostgreSQL nodes skipped without Docker. A new Game Design delivery batch calls the existing authenticated World intake and readback after committing a durable fresh-source intent; its database/composition suites compile but skip locally without Docker, so their runtime execution remains required. No World code or World contract changed in that batch. Automatic delivery worker registration, content materialization, Account-authorized commit, lifecycle wiring and activation remain separate gates. The [Game Design tracker](./game-authoring-publishing-and-activation.md#current-status) owns delivery implementation and proof; the [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#authenticated-authored-content-intake-and-tenant-association) owns the authenticated intake boundary and authorization limits. + +The additional explicitly unwired current-Version consumer first reads the exact already-committed launch pair and World source receipt, then performs the authenticated source-qualified Game Design read. It compares the full source and request, requires the returned persisted canonical Version UUID to equal the retained release attestation's UUID, accepts only `PUBLISHED` or `ACTIVE` at the descriptor's expected Game Design epoch, and does not rewrite the historical pair when currentness is denied. It uses Game Design's source-owned Version selector, never World's private local key. All 211 World unit cases pass, including the seventeen binding/currentness methods; the full local World check and boot JAR pass. Two additional PostgreSQL cases compile but skip without Docker, alongside the six pair-storage cases and all 41 World integration nodes. Their upstream readers are mocked; no real Game Design producer composition, commit fence, local published-content association, canonical lifecycle wiring or activation is proved by these cases. Snapshot currentness is not commit-time authorization or a replacement for the remaining content and lifecycle gates. + +The complete launch-binding candidate adds an explicitly unwired World owner step that retains the unchanged Game Design descriptor and its separate full release attestation against the exact already-committed World source-intake receipt. Independent readback verifies the closed component digests and all duplicated source/identity columns; exact retry reads the original pair before contacting Game Design. Forward V26 adds immutable pair storage and the exact source FK without assigning UUIDs to retained World rows. Its unbounded request-identity uniqueness constraint remains enforced by PostgreSQL; only the schema generator's unsupported TEXT index and immutable triggers are excluded from generation. At `c214e6ca4b832d70ba264eb02f47315aea2d4ae7`, [CI37248504487](https://github.com/benhook1013/FireMUD/actions/runs/37248504487) executed all eight World pair/currentness PostgreSQL methods, six Game Design complete-pair methods, four source-qualified owner snapshot methods and three physical PostgreSQL/mTLS version-read methods cleanly without skips or failures. Root independently rehashed all four raw XML suites and verified merge-ref `15f6342bb85cadf3183b3f9a47012291a2793b42` has the exact source head's tree and expected base/source parents. This executes the persisted canonical Version UUID correction and the corrected Game Design fixture; it does not execute the later V27 identity association or its new composition fixture. The external Game Design client is mocked in the World pair-storage fixture; the physical version-read cases use a real Game Design producer but a synthetic persisted source. Aggregate CI failed on concrete Python validation/dependency and TCP checks, not these 21 methods. This is non-admitting released-content evidence, not a wired lifecycle producer, local materialization, `PREPARING`, current authorization or activation. The [World API](../../architecture/microservices/world-management-service/api-contracts.md) owns the remaining lifecycle consequences and the [Game Design contract](../../architecture/microservices/game-design-service/api-contracts.md#separate-complete-release-attestation-evidence) owns the separate attestation. + The legacy World lifecycle adapter now exact-compares Game Design's persisted opaque release-bundle reference instead of reconstructing it from private numeric keys. Focused unit cases prove acceptance, substituted/missing-reference denial before persistence, and stable exact retry; the full World check and boot JAR pass with 153 clean unit results. All 25 World integration cases skip locally without Docker. This is reference-binding proof only, not complete release attestation, authenticated canonical launch composition, source-room delivery or activation. 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. diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index 63a04c8581..7999faefc9 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -39,6 +39,8 @@ service GameDesignService { rpc ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse); rpc GetLaunchDescriptor(GetLaunchDescriptorRequest) returns (GetLaunchDescriptorResponse); + rpc GetCompleteLaunchBinding(GetLaunchDescriptorRequest) + returns (GetCompleteLaunchBindingResponse); rpc CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse); rpc ApproveTemplateRemapSet(ApproveTemplateRemapSetRequest) @@ -354,6 +356,7 @@ message AuthoredWorldVersionStateEvidence { VersionLifecycleState version_state = 10; int64 version_state_epoch = 11; string evidence_digest = 12; + string canonical_version_id = 13; } // Complete immutable registration receipt, without another RPC's transient read request ID. @@ -420,6 +423,13 @@ message GetLaunchDescriptorResponse { shared.v1.ErrorDetail error = 3; } +message GetCompleteLaunchBindingResponse { + string request_id = 1; + LaunchDescriptor launch_descriptor = 2; + AuthoredWorldReleaseAttestationEvidence release_attestation = 3; + shared.v1.ErrorDetail error = 4; +} + message CreateTemplateRemapSetRequest { string tenant_id = 1; int64 source_version_id = 2; @@ -618,6 +628,31 @@ message AuthoredWorldLaunchDescriptorEvidence { string result_digest = 23; } +// Separate closed evidence: never extends or reinterprets descriptor/v1. +message AuthoredWorldReleaseAttestationEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string descriptor_result_digest = 3; + string canonical_tenant_id = 4; + string canonical_version_id = 5; + string world_slug = 6; + string authored_world_source_operation_id = 7; + string authored_world_source_evidence_digest = 8; + string launch_descriptor_id = 9; + string published_release_bundle_ref = 10; + int64 version_state_epoch = 11; + string publish_workflow_id = 12; + string commit_id = 13; + repeated ParticipantDigest participant_digests = 14; + string manifest_hash = 15; + int32 manifest_schema_version = 16; + repeated string required_manifest_asset_keys = 17; + repeated PublishedArtifactDigest artifact_digests = 18; + repeated string command_definitions = 19; + string generation_config_revision = 20; + string evidence_digest = 21; +} + message TemplateRemapSet { string remap_set_id = 1; string tenant_id = 2; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java index 26521808af..0cfe9621fe 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; /** * Explicit mTLS client for exact authored-world launch descriptor resolution and owner readback. @@ -98,6 +99,26 @@ public AuthoredWorldLaunchDescriptorEvidence get( } } + /** Reads and validates the descriptor and separate release attestation as one exact pair. */ + public CompleteLaunchBindingEvidence getComplete(GetLaunchDescriptorRequest request) { + Objects.requireNonNull(request, "request"); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCompleteLaunchBinding(request); + try { + CompleteLaunchBindingEvidence evidence = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response); + requireNamespace(evidence.descriptor().targetNamespace()); + return evidence; + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid complete authored-world launch binding evidence", + exception); + } + } + @Override protected String configuredTarget(ServiceEndpointsProperties endpoints) { return endpoints.getGameDesignService(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java index 7a182cdb42..d41a9903ef 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java @@ -1,12 +1,16 @@ package net.firedevops.firemud.common.gamedesign; import com.google.protobuf.Message; +import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; @@ -123,8 +127,121 @@ public static AuthoredWorldLaunchDescriptorEvidence fromGetResponse( return evidence; } + /** + * Validates the complete owner response as one atomic descriptor and attestation pair. The + * request is the exact immutable read selector; neither component is accepted alone. + */ + public static CompleteLaunchBindingEvidence fromCompleteResponse( + GetLaunchDescriptorRequest request, GetCompleteLaunchBindingResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(request, "GetCompleteLaunchBinding request"); + requireNoUnknownFields(response, "GetCompleteLaunchBinding response"); + if (response.hasError()) { + requireNoUnknownFields(response.getError(), "GetCompleteLaunchBinding error"); + throw new IllegalArgumentException("Game Design rejected the complete launch binding read"); + } + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId(), "read request ID"); + UUID echoedRequestId = + parseCanonicalNonNilUuid(response.getRequestId(), "read request ID echo"); + if (!readRequestId.equals(echoedRequestId)) { + throw new IllegalArgumentException("Complete launch binding read request ID echo changed"); + } + if (!response.hasLaunchDescriptor() || !response.hasReleaseAttestation()) { + throw new IllegalArgumentException( + "Complete launch binding read must return both descriptor and release attestation"); + } + + AuthoredWorldLaunchDescriptorEvidence descriptor = + decodeDescriptor(response.getLaunchDescriptor()); + if (readRequestId.equals(descriptor.authoredWorldSourceOperationId()) + || readRequestId.toString().equals(descriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Complete launch binding read request ID must be distinct from the original request"); + } + if (!descriptor.canonicalTenantId().toString().equals(request.getCanonicalTenantId()) + || !descriptor.worldSlug().equals(request.getWorldSlug()) + || !descriptor.controlPlaneRequestId().equals(request.getControlPlaneRequestId()) + || !descriptor.requestDigest().equals(request.getExpectedRequestDigest()) + || !descriptor.resultDigest().equals(request.getExpectedResultDigest())) { + throw new IllegalArgumentException( + "Complete launch binding does not match the exact read selector"); + } + + AuthoredWorldReleaseAttestationEvidence releaseAttestation = + decodeReleaseAttestation(response.getReleaseAttestation()); + try { + return new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Complete launch binding evidence is invalid", exception); + } + } + + /** Encodes the separate closed release attestation without changing descriptor/v1. */ + public static net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence + toReleaseAttestation(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + evidence.requireValid(); + var builder = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setDescriptorResultDigest(evidence.descriptorResultDigest()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setCanonicalVersionId(evidence.canonicalVersionId().toString()) + .setWorldSlug(evidence.worldSlug()) + .setAuthoredWorldSourceOperationId(evidence.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()) + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setPublishWorkflowId(evidence.publishWorkflowId()) + .setCommitId(evidence.commitId()) + .setManifestHash(evidence.manifestHash()) + .setManifestSchemaVersion(evidence.manifestSchemaVersion()) + .addAllRequiredManifestAssetKeys(evidence.requiredManifestAssetKeys()) + .addAllCommandDefinitions(evidence.commandDefinitions()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setEvidenceDigest(evidence.evidenceDigest()); + for (AuthoredWorldReleaseAttestationEvidence.Participant participant : + evidence.participantDigests()) { + ParticipantDigest.Builder participantBuilder = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigestPresent()) { + participantBuilder.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + } + builder.addParticipantDigests(participantBuilder); + } + for (AuthoredWorldReleaseAttestationEvidence.Artifact artifact : evidence.artifactDigests()) { + builder.addArtifactDigests( + PublishedArtifactDigest.newBuilder() + .setUsageKey(artifact.usageKey()) + .setArtifactKind(artifact.artifactKind()) + .setImmutableObjectKey(artifact.immutableObjectKey()) + .setContentDigest(artifact.contentDigest()) + .setContentType(artifact.contentType()) + .setArtifactSchemaVersion(artifact.artifactSchemaVersion())); + } + return builder.build(); + } + private static AuthoredWorldLaunchDescriptorEvidence decodeDescriptor( AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, LaunchDescriptor descriptor) { + AuthoredWorldLaunchDescriptorEvidence evidence = decodeDescriptor(descriptor); + if (!evidence.request().equals(expectedRequest)) { + throw new IllegalArgumentException( + "Launch descriptor does not match the exact authored-world resolve request"); + } + return evidence; + } + + private static AuthoredWorldLaunchDescriptorEvidence decodeDescriptor( + LaunchDescriptor descriptor) { requireNoUnknownFields(descriptor, "LaunchDescriptor"); if (!descriptor.hasAuthoredWorldBinding()) { throw new IllegalArgumentException("Launch descriptor has no authored-world binding"); @@ -176,10 +293,6 @@ private static AuthoredWorldLaunchDescriptorEvidence decodeDescriptor( throw new IllegalArgumentException("Authored-world launch evidence is invalid", exception); } - if (!evidence.request().equals(expectedRequest)) { - throw new IllegalArgumentException( - "Launch descriptor does not match the exact authored-world resolve request"); - } requireFlatDuplicate( descriptor.getLaunchDescriptorId(), evidence.launchDescriptorId(), "launchDescriptorId"); requireFlatDuplicate( @@ -218,6 +331,67 @@ private static AuthoredWorldLaunchDescriptorEvidence decodeDescriptor( return evidence; } + private static AuthoredWorldReleaseAttestationEvidence decodeReleaseAttestation( + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence wire) { + requireNoUnknownFields(wire, "AuthoredWorldReleaseAttestationEvidence"); + List participants = + new java.util.ArrayList<>(wire.getParticipantDigestsCount()); + for (ParticipantDigest participant : wire.getParticipantDigestsList()) { + requireNoUnknownFields(participant, "ParticipantDigest"); + participants.add( + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.getParticipantKey(), + participant.getScopeValue(), + false, + null, + participant.getAppliedCommitId(), + participant.getContentDigest(), + participant.getDigestSchemaVersion(), + participant.hasAbilitySchemaDigest(), + participant.hasAbilitySchemaDigest() ? participant.getAbilitySchemaDigest() : null)); + } + List artifacts = + new java.util.ArrayList<>(wire.getArtifactDigestsCount()); + for (PublishedArtifactDigest artifact : wire.getArtifactDigestsList()) { + requireNoUnknownFields(artifact, "PublishedArtifactDigest"); + artifacts.add( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + artifact.getUsageKey(), + artifact.getArtifactKind(), + artifact.getImmutableObjectKey(), + artifact.getContentDigest(), + artifact.getContentType(), + artifact.getArtifactSchemaVersion())); + } + try { + return new AuthoredWorldReleaseAttestationEvidence( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + wire.getDescriptorResultDigest(), + parseCanonicalNonNilUuid(wire.getCanonicalTenantId(), "canonical tenant ID"), + parseCanonicalNonNilUuid(wire.getCanonicalVersionId(), "canonical version ID"), + wire.getWorldSlug(), + parseCanonicalNonNilUuid( + wire.getAuthoredWorldSourceOperationId(), "authored-world source operation ID"), + wire.getAuthoredWorldSourceEvidenceDigest(), + wire.getLaunchDescriptorId(), + wire.getPublishedReleaseBundleRef(), + wire.getVersionStateEpoch(), + wire.getPublishWorkflowId(), + wire.getCommitId(), + participants, + wire.getManifestHash(), + wire.getManifestSchemaVersion(), + wire.getRequiredManifestAssetKeysList(), + artifacts, + wire.getCommandDefinitionsList(), + wire.getGenerationConfigRevision(), + wire.getEvidenceDigest()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Release-attestation evidence is invalid", exception); + } + } + private static void requireNoUnknownFields(Message message, String label) { if (!message.getUnknownFields().asMap().isEmpty()) { throw new IllegalArgumentException(label + " contains unsupported fields"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java new file mode 100644 index 0000000000..d8962c24bd --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java @@ -0,0 +1,576 @@ +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.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +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.tenant.AuthoredWorldSourceDigest; + +/** Closed immutable full release-attestation evidence for an authored-world launch. */ +public record AuthoredWorldReleaseAttestationEvidence( + int schemaVersion, + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + String evidenceDigest) { + public static final int SCHEMA_VERSION = 1; + private static final String EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v1"; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern PARTICIPANT_CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final List PARTICIPANT_ORDER = + List.of( + "WORLD_MANAGEMENT", + "ENTITY_MANAGEMENT", + "GAME_LOGIC", + "AUTOMATION_SCRIPTING", + "GAME_DESIGN_CONTROL_PLANE"); + private static final Map SUPPORTED_PARTICIPANT_DIGEST_SCHEMAS = + Map.of( + "WORLD_MANAGEMENT", 2, + "ENTITY_MANAGEMENT", 2, + "GAME_LOGIC", 1, + "AUTOMATION_SCRIPTING", 5, + "GAME_DESIGN_CONTROL_PLANE", 1); + private static final Comparator UNSIGNED_UTF8_ORDER = + AuthoredWorldReleaseAttestationEvidence::compareUnsignedUtf8; + + private record Field(String name, String value) {} + + /** Returns the required full-Version participant owner order. */ + public static List requiredParticipantOrder() { + return PARTICIPANT_ORDER; + } + + /** Returns the one supported digest schema for a required participant owner. */ + public static int supportedParticipantDigestSchema(String participantKey) { + Objects.requireNonNull(participantKey, "participantKey"); + Integer version = SUPPORTED_PARTICIPANT_DIGEST_SCHEMAS.get(participantKey); + if (version == null) { + throw new IllegalArgumentException("Unsupported full-Version participant owner"); + } + return version; + } + + /** One successful, immutable owner digest included in the release attestation. */ + public record Participant( + String participantKey, + String scopeValue, + boolean baseVersionIdPresent, + Long baseVersionId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + boolean abilitySchemaDigestPresent, + String abilitySchemaDigest) { + public Participant { + requireText(participantKey, "participantKey"); + requireText(scopeValue, "scopeValue"); + requireOptional(baseVersionIdPresent, baseVersionId, "baseVersionId"); + if (baseVersionIdPresent) { + requirePositive(baseVersionId, "baseVersionId"); + } + requireText(appliedCommitId, "appliedCommitId"); + requireParticipantContentDigest(contentDigest); + requirePositiveSchema(digestSchemaVersion, "digestSchemaVersion"); + requireOptional(abilitySchemaDigestPresent, abilitySchemaDigest, "abilitySchemaDigest"); + if (abilitySchemaDigestPresent) { + requireDigest(abilitySchemaDigest, "abilitySchemaDigest"); + } + } + } + + /** One content-addressed artifact included in the immutable release manifest. */ + public record Artifact( + String usageKey, + String artifactKind, + String immutableObjectKey, + String contentDigest, + String contentType, + int artifactSchemaVersion) { + public Artifact { + requireText(usageKey, "usageKey"); + requireText(artifactKind, "artifactKind"); + requireText(immutableObjectKey, "immutableObjectKey"); + requireDigest(contentDigest, "contentDigest"); + requireText(contentType, "contentType"); + requireSupportedSchema(artifactSchemaVersion, "artifactSchemaVersion"); + String digestHex = contentDigest.substring("sha256:".length()); + String expectedObjectKey = "artifacts/sha256/" + digestHex; + if (!expectedObjectKey.equals(immutableObjectKey)) { + throw new IllegalArgumentException( + "immutableObjectKey must be the content-addressed key for contentDigest"); + } + } + } + + public AuthoredWorldReleaseAttestationEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); + } + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + requireDigest(descriptorResultDigest, "descriptorResultDigest"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(authoredWorldSourceOperationId, "authoredWorldSourceOperationId"); + requireDigest(authoredWorldSourceEvidenceDigest, "authoredWorldSourceEvidenceDigest"); + requireText(launchDescriptorId, "launchDescriptorId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(commitId, "commitId"); + participantDigests = + List.copyOf(Objects.requireNonNull(participantDigests, "participantDigests")); + validateParticipants(participantDigests, commitId); + requireDigest(manifestHash, "manifestHash"); + requireSupportedSchema(manifestSchemaVersion, "manifestSchemaVersion"); + requiredManifestAssetKeys = + List.copyOf(Objects.requireNonNull(requiredManifestAssetKeys, "requiredManifestAssetKeys")); + validateOrderedUniqueStrings(requiredManifestAssetKeys, "requiredManifestAssetKeys"); + artifactDigests = List.copyOf(Objects.requireNonNull(artifactDigests, "artifactDigests")); + validateArtifacts(artifactDigests, requiredManifestAssetKeys); + commandDefinitions = + List.copyOf(Objects.requireNonNull(commandDefinitions, "commandDefinitions")); + for (String commandDefinition : commandDefinitions) { + strictUtf8(Objects.requireNonNull(commandDefinition, "commandDefinition")); + } + requireText(generationConfigRevision, "generationConfigRevision"); + requireDigest(evidenceDigest, "evidenceDigest"); + } + + /** Creates evidence from the complete owner attestation and derives its evidence digest. */ + public static AuthoredWorldReleaseAttestationEvidence create( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision) { + AuthoredWorldReleaseAttestationEvidence provisional = + new AuthoredWorldReleaseAttestationEvidence( + SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + "sha256:" + "0".repeat(64)); + AuthoredWorldReleaseAttestationEvidence evidence = + new AuthoredWorldReleaseAttestationEvidence( + provisional.schemaVersion(), + provisional.targetNamespace(), + provisional.descriptorResultDigest(), + provisional.canonicalTenantId(), + provisional.canonicalVersionId(), + provisional.worldSlug(), + provisional.authoredWorldSourceOperationId(), + provisional.authoredWorldSourceEvidenceDigest(), + provisional.launchDescriptorId(), + provisional.publishedReleaseBundleRef(), + provisional.versionStateEpoch(), + provisional.publishWorkflowId(), + provisional.commitId(), + provisional.participantDigests(), + provisional.manifestHash(), + provisional.manifestSchemaVersion(), + provisional.requiredManifestAssetKeys(), + provisional.artifactDigests(), + provisional.commandDefinitions(), + provisional.generationConfigRevision(), + computeEvidenceDigest(provisional)); + evidence.requireValid(); + return evidence; + } + + /** Recomputes the closed evidence digest after construction or deserialization. */ + public void requireValid() { + if (!computeEvidenceDigest(this).equals(evidenceDigest)) { + throw new IllegalArgumentException( + "Evidence digest does not match the exact release attestation"); + } + } + + /** Recomputes both closed digests and binds every applicable descriptor field exactly. */ + public void requireValid(AuthoredWorldLaunchDescriptorEvidence descriptor) { + Objects.requireNonNull(descriptor, "descriptor"); + requireValid(); + descriptor.requireValid(); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !descriptorResultDigest.equals(descriptor.resultDigest()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !authoredWorldSourceOperationId.equals(descriptor.authoredWorldSourceOperationId()) + || !authoredWorldSourceEvidenceDigest.equals(descriptor.authoredWorldSourceEvidenceDigest()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId()) + || !publishedReleaseBundleRef.equals(descriptor.publishedReleaseBundleRef()) + || versionStateEpoch != descriptor.versionStateEpoch() + || !generationConfigRevision.equals(descriptor.generationConfigRevision())) { + throw new IllegalArgumentException( + "Release attestation does not match the exact launch descriptor binding"); + } + String descriptorVersionScope = Long.toString(descriptor.versionId()); + for (Participant participant : participantDigests) { + if (!descriptorVersionScope.equals(participant.scopeValue())) { + throw new IllegalArgumentException( + "Participant scope does not match the launch descriptor Version"); + } + } + } + + /** Computes the digest using the fixed v1 domain and exhaustive field order. */ + public static String computeEvidenceDigest(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return "sha256:" + HexFormat.of().formatHex(sha256(evidencePreimage(evidence))); + } + + /** Returns the exact strict-UTF-8 preimage for cross-language codec proof. */ + public static byte[] evidencePreimage(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + List fields = new ArrayList<>(); + fields.add(field("schemaVersion", Integer.toString(evidence.schemaVersion()))); + fields.add(field("targetNamespace", evidence.targetNamespace())); + fields.add(field("descriptorResultDigest", evidence.descriptorResultDigest())); + fields.add(field("canonicalTenantId", evidence.canonicalTenantId().toString())); + fields.add(field("canonicalVersionId", evidence.canonicalVersionId().toString())); + fields.add(field("worldSlug", evidence.worldSlug())); + fields.add( + field( + "authoredWorldSourceOperationId", + evidence.authoredWorldSourceOperationId().toString())); + fields.add( + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest())); + fields.add(field("launchDescriptorId", evidence.launchDescriptorId())); + fields.add(field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef())); + fields.add(field("versionStateEpoch", Long.toString(evidence.versionStateEpoch()))); + fields.add(field("publishWorkflowId", evidence.publishWorkflowId())); + fields.add(field("commitId", evidence.commitId())); + fields.add( + field("participantDigests.size", Integer.toString(evidence.participantDigests().size()))); + for (int index = 0; index < evidence.participantDigests().size(); index++) { + Participant participant = evidence.participantDigests().get(index); + String prefix = "participantDigests[" + index + "]."; + fields.add(field(prefix + "participantKey", participant.participantKey())); + fields.add(field(prefix + "scopeValue", participant.scopeValue())); + fields.add(optionalPresence(prefix + "baseVersionId", participant.baseVersionIdPresent())); + fields.add( + optionalValue( + prefix + "baseVersionId", + participant.baseVersionIdPresent(), + decimal(participant.baseVersionId()))); + fields.add(field(prefix + "appliedCommitId", participant.appliedCommitId())); + fields.add(field(prefix + "contentDigest", participant.contentDigest())); + fields.add( + field( + prefix + "digestSchemaVersion", Integer.toString(participant.digestSchemaVersion()))); + fields.add( + optionalPresence( + prefix + "abilitySchemaDigest", participant.abilitySchemaDigestPresent())); + fields.add( + optionalValue( + prefix + "abilitySchemaDigest", + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())); + } + fields.add(field("manifestHash", evidence.manifestHash())); + fields.add(field("manifestSchemaVersion", Integer.toString(evidence.manifestSchemaVersion()))); + fields.add( + field( + "requiredManifestAssetKeys.size", + Integer.toString(evidence.requiredManifestAssetKeys().size()))); + for (int index = 0; index < evidence.requiredManifestAssetKeys().size(); index++) { + fields.add( + field( + "requiredManifestAssetKeys[" + index + "]", + evidence.requiredManifestAssetKeys().get(index))); + } + fields.add(field("artifactDigests.size", Integer.toString(evidence.artifactDigests().size()))); + for (int index = 0; index < evidence.artifactDigests().size(); index++) { + Artifact artifact = evidence.artifactDigests().get(index); + String prefix = "artifactDigests[" + index + "]."; + fields.add(field(prefix + "usageKey", artifact.usageKey())); + fields.add(field(prefix + "artifactKind", artifact.artifactKind())); + fields.add(field(prefix + "immutableObjectKey", artifact.immutableObjectKey())); + fields.add(field(prefix + "contentDigest", artifact.contentDigest())); + fields.add(field(prefix + "contentType", artifact.contentType())); + fields.add( + field( + prefix + "artifactSchemaVersion", + Integer.toString(artifact.artifactSchemaVersion()))); + } + fields.add( + field("commandDefinitions.size", Integer.toString(evidence.commandDefinitions().size()))); + for (int index = 0; index < evidence.commandDefinitions().size(); index++) { + fields.add( + field("commandDefinitions[" + index + "]", evidence.commandDefinitions().get(index))); + } + fields.add(field("generationConfigRevision", evidence.generationConfigRevision())); + return preimage(EVIDENCE_DOMAIN, fields.toArray(Field[]::new)); + } + + private static void validateParticipants(List participants, String commitId) { + if (participants.size() != PARTICIPANT_ORDER.size()) { + throw new IllegalArgumentException( + "A complete attestation requires exactly five participants"); + } + for (int index = 0; index < PARTICIPANT_ORDER.size(); index++) { + Participant participant = + Objects.requireNonNull(participants.get(index), "participantDigest"); + String expectedKey = PARTICIPANT_ORDER.get(index); + if (!expectedKey.equals(participant.participantKey())) { + throw new IllegalArgumentException("Participant digests are not in canonical owner order"); + } + if (supportedParticipantDigestSchema(participant.participantKey()) + != participant.digestSchemaVersion()) { + throw new IllegalArgumentException( + "Participant digest schema is unsupported for its owner"); + } + if (participant.baseVersionIdPresent()) { + throw new IllegalArgumentException( + "Full-Version participants must not have a baseVersionId"); + } + if (participant.scopeValue() == null + || !CANONICAL_POSITIVE_DECIMAL.matcher(participant.scopeValue()).matches()) { + throw new IllegalArgumentException( + "Full-Version participant scope must be a positive decimal Version"); + } + try { + if (Long.parseLong(participant.scopeValue()) <= 0) { + throw new IllegalArgumentException("Participant scope must be positive"); + } + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Participant scope must fit a positive Version id", exception); + } + if (!commitId.equals(participant.appliedCommitId())) { + throw new IllegalArgumentException("Every participant must report the attested commitId"); + } + boolean requiresAbilityDigest = "GAME_LOGIC".equals(participant.participantKey()); + if (participant.abilitySchemaDigestPresent() != requiresAbilityDigest) { + throw new IllegalArgumentException( + "Only GAME_LOGIC may supply the dedicated ability-schema digest"); + } + } + } + + private static void validateOrderedUniqueStrings(List values, String name) { + String previous = null; + for (String value : values) { + Objects.requireNonNull(value, name + " entry"); + requireText(value, name + " entry"); + if (previous != null && UNSIGNED_UTF8_ORDER.compare(previous, value) >= 0) { + throw new IllegalArgumentException(name + " must be unique and unsigned-UTF-8 ordered"); + } + previous = value; + } + } + + private static void validateArtifacts(List artifacts, List requiredKeys) { + String previous = null; + Map byUsageKey = new java.util.HashMap<>(); + for (Artifact artifact : artifacts) { + Objects.requireNonNull(artifact, "artifactDigest"); + if (previous != null && UNSIGNED_UTF8_ORDER.compare(previous, artifact.usageKey()) >= 0) { + throw new IllegalArgumentException( + "artifactDigests must be unique and unsigned-UTF-8 ordered"); + } + previous = artifact.usageKey(); + byUsageKey.put(artifact.usageKey(), artifact); + } + for (String requiredKey : requiredKeys) { + if (!byUsageKey.containsKey(requiredKey)) { + throw new IllegalArgumentException("Every required manifest key must select an artifact"); + } + } + } + + private static Field optionalPresence(String name, boolean present) { + return field(name + ".present", Boolean.toString(present)); + } + + private static Field optionalValue(String name, boolean present, String value) { + return field(name + ".value", present ? Objects.requireNonNull(value, name) : ""); + } + + private static Field field(String name, String value) { + return new Field(name, value); + } + + private static byte[] preimage(String domain, Field... fields) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + writeSegment(bytes, domain); + for (Field field : fields) { + writeSegment(bytes, field.name()); + writeSegment(bytes, field.value()); + } + return bytes.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] result = new byte[encoded.remaining()]; + encoded.get(result); + return result; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must contain valid Unicode", exception); + } + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static int compareUnsignedUtf8(String left, String right) { + byte[] leftBytes = strictUtf8(left); + byte[] rightBytes = strictUtf8(right); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int difference = Byte.toUnsignedInt(leftBytes[index]) - Byte.toUnsignedInt(rightBytes[index]); + if (difference != 0) { + return difference; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + private static void requirePositive(Long value, String name) { + if (value == null || value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireSupportedSchema(int value, String name) { + if (value != SCHEMA_VERSION) { + throw new IllegalArgumentException(name + " is unsupported"); + } + } + + private static void requirePositiveSchema(int value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + strictUtf8(value); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireParticipantContentDigest(String value) { + Objects.requireNonNull(value, "contentDigest"); + if (!PARTICIPANT_CONTENT_DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException( + "Participant contentDigest must be 64 lowercase hexadecimal characters"); + } + } +} 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 index f7b5632fc4..ec95c8bd6a 100644 --- 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 @@ -20,6 +20,7 @@ public record AuthoredWorldVersionStateEvidence( Request request, AuthoredWorldSourceEvidence sourceEvidence, + UUID canonicalVersionId, VersionLifecycleState versionState, long versionStateEpoch, String evidenceDigest) { @@ -65,6 +66,7 @@ public record Request( public AuthoredWorldVersionStateEvidence { Objects.requireNonNull(request, "request"); Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + requireCanonicalVersionId(canonicalVersionId); requireLifecycleState(versionState); if (versionStateEpoch <= 0) { throw new IllegalArgumentException("versionStateEpoch must be positive"); @@ -84,7 +86,8 @@ public record 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))) { + if (!evidenceDigest.equals( + evidenceDigest(request, canonicalVersionId, versionState, versionStateEpoch))) { throw new IllegalArgumentException( "Version-state evidence digest does not match the exact current-state tuple"); } @@ -93,39 +96,51 @@ public record Request( public static AuthoredWorldVersionStateEvidence create( Request request, AuthoredWorldSourceEvidence sourceEvidence, + UUID canonicalVersionId, VersionLifecycleState versionState, long versionStateEpoch) { Objects.requireNonNull(request, "request"); + requireCanonicalVersionId(canonicalVersionId); requireLifecycleState(versionState); return new AuthoredWorldVersionStateEvidence( request, sourceEvidence, + canonicalVersionId, versionState, versionStateEpoch, - evidenceDigest(request, versionState, versionStateEpoch)); + evidenceDigest(request, canonicalVersionId, versionState, versionStateEpoch)); } /** Recomputes the complete outer binding after construction or wire decoding. */ public void requireValid() { - if (!evidenceDigest.equals(evidenceDigest(request, versionState, versionStateEpoch))) { + if (!evidenceDigest.equals( + evidenceDigest(request, canonicalVersionId, versionState, versionStateEpoch))) { throw new IllegalArgumentException("Version-state evidence digest is invalid"); } } public static String evidenceDigest( - Request request, VersionLifecycleState versionState, long versionStateEpoch) { + Request request, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { Objects.requireNonNull(request, "request"); + requireCanonicalVersionId(canonicalVersionId); requireLifecycleState(versionState); if (versionStateEpoch <= 0) { throw new IllegalArgumentException("versionStateEpoch must be positive"); } - return sha256(evidencePreimage(request, versionState, versionStateEpoch)); + return sha256(evidencePreimage(request, canonicalVersionId, 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) { + Request request, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { Objects.requireNonNull(request, "request"); + requireCanonicalVersionId(canonicalVersionId); requireLifecycleState(versionState); if (versionStateEpoch <= 0) { throw new IllegalArgumentException("versionStateEpoch must be positive"); @@ -140,6 +155,7 @@ public static byte[] evidencePreimage( request.sourceOperationId().toString(), request.expectedSourceEvidenceDigest(), Long.toString(request.versionId()), + canonicalVersionId.toString(), lifecycleStateName(versionState), Long.toString(versionStateEpoch)); } @@ -192,4 +208,11 @@ private static void requireLifecycleState(VersionLifecycleState value) { throw new IllegalArgumentException("A recognized version lifecycle state is required"); } } + + private static void requireCanonicalVersionId(UUID value) { + Objects.requireNonNull(value, "canonicalVersionId"); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException("canonicalVersionId must be a non-nil UUID"); + } + } } 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 index 489cb77e44..21ca27f45e 100644 --- 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 @@ -86,6 +86,7 @@ public static GetAuthoredWorldVersionStateResponse toResponse( .setSourceOperationId(request.sourceOperationId().toString()) .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) .setVersionId(request.versionId()) + .setCanonicalVersionId(evidence.canonicalVersionId().toString()) .setSourceEvidence(sourceReceipt) .setVersionState(evidence.versionState()) .setVersionStateEpoch(evidence.versionStateEpoch()) @@ -154,6 +155,7 @@ public static GetAuthoredWorldVersionStateResponse toResponse( new net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence( echoedRequest, sourceEvidence, + parseCanonicalNonNilUuid(wireEvidence.getCanonicalVersionId(), "canonicalVersionId"), versionState, wireEvidence.getVersionStateEpoch(), wireEvidence.getEvidenceDigest()); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java new file mode 100644 index 0000000000..8b6089e638 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.util.Objects; + +/** The exact independently validated descriptor and release-attestation pair for a launch. */ +public record CompleteLaunchBindingEvidence( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation) { + public CompleteLaunchBindingEvidence { + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(releaseAttestation, "releaseAttestation"); + releaseAttestation.requireValid(descriptor); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java index 42df73d19a..3c39fbde18 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -68,6 +69,15 @@ void deniesResolveAndReadUntilExplicitInitializationAndAfterClose(@TempDir Path var getRequest = new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( READ_REQUEST_ID, request, "sha256:" + "b".repeat(64)); + var completeRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug("copper-coast") + .setControlPlaneRequestId("launch-operation-7") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .build(); assertThatThrownBy(() -> client.resolve(request)) .isInstanceOf(IllegalStateException.class) @@ -75,6 +85,9 @@ void deniesResolveAndReadUntilExplicitInitializationAndAfterClose(@TempDir Path assertThatThrownBy(() -> client.get(getRequest)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.getComplete(completeRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); verifyNoInteractions(channelFactory); client.close(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java index 0282115626..af709487e8 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java @@ -4,10 +4,14 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.UnknownFieldSet; +import java.util.List; import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; class AuthoredWorldLaunchDescriptorGrpcCodecTest { @@ -18,6 +22,7 @@ class AuthoredWorldLaunchDescriptorGrpcCodecTest { UUID.fromString("32345678-1234-4234-8234-123456789abc"); private static final UUID WRONG_READ_REQUEST_ID = UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final UUID VERSION_UUID = UUID.fromString("52345678-1234-4234-8234-123456789abc"); @Test void resolvesAndReadsBackSharedDigestVectorWithExactOptionalPresence() { @@ -260,6 +265,153 @@ SOURCE_OPERATION_ID, request, evidence(request).resultDigest())) .hasMessageContaining("distinct"); } + @Test + void completeReadRoundTripsTheAtomicPairAndPreservesOptionalAbilityDigestPresence() { + var descriptor = evidence(request("test", "copper-coast", false)); + var release = releaseAttestation(descriptor); + var request = completeRequest(descriptor); + var response = completeResponse(request, descriptor, release); + + CompleteLaunchBindingEvidence pair = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response); + var encoded = + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(pair.releaseAttestation()); + + assertThat(pair.descriptor()).isEqualTo(descriptor); + assertThat(pair.releaseAttestation()).isEqualTo(release); + assertThat(encoded.getParticipantDigests(0).hasAbilitySchemaDigest()).isFalse(); + assertThat(encoded.getParticipantDigests(2).hasAbilitySchemaDigest()).isTrue(); + assertThat(encoded.getParticipantDigests(2).getAbilitySchemaDigest()) + .isEqualTo("sha256:" + "f".repeat(64)); + assertThat(encoded.getArtifactDigests(0).getImmutableObjectKey()) + .isEqualTo(release.artifactDigests().get(0).immutableObjectKey()); + } + + @Test + void completeReadRejectsMissingConflictingAndUnknownEvidenceAtEveryMessageLevel() { + var descriptor = evidence(request("test", "copper-coast", false)); + var release = releaseAttestation(descriptor); + var request = completeRequest(descriptor); + var good = completeResponse(request, descriptor, release); + var unknown = unknownFields(); + + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder().setRequestId(WRONG_READ_REQUEST_ID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("echo changed"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request.toBuilder().setWorldSlug("copper-shore").build(), good)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact read selector"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, good.toBuilder().clearReleaseAttestation().build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("both descriptor and release attestation"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, good.toBuilder().clearLaunchDescriptor().build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("both descriptor and release attestation"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder().setError(ErrorDetail.newBuilder().setCode("DENIED")).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("rejected"); + + assertCompleteUnknownRejected(request.toBuilder().setUnknownFields(unknown).build(), good); + assertCompleteUnknownRejected(request, good.toBuilder().setUnknownFields(unknown).build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setLaunchDescriptor(descriptor(descriptor).toBuilder().setUnknownFields(unknown)) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setLaunchDescriptor( + descriptor(descriptor).toBuilder() + .setAuthoredWorldBinding( + descriptor(descriptor).getAuthoredWorldBinding().toBuilder() + .setUnknownFields(unknown))) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder().setUnknownFields(unknown)) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setParticipantDigests( + 0, + good.getReleaseAttestation().getParticipantDigests(0).toBuilder() + .setUnknownFields(unknown))) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setArtifactDigests( + 0, + good.getReleaseAttestation().getArtifactDigests(0).toBuilder() + .setUnknownFields(unknown))) + .build()); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setError( + ErrorDetail.newBuilder().setUnknownFields(unknown).setCode("DENIED")) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setEvidenceDigest("sha256:" + "0".repeat(64))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setParticipantDigests( + 0, + good + .getReleaseAttestation() + .getParticipantDigests(0) + .toBuilder() + .setDigestSchemaVersion(999))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Release-attestation evidence is invalid") + .hasRootCauseMessage("Participant digest schema is unsupported for its owner"); + } + private static void assertFlatDuplicateRejected(LaunchDescriptor descriptor) { var expected = request("test", "copper-coast", false); assertThatThrownBy( @@ -273,6 +425,88 @@ private static void assertFlatDuplicateRejected(LaunchDescriptor descriptor) { .hasMessageContaining("does not match evidence"); } + private static void assertCompleteUnknownRejected( + GetLaunchDescriptorRequest request, GetCompleteLaunchBindingResponse response) { + assertThatThrownBy( + () -> AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + private static GetLaunchDescriptorRequest completeRequest( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + } + + private static GetCompleteLaunchBindingResponse completeResponse( + GetLaunchDescriptorRequest request, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence release) { + return GetCompleteLaunchBindingResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setLaunchDescriptor(descriptor(descriptor)) + .setReleaseAttestation(AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(release)) + .build(); + } + + private static AuthoredWorldReleaseAttestationEvidence releaseAttestation( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + String commitId = "commit-雪"; + List participants = + new java.util.ArrayList<>(); + int index = 0; + for (String key : AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()) { + boolean ability = "GAME_LOGIC".equals(key); + participants.add( + new AuthoredWorldReleaseAttestationEvidence.Participant( + key, + Long.toString(descriptor.versionId()), + false, + null, + commitId, + String.valueOf((char) ('a' + index++)).repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(key), + ability, + ability ? "sha256:" + "f".repeat(64) : null)); + } + String artifactDigest = "sha256:" + "e".repeat(64); + var artifact = + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "world/雪", + "WORLD_CONTENT", + "artifacts/sha256/" + "e".repeat(64), + artifactDigest, + "application/octet-stream", + 1); + return AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + VERSION_UUID, + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant-key:private-workflow:雪", + commitId, + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(artifact.usageKey()), + List.of(artifact), + List.of("say 雪"), + descriptor.generationConfigRevision()); + } + private static AuthoredWorldLaunchDescriptorEvidence.Request request( String namespace, String worldSlug, boolean runtimeFlagsPresent) { return new AuthoredWorldLaunchDescriptorEvidence.Request( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidenceTest.java new file mode 100644 index 0000000000..20d7d75f37 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidenceTest.java @@ -0,0 +1,1061 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AuthoredWorldReleaseAttestationEvidenceTest { + private static final String TENANT = "12345678-1234-4234-8234-123456789abc"; + private static final String VERSION = "32345678-1234-4234-8234-123456789abc"; + private static final String SOURCE_OPERATION = "22345678-1234-4234-8234-123456789abc"; + private static final String SOURCE_DIGEST = digest("a"); + private static final String GENERATION_REVISION = "gen-rév-🧭"; + private static final long MAX_EPOCH = Long.MAX_VALUE; + private static final String EXPECTED_DESCRIPTOR_RESULT_DIGEST = + "sha256:7129db5acb9aa27830598cdcfe4996f2f2259cfbe1f6dc137db5d39ec8ebc80c"; + private static final String EXPECTED_EVIDENCE_DIGEST = + "sha256:c1a8d369e3012ced0247b6de05a152fc0434b565db611acc9095447184cbe42f"; + + @Test + void fullEvidenceMatchesIndependentUnicodeFramingVectorAndExactDescriptor() { + Fixture fixture = fixture(); + String preimage = + text(AuthoredWorldReleaseAttestationEvidence.evidencePreimage(fixture.evidence())); + + assertEquals(EXPECTED_DESCRIPTOR_RESULT_DIGEST, fixture.descriptor().resultDigest()); + assertEquals(EXPECTED_EVIDENCE_DIGEST, fixture.evidence().evidenceDigest()); + assertEquals( + EXPECTED_EVIDENCE_DIGEST, + AuthoredWorldReleaseAttestationEvidence.computeEvidenceDigest(fixture.evidence())); + assertTrue(preimage.startsWith("49:game-design-authored-world-release-attestation/v1")); + assertTrue(preimage.contains("18:launchDescriptorId5:ld-é")); + assertTrue(preimage.contains("25:publishedReleaseBundleRef18:release-bundle:雪")); + assertTrue(preimage.contains("10:commit-雪")); + assertTrue(preimage.contains("13:gen-rév-🧭")); + assertTrue(preimage.contains("43:participantDigests[0].baseVersionId.present5:false")); + assertTrue(preimage.contains("49:participantDigests[2].abilitySchemaDigest.present4:true")); + assertTrue(preimage.contains("37:artifactDigests[0].immutableObjectKey81:artifacts/sha256/")); + assertEquals(MAX_EPOCH, fixture.evidence().versionStateEpoch()); + assertEquals( + List.of( + "WORLD_MANAGEMENT", + "ENTITY_MANAGEMENT", + "GAME_LOGIC", + "AUTOMATION_SCRIPTING", + "GAME_DESIGN_CONTROL_PLANE"), + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()); + assertEquals( + List.of(2, 2, 1, 5, 1), + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map(AuthoredWorldReleaseAttestationEvidence::supportedParticipantDigestSchema) + .toList()); + assertThrows( + IllegalArgumentException.class, + () -> + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + "UNSUPPORTED")); + assertDoesNotThrow(() -> fixture.evidence().requireValid(fixture.descriptor())); + assertThrows( + UnsupportedOperationException.class, + () -> + fixture + .evidence() + .participantDigests() + .add(fixture.evidence().participantDigests().get(0))); + assertThrows( + UnsupportedOperationException.class, + () -> + fixture.evidence().artifactDigests().add(fixture.evidence().artifactDigests().get(0))); + } + + @Test + void changedFieldsAndRetainedArrayOrderChangeTheDigest() { + Fixture fixture = fixture(); + AuthoredWorldReleaseAttestationEvidence changedGeneration = + evidence( + fixture.descriptor(), + MAX_EPOCH, + fixture.evidence().participantDigests(), + fixture.evidence().requiredManifestAssetKeys(), + fixture.evidence().artifactDigests(), + fixture.evidence().commandDefinitions(), + "gen-rév-🧭-next"); + AuthoredWorldReleaseAttestationEvidence changedCommandOrder = + evidence( + fixture.descriptor(), + MAX_EPOCH, + fixture.evidence().participantDigests(), + fixture.evidence().requiredManifestAssetKeys(), + fixture.evidence().artifactDigests(), + List.of("say 雪", "LOOK"), + GENERATION_REVISION); + AuthoredWorldReleaseAttestationEvidence changedEpoch = + evidence( + fixture.descriptor(), + MAX_EPOCH - 1, + fixture.evidence().participantDigests(), + fixture.evidence().requiredManifestAssetKeys(), + fixture.evidence().artifactDigests(), + fixture.evidence().commandDefinitions(), + GENERATION_REVISION); + + assertNotEquals(fixture.evidence().evidenceDigest(), changedGeneration.evidenceDigest()); + assertNotEquals(fixture.evidence().evidenceDigest(), changedCommandOrder.evidenceDigest()); + assertNotEquals(fixture.evidence().evidenceDigest(), changedEpoch.evidenceDigest()); + assertThrows( + IllegalArgumentException.class, () -> changedGeneration.requireValid(fixture.descriptor())); + assertThrows( + IllegalArgumentException.class, () -> changedEpoch.requireValid(fixture.descriptor())); + + AuthoredWorldReleaseAttestationEvidence tampered = + rawCopy( + fixture.evidence(), + fixture.evidence().evidenceDigest(), + List.of("changed command", "LOOK")); + assertThrows(IllegalArgumentException.class, tampered::requireValid); + } + + @Test + void fullVersionParticipantSetIsExactOrderedAndBoundToTheDescriptorVersion() { + Fixture fixture = fixture(); + List participants = + fixture.evidence().participantDigests(); + + assertThrows( + IllegalArgumentException.class, + () -> + evidence( + fixture.descriptor(), + MAX_EPOCH, + participants.subList(0, 4), + keys(), + artifacts(), + commands(), + GENERATION_REVISION)); + + List wrongOwner = + new ArrayList<>(participants); + wrongOwner.set( + 0, + participant("ENTITY_MANAGEMENT", "42", false, null, "commit-雪", digest("a"), false, null)); + assertThrows( + IllegalArgumentException.class, + () -> + evidence( + fixture.descriptor(), + MAX_EPOCH, + wrongOwner, + keys(), + artifacts(), + commands(), + GENERATION_REVISION)); + + List duplicateOwner = + new ArrayList<>(participants); + duplicateOwner.set( + 4, + participant( + "AUTOMATION_SCRIPTING", "42", false, null, "commit-雪", digest("e"), false, null)); + assertThrows( + IllegalArgumentException.class, + () -> + evidence( + fixture.descriptor(), + MAX_EPOCH, + duplicateOwner, + keys(), + artifacts(), + commands(), + GENERATION_REVISION)); + + List wrongScope = + participantsWithScope("43"); + AuthoredWorldReleaseAttestationEvidence wrongScopeEvidence = + evidence( + fixture.descriptor(), + MAX_EPOCH, + wrongScope, + keys(), + artifacts(), + commands(), + GENERATION_REVISION); + assertThrows( + IllegalArgumentException.class, + () -> wrongScopeEvidence.requireValid(fixture.descriptor())); + + AuthoredWorldLaunchDescriptorEvidence version43 = + descriptor( + "test", + "cp-α", + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + 43L, + MAX_EPOCH, + GENERATION_REVISION, + "{}"); + AuthoredWorldReleaseAttestationEvidence version43WrongScope = + AuthoredWorldReleaseAttestationEvidence.create( + "test", + version43.resultDigest(), + uuid(TENANT), + uuid(VERSION), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + "publish:tenant-key:publish-request:pr-é", + "commit-雪", + participants, + digest("9"), + 1, + keys(), + artifacts(), + commands(), + GENERATION_REVISION); + assertThrows(IllegalArgumentException.class, () -> version43WrongScope.requireValid(version43)); + } + + @Test + void participantScopeBaseCommitSchemaAndAbilityEvidenceFailClosed() { + Fixture fixture = fixture(); + List participants = + fixture.evidence().participantDigests(); + + List wrongBase = + new ArrayList<>(participants); + wrongBase.set( + 0, participant("WORLD_MANAGEMENT", "42", true, 7L, "commit-雪", digest("a"), false, null)); + assertThrows( + IllegalArgumentException.class, + () -> + evidence( + fixture.descriptor(), + MAX_EPOCH, + wrongBase, + keys(), + artifacts(), + commands(), + GENERATION_REVISION)); + + List wrongCommit = + participantsWithCommit("other-commit"); + assertThrows( + IllegalArgumentException.class, + () -> + evidence( + fixture.descriptor(), + MAX_EPOCH, + wrongCommit, + keys(), + artifacts(), + commands(), + GENERATION_REVISION)); + + assertThrows( + IllegalArgumentException.class, + () -> + participant( + "WORLD_MANAGEMENT", "42", false, null, "commit-雪", digest("a"), false, null, 0)); + + List wrongSchema = + new ArrayList<>(participants); + wrongSchema.set( + 0, + participant( + "WORLD_MANAGEMENT", "42", false, null, "commit-雪", digest("a"), false, null, 1)); + assertThrows( + IllegalArgumentException.class, + () -> + evidence( + fixture.descriptor(), + MAX_EPOCH, + wrongSchema, + keys(), + artifacts(), + commands(), + GENERATION_REVISION)); + + List missingAbility = + new ArrayList<>(participants); + missingAbility.set( + 2, participant("GAME_LOGIC", "42", false, null, "commit-雪", digest("c"), false, null)); + assertThrows( + IllegalArgumentException.class, + () -> + evidence( + fixture.descriptor(), + MAX_EPOCH, + missingAbility, + keys(), + artifacts(), + commands(), + GENERATION_REVISION)); + + List wrongAbilityOwner = + new ArrayList<>(participants); + wrongAbilityOwner.set( + 0, + participant( + "WORLD_MANAGEMENT", "42", false, null, "commit-雪", digest("a"), true, digest("f"))); + assertThrows( + IllegalArgumentException.class, + () -> + evidence( + fixture.descriptor(), + MAX_EPOCH, + wrongAbilityOwner, + keys(), + artifacts(), + commands(), + GENERATION_REVISION)); + + assertThrows( + IllegalArgumentException.class, + () -> + participant( + "GAME_LOGIC", "42", false, null, "commit-雪", digest("c"), true, "not-a-digest")); + } + + @Test + void participantContentDigestUsesRawLowercaseHexWhileOtherDigestFieldsStayPrefixed() { + assertDoesNotThrow( + () -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + "WORLD_MANAGEMENT", "42", false, null, "commit-雪", "a".repeat(64), 2, false, null)); + assertThrows( + IllegalArgumentException.class, + () -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + "WORLD_MANAGEMENT", "42", false, null, "commit-雪", digest("a"), 2, false, null)); + assertDoesNotThrow( + () -> + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "world.navmesh", + "NAVMESH", + artifactKey("3"), + digest("3"), + "application/vnd.firemud.navmesh+binary", + 1)); + } + + @Test + void artifactsMustMatchContentAddressAndRequiredKeysAndManifestMustBePresent() { + Fixture fixture = fixture(); + + assertThrows( + IllegalArgumentException.class, + () -> + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "world.navmesh", + "NAVMESH", + artifactKey("4"), + digest("3"), + "application/vnd.firemud.navmesh+binary", + 1)); + assertThrows( + IllegalArgumentException.class, + () -> + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "world.navmesh", + "NAVMESH", + artifactKey("3"), + digest("3"), + "application/vnd.firemud.navmesh+binary", + 2)); + assertThrows( + IllegalArgumentException.class, + () -> + AuthoredWorldReleaseAttestationEvidence.create( + "test", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + uuid(VERSION), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + "publish:tenant-key:publish-request:pr-é", + "commit-雪", + fixture.evidence().participantDigests(), + digest("9"), + 1, + List.of("world.missing"), + artifacts(), + commands(), + GENERATION_REVISION)); + assertThrows( + NullPointerException.class, + () -> + AuthoredWorldReleaseAttestationEvidence.create( + "test", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + uuid(VERSION), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + "publish:tenant-key:publish-request:pr-é", + "commit-雪", + fixture.evidence().participantDigests(), + null, + 1, + keys(), + artifacts(), + commands(), + GENERATION_REVISION)); + assertThrows( + IllegalArgumentException.class, + () -> + AuthoredWorldReleaseAttestationEvidence.create( + "test", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + uuid(VERSION), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + "publish:tenant-key:publish-request:pr-é", + "commit-雪", + fixture.evidence().participantDigests(), + digest("9"), + 2, + keys(), + artifacts(), + commands(), + GENERATION_REVISION)); + + AuthoredWorldReleaseAttestationEvidence emptyManifest = + AuthoredWorldReleaseAttestationEvidence.create( + "test", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + uuid(VERSION), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + "publish:tenant-key:publish-request:pr-é", + "commit-雪", + fixture.evidence().participantDigests(), + digest("9"), + 1, + List.of(), + List.of(), + commands(), + GENERATION_REVISION); + assertDoesNotThrow(() -> emptyManifest.requireValid(fixture.descriptor())); + } + + @Test + void descriptorSubstitutionsAreRejectedAndRequestIdentityIsBoundByResultDigest() { + Fixture fixture = fixture(); + List substitutions = + List.of( + descriptor( + "other", + "cp-α", + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + 42L, + MAX_EPOCH, + GENERATION_REVISION, + "{}"), + descriptor( + "test", + "cp-other", + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + 42L, + MAX_EPOCH, + GENERATION_REVISION, + "{}"), + descriptor( + "test", + "cp-α", + uuid(TENANT), + "copper-shore", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + 42L, + MAX_EPOCH, + GENERATION_REVISION, + "{}"), + descriptor( + "test", + "cp-α", + uuid("52345678-1234-4234-8234-123456789abc"), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + 42L, + MAX_EPOCH, + GENERATION_REVISION, + "{}"), + descriptor( + "test", + "cp-α", + uuid(TENANT), + "copper-coast", + uuid("62345678-1234-4234-8234-123456789abc"), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + 42L, + MAX_EPOCH, + GENERATION_REVISION, + "{}"), + descriptor( + "test", + "cp-α", + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + digest("b"), + "ld-é", + "release-bundle:雪", + 42L, + MAX_EPOCH, + GENERATION_REVISION, + "{}"), + descriptor( + "test", + "cp-α", + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-other", + "release-bundle:雪", + 42L, + MAX_EPOCH, + GENERATION_REVISION, + "{}"), + descriptor( + "test", + "cp-α", + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:other", + 42L, + MAX_EPOCH, + GENERATION_REVISION, + "{}"), + descriptor( + "test", + "cp-α", + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + 42L, + MAX_EPOCH - 1, + GENERATION_REVISION, + "{}"), + descriptor( + "test", + "cp-α", + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + 42L, + MAX_EPOCH, + "new-generation", + "{}"), + descriptor( + "test", + "cp-α", + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + 42L, + MAX_EPOCH, + GENERATION_REVISION, + "{\"different\":true}")); + + for (AuthoredWorldLaunchDescriptorEvidence substitution : substitutions) { + assertThrows( + IllegalArgumentException.class, () -> fixture.evidence().requireValid(substitution)); + } + + List changedEvidenceBindings = + List.of( + evidenceWithBindings( + fixture, + "other", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + GENERATION_REVISION), + evidenceWithBindings( + fixture, + "test", + digest("8"), + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + GENERATION_REVISION), + evidenceWithBindings( + fixture, + "test", + fixture.evidence().descriptorResultDigest(), + uuid("52345678-1234-4234-8234-123456789abc"), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + GENERATION_REVISION), + evidenceWithBindings( + fixture, + "test", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + "copper-shore", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + GENERATION_REVISION), + evidenceWithBindings( + fixture, + "test", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + "copper-coast", + uuid("62345678-1234-4234-8234-123456789abc"), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + GENERATION_REVISION), + evidenceWithBindings( + fixture, + "test", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + digest("b"), + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + GENERATION_REVISION), + evidenceWithBindings( + fixture, + "test", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-other", + "release-bundle:雪", + MAX_EPOCH, + GENERATION_REVISION), + evidenceWithBindings( + fixture, + "test", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:other", + MAX_EPOCH, + GENERATION_REVISION), + evidenceWithBindings( + fixture, + "test", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH - 1, + GENERATION_REVISION), + evidenceWithBindings( + fixture, + "test", + fixture.evidence().descriptorResultDigest(), + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + MAX_EPOCH, + "new-generation")); + for (AuthoredWorldReleaseAttestationEvidence changed : changedEvidenceBindings) { + assertThrows( + IllegalArgumentException.class, () -> changed.requireValid(fixture.descriptor())); + } + } + + private static Fixture fixture() { + AuthoredWorldLaunchDescriptorEvidence descriptor = + descriptor( + "test", + "cp-α", + uuid(TENANT), + "copper-coast", + uuid(SOURCE_OPERATION), + SOURCE_DIGEST, + "ld-é", + "release-bundle:雪", + 42L, + MAX_EPOCH, + GENERATION_REVISION, + "{}"); + AuthoredWorldReleaseAttestationEvidence evidence = + evidence( + descriptor, + MAX_EPOCH, + participantsWithScope("42"), + keys(), + artifacts(), + commands(), + GENERATION_REVISION); + return new Fixture(evidence, descriptor); + } + + private static AuthoredWorldReleaseAttestationEvidence evidence( + AuthoredWorldLaunchDescriptorEvidence descriptor, + long epoch, + List participants, + List requiredKeys, + List artifacts, + List commandDefinitions, + String generationRevision) { + return evidenceWithBindings( + descriptor, + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + epoch, + generationRevision, + participants, + requiredKeys, + artifacts, + commandDefinitions); + } + + private static AuthoredWorldReleaseAttestationEvidence evidenceWithBindings( + Fixture fixture, + String namespace, + String descriptorResultDigest, + UUID tenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + String launchDescriptorId, + String releaseBundleRef, + long epoch, + String generationRevision) { + return evidenceWithBindings( + fixture.descriptor(), + namespace, + descriptorResultDigest, + tenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + launchDescriptorId, + releaseBundleRef, + epoch, + generationRevision, + fixture.evidence().participantDigests(), + fixture.evidence().requiredManifestAssetKeys(), + fixture.evidence().artifactDigests(), + fixture.evidence().commandDefinitions()); + } + + private static AuthoredWorldReleaseAttestationEvidence evidenceWithBindings( + AuthoredWorldLaunchDescriptorEvidence descriptor, + String namespace, + String descriptorResultDigest, + UUID tenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + String launchDescriptorId, + String releaseBundleRef, + long epoch, + String generationRevision, + List participants, + List requiredKeys, + List artifacts, + List commandDefinitions) { + return AuthoredWorldReleaseAttestationEvidence.create( + namespace, + descriptorResultDigest, + tenantId, + uuid(VERSION), + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + launchDescriptorId, + releaseBundleRef, + epoch, + "publish:tenant-key:publish-request:pr-é", + "commit-雪", + participants, + digest("9"), + 1, + requiredKeys, + artifacts, + commandDefinitions, + generationRevision); + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptor( + String namespace, + String requestId, + UUID tenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + String launchDescriptorId, + String releaseBundleRef, + long versionId, + long epoch, + String generationRevision, + String runtimeFlags) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + namespace, + requestId, + tenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + launchDescriptorId, + versionId, + false, + null, + runtimeFlags, + generationRevision, + epoch, + 7L, + releaseBundleRef, + false, + null); + } + + private static List participantsWithScope( + String scope) { + return List.of( + participant("WORLD_MANAGEMENT", scope, false, null, "commit-雪", digest("a"), false, null), + participant("ENTITY_MANAGEMENT", scope, false, null, "commit-雪", digest("b"), false, null), + participant("GAME_LOGIC", scope, false, null, "commit-雪", digest("c"), true, digest("f")), + participant( + "AUTOMATION_SCRIPTING", scope, false, null, "commit-雪", digest("d"), false, null), + participant( + "GAME_DESIGN_CONTROL_PLANE", scope, false, null, "commit-雪", digest("e"), false, null)); + } + + private static List participantsWithCommit( + String commit) { + return List.of( + participant("WORLD_MANAGEMENT", "42", false, null, commit, digest("a"), false, null), + participant("ENTITY_MANAGEMENT", "42", false, null, commit, digest("b"), false, null), + participant("GAME_LOGIC", "42", false, null, commit, digest("c"), true, digest("f")), + participant("AUTOMATION_SCRIPTING", "42", false, null, commit, digest("d"), false, null), + participant( + "GAME_DESIGN_CONTROL_PLANE", "42", false, null, commit, digest("e"), false, null)); + } + + private static AuthoredWorldReleaseAttestationEvidence.Participant participant( + String key, + String scope, + boolean baseVersionPresent, + Long baseVersion, + String commit, + String contentDigest, + boolean abilityPresent, + String abilityDigest) { + return participant( + key, + scope, + baseVersionPresent, + baseVersion, + commit, + contentDigest, + abilityPresent, + abilityDigest, + switch (key) { + case "WORLD_MANAGEMENT", "ENTITY_MANAGEMENT" -> 2; + case "AUTOMATION_SCRIPTING" -> 5; + case "GAME_LOGIC", "GAME_DESIGN_CONTROL_PLANE" -> 1; + default -> 1; + }); + } + + private static AuthoredWorldReleaseAttestationEvidence.Participant participant( + String key, + String scope, + boolean baseVersionPresent, + Long baseVersion, + String commit, + String contentDigest, + boolean abilityPresent, + String abilityDigest, + int schemaVersion) { + return new AuthoredWorldReleaseAttestationEvidence.Participant( + key, + scope, + baseVersionPresent, + baseVersion, + commit, + contentDigest.startsWith("sha256:") + ? contentDigest.substring("sha256:".length()) + : contentDigest, + schemaVersion, + abilityPresent, + abilityDigest); + } + + private static List keys() { + return List.of("world.navmesh", "world.雪"); + } + + private static List artifacts() { + return List.of( + artifact("world.navmesh", "NAVMESH", "3", "application/vnd.firemud.navmesh+binary"), + artifact("world.雪", "PATH_GRAPH", "4", "application/vnd.firemud.path-graph+binary")); + } + + private static AuthoredWorldReleaseAttestationEvidence.Artifact artifact( + String usageKey, String kind, String digestHex, String contentType) { + return new AuthoredWorldReleaseAttestationEvidence.Artifact( + usageKey, kind, artifactKey(digestHex), digest(digestHex), contentType, 1); + } + + private static String artifactKey(String digestHex) { + return "artifacts/sha256/" + digestHex.repeat(64); + } + + private static List commands() { + return List.of("LOOK", "say 雪"); + } + + private static AuthoredWorldReleaseAttestationEvidence rawCopy( + AuthoredWorldReleaseAttestationEvidence evidence, + String evidenceDigest, + List commandDefinitions) { + return new AuthoredWorldReleaseAttestationEvidence( + evidence.schemaVersion(), + evidence.targetNamespace(), + evidence.descriptorResultDigest(), + evidence.canonicalTenantId(), + evidence.canonicalVersionId(), + evidence.worldSlug(), + evidence.authoredWorldSourceOperationId(), + evidence.authoredWorldSourceEvidenceDigest(), + evidence.launchDescriptorId(), + evidence.publishedReleaseBundleRef(), + evidence.versionStateEpoch(), + evidence.publishWorkflowId(), + evidence.commitId(), + evidence.participantDigests(), + evidence.manifestHash(), + evidence.manifestSchemaVersion(), + evidence.requiredManifestAssetKeys(), + evidence.artifactDigests(), + commandDefinitions, + evidence.generationConfigRevision(), + evidenceDigest); + } + + private static UUID uuid(String text) { + return UUID.fromString(text); + } + + private static String digest(String value) { + return "sha256:" + value.repeat(64); + } + + private static String text(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + + private record Fixture( + AuthoredWorldReleaseAttestationEvidence evidence, + AuthoredWorldLaunchDescriptorEvidence descriptor) {} +} 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 index 1d1d58bb89..d30a1c7db1 100644 --- 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 @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.charset.StandardCharsets; import java.util.UUID; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; @@ -14,6 +15,9 @@ class AuthoredWorldVersionStateEvidenceTest { 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 UUID CANONICAL_VERSION_ID = uuid("abcdefab-cdef-4abc-8def-abcdefabcdef"); + private static final UUID OTHER_CANONICAL_VERSION_ID = + uuid("fedcbafe-dcba-4fed-8cba-fedcbafedcba"); private static final String SOURCE_DIGEST = "sha256:" + "a".repeat(64); @Test @@ -23,11 +27,33 @@ void evidenceDigestMatchesFixedLengthFramedVector() { AuthoredWorldVersionStateEvidence.create( request, independentVectorSource(), + CANONICAL_VERSION_ID, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 9_223_372_036_854_775_804L); assertThat(evidence.evidenceDigest()) - .isEqualTo("sha256:b17f213002a2ee26d4ccd7aeaf33b50e36ef7cc9d59684913d7916844fde14bd"); + .isEqualTo("sha256:6d041ac372af81cb2fc6bd427e48118d85216427bd68e699d0c4af240feb655e"); + String expectedPreimage = + "43:game-design-authored-world-version-state/v1" + + "1:1" + + "7:firemud" + + "36:33333333-3333-4333-8333-333333333333" + + "36:11111111-1111-4111-8111-111111111111" + + "12:violet-wilds" + + "36:22222222-2222-4222-8222-222222222222" + + "71:sha256:75961752d010261b637ece6ce33eeb714ea032986836bf118397473cc8a2895b" + + "19:9223372036854775805" + + "36:abcdefab-cdef-4abc-8def-abcdefabcdef" + + "5:DRAFT" + + "19:9223372036854775804"; + byte[] preimage = + AuthoredWorldVersionStateEvidence.evidencePreimage( + request, + CANONICAL_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 9_223_372_036_854_775_804L); + assertThat(new String(preimage, StandardCharsets.UTF_8)).isEqualTo(expectedPreimage); + assertThat(preimage).hasSize(354); assertThat(evidence.sourceEvidence().requestDigest()) .isEqualTo("sha256:c8853aa8d2fbdf1bc7905c80d931bdedf32b16c89e49a2c08e821a039b175e23"); assertThat(evidence.sourceEvidence().evidenceDigest()) @@ -39,27 +65,45 @@ void changedRequestStateAndEpochChangeTheOuterDigest() { var original = request("cafe-coast", 19L); String originalDigest = AuthoredWorldVersionStateEvidence.evidenceDigest( - original, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 7L); + original, + CANONICAL_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 7L); assertThat( AuthoredWorldVersionStateEvidence.evidenceDigest( request("cafe-cliff", 19L), + CANONICAL_VERSION_ID, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 7L)) .isNotEqualTo(originalDigest); assertThat( AuthoredWorldVersionStateEvidence.evidenceDigest( request("cafe-coast", 20L), + CANONICAL_VERSION_ID, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 7L)) .isNotEqualTo(originalDigest); assertThat( AuthoredWorldVersionStateEvidence.evidenceDigest( - original, VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, 7L)) + original, + CANONICAL_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 7L)) .isNotEqualTo(originalDigest); assertThat( AuthoredWorldVersionStateEvidence.evidenceDigest( - original, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 8L)) + original, + CANONICAL_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 8L)) + .isNotEqualTo(originalDigest); + assertThat( + AuthoredWorldVersionStateEvidence.evidenceDigest( + original, + OTHER_CANONICAL_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 7L)) .isNotEqualTo(originalDigest); } @@ -83,6 +127,7 @@ void rejectsInvalidCountersStateAndSourceEchoes() { () -> AuthoredWorldVersionStateEvidence.evidenceDigest( request("cafe-coast", 19L), + CANONICAL_VERSION_ID, VersionLifecycleState.VERSION_LIFECYCLE_STATE_UNSPECIFIED, 7L)) .isInstanceOf(IllegalArgumentException.class) @@ -92,6 +137,7 @@ void rejectsInvalidCountersStateAndSourceEchoes() { AuthoredWorldVersionStateEvidence.create( request("cafe-coast", 19L), sourceEvidence("Café 🐉"), + CANONICAL_VERSION_ID, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 0L)) .isInstanceOf(IllegalArgumentException.class) @@ -101,6 +147,7 @@ void rejectsInvalidCountersStateAndSourceEchoes() { AuthoredWorldVersionStateEvidence.create( request("other-world", 19L), sourceEvidence("Café 🐉"), + CANONICAL_VERSION_ID, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 7L)) .isInstanceOf(IllegalArgumentException.class) @@ -121,10 +168,21 @@ void rejectsInvalidCountersStateAndSourceEchoes() { AuthoredWorldVersionStateEvidence.create( reusedRegistrationIdentity, source, + CANONICAL_VERSION_ID, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 7L)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("original source registration request"); + assertThatThrownBy( + () -> + AuthoredWorldVersionStateEvidence.create( + request("cafe-coast", 19L), + sourceEvidence("Café 🐉"), + new UUID(0L, 0L), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 7L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); } private static AuthoredWorldVersionStateEvidence.Request request( 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 index f0bbde988b..40ecdfdebb 100644 --- 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 @@ -17,6 +17,7 @@ class AuthoredWorldVersionStateGrpcCodecTest { 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 UUID CANONICAL_VERSION_ID = uuid("abcdefab-cdef-4abc-8def-abcdefabcdef"); @Test void requestAndCompleteEvidenceRoundTrip() { @@ -27,6 +28,8 @@ void requestAndCompleteEvidenceRoundTrip() { var response = AuthoredWorldVersionStateGrpcCodec.toResponse(evidence); assertThat(decodedRequest).isEqualTo(request); + assertThat(response.getEvidence().getCanonicalVersionId()) + .isEqualTo(CANONICAL_VERSION_ID.toString()); assertThat(AuthoredWorldVersionStateGrpcCodec.fromResponse(request, response)) .isEqualTo(evidence); } @@ -150,6 +153,53 @@ void responseRejectsMissingReceiptBadDigestStateAndEpoch() { "response is invalid"); } + @Test + void responseRequiresCanonicalNonNilVersionUuidAndRejectsSubstitution() { + var request = request(); + GetAuthoredWorldVersionStateResponse valid = + AuthoredWorldVersionStateGrpcCodec.toResponse(evidence(request)); + var wireEvidence = valid.getEvidence(); + + assertInvalidResponse( + request, + valid.toBuilder().setEvidence(wireEvidence.toBuilder().clearCanonicalVersionId()).build(), + "response is invalid"); + assertInvalidResponse( + request, + valid.toBuilder() + .setEvidence(wireEvidence.toBuilder().setCanonicalVersionId("not-a-uuid")) + .build(), + "response is invalid"); + assertInvalidResponse( + request, + valid.toBuilder().setEvidence(wireEvidence.toBuilder().setCanonicalVersionId("")).build(), + "response is invalid"); + assertInvalidResponse( + request, + valid.toBuilder() + .setEvidence( + wireEvidence.toBuilder() + .setCanonicalVersionId("00000000-0000-0000-0000-000000000000")) + .build(), + "response is invalid"); + assertInvalidResponse( + request, + valid.toBuilder() + .setEvidence( + wireEvidence.toBuilder() + .setCanonicalVersionId("ABCDEFAB-CDEF-4ABC-8DEF-ABCDEFABCDEF")) + .build(), + "response is invalid"); + assertInvalidResponse( + request, + valid.toBuilder() + .setEvidence( + wireEvidence.toBuilder() + .setCanonicalVersionId("fedcbafe-dcba-4fed-8cba-fedcbafedcba")) + .build(), + "response is invalid"); + } + private static void assertInvalidResponse( AuthoredWorldVersionStateEvidence.Request request, GetAuthoredWorldVersionStateResponse response, @@ -175,7 +225,11 @@ private static AuthoredWorldVersionStateEvidence.Request request() { private static AuthoredWorldVersionStateEvidence evidence( AuthoredWorldVersionStateEvidence.Request request) { return AuthoredWorldVersionStateEvidence.create( - request, sourceEvidence(), VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 7L); + request, + sourceEvidence(), + CANONICAL_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 7L); } private static AuthoredWorldSourceEvidence sourceEvidence() { diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java index dca3029a7b..160c508730 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java @@ -14,6 +14,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.Map; import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; import net.firedevops.firemud.common.config.CommonSecurityServletAutoConfiguration; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; @@ -23,6 +24,7 @@ import net.firedevops.firemud.common.security.HttpAuthProperties; import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; @@ -31,6 +33,17 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.HandlerExecutionChain; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; class CommonSecurityAutoConfigurationTest { private final ApplicationContextRunner contextRunner = @@ -79,6 +92,65 @@ void registersSharedHttpAuthWhenEnabled() { }); } + @Test + void registersSharedHttpAuthInMvcHandlerChain() { + new WebApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class, + CommonSecurityServletAutoConfiguration.class, + WebMvcAutoConfiguration.class)) + .withBean(TenantGuardedController.class) + .withPropertyValues( + "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", + "firemud.auth.http.enabled=true") + .run( + ctx -> { + assertThat(ctx).hasSingleBean(HttpJwtAuthInterceptor.class); + assertThat(ctx).hasBean("firemudHttpAuthWebMvcConfigurer"); + RequestMappingHandlerMapping mapping = + ctx.getBean(RequestMappingHandlerMapping.class); + HandlerExecutionChain handler = + mapping.getHandler(new MockHttpServletRequest("POST", "/tenant-write")); + assertThat(handler).isNotNull(); + assertThat(handler.getInterceptors()) + .contains(ctx.getBean(HttpJwtAuthInterceptor.class)); + + MockMvc mvc = MockMvcBuilders.webAppContextSetup(ctx).build(); + assertThat( + mvc.perform(MockMvcRequestBuilders.post("/tenant-write")) + .andReturn() + .getResponse() + .getStatus()) + .isEqualTo(401); + String accountId = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + String token = + ctx.getBean(JwtUtil.class) + .generateToken( + accountId, + Map.of("accountId", accountId, "globalRoles", List.of("platformAdmin"))); + assertThat( + mvc.perform( + MockMvcRequestBuilders.post("/tenant-write") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andReturn() + .getResponse() + .getStatus()) + .isEqualTo(412); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + }); + } + + @RestController + static class TenantGuardedController { + @PostMapping("/tenant-write") + ResponseEntity write() { + SessionContext.requireTenantAccess(1L); + return ResponseEntity.status(412).build(); + } + } + @Test void reactiveAppsDoNotLoadServletHttpAuthAutoConfiguration() { new ReactiveWebApplicationContextRunner() diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index f5e0868592..1e1d27b7d3 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -1,4 +1,6 @@ +import org.gradle.api.attributes.LibraryElements + apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { @@ -15,4 +17,12 @@ dependencies { compileOnly(libs.spotbugs.annotations) implementation(libs.aws.sdk.s3) testImplementation(libs.bouncycastle.pkix) + testImplementation(project(":world-management-service")) { + attributes { + attribute( + LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, + objects.named(LibraryElements::class.java, LibraryElements.CLASSES), + ) + } + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java new file mode 100644 index 0000000000..e012bac30e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.gamedesign.dto; + +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; + +/** The closed descriptor and its independently validated full release attestation. */ +public record CompleteLaunchBindingDto( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation) { + public CompleteLaunchBindingDto { + Objects.requireNonNull(descriptor, "descriptor").requireValid(); + Objects.requireNonNull(releaseAttestation, "releaseAttestation").requireValid(descriptor); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java new file mode 100644 index 0000000000..180286e231 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java @@ -0,0 +1,548 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +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; + +/** Durable Game Design outbox for exact, fresh authored-world source delivery to World. */ +@Repository +public class GameAuthoredWorldSourceDeliveryRepository { + private static final int SCHEMA_VERSION = 1; + private static final String NEW_GAME_ROW = "NEW_GAME_ROW"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private static final Table DELIVERY = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + private static final Field DELIVERY_SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field DELIVERY_SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Integer.class); + private static final Field DELIVERY_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field DELIVERY_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + private static final Field DELIVERY_SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("source_request_digest"), String.class); + private static final Field DELIVERY_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field DELIVERY_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field DELIVERY_WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final Field DELIVERY_WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field DELIVERY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field DELIVERY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field DELIVERY_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field DELIVERY_SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field DELIVERY_INTAKE_SCHEMA_VERSION = + DSL.field(DSL.name("intake_schema_version"), Integer.class); + private static final Field DELIVERY_INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field DELIVERY_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_digest"), String.class); + private static final Field DELIVERY_WORLD_OPERATION_ID = + DSL.field(DSL.name("world_operation_id"), UUID.class); + private static final Field DELIVERY_WORLD_REQUEST_DIGEST = + DSL.field(DSL.name("world_request_digest"), String.class); + private static final Field DELIVERY_WORLD_RECEIPT_DIGEST = + DSL.field(DSL.name("world_receipt_digest"), String.class); + private static final Field DELIVERY_ACKNOWLEDGED_AT = + DSL.field(DSL.name("acknowledged_at"), OffsetDateTime.class); + + private static final Table SOURCE = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final Field SOURCE_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("registration_request_id"), UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field SOURCE_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field SOURCE_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field SOURCE_WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final Field SOURCE_WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("evidence_digest"), String.class); + + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field GAME_PROVENANCE_KIND = + DSL.field(DSL.name("tenant_identity_provenance_kind"), String.class); + private static final Field GAME_SOURCE_ROW_ID = + DSL.field(DSL.name("tenant_identity_source_game_id"), Long.class); + private static final Field GAME_SOURCE_TENANT_KEY = + DSL.field(DSL.name("tenant_identity_source_legacy_tenant_id"), String.class); + + private static final Table TENANT_BINDING = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Field BINDING_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field BINDING_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field BINDING_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field BINDING_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field BINDING_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field BINDING_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected DSLContext is the repository's owner transaction collaborator.") + public GameAuthoredWorldSourceDeliveryRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Persists one stable World intake identity inside the source-registration transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim enqueueFresh(AuthoredWorldSourceEvidence source) { + requireActiveWritableOwnerTransaction(); + requireFreshSource(source); + requireExactPersistedSource(source); + + Record existing = findDelivery(source.operationId()); + if (existing != null) { + DeliveryClaim claim = toClaim(existing); + requireSameSource(source, claim.source()); + return claim; + } + + UUID intakeRequestId = UUID.randomUUID(); + while (NIL_UUID.equals(intakeRequestId) || source.operationId().equals(intakeRequestId)) { + intakeRequestId = UUID.randomUUID(); + } + IntakeRequest request = + new IntakeRequest( + SCHEMA_VERSION, + source.targetNamespace(), + intakeRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + String intakeRequestDigest = WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request); + + int inserted = + dsl.insertInto(DELIVERY) + .set(DELIVERY_SOURCE_OPERATION_ID, source.operationId()) + .set(DELIVERY_SOURCE_SCHEMA_VERSION, source.schemaVersion()) + .set(DELIVERY_NAMESPACE, source.targetNamespace()) + .set(DELIVERY_REGISTRATION_REQUEST_ID, source.registrationRequestId()) + .set(DELIVERY_SOURCE_REQUEST_DIGEST, source.requestDigest()) + .set(DELIVERY_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(DELIVERY_TENANT_SLUG, source.tenantSlug()) + .set(DELIVERY_WORLD_SLUG, source.worldSlug()) + .set(DELIVERY_WORLD_DISPLAY_NAME, source.worldDisplayName()) + .set(DELIVERY_SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(DELIVERY_SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(DELIVERY_PROVENANCE_KIND, source.provenanceKind()) + .set(DELIVERY_SOURCE_EVIDENCE_DIGEST, source.evidenceDigest()) + .set(DELIVERY_INTAKE_SCHEMA_VERSION, request.schemaVersion()) + .set(DELIVERY_INTAKE_REQUEST_ID, request.intakeRequestId()) + .set(DELIVERY_INTAKE_REQUEST_DIGEST, intakeRequestDigest) + .onConflictDoNothing() + .execute(); + if (inserted != 1) { + Record conflict = findDelivery(source.operationId()); + if (conflict != null) { + DeliveryClaim claim = toClaim(conflict); + requireSameSource(source, claim.source()); + return claim; + } + throw new DeliveryConflictException( + "Authored-world source delivery conflicts with an existing owner claim"); + } + + Record persisted = findDelivery(source.operationId()); + if (persisted == null) { + throw new IllegalStateException("Authored-world source delivery claim is missing"); + } + DeliveryClaim claim = toClaim(persisted); + requireSameSource(source, claim.source()); + if (!request.equals(claim.request()) || claim.acknowledgedReceipt().isPresent()) { + throw new DeliveryConflictException( + "Committed authored-world source delivery differs from its original claim"); + } + return claim; + } + + /** Reads one complete committed delivery claim without allocating or repairing it. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read(UUID sourceOperationId) { + requireNonNil(sourceOperationId, "sourceOperationId"); + requireCommittedOutcomeRead(); + Record record = findDelivery(sourceOperationId); + if (record == null) { + return Optional.empty(); + } + DeliveryClaim claim = toClaim(record); + requireExactPersistedSource(claim.source()); + return Optional.of(claim); + } + + /** Records only the first full World receipt, or returns an identical concurrent winner. */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim acknowledge(DeliveryClaim expected, CommittedReceipt receipt) { + requireActiveWritableOwnerTransaction(); + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(receipt, "receipt"); + requireFreshSource(expected.source()); + requireReceiptMatchesRequest(expected.request(), receipt); + + Record currentRecord = findDelivery(expected.source().operationId()); + if (currentRecord == null) { + throw new DeliveryConflictException("Authored-world source delivery claim is missing"); + } + DeliveryClaim current = toClaim(currentRecord); + requireSameClaim(expected, current); + requireExactPersistedSource(current.source()); + if (current.acknowledgedReceipt().isPresent()) { + CommittedReceipt original = current.acknowledgedReceipt().orElseThrow(); + if (!original.equals(receipt)) { + throw new DeliveryConflictException( + "Authored-world source delivery already has a different World receipt"); + } + return current; + } + + int updated = + dsl.update(DELIVERY) + .set(DELIVERY_WORLD_OPERATION_ID, receipt.operationId()) + .set(DELIVERY_WORLD_REQUEST_DIGEST, receipt.requestDigest()) + .set(DELIVERY_WORLD_RECEIPT_DIGEST, receipt.receiptDigest()) + .set(DELIVERY_ACKNOWLEDGED_AT, OffsetDateTime.now(ZoneOffset.UTC)) + .where( + DELIVERY_SOURCE_OPERATION_ID + .eq(expected.source().operationId()) + .and(DELIVERY_WORLD_OPERATION_ID.isNull()) + .and(DELIVERY_WORLD_REQUEST_DIGEST.isNull()) + .and(DELIVERY_WORLD_RECEIPT_DIGEST.isNull()) + .and(DELIVERY_ACKNOWLEDGED_AT.isNull())) + .execute(); + if (updated > 1) { + throw new IllegalStateException("Authored-world source delivery ACK changed multiple rows"); + } + + Record acknowledgedRecord = findDelivery(expected.source().operationId()); + if (acknowledgedRecord == null) { + throw new IllegalStateException("Authored-world source delivery disappeared during ACK"); + } + DeliveryClaim acknowledged = toClaim(acknowledgedRecord); + requireSameClaim(expected, acknowledged); + CommittedReceipt durableReceipt = + acknowledged + .acknowledgedReceipt() + .orElseThrow( + () -> new DeliveryConflictException("World receipt ACK did not read back")); + if (!durableReceipt.equals(receipt)) { + throw new DeliveryConflictException( + "Concurrent authored-world source delivery ACK has a different World receipt"); + } + return acknowledged; + } + + /** Validates a pre-V41 registration retry when its optional delivery row already exists. */ + @Transactional(propagation = Propagation.MANDATORY) + void validateExistingIfPresent(AuthoredWorldSourceEvidence source) { + requireActiveWritableOwnerTransaction(); + requireFreshSource(source); + Record existing = findDelivery(source.operationId()); + if (existing == null) { + return; + } + DeliveryClaim claim = toClaim(existing); + requireSameSource(source, claim.source()); + } + + private Record findDelivery(UUID sourceOperationId) { + return dsl.selectFrom(DELIVERY) + .where(DELIVERY_SOURCE_OPERATION_ID.eq(sourceOperationId)) + .fetchOne(); + } + + private DeliveryClaim toClaim(Record row) { + AuthoredWorldSourceEvidence source; + IntakeRequest request; + Optional acknowledgedReceipt; + try { + source = + new AuthoredWorldSourceEvidence( + row.get(DELIVERY_SOURCE_SCHEMA_VERSION), + row.get(DELIVERY_NAMESPACE), + row.get(DELIVERY_REGISTRATION_REQUEST_ID), + row.get(DELIVERY_SOURCE_OPERATION_ID), + row.get(DELIVERY_SOURCE_REQUEST_DIGEST), + row.get(DELIVERY_CANONICAL_TENANT_ID), + row.get(DELIVERY_TENANT_SLUG), + row.get(DELIVERY_WORLD_SLUG), + row.get(DELIVERY_WORLD_DISPLAY_NAME), + row.get(DELIVERY_SOURCE_GAME_ROW_ID), + row.get(DELIVERY_SOURCE_GAME_TENANT_KEY), + row.get(DELIVERY_PROVENANCE_KIND), + row.get(DELIVERY_SOURCE_EVIDENCE_DIGEST)); + request = + new IntakeRequest( + row.get(DELIVERY_INTAKE_SCHEMA_VERSION), + row.get(DELIVERY_NAMESPACE), + row.get(DELIVERY_INTAKE_REQUEST_ID), + row.get(DELIVERY_CANONICAL_TENANT_ID), + row.get(DELIVERY_WORLD_SLUG), + row.get(DELIVERY_SOURCE_OPERATION_ID), + row.get(DELIVERY_SOURCE_EVIDENCE_DIGEST)); + if (!WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request) + .equals(row.get(DELIVERY_INTAKE_REQUEST_DIGEST))) { + throw new IllegalArgumentException("Persisted World intake request digest is invalid"); + } + UUID worldOperationId = row.get(DELIVERY_WORLD_OPERATION_ID); + String worldRequestDigest = row.get(DELIVERY_WORLD_REQUEST_DIGEST); + String worldReceiptDigest = row.get(DELIVERY_WORLD_RECEIPT_DIGEST); + if (worldOperationId == null && worldRequestDigest == null && worldReceiptDigest == null) { + acknowledgedReceipt = Optional.empty(); + } else { + acknowledgedReceipt = + Optional.of( + new CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + worldOperationId, + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + worldRequestDigest, + worldReceiptDigest)); + } + return new DeliveryClaim(source, request, acknowledgedReceipt); + } catch (RuntimeException exception) { + if (exception instanceof DeliveryConflictException conflict) { + throw conflict; + } + throw new InvalidDeliveryClaimException( + "Persisted authored-world source delivery claim is invalid", exception); + } + } + + private void requireExactPersistedSource(AuthoredWorldSourceEvidence expected) { + Record sourceRow = + dsl.selectFrom(SOURCE).where(SOURCE_OPERATION_ID.eq(expected.operationId())).fetchOne(); + if (sourceRow == null || !expected.equals(toSourceEvidence(sourceRow))) { + throw new InvalidDeliveryClaimException( + "Authored-world delivery does not match the complete persisted source receipt"); + } + + Record gameRow = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_PROVENANCE_KIND, + GAME_SOURCE_ROW_ID, + GAME_SOURCE_TENANT_KEY) + .from(GAME) + .where(GAME_ID.eq(expected.sourceGameRowId())) + .fetchOne(); + if (gameRow == null + || !Long.valueOf(expected.sourceGameRowId()).equals(gameRow.get(GAME_ID)) + || !expected.sourceGameTenantKey().equals(gameRow.get(GAME_TENANT_ID)) + || !expected.canonicalTenantId().equals(gameRow.get(GAME_CANONICAL_TENANT_ID)) + || !expected.provenanceKind().equals(gameRow.get(GAME_PROVENANCE_KIND)) + || !Long.valueOf(expected.sourceGameRowId()).equals(gameRow.get(GAME_SOURCE_ROW_ID)) + || !expected.sourceGameTenantKey().equals(gameRow.get(GAME_SOURCE_TENANT_KEY))) { + throw new InvalidDeliveryClaimException( + "Authored-world delivery source no longer matches its Game Design game row"); + } + + Record bindingRow = + dsl.select( + BINDING_NAMESPACE, + BINDING_CANONICAL_TENANT_ID, + BINDING_TENANT_SLUG, + BINDING_SOURCE_GAME_ROW_ID, + BINDING_SOURCE_GAME_TENANT_KEY, + BINDING_PROVENANCE_KIND) + .from(TENANT_BINDING) + .where( + BINDING_NAMESPACE + .eq(expected.targetNamespace()) + .and(BINDING_CANONICAL_TENANT_ID.eq(expected.canonicalTenantId()))) + .fetchOne(); + if (bindingRow == null + || !expected.tenantSlug().equals(bindingRow.get(BINDING_TENANT_SLUG)) + || !Long.valueOf(expected.sourceGameRowId()) + .equals(bindingRow.get(BINDING_SOURCE_GAME_ROW_ID)) + || !expected.sourceGameTenantKey().equals(bindingRow.get(BINDING_SOURCE_GAME_TENANT_KEY)) + || !expected.provenanceKind().equals(bindingRow.get(BINDING_PROVENANCE_KIND))) { + throw new InvalidDeliveryClaimException( + "Authored-world delivery source no longer matches its tenant selector binding"); + } + } + + private AuthoredWorldSourceEvidence toSourceEvidence(Record row) { + try { + return new AuthoredWorldSourceEvidence( + row.get(SOURCE_SCHEMA_VERSION), + row.get(SOURCE_NAMESPACE), + row.get(SOURCE_REGISTRATION_REQUEST_ID), + row.get(SOURCE_OPERATION_ID), + row.get(SOURCE_REQUEST_DIGEST), + row.get(SOURCE_CANONICAL_TENANT_ID), + row.get(SOURCE_TENANT_SLUG), + row.get(SOURCE_WORLD_SLUG), + row.get(SOURCE_WORLD_DISPLAY_NAME), + row.get(SOURCE_GAME_ROW_ID), + row.get(SOURCE_GAME_TENANT_KEY), + row.get(SOURCE_PROVENANCE_KIND), + row.get(SOURCE_EVIDENCE_DIGEST)); + } catch (RuntimeException exception) { + throw new InvalidDeliveryClaimException( + "Persisted authored-world source evidence is invalid", exception); + } + } + + private static void requireSameClaim(DeliveryClaim expected, DeliveryClaim actual) { + requireSameSource(expected.source(), actual.source()); + if (!expected.request().equals(actual.request())) { + throw new DeliveryConflictException( + "Authored-world source delivery request identity changed after dispatch"); + } + } + + private static void requireSameSource( + AuthoredWorldSourceEvidence expected, AuthoredWorldSourceEvidence actual) { + if (!expected.equals(actual)) { + throw new DeliveryConflictException( + "Authored-world source delivery no longer matches its immutable source evidence"); + } + } + + private static void requireReceiptMatchesRequest( + IntakeRequest request, CommittedReceipt receipt) { + if (receipt.schemaVersion() != request.schemaVersion() + || !receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.intakeRequestId().equals(request.intakeRequestId()) + || !receipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !receipt.worldSlug().equals(request.worldSlug()) + || !receipt.sourceOperationId().equals(request.sourceOperationId()) + || !receipt.sourceEvidenceDigest().equals(request.expectedSourceEvidenceDigest())) { + throw new DeliveryConflictException( + "World receipt does not bind the exact persisted authored-world source request"); + } + } + + private static void requireFreshSource(AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(source, "source"); + if (!NEW_GAME_ROW.equals(source.provenanceKind())) { + throw new DeliveryConflictException( + "Only a proven NEW_GAME_ROW authored-world source may be delivered to World"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireActiveWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Authored-world source delivery mutation requires an active writable owner transaction"); + } + } + + private static void requireCommittedOutcomeRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source delivery read requires a committed-outcome owner read"); + } + } + + /** Exact persisted source, immutable World intake identity, and first optional World ACK. */ + public record DeliveryClaim( + AuthoredWorldSourceEvidence source, + IntakeRequest request, + Optional acknowledgedReceipt) { + public DeliveryClaim { + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(acknowledgedReceipt, "acknowledgedReceipt"); + requireFreshSource(source); + IntakeRequest expected = + new IntakeRequest( + SCHEMA_VERSION, + source.targetNamespace(), + request.intakeRequestId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + if (!expected.equals(request)) { + throw new DeliveryConflictException( + "World intake request does not bind the complete authored-world source"); + } + acknowledgedReceipt.ifPresent(receipt -> requireReceiptMatchesRequest(request, receipt)); + } + } + + public static class DeliveryConflictException extends IllegalStateException { + public DeliveryConflictException(String message) { + super(message); + } + } + + public static final class InvalidDeliveryClaimException extends DeliveryConflictException { + public InvalidDeliveryClaimException(String message) { + super(message); + } + + public InvalidDeliveryClaimException(String message, Throwable cause) { + super(message); + initCause(cause); + } + } +} 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 0b619a4179..9958f7ce7c 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 @@ -12,6 +12,7 @@ import org.jooq.Record; import org.jooq.Table; import org.jooq.impl.DSL; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Propagation; @@ -86,14 +87,34 @@ public class GameAuthoredWorldSourceRepository { 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_CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("identity_source_game_row_id"), Long.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("identity_source_game_tenant_key"), String.class); + private static final Field VERSION_IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("identity_source_provenance_kind"), 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 static final UUID NIL_UUID = new UUID(0L, 0L); private final DSLContext dsl; + private final GameAuthoredWorldSourceDeliveryRepository deliveryRepository; - public GameAuthoredWorldSourceRepository(DSLContext dsl) { + @Autowired + public GameAuthoredWorldSourceRepository( + DSLContext dsl, GameAuthoredWorldSourceDeliveryRepository deliveryRepository) { this.dsl = dsl; + this.deliveryRepository = deliveryRepository; + } + + /** Retains the direct owner-test construction path while sharing its owner DSL context. */ + public GameAuthoredWorldSourceRepository(DSLContext dsl) { + this(dsl, new GameAuthoredWorldSourceDeliveryRepository(dsl)); } /** @@ -140,6 +161,10 @@ public AuthoredWorldSourceEvidence register( } requireReceiptSource(receipt, source); requireTenantBinding(receipt); + if (NEW_GAME_ROW.equals(receipt.provenanceKind())) { + // A missing pre-V41 delivery claim stays missing; exact source retry does not backfill it. + deliveryRepository.validateExistingIfPresent(receipt); + } return receipt; } @@ -198,6 +223,9 @@ public AuthoredWorldSourceEvidence register( AuthoredWorldSourceEvidence receipt = toEvidence(persisted); requireReceiptSource(receipt, source); requireTenantBinding(receipt); + if (NEW_GAME_ROW.equals(receipt.provenanceKind())) { + deliveryRepository.enqueueFresh(receipt); + } return receipt; } @@ -292,7 +320,16 @@ public Optional readVersionStateSnapshot( requireTenantBinding(receipt); Record versionRecord = - dsl.select(VERSION_ID, VERSION_TENANT_ID, VERSION_STATE, VERSION_STATE_EPOCH) + dsl.select( + VERSION_ID, + VERSION_TENANT_ID, + VERSION_CANONICAL_VERSION_ID, + VERSION_CANONICAL_TENANT_ID, + VERSION_IDENTITY_SOURCE_GAME_ROW_ID, + VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY, + VERSION_IDENTITY_SOURCE_PROVENANCE_KIND, + VERSION_STATE, + VERSION_STATE_EPOCH) .from(VERSION) .where(VERSION_ID.eq(versionId)) .fetchOne(); @@ -304,6 +341,24 @@ public Optional readVersionStateSnapshot( throw new InvalidSourceEvidenceException( "Requested version is not owned by the exact Game Design source game"); } + UUID canonicalVersionId = versionRecord.get(VERSION_CANONICAL_VERSION_ID); + if (canonicalVersionId == null || NIL_UUID.equals(canonicalVersionId)) { + throw new InvalidSourceEvidenceException( + "Requested version has no persisted canonical non-nil Version UUID"); + } + if (!source.canonicalTenantId().equals(versionRecord.get(VERSION_CANONICAL_TENANT_ID)) + || !Long.valueOf(source.sourceGameRowId()) + .equals(versionRecord.get(VERSION_IDENTITY_SOURCE_GAME_ROW_ID)) + || !source + .sourceGameTenantKey() + .equals(versionRecord.get(VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY)) + || !source + .provenanceKind() + .equals(versionRecord.get(VERSION_IDENTITY_SOURCE_PROVENANCE_KIND))) { + throw new InvalidSourceEvidenceException( + "Requested version canonical identity provenance does not match " + + "the exact Game Design source game"); + } VersionLifecycleState versionState; Long versionStateEpoch = versionRecord.get(VERSION_STATE_EPOCH); @@ -318,7 +373,8 @@ public Optional readVersionStateSnapshot( "Persisted version lifecycle state or epoch is invalid", exception); } return Optional.of( - new AuthoredWorldVersionStateSnapshot(receipt, versionState, versionStateEpoch)); + new AuthoredWorldVersionStateSnapshot( + receipt, canonicalVersionId, versionState, versionStateEpoch)); } private void ensureTenantSlugBinding( @@ -543,6 +599,7 @@ private void requireNonNil(UUID value, String label) { public record AuthoredWorldVersionStateSnapshot( AuthoredWorldSourceEvidence sourceEvidence, + UUID canonicalVersionId, VersionLifecycleState versionState, long versionStateEpoch) {} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java new file mode 100644 index 0000000000..a929542f41 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.gamedesign.service; + +import java.util.UUID; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; + +public interface CompleteLaunchBindingService { + CompleteLaunchBindingDto getCompleteLaunchBinding( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest); +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java index 1ac7a5b74e..cf337ee6e8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java @@ -15,4 +15,12 @@ ResolvedLaunchDescriptorDto getLaunchDescriptor( String controlPlaneRequestId, String expectedRequestDigest, String expectedResultDigest); + + ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest); } 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 index 55843de3eb..4b3f130926 100644 --- 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 @@ -51,6 +51,7 @@ public AuthoredWorldVersionStateEvidence read(AuthoredWorldVersionStateEvidence. return AuthoredWorldVersionStateEvidence.create( request, result.sourceEvidence(), + result.canonicalVersionId(), toProtoState(result.versionState()), result.versionStateEpoch()); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java new file mode 100644 index 0000000000..7be83c4d9c --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java @@ -0,0 +1,460 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.micrometer.core.annotation.Timed; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** Reads the already committed immutable launch descriptor and complete release evidence. */ +@Service +public class CompleteLaunchBindingServiceImpl implements CompleteLaunchBindingService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final int SUPPORTED_MANIFEST_SCHEMA_VERSION = 1; + private static final int SUPPORTED_ARTIFACT_SCHEMA_VERSION = 1; + + private final LaunchDescriptorService launchDescriptorService; + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + private final PublishedReleaseBundleService publishedReleaseBundleService; + private final VersionRepository versionRepository; + + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected Spring collaborators are internal; construction acquires no resources and this service has no finalizer.") + public CompleteLaunchBindingServiceImpl( + LaunchDescriptorService launchDescriptorService, + GameAuthoredWorldSourceRepository authoredWorldSourceRepository, + PublishedReleaseBundleService publishedReleaseBundleService, + VersionRepository versionRepository) { + this.launchDescriptorService = + Objects.requireNonNull(launchDescriptorService, "launchDescriptorService"); + this.authoredWorldSourceRepository = + Objects.requireNonNull(authoredWorldSourceRepository, "authoredWorldSourceRepository"); + this.publishedReleaseBundleService = + Objects.requireNonNull(publishedReleaseBundleService, "publishedReleaseBundleService"); + this.versionRepository = Objects.requireNonNull(versionRepository, "versionRepository"); + } + + @Override + @Transactional( + propagation = Propagation.REQUIRES_NEW, + readOnly = true, + isolation = Isolation.REPEATABLE_READ) + @Timed(value = "gamedesign.completeLaunchBinding.read") + public CompleteLaunchBindingDto getCompleteLaunchBinding( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + ResolvedLaunchDescriptorDto resolved = + launchDescriptorService.getLaunchDescriptorInOwnerSnapshot( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + AuthoredWorldLaunchDescriptorEvidence descriptor = + requireDescriptorMatchesSelector( + resolved, + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + + AuthoredWorldVersionStateSnapshot sourceSnapshot = + authoredWorldSourceRepository + .readVersionStateSnapshot( + workloadNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.versionId()) + .orElseThrow( + () -> + deny( + "AUTHORED_WORLD_SOURCE_NOT_FOUND", + "exact committed source or descriptor version is missing")); + AuthoredWorldSourceEvidence source = sourceSnapshot.sourceEvidence(); + requireSourceMatchesDescriptor(source, descriptor, canonicalTenantId, worldSlug); + if (sourceSnapshot.versionState() == null + || sourceSnapshot.versionStateEpoch() <= 0 + || sourceSnapshot.versionStateEpoch() < descriptor.versionStateEpoch()) { + throw deny("VERSION_STATE_INVALID", "same-snapshot Version state evidence is incomplete"); + } + // The current snapshot state is provenance/current-state context. The immutable descriptor + // epoch below remains the historical release binding and is not an activation decision. + + PublishedReleaseBundleDto bundle; + try { + bundle = + publishedReleaseBundleService.getPublishedReleaseBundle( + source.sourceGameTenantKey(), descriptor.versionId()); + } catch (PublishedReleaseBundleNotFoundException missing) { + throw deny( + "RELEASE_BUNDLE_NOT_FOUND", "the descriptor's committed release is missing", missing); + } + requireExactBundleBinding(bundle, source, descriptor, sourceSnapshot.canonicalVersionId()); + Version canonicalVersion = requireCanonicalVersion(bundle, source, descriptor, sourceSnapshot); + requireFullVersion(canonicalVersion, bundle); + + List participants = + requireParticipantEvidence(bundle, descriptor.versionId()); + String commitId = participants.getFirst().appliedCommitId(); + List artifacts = + requireManifestAndArtifactEvidence(bundle); + + AuthoredWorldReleaseAttestationEvidence releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersion.getCanonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + bundle.publishWorkflowId(), + commitId, + participants, + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + artifacts, + bundle.commandDefinitions(), + bundle.generationConfigRevision()); + releaseAttestation.requireValid(descriptor); + return new CompleteLaunchBindingDto(descriptor, releaseAttestation); + } + + private AuthoredWorldLaunchDescriptorEvidence requireDescriptorMatchesSelector( + ResolvedLaunchDescriptorDto resolved, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + if (readRequestId == null || NIL_UUID.equals(readRequestId)) { + throw deny("INVALID_READ_REQUEST", "readRequestId must be a canonical non-nil UUID"); + } + if (resolved == null || resolved.authoredWorldBinding() == null) { + throw deny("LAUNCH_DESCRIPTOR_NOT_FOUND", "the exact committed descriptor is missing"); + } + AuthoredWorldLaunchDescriptorEvidence descriptor = resolved.authoredWorldBinding(); + try { + descriptor.requireValid(); + } catch (RuntimeException invalid) { + throw deny("LAUNCH_DESCRIPTOR_CONFLICT", "the exact descriptor evidence is invalid", invalid); + } + if (!Objects.equals(workloadNamespace, descriptor.targetNamespace()) + || !Objects.equals(canonicalTenantId, descriptor.canonicalTenantId()) + || !Objects.equals(worldSlug, descriptor.worldSlug()) + || !Objects.equals(controlPlaneRequestId, descriptor.controlPlaneRequestId()) + || !Objects.equals(expectedRequestDigest, descriptor.requestDigest()) + || !Objects.equals(expectedResultDigest, descriptor.resultDigest()) + || !Objects.equals(resolved.launchDescriptorId(), descriptor.launchDescriptorId()) + || !Objects.equals(resolved.canonicalTenantId(), descriptor.canonicalTenantId().toString()) + || !Objects.equals(resolved.controlPlaneRequestId(), descriptor.controlPlaneRequestId()) + || resolved.gameTemplateId() != descriptor.gameTemplateId() + || resolved.versionId() != descriptor.versionId() + || !Objects.equals(resolved.scriptPatchVersion(), descriptor.scriptPatchVersion()) + || !Objects.equals(resolved.runtimeFlagsJson(), descriptor.runtimeFlagsJson()) + || !Objects.equals( + resolved.generationConfigRevision(), descriptor.generationConfigRevision()) + || resolved.versionStateEpoch() != descriptor.versionStateEpoch() + || resolved.releaseBundleId() != descriptor.releaseBundleId() + || !Objects.equals( + resolved.publishedReleaseBundleRef(), descriptor.publishedReleaseBundleRef()) + || !Objects.equals(resolved.remapSetId(), descriptor.remapSetId())) { + throw deny( + "LAUNCH_DESCRIPTOR_CONFLICT", + "the resolved descriptor does not match the exact read selector and evidence"); + } + return descriptor; + } + + private void requireSourceMatchesDescriptor( + AuthoredWorldSourceEvidence source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID canonicalTenantId, + String worldSlug) { + if (source == null + || !Objects.equals(workloadNamespace, source.targetNamespace()) + || !Objects.equals(canonicalTenantId, source.canonicalTenantId()) + || !Objects.equals(worldSlug, source.worldSlug()) + || !Objects.equals(descriptor.canonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(descriptor.worldSlug(), source.worldSlug()) + || !Objects.equals(descriptor.authoredWorldSourceOperationId(), source.operationId()) + || !Objects.equals(descriptor.authoredWorldSourceEvidenceDigest(), source.evidenceDigest()) + || source.sourceGameRowId() <= 0 + || source.sourceGameTenantKey() == null + || source.sourceGameTenantKey().isBlank() + || source.provenanceKind() == null + || source.provenanceKind().isBlank()) { + throw deny("AUTHORED_WORLD_SOURCE_CHANGED", "source evidence does not match the descriptor"); + } + } + + private void requireExactBundleBinding( + PublishedReleaseBundleDto bundle, + AuthoredWorldSourceEvidence source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID snapshotCanonicalVersionId) { + if (bundle == null + || bundle.id() == null + || bundle.id() <= 0 + || bundle.versionId() == null + || bundle.versionId() <= 0 + || bundle.versionNumber() <= 0 + || bundle.canonicalTenantId() == null + || bundle.canonicalVersionId() == null + || NIL_UUID.equals(bundle.canonicalTenantId()) + || NIL_UUID.equals(bundle.canonicalVersionId()) + || snapshotCanonicalVersionId == null + || NIL_UUID.equals(snapshotCanonicalVersionId) + || !Objects.equals(snapshotCanonicalVersionId, bundle.canonicalVersionId()) + || !"v1".equals(bundle.attestationSchemaVersion()) + || !Objects.equals(bundle.id(), descriptor.releaseBundleId()) + || !Objects.equals(bundle.versionId(), descriptor.versionId()) + || !Objects.equals(bundle.tenantId(), source.sourceGameTenantKey()) + || !Objects.equals(bundle.canonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(bundle.generationConfigRevision(), descriptor.generationConfigRevision()) + || !Objects.equals( + bundle.publishedReleaseBundleRef(), descriptor.publishedReleaseBundleRef()) + || bundle.publishWorkflowId() == null + || bundle.publishWorkflowId().isBlank()) { + throw deny( + "RELEASE_ATTESTATION_MISMATCH", + "release bundle identity does not match the exact descriptor and source"); + } + } + + private Version requireCanonicalVersion( + PublishedReleaseBundleDto bundle, + AuthoredWorldSourceEvidence source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldVersionStateSnapshot sourceSnapshot) { + Version version = + versionRepository + .findByCanonicalTenantIdAndCanonicalVersionId( + bundle.canonicalTenantId(), bundle.canonicalVersionId()) + .orElseThrow( + () -> + deny( + "CANONICAL_VERSION_NOT_FOUND", + "release canonical Version identity has no exact persisted owner source")); + if (!Objects.equals(version.getId(), descriptor.versionId()) + || !Objects.equals(version.getTenantId(), source.sourceGameTenantKey()) + || !Objects.equals(version.getCanonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(version.getCanonicalVersionId(), bundle.canonicalVersionId()) + || !Objects.equals(version.getCanonicalVersionId(), sourceSnapshot.canonicalVersionId()) + || !Objects.equals(version.getIdentitySourceGameRowId(), source.sourceGameRowId()) + || !Objects.equals(version.getIdentitySourceGameTenantKey(), source.sourceGameTenantKey()) + || !Objects.equals(version.getIdentitySourceProvenanceKind(), source.provenanceKind()) + || !Objects.equals(version.getVersionNumber(), bundle.versionNumber()) + || version.getVersionState() != sourceSnapshot.versionState() + || !Objects.equals(version.getVersionStateEpoch(), sourceSnapshot.versionStateEpoch())) { + throw deny( + "CANONICAL_VERSION_MISMATCH", + "persisted Version UUID and Game source provenance do not match this release"); + } + return version; + } + + private void requireFullVersion(Version version, PublishedReleaseBundleDto bundle) { + if (version.isScriptOnly() + || version.getBaseVersionId() != null + || version.getScriptPatchVersion() != null + || bundle.scriptOnly() + || bundle.scriptPatchVersion() != null) { + throw deny( + "RELEASE_ATTESTATION_MISMATCH", + "a script-only publication cannot attest a full-Version launch descriptor"); + } + } + + private List requireParticipantEvidence( + PublishedReleaseBundleDto bundle, long versionId) { + List observed = bundle.participantDigests(); + List requiredParticipantOrder = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); + if (observed == null || observed.size() != requiredParticipantOrder.size()) { + throw deny( + "PARTICIPANT_EVIDENCE_INCOMPLETE", "exactly five full-Version owners are required"); + } + List participants = + new ArrayList<>(requiredParticipantOrder.size()); + String expectedScope = Long.toString(versionId); + String appliedCommitId = null; + for (int index = 0; index < requiredParticipantOrder.size(); index++) { + String expectedParticipantKey = requiredParticipantOrder.get(index); + int supportedDigestSchemaVersion = + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + expectedParticipantKey); + PublishParticipantDigestDto digest = observed.get(index); + if (digest == null + || !expectedParticipantKey.equals(digest.participantKey()) + || !expectedScope.equals(digest.scopeValue()) + || digest.baseVersionId() != null + || !digest.succeeded() + || (digest.errorMessage() != null && !digest.errorMessage().isBlank()) + || !isParticipantContentDigest(digest.contentDigest()) + || digest.digestSchemaVersion() == null + || digest.digestSchemaVersion() != supportedDigestSchemaVersion + || digest.appliedCommitId() == null + || digest.appliedCommitId().isBlank()) { + throw deny( + "PARTICIPANT_EVIDENCE_INVALID", + "full-Version participant evidence is missing, failed, unsupported, or out of order"); + } + if (appliedCommitId == null) { + appliedCommitId = digest.appliedCommitId(); + } else if (!appliedCommitId.equals(digest.appliedCommitId())) { + throw deny("PARTICIPANT_COMMIT_MISMATCH", "full-Version owners attest different commits"); + } + boolean abilityPresent = digest.abilitySchemaDigest() != null; + if ("GAME_LOGIC".equals(expectedParticipantKey)) { + if (!abilityPresent || !isDigest(digest.abilitySchemaDigest())) { + throw deny( + "ABILITY_SCHEMA_EVIDENCE_MISSING", + "Game Logic must provide its dedicated ability-schema digest"); + } + } else if (abilityPresent) { + throw deny( + "ABILITY_SCHEMA_EVIDENCE_OWNER_MISMATCH", + "only Game Logic may provide the ability-schema digest"); + } + participants.add( + new AuthoredWorldReleaseAttestationEvidence.Participant( + digest.participantKey(), + digest.scopeValue(), + false, + null, + digest.appliedCommitId(), + digest.contentDigest(), + digest.digestSchemaVersion(), + abilityPresent, + digest.abilitySchemaDigest())); + } + if (appliedCommitId == null || appliedCommitId.isBlank()) { + throw deny("PARTICIPANT_COMMIT_MISSING", "full-Version commit identity is missing"); + } + return List.copyOf(participants); + } + + private List requireManifestAndArtifactEvidence( + PublishedReleaseBundleDto bundle) { + if (!isDigest(bundle.manifestHash()) + || bundle.manifestSchemaVersion() == null + || bundle.manifestSchemaVersion() != SUPPORTED_MANIFEST_SCHEMA_VERSION + || bundle.requiredManifestAssetKeys() == null + || bundle.artifactDigests() == null + || bundle.commandDefinitions() == null + || bundle.commandDefinitions().stream().anyMatch(value -> value == null || value.isBlank()) + || bundle.generationConfigRevision() == null + || bundle.generationConfigRevision().isBlank()) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_INCOMPLETE", + "manifest, required-key, actual-artifact, command, or generation proof is missing"); + } + List requiredKeys = bundle.requiredManifestAssetKeys(); + for (int index = 0; index < requiredKeys.size(); index++) { + String key = requiredKeys.get(index); + if (key == null + || key.isBlank() + || (index > 0 + && PublishedArtifactDigest.compareUsageKeysUtf8(requiredKeys.get(index - 1), key) + >= 0)) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_INVALID", + "required manifest asset keys must be unique and in unsigned UTF-8 order"); + } + } + List observedArtifacts = bundle.artifactDigests(); + List artifacts = + new ArrayList<>(observedArtifacts.size()); + String previousUsageKey = null; + for (PublishedArtifactDigest artifact : observedArtifacts) { + if (artifact == null + || artifact.artifactSchemaVersion() != SUPPORTED_ARTIFACT_SCHEMA_VERSION + || (previousUsageKey != null + && PublishedArtifactDigest.compareUsageKeysUtf8(previousUsageKey, artifact.usageKey()) + >= 0)) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_INVALID", + "artifact entries must be unique and in unsigned UTF-8 usage-key order"); + } + previousUsageKey = artifact.usageKey(); + artifacts.add( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + artifact.usageKey(), + artifact.artifactKind(), + artifact.immutableObjectKey(), + artifact.contentDigest(), + artifact.contentType(), + artifact.artifactSchemaVersion())); + } + for (String requiredKey : requiredKeys) { + long matches = + observedArtifacts.stream() + .filter(artifact -> requiredKey.equals(artifact.usageKey())) + .count(); + if (matches != 1) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_MISMATCH", + "each required manifest key must select exactly one actual-byte artifact proof"); + } + } + return List.copyOf(artifacts); + } + + private boolean isDigest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private boolean isParticipantContentDigest(String value) { + return value != null && value.matches("[0-9a-f]{64}"); + } + + private IllegalArgumentException deny(String code, String detail) { + return new IllegalArgumentException("COMPLETE_LAUNCH_BINDING_" + code + ": " + detail); + } + + private IllegalArgumentException deny(String code, String detail, Throwable cause) { + return new IllegalArgumentException("COMPLETE_LAUNCH_BINDING_" + code + ": " + detail, cause); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryService.java new file mode 100644 index 0000000000..10fa91c76c --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryService.java @@ -0,0 +1,175 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** One-item durable delivery pass, intentionally not registered as a Spring bean or scheduler. */ +public final class GameAuthoredWorldSourceDeliveryService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final GameAuthoredWorldSourceDeliveryRepository repository; + private final WorldAuthoredSourceIntakeClient client; + private final TransactionTemplate ownerWrite; + private final String workloadNamespace; + + public GameAuthoredWorldSourceDeliveryService( + GameAuthoredWorldSourceDeliveryRepository repository, + WorldAuthoredSourceIntakeClient client, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.client = Objects.requireNonNull(client, "client"); + this.workloadNamespace = requireNamespace(workloadNamespace); + this.ownerWrite = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + this.ownerWrite.setName("game-authored-world-source-delivery-acknowledge"); + this.ownerWrite.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerWrite.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerWrite.setTimeout(10); + } + + /** + * Dispatches one persisted source claim and returns only a complete durably acknowledged result. + */ + public DeliveryClaim deliver(UUID sourceOperationId) { + requireNonNil(sourceOperationId, "sourceOperationId"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source delivery cannot start inside an ambient transaction"); + } + + DeliveryClaim claim = + repository + .read(sourceOperationId) + .orElseThrow( + () -> + new DeliveryNotFoundException( + "No durable fresh authored-world delivery claim exists for the source")); + if (!workloadNamespace.equals(claim.request().targetNamespace())) { + throw new DeliveryConflictException( + "Authored-world source delivery belongs to another workload namespace"); + } + Optional acknowledged = claim.acknowledgedReceipt(); + if (acknowledged.isPresent()) { + return claim; + } + + // The outbox identity is stable, so a retry after an ambiguous response replays this exact + // idempotent intake request. World dispatch and its independent read happen outside DB work. + CommittedReceipt intakeReceipt = client.intake(claim.request()); + ReadRequest readRequest = new ReadRequest(claim.request(), freshReadRequestId(claim)); + CommittedReceipt readReceipt = client.read(readRequest); + if (!intakeReceipt.equals(readReceipt)) { + throw new DeliveryConflictException( + "World intake and independent readback did not return the same complete receipt"); + } + + return persistAndReadBack(claim, readReceipt); + } + + private DeliveryClaim persistAndReadBack(DeliveryClaim expected, CommittedReceipt receipt) { + DeliveryClaim transactionResult; + try { + transactionResult = ownerWrite.execute(status -> repository.acknowledge(expected, receipt)); + } catch (RuntimeException transactionFailure) { + // A JDBC/transaction-manager failure can occur after the database committed. Resolve that + // ambiguity only from a fresh durable read; never dispatch again from this call. + try { + Optional recovered = repository.read(expected.source().operationId()); + if (recovered.isPresent()) { + DeliveryClaim claim = recovered.orElseThrow(); + requireSameRequest(expected, claim); + Optional durableReceipt = claim.acknowledgedReceipt(); + if (durableReceipt.isPresent()) { + if (!receipt.equals(durableReceipt.orElseThrow())) { + throw new DeliveryConflictException( + "A different World receipt won the durable delivery acknowledgement"); + } + return claim; + } + } + } catch (DeliveryConflictException conflict) { + conflict.addSuppressed(transactionFailure); + throw conflict; + } catch (RuntimeException readFailure) { + transactionFailure.addSuppressed(readFailure); + } + throw transactionFailure; + } + if (transactionResult == null) { + throw new IllegalStateException( + "World receipt acknowledgement transaction returned no proof"); + } + + Optional durableReadback = repository.read(expected.source().operationId()); + if (durableReadback.isEmpty()) { + throw new IllegalStateException( + "Committed World receipt acknowledgement is missing from independent owner readback"); + } + DeliveryClaim readback = durableReadback.orElseThrow(); + requireSameRequest(expected, readback); + if (!transactionResult.source().equals(readback.source()) + || !transactionResult.request().equals(readback.request()) + || !transactionResult.acknowledgedReceipt().equals(readback.acknowledgedReceipt()) + || readback.acknowledgedReceipt().isEmpty() + || !receipt.equals(readback.acknowledgedReceipt().orElseThrow())) { + throw new DeliveryConflictException( + "Committed World receipt acknowledgement failed exact durable owner readback"); + } + return readback; + } + + private static void requireSameRequest(DeliveryClaim expected, DeliveryClaim actual) { + if (!expected.source().equals(actual.source()) + || !expected.request().equals(actual.request())) { + throw new DeliveryConflictException( + "Authored-world source delivery changed while World intake was in flight"); + } + } + + private static UUID freshReadRequestId(DeliveryClaim claim) { + UUID requestId = UUID.randomUUID(); + while (NIL_UUID.equals(requestId) + || requestId.equals(claim.request().intakeRequestId()) + || requestId.equals(claim.source().operationId())) { + requestId = UUID.randomUUID(); + } + return requestId; + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static String requireNamespace(String namespace) { + Objects.requireNonNull(namespace, "workloadNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + return namespace; + } + + public static class DeliveryConflictException extends IllegalStateException { + public DeliveryConflictException(String message) { + super(message); + } + } + + public static final class DeliveryNotFoundException extends IllegalStateException { + public DeliveryNotFoundException(String message) { + super(message); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 2abfb6542c..6d657e5959 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 @@ -17,6 +17,7 @@ import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.settings.GameDesignSettingsProtoMapper; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.HelpTopicDto; import net.firedevops.firemud.gamedesign.dto.PublishedPluginVersionDto; @@ -25,6 +26,7 @@ import net.firedevops.firemud.gamedesign.dto.TemplateRemapEntryDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -55,6 +57,7 @@ import net.firedevops.firemud.gamedesign.v1.FinalizePurgeVersionAssetsRequest; import net.firedevops.firemud.gamedesign.v1.FinalizePurgeVersionAssetsResponse; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestResponse; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; @@ -133,6 +136,7 @@ public class GameDesignGrpcService extends GameDesignServiceGrpc.GameDesignServi private final RevisionService revisionService; private final VersionService versionService; private final LaunchDescriptorService launchDescriptorService; + private final CompleteLaunchBindingService completeLaunchBindingService; private final TemplateRemapSetService templateRemapSetService; private final VersionAssetArtifactService versionAssetArtifactService; private final SettingsAuthorityService settingsAuthorityService; @@ -1027,6 +1031,85 @@ public void getLaunchDescriptor( responseObserver.onCompleted(); } + @Override + @Timed(value = "gamedesignGrpc.getCompleteLaunchBinding") + public void getCompleteLaunchBinding( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + GetCompleteLaunchBindingResponse.Builder builder = + GetCompleteLaunchBindingResponse.newBuilder(); + try { + requireLaunchDescriptorReadAccess(); + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (readRequestId == null + || canonicalTenantId == null + || request.getWorldSlug().isBlank() + || request.getControlPlaneRequestId().isBlank() + || request.getExpectedRequestDigest().isBlank() + || request.getExpectedResultDigest().isBlank() + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Canonical exact complete launch binding read is required"); + } + CompleteLaunchBindingDto binding = + completeLaunchBindingService.getCompleteLaunchBinding( + readRequestId, + canonicalTenantId, + request.getWorldSlug(), + request.getControlPlaneRequestId(), + request.getExpectedRequestDigest(), + request.getExpectedResultDigest()); + AuthoredWorldLaunchDescriptorEvidence descriptorEvidence = binding.descriptor(); + var descriptorDto = + new net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto( + descriptorEvidence.launchDescriptorId(), + descriptorEvidence.canonicalTenantId().toString(), + descriptorEvidence.gameTemplateId(), + descriptorEvidence.controlPlaneRequestId(), + descriptorEvidence.versionId(), + descriptorEvidence.scriptPatchVersionPresent() + ? descriptorEvidence.scriptPatchVersion() + : null, + descriptorEvidence.runtimeFlagsJson(), + descriptorEvidence.generationConfigRevision(), + descriptorEvidence.versionStateEpoch(), + descriptorEvidence.releaseBundleId(), + descriptorEvidence.publishedReleaseBundleRef(), + descriptorEvidence.remapSetIdPresent() ? descriptorEvidence.remapSetId() : null, + descriptorEvidence); + var protoDescriptor = toProtoLaunchDescriptor(descriptorDto); + var protoReleaseAttestation = + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .toReleaseAttestation(binding.releaseAttestation()); + builder + .setRequestId(readRequestId.toString()) + .setLaunchDescriptor(protoDescriptor) + .setReleaseAttestation(protoReleaseAttestation); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + "PERMISSION_DENIED", + ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + completeLaunchBindingErrorCode(ex.getMessage()), + ex.getMessage())); + } catch (Exception ex) { + builder.setError( + GrpcAppErrors.internal(meterRegistry, logger, "GetCompleteLaunchBinding", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + @Override @Timed(value = "gamedesignGrpc.createTemplateRemapSet") public void createTemplateRemapSet( @@ -2162,6 +2245,16 @@ private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsu return "INVALID_ARGUMENT"; } + private String completeLaunchBindingErrorCode(String message) { + if (message != null && message.startsWith("COMPLETE_LAUNCH_BINDING_")) { + int delimiter = message.indexOf(':'); + if (delimiter > 0) { + return message.substring(0, delimiter); + } + } + return launchDescriptorErrorCode(message, true); + } + private String remapSetErrorCode(String message) { if (message == null || message.isBlank()) { return "INVALID_ARGUMENT"; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index b4d491e439..6c6ca9567d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -27,7 +27,10 @@ import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.ObjectMapper; @Service @@ -241,6 +244,86 @@ public ResolvedLaunchDescriptorDto getLaunchDescriptor( String controlPlaneRequestId, String expectedRequestDigest, String expectedResultDigest) { + DescriptorReadContext context = + findExactSuccessfulDescriptor( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + LaunchDescriptor descriptor = context.descriptor(); + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = context.request(); + AuthoredWorldSourceEvidence source = readExactSource(storedRequest); + String sourceJson = writeJson(source); + if (!sourceJson.equals(descriptor.getSourceEvidenceJson())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); + } + return readStored( + descriptor, + storedRequest, + descriptor.getOriginalRequestJson(), + descriptor.getSourceEvidenceJson()); + } + + @Override + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + @Timed(value = "gamedesign.launchDescriptor.readOwnerSnapshot") + public ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + requireOwnerSnapshot(); + DescriptorReadContext context = + findExactSuccessfulDescriptor( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + LaunchDescriptor descriptor = context.descriptor(); + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = context.request(); + var sourceSnapshot = + authoredWorldSourceRepository + .readVersionStateSnapshot( + workloadNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + storedRequest.authoredWorldSourceOperationId(), + storedRequest.authoredWorldSourceEvidenceDigest(), + Objects.requireNonNull(descriptor.getVersionId(), "descriptor versionId")) + .orElseThrow( + () -> + new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source or version is missing")); + AuthoredWorldSourceEvidence source = sourceSnapshot.sourceEvidence(); + requireExactSource(storedRequest, source); + String sourceJson = writeJson(source); + if (!sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !Objects.equals(source.sourceGameTenantKey(), descriptor.getTenantId())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); + } + return readStored( + descriptor, + storedRequest, + descriptor.getOriginalRequestJson(), + descriptor.getSourceEvidenceJson()); + } + + private DescriptorReadContext findExactSuccessfulDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { if (readRequestId == null || NIL_UUID.equals(readRequestId)) { throw new IllegalArgumentException("Canonical nonnil read request ID is required"); } @@ -276,17 +359,7 @@ public ResolvedLaunchDescriptorDto getLaunchDescriptor( } AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = readRequest(descriptor.getOriginalRequestJson()); - AuthoredWorldSourceEvidence source = readExactSource(storedRequest); - String sourceJson = writeJson(source); - if (!sourceJson.equals(descriptor.getSourceEvidenceJson())) { - throw new IllegalArgumentException( - "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); - } - return readStored( - descriptor, - storedRequest, - descriptor.getOriginalRequestJson(), - descriptor.getSourceEvidenceJson()); + return new DescriptorReadContext(descriptor, storedRequest); } private AuthoredWorldSourceEvidence readExactSource( @@ -302,6 +375,12 @@ private AuthoredWorldSourceEvidence readExactSource( () -> new IllegalArgumentException( "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing")); + requireExactSource(request, source); + return source; + } + + private void requireExactSource( + AuthoredWorldLaunchDescriptorEvidence.Request request, AuthoredWorldSourceEvidence source) { if (!workloadNamespace.equals(source.targetNamespace()) || !request.canonicalTenantId().equals(source.canonicalTenantId()) || !request.worldSlug().equals(source.worldSlug()) @@ -310,9 +389,21 @@ private AuthoredWorldSourceEvidence readExactSource( throw new IllegalArgumentException( "AUTHORED_WORLD_SOURCE_CHANGED: source evidence does not match the exact request"); } - return source; } + private void requireOwnerSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Launch descriptor snapshot read requires a read-only REPEATABLE_READ owner snapshot"); + } + } + + private record DescriptorReadContext( + LaunchDescriptor descriptor, AuthoredWorldLaunchDescriptorEvidence.Request request) {} + private ResolvedLaunchDescriptorDto readStored( LaunchDescriptor descriptor, AuthoredWorldLaunchDescriptorEvidence.Request request, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java index a6d8ed34b1..f67e9bc383 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java @@ -5,6 +5,8 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.stream.Collectors; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; import net.firedevops.firemud.gamedesign.client.EntityManagementClient; @@ -23,19 +25,15 @@ @Service public class PublishGateServiceImpl implements PublishGateService { private static final Map SUPPORTED_DIGEST_SCHEMA_VERSIONS = - Map.of( - PublishParticipantKey.WORLD_MANAGEMENT.name(), 2, - PublishParticipantKey.ENTITY_MANAGEMENT.name(), 2, - PublishParticipantKey.GAME_LOGIC.name(), 1, - PublishParticipantKey.AUTOMATION_SCRIPTING.name(), 5, - PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE.name(), 1); + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .collect( + Collectors.toUnmodifiableMap( + participantKey -> participantKey, + AuthoredWorldReleaseAttestationEvidence::supportedParticipantDigestSchema)); private static final List FULL_VERSION_PARTICIPANTS = - List.of( - PublishParticipantKey.WORLD_MANAGEMENT, - PublishParticipantKey.ENTITY_MANAGEMENT, - PublishParticipantKey.GAME_LOGIC, - PublishParticipantKey.AUTOMATION_SCRIPTING, - PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE); + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map(PublishParticipantKey::valueOf) + .toList(); private static final List SCRIPT_PATCH_PARTICIPANTS = List.of( diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index baa0577a12..ea9ca1244b 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -57,6 +57,7 @@ firemud: - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor - gamedesign.v1.GameDesignService/GetLaunchDescriptor + - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index 11eb2e498e..bd2d7ea02f 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -89,6 +89,7 @@ firemud: - gamedesign.v1.TenantIdentityService/ResolveLegacyGameSessionTenantAssociation - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor - gamedesign.v1.GameDesignService/GetLaunchDescriptor + - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql b/services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql new file mode 100644 index 0000000000..90883b945b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql @@ -0,0 +1,249 @@ +ALTER TABLE game_design_authored_world_source_operations + ADD CONSTRAINT uq_gd_authored_world_source_delivery_source UNIQUE ( + operation_id, + schema_version, + target_namespace, + registration_request_id, + request_digest, + canonical_tenant_id, + tenant_slug, + world_slug, + world_display_name, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ); + +CREATE TABLE game_design_authored_world_source_deliveries ( + source_operation_id UUID PRIMARY KEY, + source_schema_version INTEGER NOT NULL CHECK (source_schema_version = 1), + target_namespace VARCHAR(63) NOT NULL, + registration_request_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_slug VARCHAR(120) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(400) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_schema_version INTEGER NOT NULL CHECK (intake_schema_version = 1), + intake_request_id UUID NOT NULL, + intake_request_digest VARCHAR(71) NOT NULL, + world_operation_id UUID, + world_request_digest VARCHAR(71), + world_receipt_digest VARCHAR(71), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + acknowledged_at TIMESTAMPTZ, + CONSTRAINT uq_gd_authored_world_source_delivery_request + UNIQUE (target_namespace, intake_request_id), + CONSTRAINT fk_gd_authored_world_source_delivery_source FOREIGN KEY ( + source_operation_id, + source_schema_version, + target_namespace, + registration_request_id, + source_request_digest, + canonical_tenant_id, + tenant_slug, + world_slug, + world_display_name, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + source_evidence_digest + ) REFERENCES game_design_authored_world_source_operations ( + operation_id, + schema_version, + target_namespace, + registration_request_id, + request_digest, + canonical_tenant_id, + tenant_slug, + world_slug, + world_display_name, + source_game_row_id, + source_game_tenant_key, + provenance_kind, + evidence_digest + ), + CONSTRAINT chk_gd_authored_world_source_delivery_fresh CHECK ( + provenance_kind = 'NEW_GAME_ROW' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_ids CHECK ( + source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND registration_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_game_row_id > 0 + ), + CONSTRAINT chk_gd_authored_world_source_delivery_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_digests CHECK ( + source_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND ( + (world_operation_id IS NULL + AND world_request_digest IS NULL + AND world_receipt_digest IS NULL + AND acknowledged_at IS NULL) + OR + (world_operation_id IS NOT NULL + AND world_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_request_digest IS NOT NULL + AND world_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_receipt_digest IS NOT NULL + AND world_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND acknowledged_at IS NOT NULL) + ) + ), + CONSTRAINT chk_gd_authored_world_source_delivery_slugs CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_display_name CHECK ( + char_length(world_display_name) BETWEEN 1 AND 100 + AND octet_length(world_display_name) <= 400 + AND world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_authored_world_source_delivery_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_authored_world_source_delivery() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Design authored-world source delivery is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.world_operation_id IS NOT NULL + OR NEW.world_request_digest IS NOT NULL + OR NEW.world_receipt_digest IS NOT NULL + OR NEW.acknowledged_at IS NOT NULL THEN + RAISE EXCEPTION 'New Game Design authored-world delivery cannot start acknowledged' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM game_design_authored_world_source_operations o + JOIN game_design_tenant_slug_binding b + ON b.target_namespace = o.target_namespace + AND b.canonical_tenant_id = o.canonical_tenant_id + AND b.tenant_slug = o.tenant_slug + AND b.source_game_row_id = o.source_game_row_id + AND b.source_game_tenant_key = o.source_game_tenant_key + AND b.provenance_kind = o.provenance_kind + JOIN game g + ON g.id = o.source_game_row_id + AND g.tenant_id = o.source_game_tenant_key + AND g.canonical_tenant_id = o.canonical_tenant_id + AND g.tenant_identity_provenance_kind = o.provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE o.operation_id = NEW.source_operation_id + AND o.schema_version = NEW.source_schema_version + AND o.target_namespace = NEW.target_namespace + AND o.registration_request_id = NEW.registration_request_id + AND o.request_digest = NEW.source_request_digest + AND o.canonical_tenant_id = NEW.canonical_tenant_id + AND o.tenant_slug = NEW.tenant_slug + AND o.world_slug = NEW.world_slug + AND o.world_display_name = NEW.world_display_name + AND o.source_game_row_id = NEW.source_game_row_id + AND o.source_game_tenant_key = NEW.source_game_tenant_key + AND o.provenance_kind = 'NEW_GAME_ROW' + AND o.evidence_digest = NEW.source_evidence_digest + ) INTO source_matches; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Game Design authored-world delivery has no exact fresh source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF ROW( + NEW.source_operation_id, + NEW.source_schema_version, + NEW.target_namespace, + NEW.registration_request_id, + NEW.source_request_digest, + NEW.canonical_tenant_id, + NEW.tenant_slug, + NEW.world_slug, + NEW.world_display_name, + NEW.source_game_row_id, + NEW.source_game_tenant_key, + NEW.provenance_kind, + NEW.source_evidence_digest, + NEW.intake_schema_version, + NEW.intake_request_id, + NEW.intake_request_digest, + NEW.created_at + ) IS DISTINCT FROM ROW( + OLD.source_operation_id, + OLD.source_schema_version, + OLD.target_namespace, + OLD.registration_request_id, + OLD.source_request_digest, + OLD.canonical_tenant_id, + OLD.tenant_slug, + OLD.world_slug, + OLD.world_display_name, + OLD.source_game_row_id, + OLD.source_game_tenant_key, + OLD.provenance_kind, + OLD.source_evidence_digest, + OLD.intake_schema_version, + OLD.intake_request_id, + OLD.intake_request_digest, + OLD.created_at + ) THEN + RAISE EXCEPTION 'Game Design authored-world delivery claim cannot be rebound' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.world_operation_id IS NULL + AND OLD.world_request_digest IS NULL + AND OLD.world_receipt_digest IS NULL + AND OLD.acknowledged_at IS NULL + AND NEW.world_operation_id IS NOT NULL + AND NEW.world_request_digest IS NOT NULL + AND NEW.world_receipt_digest IS NOT NULL + AND NEW.acknowledged_at IS NOT NULL THEN + RETURN NEW; + END IF; + + RAISE EXCEPTION 'Game Design authored-world delivery acknowledgement is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_delivery_immutable + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_world_source_deliveries + FOR EACH ROW EXECUTE FUNCTION enforce_gd_authored_world_source_delivery(); + +CREATE FUNCTION reject_gd_authored_world_source_delivery_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Design authored-world source delivery is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gd_authored_world_source_delivery_no_truncate + BEFORE TRUNCATE ON game_design_authored_world_source_deliveries + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_authored_world_source_delivery_truncate(); +-- [jooq ignore end] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java new file mode 100644 index 0000000000..fb4185309d --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java @@ -0,0 +1,684 @@ +package integration.net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.service.impl.GameAuthoredWorldSourceDeliveryService; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +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 GameAuthoredWorldSourceDeliveryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String NAMESPACE = "authored-world-delivery-test"; + private static final MigrationVersion PRE_DELIVERY_VERSION = MigrationVersion.fromVersion("40"); + private static final Table GAME = DSL.table(DSL.name("game")); + private static final Table SOURCE_OPERATIONS = + DSL.table(DSL.name("game_design_authored_world_source_operations")); + private static final Table TENANT_BINDINGS = + DSL.table(DSL.name("game_design_tenant_slug_binding")); + private static final Table DELIVERIES = + DSL.table(DSL.name("game_design_authored_world_source_deliveries")); + private static final org.jooq.Field GAME_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field GAME_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final org.jooq.Field GAME_NAME = DSL.field(DSL.name("name"), String.class); + private static final org.jooq.Field GAME_DESCRIPTION = + DSL.field(DSL.name("description"), String.class); + private static final org.jooq.Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void freshRegistrationQueuesOneStableWorldRequestAndExactSourceRetryReusesIt() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("11111111-1111-4111-8111-111111111111"); + + AuthoredWorldSourceEvidence source = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim firstClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + AuthoredWorldSourceEvidence retry = + fixture.register( + registrationRequestId, fixture.freshGame(), "fresh-tenant", "silver-march"); + DeliveryClaim retryClaim = + fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + + assertThat(firstClaim.source()).isEqualTo(source); + assertThat(firstClaim.request().schemaVersion()).isEqualTo(1); + assertThat(firstClaim.request().targetNamespace()).isEqualTo(NAMESPACE); + assertThat(firstClaim.request().canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(firstClaim.request().worldSlug()).isEqualTo(source.worldSlug()); + assertThat(firstClaim.request().sourceOperationId()).isEqualTo(source.operationId()); + assertThat(firstClaim.request().expectedSourceEvidenceDigest()) + .isEqualTo(source.evidenceDigest()); + assertThat(firstClaim.request().intakeRequestId()).isNotEqualTo(source.operationId()); + assertThat(retry).isEqualTo(source); + assertThat(retryClaim).isEqualTo(firstClaim); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isEqualTo(1); + } + + @Test + void sourceAndDeliveryIntentRollBackTogether() { + Fixture fixture = fixture(null); + UUID registrationRequestId = uuid("22222222-2222-4222-8222-222222222222"); + AtomicReference sourceRef = new AtomicReference<>(); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + sourceRef.set( + fixture + .sourceRepository() + .register( + NAMESPACE, + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")); + throw new IllegalStateException("simulate failed source owner commit"); + })) + .hasMessageContaining("simulate failed source owner commit"); + + AuthoredWorldSourceEvidence attempted = sourceRef.get(); + assertThat(attempted).isNotNull(); + assertThat( + fixture + .sourceRepository() + .read( + attempted.operationId(), + attempted.canonicalTenantId(), + attempted.worldSlug(), + attempted.targetNamespace())) + .isEmpty(); + assertThat(fixture.deliveryRepository().read(attempted.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(SOURCE_OPERATIONS)).isZero(); + assertThat(fixture.dsl().fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void concurrentExactDeliveriesReturnOneDurableAckAndChangedReceiptIsDenied() throws Exception { + Fixture fixture = fixture(null); + AuthoredWorldSourceEvidence source = fixture.registerFresh(33); + DeliveryClaim pending = fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("44444444-4444-4444-8444-444444444444"), 'a'); + WorldAuthoredSourceIntakeClient worldClient = mock(WorldAuthoredSourceIntakeClient.class); + CountDownLatch intakeCalls = new CountDownLatch(2); + CountDownLatch releaseIntake = new CountDownLatch(1); + when(worldClient.intake(pending.request())) + .thenAnswer( + invocation -> { + intakeCalls.countDown(); + await(releaseIntake); + return receipt; + }); + when(worldClient.read(any(WorldAuthoredSourceIntakeGrpcCodec.ReadRequest.class))) + .thenReturn(receipt); + GameAuthoredWorldSourceDeliveryService service = + new GameAuthoredWorldSourceDeliveryService( + fixture.deliveryRepository(), worldClient, fixture.transactionManager(), NAMESPACE); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = executor.submit(() -> service.deliver(source.operationId())); + Future second = executor.submit(() -> service.deliver(source.operationId())); + assertThat(intakeCalls.await(10, TimeUnit.SECONDS)).isTrue(); + releaseIntake.countDown(); + + DeliveryClaim firstResult = first.get(10, TimeUnit.SECONDS); + DeliveryClaim secondResult = second.get(10, TimeUnit.SECONDS); + assertThat(firstResult).isEqualTo(secondResult); + assertThat(firstResult.acknowledgedReceipt()).contains(receipt); + assertThat(fixture.deliveryRepository().read(source.operationId())).contains(firstResult); + verify(worldClient, times(2)).intake(pending.request()); + verify(worldClient, times(2)).read(any(WorldAuthoredSourceIntakeGrpcCodec.ReadRequest.class)); + } finally { + releaseIntake.countDown(); + executor.shutdownNow(); + } + + CommittedReceipt changedReceipt = + committedReceipt(pending.request(), receipt.operationId(), 'b'); + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> + fixture.deliveryRepository().acknowledge(pending, changedReceipt))) + .isInstanceOf(GameAuthoredWorldSourceDeliveryRepository.DeliveryConflictException.class) + .hasMessageContaining("different World receipt"); + assertThat( + fixture + .deliveryRepository() + .read(source.operationId()) + .orElseThrow() + .acknowledgedReceipt()) + .contains(receipt); + } + + @Test + void databaseRejectsDeliverySourceRebindingAndReceiptMutation() { + Fixture fixture = fixture(null); + AuthoredWorldSourceEvidence source = fixture.registerFresh(44); + DeliveryClaim pending = fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("55555555-5555-4555-8555-555555555555"), 'c'); + DeliveryClaim acknowledged = + fixture + .transactionTemplate() + .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); + assertThat(acknowledged).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET source_evidence_digest = ? WHERE source_operation_id = ?", + digest('d'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("claim cannot be rebound"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET world_receipt_digest = ? WHERE source_operation_id = ?", + digest('e'), + source.operationId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("acknowledgement is immutable"); + assertThat(fixture.deliveryRepository().read(source.operationId()).orElseThrow()) + .isEqualTo(acknowledged); + } + + @Test + void committedAckWithLostLocalCommitAcknowledgementRecoversFromDurableRead() { + Fixture fixture = fixture(null); + AuthoredWorldSourceEvidence source = fixture.registerFresh(55); + DeliveryClaim pending = fixture.deliveryRepository().read(source.operationId()).orElseThrow(); + CommittedReceipt receipt = + committedReceipt(pending.request(), uuid("66666666-6666-4666-8666-666666666666"), 'f'); + WorldAuthoredSourceIntakeClient worldClient = mock(WorldAuthoredSourceIntakeClient.class); + when(worldClient.intake(pending.request())).thenReturn(receipt); + when(worldClient.read(any(WorldAuthoredSourceIntakeGrpcCodec.ReadRequest.class))) + .thenReturn(receipt); + CommitAfterCommitLosesAcknowledgementTransactionManager lostAckManager = + new CommitAfterCommitLosesAcknowledgementTransactionManager(fixture.dataSource()); + GameAuthoredWorldSourceDeliveryService service = + new GameAuthoredWorldSourceDeliveryService( + fixture.deliveryRepository(), worldClient, lostAckManager, NAMESPACE); + + DeliveryClaim recovered = service.deliver(source.operationId()); + DeliveryClaim retry = service.deliver(source.operationId()); + + assertThat(recovered.acknowledgedReceipt()).contains(receipt); + assertThat(retry).isEqualTo(recovered); + assertThat(fixture.deliveryRepository().read(source.operationId())).contains(recovered); + verify(worldClient).intake(pending.request()); + verify(worldClient).read(any(WorldAuthoredSourceIntakeGrpcCodec.ReadRequest.class)); + } + + @Test + void retainedSourceAndGameRowsRemainUnchangedAcrossV41WithoutDeliveryAssociation() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + Map retainedGameBefore = + gameSnapshot(fixture.dsl(), fixture.retainedGameRowId()); + UUID registrationRequestId = uuid("77777777-7777-4777-8777-777777777777"); + AuthoredWorldSourceEvidence retainedSource = + fixture.register( + registrationRequestId, + fixture.retainedCanonicalTenantId(), + "retained-tenant", + "old-coast", + "Retained Coast"); + Map retainedSourceBefore = + sourceSnapshot(fixture.dsl(), retainedSource.operationId()); + Map retainedBindingBefore = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding before V41 migration") + .intoMap(); + + fixture.migrate(null); + + assertThat(gameSnapshot(fixture.dsl(), fixture.retainedGameRowId())) + .isEqualTo(retainedGameBefore); + assertThat(sourceSnapshot(fixture.dsl(), retainedSource.operationId())) + .isEqualTo(retainedSourceBefore); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_tenant_slug_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + retainedSource.canonicalTenantId()), + "Expected retained tenant binding after V41 migration") + .intoMap()) + .isEqualTo(retainedBindingBefore); + assertThat( + fixture + .sourceRepository() + .read( + retainedSource.operationId(), + retainedSource.canonicalTenantId(), + retainedSource.worldSlug(), + retainedSource.targetNamespace())) + .contains(retainedSource); + assertThat(fixture.deliveryRepository().read(retainedSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + } + + @Test + void historicalFreshSourceRetryDoesNotBackfillMissingV41DeliveryClaim() { + Fixture fixture = fixture(PRE_DELIVERY_VERSION); + UUID registrationRequestId = uuid("88888888-8888-4888-8888-888888888888"); + String tenantSlug = "historic-tenant"; + String worldSlug = "historic-world"; + String displayName = "Historical Fresh World"; + AuthoredWorldSourceEvidence historicalSource = + seedPreDeliverySource( + fixture, + fixture.freshGame(), + registrationRequestId, + tenantSlug, + worldSlug, + displayName); + + fixture.migrate(null); + + AuthoredWorldSourceEvidence exactRetry = + fixture.register( + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + tenantSlug, + worldSlug, + displayName); + assertThat(exactRetry).isEqualTo(historicalSource); + assertThat(fixture.deliveryRepository().read(historicalSource.operationId())).isEmpty(); + assertThat(fixture.dsl().fetchCount(DELIVERIES)).isZero(); + + WorldAuthoredSourceIntakeClient worldClient = mock(WorldAuthoredSourceIntakeClient.class); + GameAuthoredWorldSourceDeliveryService service = + new GameAuthoredWorldSourceDeliveryService( + fixture.deliveryRepository(), worldClient, fixture.transactionManager(), NAMESPACE); + assertThatThrownBy(() -> service.deliver(historicalSource.operationId())) + .isInstanceOf(GameAuthoredWorldSourceDeliveryService.DeliveryNotFoundException.class); + verifyNoWorldCalls(worldClient); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "gd_source_delivery_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("29")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + Long retainedGameRowId = + legacyDsl + .insertInto(GAME) + .set(GAME_TENANT_ID, "retained-delivery-source") + .set(GAME_NAME, "Retained Delivery Source") + .set(GAME_DESCRIPTION, "Created before canonical tenant identity") + .returning(GAME_ID) + .fetchOne(GAME_ID); + assertThat(retainedGameRowId).isNotNull(); + migrate(dataSource, schema, target); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + GameAuthoredWorldSourceDeliveryRepository deliveryRepository = + new GameAuthoredWorldSourceDeliveryRepository(dsl); + GameAuthoredWorldSourceRepository sourceRepository = + new GameAuthoredWorldSourceRepository(dsl, deliveryRepository); + GameRepository gameRepository = new GameRepository(dsl); + UUID retainedCanonicalTenantId = + dsl.select(GAME_CANONICAL_TENANT_ID) + .from(GAME) + .where(GAME_ID.eq(retainedGameRowId)) + .fetchOne(GAME_CANONICAL_TENANT_ID); + Game freshGame = new Game(); + freshGame.setTenantId(UUID.randomUUID().toString()); + freshGame.setName("Fresh Delivery Source"); + freshGame.setDescription("Created through the current Game Design owner repository"); + Game persistedFreshGame = transactionTemplate.execute(status -> gameRepository.save(freshGame)); + assertThat(persistedFreshGame).isNotNull(); + return new Fixture( + schema, + dataSource, + dsl, + transactionManager, + transactionTemplate, + sourceRepository, + deliveryRepository, + retainedGameRowId, + retainedCanonicalTenantId, + persistedFreshGame); + } + + 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 static void migrate( + DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + Path gameDesignMigrations = + repositoryRoot().resolve("services/game-design-service/src/main/resources/db/migration"); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + gameDesignMigrations); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private static Path repositoryRoot() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + if (Files.exists(current.resolve("settings.gradle.kts"))) { + return current; + } + current = current.getParent(); + } + throw new IllegalStateException("Unable to locate repository migration sources"); + } + + private AuthoredWorldSourceEvidence seedPreDeliverySource( + Fixture fixture, + Game game, + UUID registrationRequestId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + UUID operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + game.getId(), + game.getTenantId(), + "NEW_GAME_ROW")); + + fixture + .transactionTemplate() + .execute( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, " + + "source_game_row_id, source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + fixture + .dsl() + .execute( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, " + + "registration_request_id, request_digest, canonical_tenant_id, " + + "tenant_slug, world_slug, world_display_name, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, evidence_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + source.operationId(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + return null; + }); + return source; + } + + private static CommittedReceipt committedReceipt( + IntakeRequest request, UUID worldOperationId, char receiptMarker) { + return new CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + worldOperationId, + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request), + digest(receiptMarker)); + } + + private static Map gameSnapshot(DSLContext dsl, long gameRowId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id, " + + "xmin::text AS xmin FROM game WHERE id = ?", + gameRowId), + "Expected game snapshot for row " + gameRowId) + .intoMap(); + } + + private static Map sourceSnapshot(DSLContext dsl, UUID operationId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT *, xmin::text AS xmin FROM game_design_authored_world_source_operations " + + "WHERE operation_id = ?", + operationId), + "Expected authored-world source snapshot for operation " + operationId) + .intoMap(); + } + + private static String digest(char marker) { + return "sha256:" + String.valueOf(marker).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent World intake delivery"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while awaiting concurrent delivery", exception); + } + } + + private static void verifyNoWorldCalls(WorldAuthoredSourceIntakeClient client) { + verify(client, never()).intake(any()); + verify(client, never()).read(any()); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactionTemplate, + GameAuthoredWorldSourceRepository sourceRepository, + GameAuthoredWorldSourceDeliveryRepository deliveryRepository, + long retainedGameRowId, + UUID retainedCanonicalTenantId, + Game freshGame) { + AuthoredWorldSourceEvidence registerFresh(int suffix) { + return register( + uuid(String.format("%08d-1111-4111-8111-111111111111", suffix)), + freshGame, + "fresh-tenant-" + suffix, + "fresh-world-" + suffix); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, Game sourceGame, String tenantSlug, String worldSlug) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + NAMESPACE, + registrationRequestId, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + "Authored World " + worldSlug)); + return java.util.Objects.requireNonNull(source); + } + + AuthoredWorldSourceEvidence register( + UUID registrationRequestId, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + AuthoredWorldSourceEvidence source = + transactionTemplate.execute( + status -> + sourceRepository.register( + NAMESPACE, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); + return java.util.Objects.requireNonNull(source); + } + + void migrate(MigrationVersion target) { + GameAuthoredWorldSourceDeliveryIntegrationTest.migrate(dataSource, schema, target); + } + } + + private static final class CommitAfterCommitLosesAcknowledgementTransactionManager + extends DataSourceTransactionManager { + private boolean loseNextAcknowledgement = true; + + CommitAfterCommitLosesAcknowledgementTransactionManager(DriverManagerDataSource dataSource) { + super(dataSource); + } + + @Override + protected void doCommit( + org.springframework.transaction.support.DefaultTransactionStatus status) { + super.doCommit(status); + if (loseNextAcknowledgement) { + loseNextAcknowledgement = false; + throw new IllegalStateException("simulated lost local commit acknowledgement"); + } + } + } +} 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 index 12e6feee34..6004e2c746 100644 --- 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 @@ -99,6 +99,10 @@ void readsCompletePersistedSourceAndCurrentVersionWithoutMutatingOwnerRows() { assertThat(first.request().canonicalTenantId().toString()) .isNotEqualTo(fixture.privateTenantKey()); assertThat(first.sourceEvidence()).isEqualTo(fixture.source()); + assertThat(first.canonicalVersionId()).isEqualTo(fixture.version().getCanonicalVersionId()); + assertThat(first.canonicalVersionId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(first.canonicalVersionId().toString()) + .isNotEqualTo(Long.toString(fixture.version().getId())); assertThat(first.versionState()) .isEqualTo( net.firedevops.firemud.gamedesign.v1.VersionLifecycleState @@ -113,6 +117,7 @@ void readsCompletePersistedSourceAndCurrentVersionWithoutMutatingOwnerRows() { AuthoredWorldVersionStateEvidence current = service.read(request(fixture, UUID.randomUUID())); assertThat(current.sourceEvidence()).isEqualTo(first.sourceEvidence()); + assertThat(current.canonicalVersionId()).isEqualTo(first.canonicalVersionId()); assertThat(current.versionState()) .isEqualTo( net.firedevops.firemud.gamedesign.v1.VersionLifecycleState 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 index 39c66b9539..906c1935d3 100644 --- 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 @@ -1,8 +1,14 @@ package integration.net.firedevops.firemud.gamedesign.service; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.grpc.Context; +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; @@ -24,15 +30,19 @@ import java.time.Instant; import java.util.Base64; import java.util.Date; +import java.util.LinkedHashMap; import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Supplier; 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.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; @@ -46,6 +56,11 @@ import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateService; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; import org.assertj.core.api.Assertions; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.BasicConstraints; @@ -59,6 +74,11 @@ import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.DataSourceConnectionProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -67,9 +87,13 @@ 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.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +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; @@ -79,11 +103,14 @@ * 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. + * transaction manager, standalone production handler, peer interceptor, physical World client, and + * World identity owner repositories are real. The World source intake is explicitly + * fixture-injected from the exact persisted Game Design source under the authenticated + * same-namespace caller context; this does not prove automatic delivery. The proof creates no World + * content or lifecycle rows and does not prove publication or activation. 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( @@ -104,10 +131,31 @@ class AuthoredWorldVersionStateMtlsIntegrationTest { private static final String NAMESPACE = "authored-version-state-mtls-test"; private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1L); + private static final java.util.List WORLD_CONTENT_AND_LIFECYCLE_TABLES = + java.util.List.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"); @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + @Container + static PostgreSQLContainer worldPostgres = new PostgreSQLContainer<>("postgres:16-alpine"); + private static TestPki pki; @DynamicPropertySource @@ -124,6 +172,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private org.jooq.DSLContext dsl; private Server server; + private final AtomicLong producerReadCalls = new AtomicLong(); @BeforeAll static void createEphemeralTestCertificates() throws Exception { @@ -156,6 +205,7 @@ static void createEphemeralTestCertificates() throws Exception { void startProductionHandlerOnPhysicalMutualTlsSocket() throws Exception { AuthoredWorldVersionStateGrpcService handler = new AuthoredWorldVersionStateGrpcService(versionStateService, NAMESPACE); + producerReadCalls.set(0L); server = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .sslContext( @@ -166,7 +216,24 @@ void startProductionHandlerOnPhysicalMutualTlsSocket() throws Exception { .trustManager(pki.caCertificate()) .clientAuth(ClientAuth.REQUIRE) .build()) - .addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())) + .addService( + ServerInterceptors.intercept( + handler, + new GrpcPeerIdentityInterceptor(), + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + if (call.getMethodDescriptor() + .getBareMethodName() + .equals("GetAuthoredWorldVersionState")) { + producerReadCalls.incrementAndGet(); + } + return next.startCall(call, headers); + } + })) .build() .start(); } @@ -197,10 +264,12 @@ void returnsCompletePersistedSourceAndVersionStateOverSocketWithoutMutation( AuthoredWorldVersionStateEvidence.create( request, fixture.source(), + fixture.version().getCanonicalVersionId(), net.firedevops.firemud.gamedesign.v1.VersionLifecycleState .VERSION_LIFECYCLE_STATE_DRAFT, 1L); assertThat(actual).isEqualTo(expected); + assertThat(actual.canonicalVersionId()).isEqualTo(fixture.version().getCanonicalVersionId()); assertThat(actual.request()).isEqualTo(request); assertThat(actual.sourceEvidence()).isEqualTo(fixture.source()); assertThat(actual.request().canonicalTenantId().toString()) @@ -280,6 +349,7 @@ void sameReadIdentityObservesFreshCommittedLifecycleAndEpochSnapshot(@TempDir Pa assertThat(first.request()).isEqualTo(sameRequest); assertThat(first.sourceEvidence()).isEqualTo(fixture.source()); + assertThat(first.canonicalVersionId()).isEqualTo(fixture.version().getCanonicalVersionId()); assertThat(first.versionState()) .isEqualTo( net.firedevops.firemud.gamedesign.v1.VersionLifecycleState @@ -287,6 +357,7 @@ void sameReadIdentityObservesFreshCommittedLifecycleAndEpochSnapshot(@TempDir Pa assertThat(first.versionStateEpoch()).isEqualTo(1L); assertThat(current.request()).isEqualTo(sameRequest); assertThat(current.sourceEvidence()).isEqualTo(first.sourceEvidence()); + assertThat(current.canonicalVersionId()).isEqualTo(first.canonicalVersionId()); assertThat(current.versionState()) .isEqualTo( net.firedevops.firemud.gamedesign.v1.VersionLifecycleState @@ -295,6 +366,289 @@ void sameReadIdentityObservesFreshCommittedLifecycleAndEpochSnapshot(@TempDir Pa assertThat(current.evidenceDigest()).isNotEqualTo(first.evidenceDigest()); } + @Test + void composesPersistedGameDesignVersionOverMtlsWithWorldIdentityReadbackAndExactRetry( + @TempDir Path directory) throws Exception { + Fixture fixture = fixture("world-version-identity-over-mtls"); + WorldFixture world = worldFixture(); + WorldAuthoredSourceIntakeReceipt intake = acceptWorldSourceIntake(world, fixture); + Map contentBefore = worldContentAndLifecycleCounts(world.dsl()); + assertThat(contentBefore.values()).containsOnly(0L); + assertThat(worldIdentityCount(world.dsl())).isZero(); + + UUID canonicalVersionId = fixture.version().getCanonicalVersionId(); + long gameDesignVersionId = fixture.version().getId(); + UUID initialReadRequestId = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request initialRequest = + request(fixture, initialReadRequestId); + AuthoredWorldVersionStateEvidence expectedOriginalEvidence = + AuthoredWorldVersionStateEvidence.create( + initialRequest, + fixture.source(), + canonicalVersionId, + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + + try (AuthoredWorldVersionStateClient client = newClient(directory)) { + client.init(); + WorldAuthoredVersionIdentityRepository identityRepository = + new WorldAuthoredVersionIdentityRepository(world.dsl()); + WorldAuthoredVersionIdentityService identityService = + new WorldAuthoredVersionIdentityService( + client, + identityRepository, + world.sourceRepository(), + world.transactionManager(), + NAMESPACE); + + WorldAuthoredVersionIdentityReceipt first = + associate(identityService, fixture, canonicalVersionId, initialReadRequestId); + + assertThat(producerReadCalls.get()).isEqualTo(1L); + assertThat(first.sourceIntakeReceipt()).isEqualTo(intake); + assertThat(first.sourceIntakeReceipt().source()).isEqualTo(fixture.source()); + assertThat(first.sourceIntakeReceipt().localTenantKey()).isPositive(); + assertThat(first.localVersionKey()).isPositive(); + assertThat(first.canonicalVersionId()).isEqualTo(canonicalVersionId); + assertThat(first.gameDesignVersionId()).isEqualTo(gameDesignVersionId); + assertThat(first.versionStateEvidence()).isEqualTo(expectedOriginalEvidence); + assertThat(first.versionStateEvidence().request()).isEqualTo(initialRequest); + assertThat(first.versionStateEvidence().sourceEvidence()).isEqualTo(fixture.source()); + assertThat(first.versionStateEvidence().versionStateEpoch()).isEqualTo(1L); + + Map beforeAdvance = rowVersions(fixture); + Version advanced = fixture.version(); + advanced.setVersionState(VersionLifecycleState.RETIRED); + advanced.setVersionStateEpoch(2L); + new TransactionTemplate(transactionManager) + .execute(status -> versionRepository.save(advanced)); + Map afterAdvance = rowVersions(fixture); + assertThat(afterAdvance).containsEntry("game", beforeAdvance.get("game")); + assertThat(afterAdvance).containsEntry("binding", beforeAdvance.get("binding")); + assertThat(afterAdvance).containsEntry("source", beforeAdvance.get("source")); + assertThat(afterAdvance.get("version")).isNotEqualTo(beforeAdvance.get("version")); + var advancedVersionRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT version_state, version_state_epoch FROM version WHERE id = ?", + gameDesignVersionId), + "Advanced Game Design Version row is missing"); + assertThat(advancedVersionRow.get("version_state", String.class)).isEqualTo("RETIRED"); + assertThat(advancedVersionRow.get("version_state_epoch", Long.class)).isEqualTo(2L); + + WorldAuthoredVersionIdentityReceipt retry = + associate(identityService, fixture, canonicalVersionId, UUID.randomUUID()); + assertThat(retry).isEqualTo(first); + assertThat(retry.versionStateEvidence()).isEqualTo(expectedOriginalEvidence); + assertThat(producerReadCalls.get()).isEqualTo(1L); + assertThat(rowVersions(fixture)).isEqualTo(afterAdvance); + + assertThat( + identityRepository.readByCanonicalVersion( + NAMESPACE, + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + canonicalVersionId)) + .contains(first); + assertThat( + identityRepository.readByGameDesignVersion( + NAMESPACE, + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + gameDesignVersionId)) + .contains(first); + assertThat(world.sourceRepository().read(NAMESPACE, intake.intakeRequestId())) + .contains(intake); + assertThat(worldIdentityCount(world.dsl())).isEqualTo(1L); + assertThat(worldContentAndLifecycleCounts(world.dsl()).values()).containsOnly(0L); + } + } + + @Test + void rejectsSubstitutedCanonicalVersionBeforeWorldIdentityPersistence(@TempDir Path directory) + throws Exception { + Fixture fixture = fixture("world-version-identity-substituted-uuid"); + WorldFixture world = worldFixture(); + WorldAuthoredSourceIntakeReceipt intake = acceptWorldSourceIntake(world, fixture); + Map contentBefore = worldContentAndLifecycleCounts(world.dsl()); + assertThat(contentBefore.values()).containsOnly(0L); + + UUID canonicalVersionId = fixture.version().getCanonicalVersionId(); + UUID substitutedCanonicalVersionId = UUID.randomUUID(); + assertThat(substitutedCanonicalVersionId).isNotEqualTo(canonicalVersionId); + long gameDesignVersionId = fixture.version().getId(); + WorldAuthoredVersionIdentityRepository identityRepository = + new WorldAuthoredVersionIdentityRepository(world.dsl()); + + try (AuthoredWorldVersionStateClient client = newClient(directory)) { + client.init(); + WorldAuthoredVersionIdentityService identityService = + new WorldAuthoredVersionIdentityService( + client, + identityRepository, + world.sourceRepository(), + world.transactionManager(), + NAMESPACE); + + assertThatThrownBy( + () -> + associate( + identityService, fixture, substitutedCanonicalVersionId, UUID.randomUUID())) + .isInstanceOf( + WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("expected UUID"); + + assertThat(producerReadCalls.get()).isEqualTo(1L); + assertThat(worldIdentityCount(world.dsl())).isZero(); + assertThat(world.sourceRepository().read(NAMESPACE, intake.intakeRequestId())) + .contains(intake); + assertThat(worldContentAndLifecycleCounts(world.dsl())).isEqualTo(contentBefore); + + WorldAuthoredVersionIdentityReceipt accepted = + associate(identityService, fixture, canonicalVersionId, UUID.randomUUID()); + assertThat(accepted.canonicalVersionId()).isEqualTo(canonicalVersionId); + assertThat(accepted.gameDesignVersionId()).isEqualTo(gameDesignVersionId); + assertThat(accepted.sourceIntakeReceipt()).isEqualTo(intake); + assertThat(accepted.versionStateEvidence().sourceEvidence()).isEqualTo(fixture.source()); + assertThat(producerReadCalls.get()).isEqualTo(2L); + assertThat(worldIdentityCount(world.dsl())).isEqualTo(1L); + assertThat( + identityRepository.readByCanonicalVersion( + NAMESPACE, + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + canonicalVersionId)) + .contains(accepted); + assertThat(world.sourceRepository().read(NAMESPACE, intake.intakeRequestId())) + .contains(intake); + assertThat(worldContentAndLifecycleCounts(world.dsl()).values()).containsOnly(0L); + } + } + + private WorldFixture worldFixture() throws Exception { + String schema = "world_identity_mtls_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(worldPostgres.getJdbcUrl()); + dataSource.setUsername(worldPostgres.getUsername()); + dataSource.setPassword(worldPostgres.getPassword()); + dataSource.setSchema(schema); + + Path repositoryRoot = repositoryRoot(); + Path worldMigrations = + repositoryRoot.resolve("services/world-management-service/src/main/resources/db/migration"); + Path sagaMigrations = + repositoryRoot.resolve("services/common-saga/src/main/resources/db/migration/saga"); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + worldMigrations, "filesystem:" + sagaMigrations) + .load() + .migrate(); + + DSLContext worldDsl = + DSL.using( + new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(dataSource)), + SQLDialect.POSTGRES); + PlatformTransactionManager worldTransactionManager = + new DataSourceTransactionManager(dataSource); + return new WorldFixture( + worldDsl, new WorldAuthoredSourceIntakeRepository(worldDsl), worldTransactionManager); + } + + private static Path repositoryRoot() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + if (Files.exists(current.resolve("settings.gradle.kts"))) { + return current; + } + current = current.getParent(); + } + throw new IllegalStateException("Unable to locate repository migration sources"); + } + + /** + * Persists the exact Game Design owner receipt as test-fixture World intake under the same + * authenticated caller context. This fixture injection is not automatic service delivery. + */ + private WorldAuthoredSourceIntakeReceipt acceptWorldSourceIntake( + WorldFixture world, Fixture gameDesignFixture) { + UUID intakeRequestId = UUID.randomUUID(); + TransactionTemplate ownerTransaction = new TransactionTemplate(world.transactionManager()); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + WorldAuthoredSourceIntakeReceipt accepted = + ownerTransaction.execute( + status -> + withGameDesign( + () -> + world + .sourceRepository() + .acceptFresh(NAMESPACE, intakeRequestId, gameDesignFixture.source()))); + assertThat(accepted).isNotNull(); + WorldAuthoredSourceIntakeReceipt independentReadback = + withGameDesign( + () -> + world + .sourceRepository() + .read(NAMESPACE, intakeRequestId) + .orElseThrow( + () -> new IllegalStateException("World source intake is missing"))); + assertThat(independentReadback).isEqualTo(accepted); + return independentReadback; + } + + private static WorldAuthoredVersionIdentityReceipt associate( + WorldAuthoredVersionIdentityService service, + Fixture fixture, + UUID expectedCanonicalVersionId, + UUID readRequestId) { + return withGameDesign( + () -> + service.associate( + NAMESPACE, + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.source().operationId(), + fixture.source().evidenceDigest(), + expectedCanonicalVersionId, + fixture.version().getId(), + readRequestId)); + } + + private static T withGameDesign(Supplier action) { + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service", + NAMESPACE, + "game-design-service"); + Context authenticated = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = authenticated.attach(); + try { + return action.get(); + } finally { + authenticated.detach(previous); + } + } + + private static long worldIdentityCount(DSLContext worldDsl) { + return Objects.requireNonNull( + worldDsl.fetchOne("SELECT COUNT(*) FROM world_authored_version_identity")) + .get(0, Long.class); + } + + private static Map worldContentAndLifecycleCounts(DSLContext worldDsl) { + Map counts = new LinkedHashMap<>(); + for (String table : WORLD_CONTENT_AND_LIFECYCLE_TABLES) { + counts.put( + table, + Objects.requireNonNull(worldDsl.fetchOne("SELECT COUNT(*) FROM " + table)) + .get(0, Long.class)); + } + return Map.copyOf(counts); + } + private AuthoredWorldVersionStateClient newClient(Path directory) throws Exception { Files.createDirectories(directory); Path caCertificate = @@ -493,6 +847,11 @@ private record Fixture( AuthoredWorldSourceEvidence source, Version version) {} + private record WorldFixture( + DSLContext dsl, + WorldAuthoredSourceIntakeRepository sourceRepository, + PlatformTransactionManager transactionManager) {} + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} private record TestPki( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java new file mode 100644 index 0000000000..d6f7f00c9e --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java @@ -0,0 +1,582 @@ +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.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +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.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameTemplate; +import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; +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.GameTemplateRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.Configuration; +import org.jooq.ExecuteContext; +import org.jooq.ExecuteListenerProvider; +import org.jooq.impl.DSL; +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.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** PostgreSQL proof for the immutable descriptor/release pair read from one owner snapshot. */ +@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=complete-launch-binding-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 CompleteLaunchBindingServiceIntegrationTest { + private static final String NAMESPACE = "complete-launch-binding-test"; + private static final org.jooq.Table VERSION_TABLE = 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 CompleteLaunchBindingService completeLaunchBindingService; + @Autowired private LaunchDescriptorService launchDescriptorService; + @Autowired private GameRepository gameRepository; + @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + @Autowired private GameTemplateRepository gameTemplateRepository; + @Autowired private VersionRepository versionRepository; + @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; + @Autowired private LaunchDescriptorRepository launchDescriptorRepository; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private org.jooq.DSLContext dsl; + @Autowired private ObjectMapper objectMapper; + + @Test + void returnsAndRetriesThePersistedCompletePairWithoutChangingOwnerRows() { + Fixture fixture = fixture("complete-pair", true); + Map before = rowVersions(fixture); + + CompleteLaunchBindingDto first = readComplete(fixture); + CompleteLaunchBindingDto retry = readComplete(fixture); + + assertThat(first).isEqualTo(retry); + assertThat(first.descriptor()).isEqualTo(fixture.descriptor().authoredWorldBinding()); + first.releaseAttestation().requireValid(first.descriptor()); + assertThat(first.releaseAttestation().canonicalTenantId()) + .isEqualTo(fixture.canonicalTenantId()); + assertThat(first.releaseAttestation().canonicalVersionId()) + .isEqualTo(fixture.version().getCanonicalVersionId()); + assertThat(first.releaseAttestation().versionStateEpoch()) + .isEqualTo(fixture.descriptor().versionStateEpoch()); + assertThat(fixture.descriptor().releaseBundleId()).isEqualTo(fixture.bundle().getId()); + assertThat(fixture.descriptor().publishedReleaseBundleRef()) + .isEqualTo(fixture.bundle().getPublishedReleaseBundleRef()); + assertThat(first.releaseAttestation().participantDigests()) + .extracting(AuthoredWorldReleaseAttestationEvidence.Participant::participantKey) + .containsExactlyElementsOf( + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()); + assertThat(first.releaseAttestation().artifactDigests()).hasSize(1); + + LaunchDescriptor persisted = persistedDescriptor(fixture); + assertThat(persisted.getLaunchDescriptorId()) + .isEqualTo(first.descriptor().launchDescriptorId()); + assertThat(persisted.getResultDigest()).isEqualTo(first.descriptor().resultDigest()); + assertThat(rowVersions(fixture)).isEqualTo(before); + } + + @Test + void retainsTheHistoricalAttestationWhenCurrentVersionStateAdvances() { + Fixture fixture = fixture("historical-epoch", true); + CompleteLaunchBindingDto original = readComplete(fixture); + Map immutableRowsBefore = immutableRowVersions(fixture); + + advanceVersion(fixture, VersionLifecycleState.RETIRED, 2L); + CompleteLaunchBindingDto later = readComplete(fixture); + + assertThat(later.descriptor()).isEqualTo(original.descriptor()); + assertThat(later.releaseAttestation()).isEqualTo(original.releaseAttestation()); + assertThat(later.releaseAttestation().versionStateEpoch()) + .isEqualTo(original.descriptor().versionStateEpoch()); + assertThat( + dsl.select(VERSION_STATE) + .from(VERSION_TABLE) + .where(VERSION_ID.eq(fixture.version().getId())) + .fetchOne(VERSION_STATE)) + .isEqualTo(VersionLifecycleState.RETIRED.name()); + assertThat( + dsl.select(VERSION_STATE_EPOCH) + .from(VERSION_TABLE) + .where(VERSION_ID.eq(fixture.version().getId())) + .fetchOne(VERSION_STATE_EPOCH)) + .isEqualTo(2L); + assertThat(immutableRowVersions(fixture)).isEqualTo(immutableRowsBefore); + // This is historical evidence equality, not a claim that RETIRED is currently launch-eligible. + } + + @Test + void deniesCrossTenantAndSubstitutedSourceSelectorsWithoutMutatingPersistedEvidence() { + Fixture first = fixture("cross-tenant-first", true); + Fixture second = fixture("cross-tenant-second", true); + Map firstBefore = rowVersions(first); + Map secondBefore = rowVersions(second); + UUID absentCanonicalTenant = UUID.randomUUID(); + + assertDenied( + () -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + second.canonicalTenantId(), + second.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); + assertDenied( + () -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + first.canonicalTenantId(), + second.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); + assertDenied( + () -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + absentCanonicalTenant, + first.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); + + PublishedReleaseBundle swappedCanonicalSource = new PublishedReleaseBundle(); + swappedCanonicalSource.setTenantId(first.privateTenantKey()); + swappedCanonicalSource.setVersionId(first.version().getId()); + swappedCanonicalSource.setCanonicalTenantId(second.canonicalTenantId()); + swappedCanonicalSource.setCanonicalVersionId(second.version().getCanonicalVersionId()); + assertThatThrownBy(() -> publishedReleaseBundleRepository.save(swappedCanonicalSource)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical release identity"); + + assertThat(rowVersions(first)).isEqualTo(firstBefore); + assertThat(rowVersions(second)).isEqualTo(secondBefore); + } + + @Test + void deniesPersistedDescriptorWhoseBundleLacksCompleteOwnerEvidenceWithoutMutation() { + Fixture fixture = fixture("missing-owner-evidence", false); + Map before = rowVersions(fixture); + + assertThatThrownBy(() -> readComplete(fixture)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("PARTICIPANT_EVIDENCE_INCOMPLETE"); + + assertThat(rowVersions(fixture)).isEqualTo(before); + } + + @Test + void descriptorSnapshotRejectsNonRepeatableReadBeforeAnyWrite() { + Fixture fixture = fixture("snapshot-guard", true); + Map before = rowVersions(fixture); + TransactionTemplate readCommitted = new TransactionTemplate(transactionManager); + readCommitted.setReadOnly(true); + readCommitted.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + assertThatThrownBy( + () -> + readCommitted.execute( + status -> + launchDescriptorService.getLaunchDescriptorInOwnerSnapshot( + fixture.readRequestId(), + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.controlPlaneRequestId(), + fixture.descriptor().authoredWorldBinding().requestDigest(), + fixture.descriptor().authoredWorldBinding().resultDigest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("read-only REPEATABLE_READ"); + + assertThat(rowVersions(fixture)).isEqualTo(before); + } + + @Test + void concurrentVersionAdvanceCannotSplitTheCompleteOwnerSnapshot() throws Exception { + Fixture fixture = fixture("concurrent-owner-snapshot", true); + Map immutableRowsBefore = immutableRowVersions(fixture); + CountDownLatch producerVersionReadCompleted = new CountDownLatch(1); + CountDownLatch continueRead = new CountDownLatch(1); + AtomicInteger versionStateSnapshotReads = new AtomicInteger(); + AtomicReference readOnlyObserved = new AtomicReference<>(false); + AtomicReference isolationObserved = new AtomicReference<>(); + DefaultExecuteListener interlock = + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && isVersionStateSnapshotQuery(sql) + && versionStateSnapshotReads.incrementAndGet() == 2) { + readOnlyObserved.set( + TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + isolationObserved.set( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()); + producerVersionReadCompleted.countDown(); + awaitInterlock(continueRead); + } + } + }; + Configuration configuration = dsl.configuration(); + ExecuteListenerProvider[] originalProviders = configuration.executeListenerProviders(); + List providers = new ArrayList<>(Arrays.asList(originalProviders)); + providers.add(new DefaultExecuteListenerProvider(interlock)); + configuration.set(providers.toArray(ExecuteListenerProvider[]::new)); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future inFlightRead = executor.submit(() -> readComplete(fixture)); + assertThat(producerVersionReadCompleted.await(10, TimeUnit.SECONDS)).isTrue(); + + advanceVersion(fixture, VersionLifecycleState.RETIRED, 2L); + continueRead.countDown(); + + CompleteLaunchBindingDto snapshot = inFlightRead.get(20, TimeUnit.SECONDS); + assertThat(readOnlyObserved.get()).isTrue(); + assertThat(isolationObserved.get()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(snapshot.descriptor()).isEqualTo(fixture.descriptor().authoredWorldBinding()); + assertThat(snapshot.releaseAttestation().versionStateEpoch()) + .isEqualTo(fixture.descriptor().versionStateEpoch()); + assertThat(snapshot.releaseAttestation()) + .isEqualTo(readComplete(fixture).releaseAttestation()); + assertThat(immutableRowVersions(fixture)).isEqualTo(immutableRowsBefore); + assertThat( + dsl.select(VERSION_STATE_EPOCH) + .from(VERSION_TABLE) + .where(VERSION_ID.eq(fixture.version().getId())) + .fetchOne(VERSION_STATE_EPOCH)) + .isEqualTo(2L); + } finally { + continueRead.countDown(); + executor.shutdownNow(); + executor.awaitTermination(5, TimeUnit.SECONDS); + configuration.set(originalProviders); + } + } + + private boolean isVersionStateSnapshotQuery(String sql) { + String compact = sql.toLowerCase(Locale.ROOT).replace("\"", "").replaceAll("\\s+", ""); + return compact.contains( + "selectid,tenant_id,canonical_version_id,canonical_tenant_id," + + "identity_source_game_row_id,identity_source_game_tenant_key," + + "identity_source_provenance_kind,version_state,version_state_epoch" + + "fromversionwhereid=?"); + } + + private Fixture fixture(String label, boolean completeEvidence) { + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + String privateTenantKey = "gd-" + UUID.randomUUID().toString().replace("-", ""); + assertThat(privateTenantKey).matches("gd-[0-9a-f]{32}").hasSize(35); + Game game = new Game(); + game.setTenantId(privateTenantKey); + game.setName("Complete binding source " + label + " " + suffix); + game.setDescription("Fresh persisted Game provenance for complete-binding proof"); + Game persistedGame = gameRepository.save(game); + assertThat(privateTenantKey).isNotEqualTo(persistedGame.getCanonicalTenantId().toString()); + + AuthoredWorldSourceEvidence source = + new TransactionTemplate(transactionManager) + .execute( + status -> + authoredWorldSourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Synthetic Complete Binding World")); + + Version version = new Version(); + version.setTenantId(privateTenantKey); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(1L); + version.setNotes("synthetic complete-release evidence fixture"); + version.setUpdatedAt(LocalDateTime.now()); + version = versionRepository.save(version); + + GameTemplate template = new GameTemplate(); + template.setTenantId(privateTenantKey); + template.setName("Complete Binding Template " + suffix); + template.setDescription("Persisted launch descriptor fixture"); + template.setConfig("{}"); + template.setDefaultVersionId(version.getId()); + template.setDefaultRuntimeFlagsJson("{}"); + template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); + template = gameTemplateRepository.save(template); + + PublishedReleaseBundle bundle = + syntheticBundle(privateTenantKey, version, suffix, completeEvidence); + PublishedReleaseBundle persistedBundle = publishedReleaseBundleRepository.save(bundle); + String controlPlaneRequestId = "complete-launch-" + suffix; + UUID readRequestId = UUID.randomUUID(); + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + persistedGame.getCanonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + template.getId(), + false, + null, + false, + null, + false, + null, + false, + null); + ResolvedLaunchDescriptorDto descriptor = + launchDescriptorService.resolveLaunchDescriptor(request); + LaunchDescriptor storedDescriptor = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, persistedGame.getCanonicalTenantId(), controlPlaneRequestId) + .orElseThrow(); + + return new Fixture( + readRequestId, + controlPlaneRequestId, + persistedGame.getId(), + persistedGame.getCanonicalTenantId(), + privateTenantKey, + source, + version, + template, + persistedBundle, + descriptor, + storedDescriptor); + } + + private PublishedReleaseBundle syntheticBundle( + String privateTenantKey, Version version, String suffix, boolean completeEvidence) { + // Synthetic fixture bytes produce real content-addressed hashes; this is not a claim that + // Game Logic or external object storage performed a normal publication in this test. + byte[] artifactBytes = + ("synthetic complete-binding artifact " + suffix).getBytes(StandardCharsets.UTF_8); + String artifactHex = sha256Hex(artifactBytes); + String artifactDigest = "sha256:" + artifactHex; + String manifestBytes = + "{\"schemaVersion\":1,\"assets\":[{\"usageKey\":\"world.navmesh\",\"contentDigest\":\"" + + artifactDigest + + "\"}]}"; + String manifestHash = "sha256:" + sha256Hex(manifestBytes.getBytes(StandardCharsets.UTF_8)); + PublishedArtifactDigest artifact = + new PublishedArtifactDigest( + "world.navmesh", + "world-navmesh", + "artifacts/sha256/" + artifactHex, + artifactDigest, + "application/octet-stream", + 1); + + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(privateTenantKey); + bundle.setVersionId(version.getId()); + bundle.setVersionNumber(version.getVersionNumber()); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId("synthetic-publish-workflow:" + suffix); + bundle.setManifestHash(manifestHash); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson(objectMapper.writeValueAsString(List.of(artifact))); + bundle.setGenerationConfigRevision("generation-config:" + suffix + ":" + "g".repeat(180)); + bundle.setRequiredManifestAssetKeysJson( + objectMapper.writeValueAsString(List.of("world.navmesh"))); + bundle.setParticipantDigestsJson( + objectMapper.writeValueAsString( + completeEvidence ? syntheticParticipants(version) : List.of())); + bundle.setCommandDefinitionsJson( + objectMapper.writeValueAsString(List.of("{\"commandId\":\"look\"}"))); + bundle.setScriptOnly(false); + return bundle; + } + + private List syntheticParticipants(Version version) { + List participants = new ArrayList<>(); + for (String participantKey : + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()) { + boolean gameLogic = "GAME_LOGIC".equals(participantKey); + participants.add( + new PublishParticipantDigestDto( + participantKey, + Long.toString(version.getId()), + null, + "synthetic-applied-commit-" + version.getId(), + "a".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey), + gameLogic ? "sha256:" + "b".repeat(64) : null, + null, + null)); + } + return List.copyOf(participants); + } + + private CompleteLaunchBindingDto readComplete(Fixture fixture) { + AuthoredWorldLaunchDescriptorEvidence descriptor = fixture.descriptor().authoredWorldBinding(); + return completeLaunchBindingService.getCompleteLaunchBinding( + fixture.readRequestId(), + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.controlPlaneRequestId(), + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + private void advanceVersion(Fixture fixture, VersionLifecycleState state, long epoch) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.execute( + status -> { + Version current = + versionRepository + .findByTenantIdAndId(fixture.privateTenantKey(), fixture.version().getId()) + .orElseThrow(); + current.setVersionState(state); + current.setVersionStateEpoch(epoch); + return versionRepository.save(current); + }); + } + + private Map rowVersions(Fixture fixture) { + Map snapshot = immutableRowVersions(fixture); + snapshot.put("version", rowXmin("version", "id", fixture.version().getId())); + return snapshot; + } + + private Map immutableRowVersions(Fixture fixture) { + Map snapshot = new LinkedHashMap<>(); + snapshot.put("game", rowXmin("game", "id", fixture.gameRowId())); + snapshot.put( + "source", + rowXmin( + "game_design_authored_world_source_operations", + "operation_id", + fixture.source().operationId())); + snapshot.put("template", rowXmin("game_templates", "id", fixture.template().getId())); + snapshot.put("bundle", rowXmin("published_release_bundle", "id", fixture.bundle().getId())); + snapshot.put( + "descriptor", rowXmin("launch_descriptor", "id", fixture.storedDescriptor().getId())); + return snapshot; + } + + private String rowXmin(String table, String idColumn, Object id) { + var row = dsl.fetchOne("SELECT xmin::text FROM " + table + " WHERE " + idColumn + " = ?", id); + return row == null ? "" : row.get(0, String.class); + } + + private LaunchDescriptor persistedDescriptor(Fixture fixture) { + return launchDescriptorRepository + .findBoundByRequest(NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + } + + private void assertDenied(Runnable operation) { + assertThatThrownBy(operation::run).isInstanceOf(IllegalArgumentException.class); + } + + private void awaitInterlock(CountDownLatch continueRead) { + try { + if (!continueRead.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to resume complete-binding snapshot"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while holding complete-binding snapshot", exception); + } + } + + private static String sha256Hex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is required by the JDK", impossible); + } + } + + private record Fixture( + UUID readRequestId, + String controlPlaneRequestId, + long gameRowId, + UUID canonicalTenantId, + String privateTenantKey, + AuthoredWorldSourceEvidence source, + Version version, + GameTemplate template, + PublishedReleaseBundle bundle, + ResolvedLaunchDescriptorDto descriptor, + LaunchDescriptor storedDescriptor) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/GameAuthoredWorldSourceDeliveryMtlsIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/GameAuthoredWorldSourceDeliveryMtlsIntegrationTest.java new file mode 100644 index 0000000000..476953d275 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/GameAuthoredWorldSourceDeliveryMtlsIntegrationTest.java @@ -0,0 +1,826 @@ +package integration.net.firedevops.firemud.gamedesign.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.ForwardingServerCall; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.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.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.service.impl.GameAuthoredWorldSourceDeliveryService; +import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +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.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.DataSourceConnectionProvider; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +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.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +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.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL-to-physical-mTLS proof of durable fresh Game Design source delivery to World. + * + *

The Game Design source and delivery repositories, Game Design source handler, World source + * client, World intake service/repository/handler, delivery service, and both transaction managers + * are real. Ephemeral file-backed workload certificates protect both physical service directions. + * The Game row is a synthetic persisted source fixture; this does not exercise a public creator, + * content materialization, release publication, lifecycle wiring, or runtime activation. + */ +@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-source-delivery-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 GameAuthoredWorldSourceDeliveryMtlsIntegrationTest { + private static final String NAMESPACE = "authored-source-delivery-mtls-test"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1L); + private static TestPki pki; + + @Container + static PostgreSQLContainer gameDesignPostgres = + new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static PostgreSQLContainer worldPostgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @TempDir Path temporaryDirectory; + + @Autowired private GameRepository gameRepository; + @Autowired private GameAuthoredWorldSourceRepository sourceRepository; + @Autowired private TenantIdentityGrpcService sourceHandler; + @Autowired private PlatformTransactionManager gameDesignTransactionManager; + @Autowired private DSLContext gameDesignDsl; + + private final List servers = new ArrayList<>(); + private final List sourceClients = new ArrayList<>(); + private final List intakeClients = new ArrayList<>(); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, gameDesignPostgres, "game_design_service"); + } + + @BeforeAll + static void createEphemeralWorkloadCertificates() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = + new X500Name("CN=Authored Source Delivery Integration Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null); + pki = + new TestPki( + caCertificate, + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-server", + workloadUri("game-design-service"), + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "world-management-server", + workloadUri("world-management-service"), + true), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-design-service", + workloadUri("game-design-service"), + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "world-management-service", + workloadUri("world-management-service"), + false), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "account-service", + workloadUri("account-service"), + false)); + } + + @AfterEach + void closePhysicalClientsAndServers() throws Exception { + for (WorldAuthoredSourceIntakeClient client : intakeClients) { + client.close(); + } + intakeClients.clear(); + for (AuthoredWorldSourceClient client : sourceClients) { + client.close(); + } + sourceClients.clear(); + for (Server server : servers) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + servers.clear(); + } + + @Test + void deliversPersistedFreshSourceAndCompletedRestartRetryReturnsOriginalReceipt() + throws Exception { + Composition composition = compose(pki.gameDesignClient(), new AtomicBoolean(false)); + AuthoredWorldSourceEvidence source = composition.fixture().source(); + DeliveryClaim originalClaim = pendingClaim(composition, source); + + AuthoredWorldSourceEvidence exactRegistrationRetry = registerAgain(composition.fixture()); + DeliveryClaim claimAfterRegistrationRetry = + composition.deliveryRepository().read(source.operationId()).orElseThrow(); + assertThat(exactRegistrationRetry).isEqualTo(source); + assertThat(claimAfterRegistrationRetry).isEqualTo(originalClaim); + assertThat(claimAfterRegistrationRetry.request().intakeRequestId()) + .isNotEqualTo(source.operationId()); + assertThat(worldCounts(composition.world(), source)).isEqualTo(new WorldCounts(0, 0, 0)); + + DeliveryClaim delivered = composition.deliveryService().deliver(source.operationId()); + DeliveryClaim durableClaim = + composition.deliveryRepository().read(source.operationId()).orElseThrow(); + WorldAuthoredSourceIntakeReceipt worldReceipt = + composition + .world() + .sourceRepository() + .read(NAMESPACE, originalClaim.request().intakeRequestId()) + .orElseThrow(); + + assertThat(source.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(delivered).isEqualTo(durableClaim); + assertThat(durableClaim.source()).isEqualTo(source); + assertThat(durableClaim.request()).isEqualTo(originalClaim.request()); + assertThat(durableClaim.acknowledgedReceipt()).contains(publicReceipt(worldReceipt)); + assertThat(worldReceipt.source()).isEqualTo(source); + assertThat(worldReceipt.canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(worldReceipt.worldSlug()).isEqualTo(source.worldSlug()); + assertThat(worldReceipt.intakeRequestId()).isEqualTo(originalClaim.request().intakeRequestId()); + assertThat(worldCounts(composition.world(), source)).isEqualTo(new WorldCounts(1, 1, 1)); + assertThat(composition.worldIntakeCalls().get()).isEqualTo(1); + assertThat(composition.worldReadCalls().get()).isEqualTo(1); + assertThat(composition.gameDesignSourceReadCalls().get()).isEqualTo(1); + + WorldAuthoredSourceIntakeClient restartedClient = + newIntakeClient(composition.worldServer(), pki.gameDesignClient(), "completed-restart"); + GameAuthoredWorldSourceDeliveryService restartedService = + new GameAuthoredWorldSourceDeliveryService( + composition.deliveryRepository(), + restartedClient, + gameDesignTransactionManager, + NAMESPACE); + assertThat(restartedService.deliver(source.operationId())).isEqualTo(durableClaim); + assertThat(composition.worldIntakeCalls().get()).isEqualTo(1); + assertThat(composition.worldReadCalls().get()).isEqualTo(1); + assertThat(composition.gameDesignSourceReadCalls().get()).isEqualTo(1); + assertThat(worldCounts(composition.world(), source)).isEqualTo(new WorldCounts(1, 1, 1)); + } + + @Test + void lostWorldResponseLeavesPendingIntentAndExactRetryRecoversCommittedOwnerReceipt() + throws Exception { + Composition composition = compose(pki.gameDesignClient(), new AtomicBoolean(true)); + AuthoredWorldSourceEvidence source = composition.fixture().source(); + DeliveryClaim originalClaim = pendingClaim(composition, source); + + assertThatThrownBy(() -> composition.deliveryService().deliver(source.operationId())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + + DeliveryClaim afterLostResponse = + composition.deliveryRepository().read(source.operationId()).orElseThrow(); + WorldAuthoredSourceIntakeReceipt committedWorldReceipt = + composition + .world() + .sourceRepository() + .read(NAMESPACE, originalClaim.request().intakeRequestId()) + .orElseThrow(); + assertThat(afterLostResponse.source()).isEqualTo(source); + assertThat(afterLostResponse.request()).isEqualTo(originalClaim.request()); + assertThat(afterLostResponse.acknowledgedReceipt()).isEmpty(); + assertThat(committedWorldReceipt.source()).isEqualTo(source); + assertThat(committedWorldReceipt.intakeRequestId()) + .isEqualTo(originalClaim.request().intakeRequestId()); + assertThat(worldCounts(composition.world(), source)).isEqualTo(new WorldCounts(1, 1, 1)); + assertThat(composition.worldIntakeCalls().get()).isEqualTo(1); + assertThat(composition.worldReadCalls().get()).isZero(); + assertThat(composition.gameDesignSourceReadCalls().get()).isEqualTo(1); + + assertThat(registerAgain(composition.fixture())).isEqualTo(source); + DeliveryClaim afterExactRegistrationRetry = + composition.deliveryRepository().read(source.operationId()).orElseThrow(); + assertThat(afterExactRegistrationRetry.request()).isEqualTo(originalClaim.request()); + assertThat(afterExactRegistrationRetry.acknowledgedReceipt()).isEmpty(); + + WorldAuthoredSourceIntakeClient restartedClient = + newIntakeClient(composition.worldServer(), pki.gameDesignClient(), "lost-response-retry"); + GameAuthoredWorldSourceDeliveryService restartedService = + new GameAuthoredWorldSourceDeliveryService( + composition.deliveryRepository(), + restartedClient, + gameDesignTransactionManager, + NAMESPACE); + DeliveryClaim recovered = restartedService.deliver(source.operationId()); + WorldAuthoredSourceIntakeReceipt durableWorldReceipt = + composition + .world() + .sourceRepository() + .read(NAMESPACE, originalClaim.request().intakeRequestId()) + .orElseThrow(); + + assertThat(recovered.request()).isEqualTo(originalClaim.request()); + assertThat(recovered.acknowledgedReceipt()).contains(publicReceipt(committedWorldReceipt)); + assertThat(durableWorldReceipt).isEqualTo(committedWorldReceipt); + assertThat(worldCounts(composition.world(), source)).isEqualTo(new WorldCounts(1, 1, 1)); + assertThat(composition.worldIntakeCalls().get()).isEqualTo(2); + assertThat(composition.worldReadCalls().get()).isEqualTo(1); + assertThat(composition.gameDesignSourceReadCalls().get()).isEqualTo(1); + } + + @Test + void wrongAuthenticatedWorldCallerCannotCreateOwnerRowsOrAcknowledgeDelivery() throws Exception { + Composition composition = compose(pki.accountClient(), new AtomicBoolean(false)); + AuthoredWorldSourceEvidence source = composition.fixture().source(); + DeliveryClaim originalClaim = pendingClaim(composition, source); + + assertThatThrownBy(() -> composition.deliveryService().deliver(source.operationId())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + DeliveryClaim afterDeniedCaller = + composition.deliveryRepository().read(source.operationId()).orElseThrow(); + assertThat(afterDeniedCaller.source()).isEqualTo(source); + assertThat(afterDeniedCaller.request()).isEqualTo(originalClaim.request()); + assertThat(afterDeniedCaller.acknowledgedReceipt()).isEmpty(); + assertThat(worldCounts(composition.world(), source)).isEqualTo(new WorldCounts(0, 0, 0)); + assertThat(composition.worldIntakeCalls().get()).isEqualTo(1); + assertThat(composition.worldReadCalls().get()).isZero(); + assertThat(composition.gameDesignSourceReadCalls().get()).isZero(); + } + + private Composition compose(TestCertificate deliveryCaller, AtomicBoolean dropFirstIntakeReply) + throws Exception { + AuthoredSourceFixture fixture = createPersistedSource(); + WorldFixture world = worldFixture(); + AtomicInteger gameDesignSourceReadCalls = new AtomicInteger(); + Server gameDesignServer = startGameDesignSourceServer(gameDesignSourceReadCalls); + + AuthoredWorldSourceClient worldToGameDesignClient = + new AuthoredWorldSourceClient( + gameDesignEndpoints(gameDesignServer), + tlsProperties(pki.worldManagementClient(), "world-to-game-design"), + new GrpcChannelFactory(), + NAMESPACE); + worldToGameDesignClient.init(); + sourceClients.add(worldToGameDesignClient); + + AtomicInteger worldIntakeCalls = new AtomicInteger(); + AtomicInteger worldReadCalls = new AtomicInteger(); + WorldAuthoredSourceIntakeService worldOwner = + new WorldAuthoredSourceIntakeService( + worldToGameDesignClient, + world.sourceRepository(), + world.transactionManager(), + NAMESPACE); + WorldAuthoredSourceIntakeGrpcService worldHandler = + new WorldAuthoredSourceIntakeGrpcService(worldOwner, NAMESPACE); + Server worldServer = + startWorldServer(worldHandler, worldIntakeCalls, worldReadCalls, dropFirstIntakeReply); + WorldAuthoredSourceIntakeClient gameDesignToWorldClient = + newIntakeClient(worldServer, deliveryCaller, "game-design-to-world"); + GameAuthoredWorldSourceDeliveryRepository deliveryRepository = + new GameAuthoredWorldSourceDeliveryRepository(gameDesignDsl); + GameAuthoredWorldSourceDeliveryService deliveryService = + new GameAuthoredWorldSourceDeliveryService( + deliveryRepository, gameDesignToWorldClient, gameDesignTransactionManager, NAMESPACE); + return new Composition( + fixture, + world, + worldServer, + deliveryRepository, + deliveryService, + gameDesignSourceReadCalls, + worldIntakeCalls, + worldReadCalls); + } + + private Server startGameDesignSourceServer(AtomicInteger sourceReadCalls) throws Exception { + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(serverTlsContext(pki.gameDesignServer())) + .addService( + ServerInterceptors.intercept( + sourceHandler, + new GrpcPeerIdentityInterceptor(), + countingMethod("ResolveAuthoredWorldSource", sourceReadCalls, null, null))) + .build() + .start(); + servers.add(server); + return server; + } + + private Server startWorldServer( + WorldAuthoredSourceIntakeGrpcService handler, + AtomicInteger intakeCalls, + AtomicInteger readCalls, + AtomicBoolean dropFirstIntakeReply) + throws Exception { + var authenticated = ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor()); + var observed = + ServerInterceptors.intercept( + authenticated, + countingMethod( + "IntakeAuthoredWorldSource", intakeCalls, readCalls, dropFirstIntakeReply)); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(serverTlsContext(pki.worldManagementServer())) + .addService(observed) + .build() + .start(); + servers.add(server); + return server; + } + + private static ServerInterceptor countingMethod( + String intakeMethod, + AtomicInteger intakeCalls, + AtomicInteger readCalls, + AtomicBoolean dropFirstIntakeReply) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + String method = call.getMethodDescriptor().getBareMethodName(); + if (intakeCalls != null && method.equals(intakeMethod)) { + intakeCalls.incrementAndGet(); + } else if (readCalls != null && method.equals("ReadAuthoredWorldSourceIntake")) { + readCalls.incrementAndGet(); + } + ServerCall observedCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + private boolean droppedCommittedIntakeReply; + + @Override + public void sendMessage(ResponseT message) { + if (message instanceof IntakeAuthoredWorldSourceResponse + && dropFirstIntakeReply != null + && dropFirstIntakeReply.compareAndSet(true, false)) { + droppedCommittedIntakeReply = true; + return; + } + super.sendMessage(message); + } + + @Override + public void close(Status status, Metadata trailers) { + if (droppedCommittedIntakeReply && status.isOk()) { + super.close( + Status.UNAVAILABLE.withDescription( + "Test deliberately lost a committed World intake acknowledgement"), + trailers); + return; + } + super.close(status, trailers); + } + }; + return next.startCall(observedCall, headers); + } + }; + } + + private WorldAuthoredSourceIntakeClient newIntakeClient( + Server server, TestCertificate certificate, String label) throws Exception { + WorldAuthoredSourceIntakeClient client = + new WorldAuthoredSourceIntakeClient( + worldEndpoints(server), + tlsProperties(certificate, label), + new GrpcChannelFactory(), + NAMESPACE); + client.init(); + intakeClients.add(client); + return client; + } + + private AuthoredSourceFixture createPersistedSource() { + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + String privateTenantKey = "delivery-source-" + suffix; + Game game = new Game(); + game.setTenantId(privateTenantKey); + game.setName("Synthetic authored source delivery " + suffix); + game.setDescription("Persisted source fixture for PostgreSQL and workload-mTLS composition"); + Game persistedGame = + new TransactionTemplate(gameDesignTransactionManager) + .execute(status -> gameRepository.save(game)); + assertThat(persistedGame).isNotNull(); + + UUID registrationRequestId = UUID.randomUUID(); + String tenantSlug = "tenant-" + suffix; + String worldSlug = "world-" + suffix; + String worldDisplayName = "Delivery World " + suffix; + AuthoredWorldSourceEvidence source = + new TransactionTemplate(gameDesignTransactionManager) + .execute( + status -> + sourceRepository.register( + NAMESPACE, + registrationRequestId, + persistedGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName)); + assertThat(source).isNotNull(); + assertThat(source.provenanceKind()).isEqualTo("NEW_GAME_ROW"); + return new AuthoredSourceFixture( + persistedGame.getCanonicalTenantId(), + registrationRequestId, + tenantSlug, + worldSlug, + worldDisplayName, + source); + } + + private AuthoredWorldSourceEvidence registerAgain(AuthoredSourceFixture fixture) { + AuthoredWorldSourceEvidence source = fixture.source(); + AuthoredWorldSourceEvidence retry = + new TransactionTemplate(gameDesignTransactionManager) + .execute( + status -> + sourceRepository.register( + NAMESPACE, + fixture.registrationRequestId(), + fixture.canonicalTenantId(), + fixture.tenantSlug(), + fixture.worldSlug(), + fixture.worldDisplayName())); + assertThat(retry).isEqualTo(source); + return retry; + } + + private DeliveryClaim pendingClaim(Composition composition, AuthoredWorldSourceEvidence source) { + DeliveryClaim claim = composition.deliveryRepository().read(source.operationId()).orElseThrow(); + assertThat(claim.source()).isEqualTo(source); + assertThat(claim.acknowledgedReceipt()).isEmpty(); + assertThat(claim.request().targetNamespace()).isEqualTo(NAMESPACE); + assertThat(claim.request().canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(claim.request().worldSlug()).isEqualTo(source.worldSlug()); + assertThat(claim.request().sourceOperationId()).isEqualTo(source.operationId()); + assertThat(claim.request().expectedSourceEvidenceDigest()).isEqualTo(source.evidenceDigest()); + return claim; + } + + private WorldFixture worldFixture() throws Exception { + String schema = "world_source_delivery_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(worldPostgres.getJdbcUrl()); + dataSource.setUsername(worldPostgres.getUsername()); + dataSource.setPassword(worldPostgres.getPassword()); + dataSource.setSchema(schema); + + Path repositoryRoot = repositoryRoot(); + Path worldMigrations = + repositoryRoot.resolve("services/world-management-service/src/main/resources/db/migration"); + Path sagaMigrations = + repositoryRoot.resolve("services/common-saga/src/main/resources/db/migration/saga"); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + worldMigrations, "filesystem:" + sagaMigrations) + .load() + .migrate(); + + DSLContext worldDsl = + DSL.using( + new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(dataSource)), + SQLDialect.POSTGRES); + PlatformTransactionManager worldTransactionManager = + new DataSourceTransactionManager(dataSource); + return new WorldFixture( + worldDsl, new WorldAuthoredSourceIntakeRepository(worldDsl), worldTransactionManager); + } + + private static Path repositoryRoot() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + if (Files.exists(current.resolve("settings.gradle.kts"))) { + return current; + } + current = current.getParent(); + } + throw new IllegalStateException("Unable to locate repository migration sources"); + } + + private static WorldCounts worldCounts(WorldFixture world, AuthoredWorldSourceEvidence source) { + return new WorldCounts( + count( + world.dsl(), + "SELECT COUNT(*) FROM world_authored_source_intake " + + "WHERE target_namespace = ? AND source_operation_id = ?", + NAMESPACE, + source.operationId()), + count( + world.dsl(), + "SELECT COUNT(*) FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + source.canonicalTenantId()), + count( + world.dsl(), + "SELECT COUNT(*) FROM world_authored_source_tenant_key_reservation " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND claim_kind = 'CANONICAL_AUTHORED_SOURCE'", + NAMESPACE, + source.canonicalTenantId())); + } + + private static long count(DSLContext dsl, String query, Object... bindings) { + return Objects.requireNonNull(dsl.fetchOne(query, bindings), "Count query returned no row") + .get(0, Long.class); + } + + private static CommittedReceipt publicReceipt(WorldAuthoredSourceIntakeReceipt receipt) { + return new CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest()); + } + + private ServiceEndpointsProperties gameDesignEndpoints(Server server) { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + server.getPort()); + return endpoints; + } + + private ServiceEndpointsProperties worldEndpoints(Server server) { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + server.getPort()); + return endpoints; + } + + private CommonGrpcClientProperties tlsProperties(TestCertificate certificate, String label) + throws Exception { + Path clientCertificate = temporaryDirectory.resolve(label + "-client.crt"); + Path clientPrivateKey = temporaryDirectory.resolve(label + "-client.key"); + Path caCertificate = temporaryDirectory.resolve("test-ca.crt"); + Files.writeString( + clientCertificate, pem("CERTIFICATE", certificate.certificate().getEncoded())); + Files.writeString(clientPrivateKey, pem("PRIVATE KEY", certificate.privateKey().getEncoded())); + Files.writeString(caCertificate, pem("CERTIFICATE", pki.caCertificate().getEncoded())); + + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(clientCertificate.toString()); + tls.setPrivateKey(clientPrivateKey.toString()); + tls.setCaCert(caCertificate.toString()); + return tls; + } + + private static io.grpc.netty.shaded.io.netty.handler.ssl.SslContext serverTlsContext( + TestCertificate certificate) throws Exception { + return GrpcSslContexts.configure( + SslContextBuilder.forServer(certificate.privateKey(), certificate.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build(); + } + + private static String workloadUri(String service) { + return "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service; + } + + private static String pem(String type, byte[] encoded) { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + return "-----BEGIN " + type + "-----\n" + body + "\n-----END " + type + "-----\n"; + } + + 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") + }); + return new TestCertificate( + keyPair.getPrivate(), + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + subjectAltNames, + serverCertificate)); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + return issueCertificate( + subject, publicKey, issuer, issuerPrivateKey, ca, subjectAltNames, false); + } + + 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 AuthoredSourceFixture( + UUID canonicalTenantId, + UUID registrationRequestId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + AuthoredWorldSourceEvidence source) {} + + private record WorldFixture( + DSLContext dsl, + WorldAuthoredSourceIntakeRepository sourceRepository, + PlatformTransactionManager transactionManager) {} + + private record Composition( + AuthoredSourceFixture fixture, + WorldFixture world, + Server worldServer, + GameAuthoredWorldSourceDeliveryRepository deliveryRepository, + GameAuthoredWorldSourceDeliveryService deliveryService, + AtomicInteger gameDesignSourceReadCalls, + AtomicInteger worldIntakeCalls, + AtomicInteger worldReadCalls) {} + + private record WorldCounts(long intakes, long tenantAssociations, long reservations) {} + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate gameDesignServer, + TestCertificate worldManagementServer, + TestCertificate gameDesignClient, + TestCertificate worldManagementClient, + TestCertificate accountClient) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index a8f4028f3e..8862c7874a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -12,6 +12,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; @@ -635,16 +636,14 @@ void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfil assertThat(persistedGame).isNotNull(); String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); AuthoredWorldSourceEvidence source = - isolatedTransaction.execute( - status -> - new GameAuthoredWorldSourceRepository(isolatedDsl) - .register( - NAMESPACE, - UUID.randomUUID(), - persistedGame.getCanonicalTenantId(), - "tenant-" + suffix, - "world-" + suffix, - "Retained World 🐉")); + seedPreV41AuthoredWorldSource( + isolatedDsl, + isolatedTransaction, + persistedGame, + UUID.randomUUID(), + "tenant-" + suffix, + "world-" + suffix, + "Retained World 🐉"); assertThat(source).isNotNull(); Long versionId = @@ -1046,6 +1045,89 @@ private DriverManagerDataSource isolatedDataSource(String schema) { return dataSource; } + /** Seeds the immutable source/binding shape written before V41 added automatic delivery. */ + private AuthoredWorldSourceEvidence seedPreV41AuthoredWorldSource( + DSLContext isolatedDsl, + TransactionTemplate isolatedTransaction, + Game sourceGame, + UUID registrationRequestId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + UUID operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + sourceGame.getId(), + sourceGame.getTenantId(), + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + sourceGame.getId(), + sourceGame.getTenantId(), + "NEW_GAME_ROW", + evidenceDigest); + + isolatedTransaction.execute( + status -> { + isolatedDsl.execute( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + isolatedDsl.execute( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, registration_request_id, " + + "request_digest, canonical_tenant_id, tenant_slug, world_slug, " + + "world_display_name, source_game_row_id, source_game_tenant_key, " + + "provenance_kind, evidence_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + source.operationId(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + return null; + }); + return source; + } + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { var configuration = Flyway.configure() diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/TenantIdentityAuthConfigurationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/TenantIdentityAuthConfigurationTest.java index f0fb761521..6a73e9c2cf 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/TenantIdentityAuthConfigurationTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/TenantIdentityAuthConfigurationTest.java @@ -46,6 +46,8 @@ class TenantIdentityAuthConfigurationTest { "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor"; private static final String GET_LAUNCH_DESCRIPTOR_METHOD = "gamedesign.v1.GameDesignService/GetLaunchDescriptor"; + private static final String GET_COMPLETE_LAUNCH_BINDING_METHOD = + "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding"; @Test void baseConfigurationExemptsOnlyTheIntendedTenantIdentityMethods() throws IOException { @@ -85,7 +87,8 @@ private void assertConfiguration(GrpcAuthProperties properties) { AUTHORED_WORLD_SOURCE_METHOD, GAME_SESSION_ASSOCIATION_METHOD, RESOLVE_LAUNCH_DESCRIPTOR_METHOD, - GET_LAUNCH_DESCRIPTOR_METHOD); + GET_LAUNCH_DESCRIPTOR_METHOD, + GET_COMPLETE_LAUNCH_BINDING_METHOD); AuthTokenInterceptor interceptor = new AuthTokenInterceptor(null, Set.copyOf(properties.getPublicMethods())); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java index 1f2555b239..9af6368397 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldLaunchDescriptorMtlsTest.java @@ -52,12 +52,15 @@ import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.security.AuthTokenInterceptor; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -67,6 +70,7 @@ import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; @@ -111,7 +115,10 @@ class AuthoredWorldLaunchDescriptorMtlsTest { private static final String RESOLVE_METHOD = "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor"; private static final String READ_METHOD = "gamedesign.v1.GameDesignService/GetLaunchDescriptor"; - private static final Set DESCRIPTOR_METHODS = Set.of(RESOLVE_METHOD, READ_METHOD); + private static final String COMPLETE_READ_METHOD = + "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding"; + private static final Set DESCRIPTOR_METHODS = + Set.of(RESOLVE_METHOD, READ_METHOD, COMPLETE_READ_METHOD); private static final Metadata.Key AUTHORIZATION = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); private static final UUID TENANT_ID = UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21"); @@ -151,9 +158,16 @@ class AuthoredWorldLaunchDescriptorMtlsTest { "release-bundle:" + TENANT_ID + ":12:29", true, "remap-set-4"); + private static final AuthoredWorldReleaseAttestationEvidence RELEASE_ATTESTATION = + releaseAttestation(BOUND_EVIDENCE); + private static final AuthoredWorldLaunchDescriptorEvidence SWAPPED_DESCRIPTOR = + swappedDescriptor(); + private static final AuthoredWorldReleaseAttestationEvidence SWAPPED_RELEASE_ATTESTATION = + releaseAttestation(SWAPPED_DESCRIPTOR); private static TestPki pki; private LaunchDescriptorService launchDescriptorService; + private CompleteLaunchBindingService completeLaunchBindingService; private Server server; private AtomicReference responseMutation; @@ -214,6 +228,7 @@ static void generateEphemeralPki() throws Exception { @BeforeEach void startPhysicalReceiver() throws Exception { launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); + completeLaunchBindingService = Mockito.mock(CompleteLaunchBindingService.class); responseMutation = new AtomicReference<>(ResponseMutation.NONE); server = startReceiver(pki.serverCertificate()); } @@ -230,6 +245,7 @@ private Server startReceiver( Mockito.mock(RevisionService.class), Mockito.mock(VersionService.class), launchDescriptorService, + completeLaunchBindingService, Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -326,6 +342,44 @@ void gameSessionAndWorldPeersReadExactDescriptorAndEchoReadRequestIdentity() thr BOUND_EVIDENCE.resultDigest()); } + @Test + void gameSessionAndWorldPeersReadExactCompleteBindingAndEchoReadRequestIdentity() + throws Exception { + when(completeLaunchBindingService.getCompleteLaunchBinding( + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString())) + .thenReturn(completeBinding()); + + for (TestCertificate certificate : + List.of(pki.gameSessionCertificate(), pki.worldManagementCertificate())) { + ManagedChannel channel = channel(certificate, false); + try { + GetCompleteLaunchBindingResponse response = + stub(channel).getCompleteLaunchBinding(readRequest()); + + assertThat(response.getError().getCode()).isEmpty(); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.hasLaunchDescriptor()).isTrue(); + assertThat(response.getLaunchDescriptor()).isEqualTo(expectedProtoDescriptor()); + assertThat(response.hasReleaseAttestation()).isTrue(); + assertThat(response.getReleaseAttestation().getEvidenceDigest()) + .isEqualTo(RELEASE_ATTESTATION.evidenceDigest()); + assertThat(response.getReleaseAttestation().getDescriptorResultDigest()) + .isEqualTo(BOUND_EVIDENCE.resultDigest()); + } finally { + stopChannel(channel); + } + } + + verify(completeLaunchBindingService, Mockito.times(2)) + .getCompleteLaunchBinding( + READ_REQUEST_ID, + TENANT_ID, + BOUND_REQUEST.worldSlug(), + BOUND_REQUEST.controlPlaneRequestId(), + BOUND_EVIDENCE.requestDigest(), + BOUND_EVIDENCE.resultDigest()); + } + @Test void sharedClientResolvesAndReadsExactDescriptorOverPhysicalMtlsSocket(@TempDir Path directory) throws Exception { @@ -333,6 +387,9 @@ void sharedClientResolvesAndReadsExactDescriptorOverPhysicalMtlsSocket(@TempDir when(launchDescriptorService.getLaunchDescriptor( any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString())) .thenReturn(resolvedDescriptor()); + when(completeLaunchBindingService.getCompleteLaunchBinding( + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString())) + .thenReturn(completeBinding()); AuthoredWorldLaunchDescriptorClient client = newSharedClient(directory, server); try { @@ -344,6 +401,10 @@ void sharedClientResolvesAndReadsExactDescriptorOverPhysicalMtlsSocket(@TempDir AuthoredWorldLaunchDescriptorEvidence readBack = client.get(readClientRequest()); assertThat(readBack).isEqualTo(BOUND_EVIDENCE); + var completeReadBack = client.getComplete(readRequest()); + assertThat(completeReadBack.descriptor()).isEqualTo(BOUND_EVIDENCE); + assertThat(completeReadBack.releaseAttestation()).isEqualTo(RELEASE_ATTESTATION); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(AuthoredWorldLaunchDescriptorEvidence.Request.class); verify(launchDescriptorService).resolveLaunchDescriptor(requestCaptor.capture()); @@ -356,6 +417,14 @@ void sharedClientResolvesAndReadsExactDescriptorOverPhysicalMtlsSocket(@TempDir BOUND_REQUEST.controlPlaneRequestId(), BOUND_EVIDENCE.requestDigest(), BOUND_EVIDENCE.resultDigest()); + verify(completeLaunchBindingService) + .getCompleteLaunchBinding( + READ_REQUEST_ID, + TENANT_ID, + BOUND_REQUEST.worldSlug(), + BOUND_REQUEST.controlPlaneRequestId(), + BOUND_EVIDENCE.requestDigest(), + BOUND_EVIDENCE.resultDigest()); } finally { client.close(); } @@ -379,6 +448,7 @@ void sharedClientRejectsWrongGameDesignServerWorkloadAndNamespaceBeforeReturning client.init(); assertServerPeerRefused(() -> client.resolve(BOUND_REQUEST)); assertServerPeerRefused(() -> client.get(readClientRequest())); + assertServerPeerRefused(() -> client.getComplete(readRequest())); inboundRpcCapture.assertNoInboundRequests(); } finally { client.close(); @@ -386,6 +456,7 @@ void sharedClientRejectsWrongGameDesignServerWorkloadAndNamespaceBeforeReturning } } verifyNoInteractions(launchDescriptorService); + verifyNoInteractions(completeLaunchBindingService); } @Test @@ -395,6 +466,9 @@ void sharedClientCodecRejectsChangedDescriptorReadEchoAndDigestOverPhysicalSocke when(launchDescriptorService.getLaunchDescriptor( any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString())) .thenReturn(resolvedDescriptor()); + when(completeLaunchBindingService.getCompleteLaunchBinding( + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString())) + .thenReturn(completeBinding()); AuthoredWorldLaunchDescriptorClient client = newSharedClient(directory, server); try { @@ -411,6 +485,18 @@ void sharedClientCodecRejectsChangedDescriptorReadEchoAndDigestOverPhysicalSocke responseMutation.set(ResponseMutation.CHANGE_RESULT_DIGEST); assertClientCodecRejected( () -> client.get(readClientRequest()), "Authored-world launch evidence is invalid"); + + responseMutation.set(ResponseMutation.CHANGE_COMPLETE_READ_REQUEST_ID); + assertCompleteClientCodecRejected(() -> client.getComplete(readRequest())); + + responseMutation.set(ResponseMutation.SWAP_COMPLETE_RELEASE_ATTESTATION); + assertCompleteClientCodecRejected(() -> client.getComplete(readRequest())); + + responseMutation.set(ResponseMutation.MISSING_COMPLETE_RELEASE_ATTESTATION); + assertCompleteClientCodecRejected(() -> client.getComplete(readRequest())); + + responseMutation.set(ResponseMutation.MISSING_COMPLETE_DESCRIPTOR); + assertCompleteClientCodecRejected(() -> client.getComplete(readRequest())); } finally { client.close(); } @@ -427,6 +513,7 @@ void worldPeerCannotResolveBeforeDescriptorProducerAccess() throws Exception { stopChannel(channel); } verifyNoInteractions(launchDescriptorService); + verifyNoInteractions(completeLaunchBindingService); } @Test @@ -437,10 +524,12 @@ void missingClientCertificateFailsWithTlsHandshakeEvidenceBeforeProducerAccess() var stub = stub(channel); assertTlsDenied(() -> stub.resolveLaunchDescriptor(resolveRequest()), RESOLVE_METHOD); assertTlsDenied(() -> stub.getLaunchDescriptor(readRequest()), READ_METHOD); + assertTlsDenied(() -> stub.getCompleteLaunchBinding(readRequest()), COMPLETE_READ_METHOD); } finally { stopChannel(channel); } verifyNoInteractions(launchDescriptorService); + verifyNoInteractions(completeLaunchBindingService); } @Test @@ -450,10 +539,12 @@ void jwtOnlyCallerWithoutClientCertificateFailsWithTlsHandshakeEvidence() throws var stub = stub(channel); assertTlsDenied(() -> stub.resolveLaunchDescriptor(resolveRequest()), RESOLVE_METHOD); assertTlsDenied(() -> stub.getLaunchDescriptor(readRequest()), READ_METHOD); + assertTlsDenied(() -> stub.getCompleteLaunchBinding(readRequest()), COMPLETE_READ_METHOD); } finally { stopChannel(channel); } verifyNoInteractions(launchDescriptorService); + verifyNoInteractions(completeLaunchBindingService); } @Test @@ -483,15 +574,26 @@ void malformedAndUnknownClosedRequestsFailBeforeDescriptorProducerAccess() throw .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build()) .build(); + GetLaunchDescriptorRequest malformedCompleteRequest = + readRequest().toBuilder().setCanonicalTenantId("not-a-canonical-uuid").build(); + GetLaunchDescriptorRequest unknownCompleteRequest = + readRequest().toBuilder().setUnknownFields(unknownField.getUnknownFields()).build(); try { assertThat(stub(channel).resolveLaunchDescriptor(malformed).getError().getCode()) .isEqualTo("INVALID_ARGUMENT"); assertThat(stub(channel).resolveLaunchDescriptor(unknownField).getError().getCode()) .isEqualTo("INVALID_ARGUMENT"); + assertThat( + stub(channel).getCompleteLaunchBinding(malformedCompleteRequest).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); + assertThat( + stub(channel).getCompleteLaunchBinding(unknownCompleteRequest).getError().getCode()) + .isEqualTo("INVALID_ARGUMENT"); } finally { stopChannel(channel); } verifyNoInteractions(launchDescriptorService); + verifyNoInteractions(completeLaunchBindingService); } @Test @@ -515,10 +617,13 @@ private void assertWrongPeerDenied(TestCertificate certificate) throws Exception .isEqualTo("PERMISSION_DENIED"); assertThat(stub.getLaunchDescriptor(readRequest()).getError().getCode()) .isEqualTo("PERMISSION_DENIED"); + assertThat(stub.getCompleteLaunchBinding(readRequest()).getError().getCode()) + .isEqualTo("PERMISSION_DENIED"); } finally { stopChannel(channel); } verifyNoInteractions(launchDescriptorService); + verifyNoInteractions(completeLaunchBindingService); } private static ServerInterceptor responseMutationInterceptor( @@ -569,6 +674,25 @@ private static Response mutateResponse(Response response, ResponseMut descriptor.toBuilder().setAuthoredWorldBinding(changedBinding).build(); return (Response) read.toBuilder().setLaunchDescriptor(changedDescriptor).build(); } + if (mutation == ResponseMutation.CHANGE_COMPLETE_READ_REQUEST_ID + && response instanceof GetCompleteLaunchBindingResponse read) { + return (Response) + read.toBuilder().setRequestId("44444444-4444-4444-8444-444444444444").build(); + } + if (mutation == ResponseMutation.SWAP_COMPLETE_RELEASE_ATTESTATION + && response instanceof GetCompleteLaunchBindingResponse read) { + var swappedEvidence = + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(SWAPPED_RELEASE_ATTESTATION); + return (Response) read.toBuilder().setReleaseAttestation(swappedEvidence).build(); + } + if (mutation == ResponseMutation.MISSING_COMPLETE_RELEASE_ATTESTATION + && response instanceof GetCompleteLaunchBindingResponse read) { + return (Response) read.toBuilder().clearReleaseAttestation().build(); + } + if (mutation == ResponseMutation.MISSING_COMPLETE_DESCRIPTOR + && response instanceof GetCompleteLaunchBindingResponse read) { + return (Response) read.toBuilder().clearLaunchDescriptor().build(); + } throw new IllegalStateException("Response mutation does not match the physical RPC response"); } @@ -616,6 +740,12 @@ private static void assertClientCodecRejected(Runnable call, String expectedCaus .hasMessageContaining(expectedCauseMessage); } + private static void assertCompleteClientCodecRejected(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(IllegalStateException.class); + assertThat(failure.getCause()).isInstanceOf(IllegalArgumentException.class); + } + private static AuthoredWorldLaunchDescriptorClient newSharedClient( Path directory, Server receiver) throws Exception { Files.createDirectories(directory); @@ -722,6 +852,93 @@ private static AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest readClientReque READ_REQUEST_ID, BOUND_REQUEST, BOUND_EVIDENCE.resultDigest()); } + private static CompleteLaunchBindingDto completeBinding() { + return new CompleteLaunchBindingDto(BOUND_EVIDENCE, RELEASE_ATTESTATION); + } + + private static AuthoredWorldReleaseAttestationEvidence releaseAttestation( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + participantKey -> { + boolean abilityPresent = "GAME_LOGIC".equals(participantKey); + return new AuthoredWorldReleaseAttestationEvidence.Participant( + participantKey, + Long.toString(descriptor.versionId()), + false, + null, + "commit-17", + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey), + abilityPresent, + abilityPresent ? "sha256:" + "c".repeat(64) : null); + }) + .toList(); + AuthoredWorldReleaseAttestationEvidence.Artifact artifact = + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "world.fixture", + "WORLD_FIXTURE", + "artifacts/sha256/" + "d".repeat(64), + "sha256:" + "d".repeat(64), + "application/octet-stream", + 1); + return AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + UUID.fromString("d7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21"), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish-workflow-opaque-17", + "commit-17", + participants, + "sha256:" + "e".repeat(64), + 1, + List.of("world.fixture"), + List.of(artifact), + List.of("LOOK"), + descriptor.generationConfigRevision()); + } + + private static AuthoredWorldLaunchDescriptorEvidence swappedDescriptor() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "launch-request-swapped", + TENANT_ID, + "other-harbor-world", + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 17L, + true, + "requested-patch-2", + true, + 9L, + true, + 12L, + true, + "{\"requested\":true}"); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "launch-descriptor-swapped", + 12L, + true, + "resolved-patch-2", + "{\"runtime\":true}", + "generation-revision-3", + 6L, + 29L, + "release-bundle:" + TENANT_ID + ":12:29", + true, + "remap-set-4"); + } + private static ResolvedLaunchDescriptorDto resolvedDescriptor() { return new ResolvedLaunchDescriptorDto( BOUND_EVIDENCE.launchDescriptorId(), @@ -942,7 +1159,11 @@ private enum ResponseMutation { NONE, CHANGE_DESCRIPTOR_DUPLICATE, CHANGE_READ_REQUEST_ID, - CHANGE_RESULT_DIGEST + CHANGE_RESULT_DIGEST, + CHANGE_COMPLETE_READ_REQUEST_ID, + SWAP_COMPLETE_RELEASE_ATTESTATION, + MISSING_COMPLETE_RELEASE_ATTESTATION, + MISSING_COMPLETE_DESCRIPTOR } private record TestPki( 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 index 63a95db34f..67feb4debf 100644 --- 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 @@ -27,6 +27,7 @@ class AuthoredWorldVersionStateGrpcServiceTest { 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 UUID CANONICAL_VERSION_ID = uuid("55555555-5555-4555-8555-555555555555"); @Test void exactWorldPeerMayReadAndReceivesClosedEvidence() { @@ -34,7 +35,11 @@ void exactWorldPeerMayReadAndReceivesClosedEvidence() { var request = request(); var evidence = AuthoredWorldVersionStateEvidence.create( - request, sourceEvidence(), VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 7L); + request, + sourceEvidence(), + CANONICAL_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 7L); when(service.read(request)).thenReturn(evidence); var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); TestObserver observer = new TestObserver<>(); @@ -47,6 +52,16 @@ void exactWorldPeerMayReadAndReceivesClosedEvidence() { assertThat(observer.error).isNull(); assertThat(observer.completed).isTrue(); + assertThat(observer.value.getEvidence().getCanonicalVersionId()) + .isEqualTo(CANONICAL_VERSION_ID.toString()); + assertThat( + observer + .value + .getEvidence() + .getDescriptorForType() + .findFieldByName("canonical_version_id") + .getNumber()) + .isEqualTo(13); assertThat(AuthoredWorldVersionStateGrpcCodec.fromResponse(request, observer.value)) .isEqualTo(evidence); verify(service).read(request); 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 index 8669fc5448..a48ff7b72f 100644 --- 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 @@ -96,6 +96,8 @@ class AuthoredWorldVersionStateMtlsTest { 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 UUID CANONICAL_VERSION_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1L); private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); private static final AuthoredWorldVersionStateEvidence.Request READ_REQUEST = @@ -110,7 +112,11 @@ class AuthoredWorldVersionStateMtlsTest { 17L); private static final AuthoredWorldVersionStateEvidence VERSION_STATE_EVIDENCE = AuthoredWorldVersionStateEvidence.create( - READ_REQUEST, SOURCE_EVIDENCE, VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 9L); + READ_REQUEST, + SOURCE_EVIDENCE, + CANONICAL_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 9L); private static TestPki pki; private AuthoredWorldVersionStateService versionStateService; 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 index 5ec7448976..77743c83e2 100644 --- 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 @@ -27,6 +27,7 @@ class AuthoredWorldVersionStateServiceTest { 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 UUID CANONICAL_VERSION_ID = uuid("55555555-5555-4555-8555-555555555555"); @Test void readsCompleteSourceAndVersionInsideFreshReadOnlyRepeatableReadTransaction() { @@ -45,6 +46,7 @@ void readsCompleteSourceAndVersionInsideFreshReadOnlyRepeatableReadTransaction() Optional.of( new AuthoredWorldVersionStateSnapshot( source, + CANONICAL_VERSION_ID, net.firedevops.firemud.gamedesign.model.VersionLifecycleState.PUBLISHED, 7L))); AuthoredWorldVersionStateService service = @@ -53,6 +55,7 @@ void readsCompleteSourceAndVersionInsideFreshReadOnlyRepeatableReadTransaction() AuthoredWorldVersionStateEvidence evidence = service.read(request(source.evidenceDigest())); assertThat(evidence.sourceEvidence()).isEqualTo(source); + assertThat(evidence.canonicalVersionId()).isEqualTo(CANONICAL_VERSION_ID); assertThat(evidence.versionState()) .isEqualTo(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED); assertThat(evidence.versionStateEpoch()).isEqualTo(7L); @@ -117,6 +120,42 @@ void repositoryOwnerConsistencyFailuresDoNotBecomeEvidence() { .hasMessageContaining("source binding changed"); } + @Test + void missingOrNilPersistedCanonicalVersionIdFailsClosed() { + for (UUID canonicalVersionId : new UUID[] {null, new UUID(0L, 0L)}) { + 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, + canonicalVersionId, + net.firedevops.firemud.gamedesign.model.VersionLifecycleState.PUBLISHED, + 7L))); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + if (canonicalVersionId == null) { + assertThatThrownBy(() -> service.read(request(source.evidenceDigest()))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("canonicalVersionId"); + } else { + assertThatThrownBy(() -> service.read(request(source.evidenceDigest()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + } + } + } + private static AuthoredWorldVersionStateEvidence.Request request(String sourceDigest) { return new AuthoredWorldVersionStateEvidence.Request( 1, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java new file mode 100644 index 0000000000..9b153914fd --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -0,0 +1,961 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.test.util.ReflectionTestUtils; + +class CompleteLaunchBindingServiceImplTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = + UUID.fromString("72345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_REGISTRATION_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final String WORLD_SLUG = "silver-march"; + private static final String PRIVATE_TENANT_KEY = "game-owner-key-901"; + private static final long VERSION_ID = 7L; + private static final int VERSION_NUMBER = 12; + private static final long BUNDLE_ID = 211L; + private static final String CONTROL_PLANE_REQUEST_ID = "launch-request-901"; + private static final String BUNDLE_REF = "opaque-release-reference-from-owner"; + private static final String WORKFLOW_ID = + "publish:game-owner-key-901:publish-request:publish-901"; + private static final String MANIFEST_HASH = "sha256:" + "c".repeat(64); + private static final String CONTENT_DIGEST = "d".repeat(64); + private static final String ABILITY_SCHEMA_DIGEST = "sha256:" + "e".repeat(64); + private static final String ARTIFACT_DIGEST = "sha256:" + "f".repeat(64); + + @Mock private LaunchDescriptorService launchDescriptorService; + @Mock private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + @Mock private PublishedReleaseBundleService publishedReleaseBundleService; + @Mock private VersionRepository versionRepository; + + private CompleteLaunchBindingServiceImpl service; + private AuthoredWorldSourceEvidence source; + private AuthoredWorldLaunchDescriptorEvidence descriptor; + private ResolvedLaunchDescriptorDto resolved; + private PublishedReleaseBundleDto bundle; + private Version version; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + source = sourceEvidence(WORLD_SLUG); + descriptor = descriptorEvidence(source); + resolved = resolvedDescriptor(descriptor); + bundle = validBundle(); + version = canonicalVersion(); + service = + new CompleteLaunchBindingServiceImpl( + launchDescriptorService, + authoredWorldSourceRepository, + publishedReleaseBundleService, + versionRepository); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + givenValidSnapshot(); + } + + @Test + void returnsImmutableFullBindingUsingTheDescriptorEpochAfterCurrentVersionStateAdvances() { + var first = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + version.setVersionState(VersionLifecycleState.RETIRED); + version.setVersionStateEpoch(44L); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.RETIRED, 44L))); + + var later = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + + assertEquals(descriptor, first.descriptor()); + assertEquals(descriptor.versionStateEpoch(), first.releaseAttestation().versionStateEpoch()); + assertEquals(first.releaseAttestation(), later.releaseAttestation()); + assertEquals( + first.releaseAttestation().evidenceDigest(), later.releaseAttestation().evidenceDigest()); + verifyReadOnlyCallsOnly(); + } + + @Test + void rejectsMissingOrSubstitutedSourceEvidence() { + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn(Optional.empty()); + assertDenied(); + + AuthoredWorldSourceEvidence substituted = sourceEvidence("other-world"); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + substituted, CANONICAL_VERSION_ID, VersionLifecycleState.PUBLISHED, 17L))); + assertDenied(); + } + + @Test + void rejectsMissingOrSubstitutedReleaseIdentityAndReference() { + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_TENANT_KEY, VERSION_ID)) + .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_TENANT_KEY, VERSION_ID)); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID + 1, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + bundle.publishedReleaseBundleRef(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + "substituted-reference", + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + "other-private-key", + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID + 1, + VERSION_NUMBER, + BUNDLE_REF, + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER + 1, + BUNDLE_REF, + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + } + + @Test + void rejectsMissingCanonicalVersionOrContradictoryPersistedGameProvenance() { + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.empty()); + assertDenied(); + + version.setIdentitySourceGameRowId(74L); + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.of(version)); + assertDenied(); + } + + @Test + void rejectsCanonicalTenantOrVersionUuidSubstitution() { + UUID otherCanonicalTenant = UUID.fromString("92345678-1234-4234-8234-123456789abc"); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + otherCanonicalTenant, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + UUID otherCanonicalVersion = UUID.fromString("a2345678-1234-4234-8234-123456789abc"); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + otherCanonicalVersion, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + } + + @Test + void requiresOneConsistentOwnerSnapshotAndMonotonicHistoricalEpoch() { + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.PUBLISHED, 16L))); + assertDenied(); + + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.RETIRED, 23L))); + assertDenied(); + } + + @Test + void rejectsReleaseVersionUuidThatDiffersFromTheSameSourceSnapshot() { + UUID differentVersionId = UUID.fromString("b2345678-1234-4234-8234-123456789abc"); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, differentVersionId, VersionLifecycleState.PUBLISHED, 23L))); + + assertDenied(); + verify(versionRepository, never()) + .findByCanonicalTenantIdAndCanonicalVersionId(CANONICAL_TENANT_ID, CANONICAL_VERSION_ID); + } + + @Test + void rejectsAbsentOrNilCanonicalVersionUuidWithoutNumericInference() { + UUID nil = new UUID(0L, 0L); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + nil, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + verify(versionRepository, never()) + .findByCanonicalTenantIdAndCanonicalVersionId(CANONICAL_TENANT_ID, nil); + } + + @Test + void rejectsScriptOnlyVersionMetadata() { + version.setScriptOnly(true); + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.of(version)); + assertDenied(); + + version.setScriptOnly(false); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + true, + "patch-1")); + assertDenied(); + } + + @Test + void rejectsMissingOrContradictoryManifestAndArtifactProof() { + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + null, + bundle.manifestHash(), + null, + false, + null)); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + "not-a-digest", + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + List.of("world.navmesh"), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + List.of(), + false, + null)); + assertDenied(); + } + + @Test + void rejectsMissingFailedUnsupportedAndMisorderedParticipantEvidence() { + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + List.of(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List unsupported = + new java.util.ArrayList<>(bundle.participantDigests()); + unsupported.set( + 0, + new PublishParticipantDigestDto( + PublishParticipantKey.WORLD_MANAGEMENT.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 99, + null, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + unsupported, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List failed = + new java.util.ArrayList<>(bundle.participantDigests()); + failed.set( + 0, + new PublishParticipantDigestDto( + PublishParticipantKey.WORLD_MANAGEMENT.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 2, + null, + "OWNER_FAILED", + "owner failed")); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + failed, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List misordered = + new java.util.ArrayList<>(bundle.participantDigests()); + java.util.Collections.swap(misordered, 0, 1); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + misordered, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + } + + @Test + void requiresGameLogicOwnedAbilityProofAndOneSharedParticipantCommit() { + List missingAbility = + new java.util.ArrayList<>(bundle.participantDigests()); + missingAbility.set( + 2, + new PublishParticipantDigestDto( + PublishParticipantKey.GAME_LOGIC.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 1, + null, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + missingAbility, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List mismatchedCommit = + new java.util.ArrayList<>(bundle.participantDigests()); + mismatchedCommit.set( + 4, + new PublishParticipantDigestDto( + PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE.name(), + Long.toString(VERSION_ID), + null, + "different-commit", + CONTENT_DIGEST, + 1, + null, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + mismatchedCommit, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List wrongAbilityOwner = + new java.util.ArrayList<>(bundle.participantDigests()); + wrongAbilityOwner.set( + 0, + new PublishParticipantDigestDto( + PublishParticipantKey.WORLD_MANAGEMENT.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 2, + ABILITY_SCHEMA_DIGEST, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + wrongAbilityOwner, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + } + + private void givenValidSnapshot() { + when(launchDescriptorService.getLaunchDescriptorInOwnerSnapshot( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest())) + .thenReturn(resolved); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.PUBLISHED, 23L))); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_TENANT_KEY, VERSION_ID)) + .thenReturn(bundle); + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.of(version)); + } + + private void givenBundle(PublishedReleaseBundleDto replacement) { + doReturn(replacement) + .when(publishedReleaseBundleService) + .getPublishedReleaseBundle(PRIVATE_TENANT_KEY, VERSION_ID); + } + + private void assertDenied() { + IllegalArgumentException denied = + assertThrows( + IllegalArgumentException.class, + () -> + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest())); + assertTrue( + denied.getMessage().startsWith("COMPLETE_LAUNCH_BINDING_") + || denied.getMessage().startsWith("LAUNCH_DESCRIPTOR_") + || denied.getMessage().startsWith("AUTHORED_WORLD_SOURCE_")); + verifyReadOnlyCallsOnly(); + } + + private void verifyReadOnlyCallsOnly() { + verify(launchDescriptorService, never()).resolveLaunchDescriptor(any()); + verify(authoredWorldSourceRepository, never()) + .register( + anyString(), any(UUID.class), any(UUID.class), anyString(), anyString(), anyString()); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle(any(), anyString(), any(), anyString(), any()); + verify(versionRepository, never()).save(any(Version.class)); + verify(versionRepository, never()).delete(any(Version.class)); + } + + private AuthoredWorldSourceEvidence sourceEvidence(String worldSlug) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + CANONICAL_TENANT_ID, + "silver-tenant", + worldSlug, + "Silver March"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + "silver-tenant", + worldSlug, + "Silver March", + 73L, + PRIVATE_TENANT_KEY, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + "silver-tenant", + worldSlug, + "Silver March", + 73L, + PRIVATE_TENANT_KEY, + "NEW_GAME_ROW", + evidenceDigest); + } + + private AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( + AuthoredWorldSourceEvidence sourceEvidence) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + CONTROL_PLANE_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence.evidenceDigest(), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-71234567-1234-4234-8234-123456789abc", + VERSION_ID, + false, + null, + "{}", + "generation-config-12", + 17L, + BUNDLE_ID, + BUNDLE_REF, + false, + null); + } + + private ResolvedLaunchDescriptorDto resolvedDescriptor( + AuthoredWorldLaunchDescriptorEvidence evidence) { + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private PublishedReleaseBundleDto validBundle() { + String artifactObjectKey = "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()); + return new PublishedReleaseBundleDto( + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + "v1", + WORKFLOW_ID, + MANIFEST_HASH, + List.of("world.navmesh"), + validParticipants(), + List.of("{\"commandId\":\"look\"}"), + "generation-config-12", + false, + null, + null, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + BUNDLE_REF, + 1, + List.of( + new PublishedArtifactDigest( + "world.navmesh", + "world-navmesh", + artifactObjectKey, + ARTIFACT_DIGEST, + "application/octet-stream", + 1))); + } + + private List validParticipants() { + return List.of( + participant(PublishParticipantKey.WORLD_MANAGEMENT.name(), 2, null), + participant(PublishParticipantKey.ENTITY_MANAGEMENT.name(), 2, null), + participant(PublishParticipantKey.GAME_LOGIC.name(), 1, ABILITY_SCHEMA_DIGEST), + participant(PublishParticipantKey.AUTOMATION_SCRIPTING.name(), 5, null), + participant(PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE.name(), 1, null)); + } + + private PublishParticipantDigestDto participant( + String participantKey, int digestSchemaVersion, String abilitySchemaDigest) { + return new PublishParticipantDigestDto( + participantKey, + Long.toString(VERSION_ID), + null, + "commit-12", + CONTENT_DIGEST, + digestSchemaVersion, + abilitySchemaDigest, + null, + null); + } + + private Version canonicalVersion() { + Version result = new Version(); + result.setId(VERSION_ID); + result.setTenantId(PRIVATE_TENANT_KEY); + result.setCanonicalTenantId(CANONICAL_TENANT_ID); + result.setCanonicalVersionId(CANONICAL_VERSION_ID); + result.setIdentitySourceGameRowId(73L); + result.setIdentitySourceGameTenantKey(PRIVATE_TENANT_KEY); + result.setIdentitySourceProvenanceKind("NEW_GAME_ROW"); + result.setVersionNumber((int) VERSION_NUMBER); + result.setVersionState(VersionLifecycleState.PUBLISHED); + result.setVersionStateEpoch(23L); + return result; + } + + private PublishedReleaseBundleDto copyBundle( + PublishedReleaseBundleDto original, + long id, + String tenantId, + long versionId, + int versionNumber, + String releaseRef, + UUID canonicalTenantId, + UUID canonicalVersionId, + List requiredKeys, + List participants, + Integer manifestSchemaVersion, + String manifestHash, + List artifacts, + boolean scriptOnly, + String scriptPatchVersion) { + return new PublishedReleaseBundleDto( + id, + tenantId, + versionId, + versionNumber, + original.attestationSchemaVersion(), + original.publishWorkflowId(), + manifestHash, + requiredKeys, + participants, + original.commandDefinitions(), + original.generationConfigRevision(), + scriptOnly, + scriptPatchVersion, + original.publishedAt(), + canonicalTenantId, + canonicalVersionId, + releaseRef, + manifestSchemaVersion, + artifacts); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryServiceTest.java new file mode 100644 index 0000000000..4f09ce648a --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredWorldSourceDeliveryServiceTest.java @@ -0,0 +1,391 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ReadRequest; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameAuthoredWorldSourceDeliveryServiceTest { + private static final String NAMESPACE = "authored-world-test"; + private static final UUID SOURCE_OPERATION_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REGISTRATION_REQUEST_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INTAKE_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID WORLD_OPERATION_ID = uuid("55555555-5555-4555-8555-555555555555"); + + private final GameAuthoredWorldSourceDeliveryRepository repository = + mock(GameAuthoredWorldSourceDeliveryRepository.class); + private final WorldAuthoredSourceIntakeClient worldClient = + mock(WorldAuthoredSourceIntakeClient.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final GameAuthoredWorldSourceDeliveryService service = + new GameAuthoredWorldSourceDeliveryService( + repository, worldClient, transactionManager, NAMESPACE); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactCompletedRetryReturnsDurableReceiptWithoutCallingWorld() { + DeliveryClaim completed = claim(Optional.of(receipt(request(), WORLD_OPERATION_ID, 'a'))); + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(completed)); + + DeliveryClaim result = service.deliver(SOURCE_OPERATION_ID); + + assertThat(result).isEqualTo(completed); + verify(repository).read(SOURCE_OPERATION_ID); + verify(repository, never()).acknowledge(any(), any()); + verifyNoInteractions(worldClient); + assertThat(transactionManager.beginCount).hasValue(0); + } + + @Test + void missingDeliveryClaimIsDeniedWithoutCallingWorld() { + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(GameAuthoredWorldSourceDeliveryService.DeliveryNotFoundException.class); + + verify(repository).read(SOURCE_OPERATION_ID); + verify(repository, never()).acknowledge(any(), any()); + verifyNoInteractions(worldClient); + } + + @Test + void wrongNamespaceClaimIsDeniedBeforeCallingWorld() { + DeliveryClaim wrongNamespace = claim(NAMESPACE, Optional.empty()); + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(wrongNamespace)); + GameAuthoredWorldSourceDeliveryService otherNamespaceService = + new GameAuthoredWorldSourceDeliveryService( + repository, worldClient, transactionManager, "different-namespace"); + + assertThatThrownBy(() -> otherNamespaceService.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(GameAuthoredWorldSourceDeliveryService.DeliveryConflictException.class); + + verify(repository).read(SOURCE_OPERATION_ID); + verify(repository, never()).acknowledge(any(), any()); + verifyNoInteractions(worldClient); + } + + @Test + void writableAmbientTransactionIsDeniedBeforeOwnerReadOrWorldCall() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(IllegalStateException.class); + + verifyNoInteractions(repository, worldClient); + } + + @Test + void mismatchedWorldIntakeOrReadbackNeverAcknowledges() { + DeliveryClaim pending = claim(Optional.empty()); + CommittedReceipt expected = receipt(pending.request(), WORLD_OPERATION_ID, 'a'); + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(pending)); + when(worldClient.intake(pending.request())) + .thenReturn(receipt(pending.request(), uuid("66666666-6666-4666-8666-666666666666"), 'b')); + when(worldClient.read(any(ReadRequest.class))).thenReturn(expected); + + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(GameAuthoredWorldSourceDeliveryService.DeliveryConflictException.class) + .hasMessageContaining("same complete receipt"); + verify(repository, never()).acknowledge(any(), any()); + + org.mockito.Mockito.reset(repository, worldClient); + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(pending)); + when(worldClient.intake(pending.request())).thenReturn(expected); + when(worldClient.read(any(ReadRequest.class))) + .thenReturn(receipt(pending.request(), uuid("77777777-7777-4777-8777-777777777777"), 'c')); + + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(GameAuthoredWorldSourceDeliveryService.DeliveryConflictException.class) + .hasMessageContaining("same complete receipt"); + + verify(worldClient).intake(pending.request()); + verify(worldClient).read(any(ReadRequest.class)); + verify(repository, never()).acknowledge(any(), any()); + } + + @Test + void ambiguousWorldIntakeOrReadbackLeavesClaimPending() { + DeliveryClaim pending = claim(Optional.empty()); + CommittedReceipt expected = receipt(pending.request(), WORLD_OPERATION_ID, 'a'); + + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(pending)); + when(worldClient.intake(pending.request())) + .thenThrow(new IllegalStateException("lost intake reply")); + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .hasMessageContaining("lost intake reply"); + verify(repository, never()).acknowledge(any(), any()); + + org.mockito.Mockito.reset(repository, worldClient); + when(repository.read(SOURCE_OPERATION_ID)).thenReturn(Optional.of(pending)); + when(worldClient.intake(pending.request())).thenReturn(expected); + when(worldClient.read(any(ReadRequest.class))) + .thenThrow(new IllegalStateException("World readback unavailable")); + + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .hasMessageContaining("World readback unavailable"); + + verify(repository, never()).acknowledge(any(), any()); + } + + @Test + void exactWorldReceiptIsAcknowledgedInShortTransactionAndReadBackAfterCommit() { + DeliveryClaim pending = claim(Optional.empty()); + CommittedReceipt worldReceipt = receipt(pending.request(), WORLD_OPERATION_ID, 'a'); + DeliveryClaim acknowledged = claim(Optional.of(worldReceipt)); + AtomicInteger reads = new AtomicInteger(); + AtomicBoolean acknowledgementWasTransactional = new AtomicBoolean(); + AtomicBoolean readbackWasOutsideTransaction = new AtomicBoolean(); + AtomicBoolean worldCallsWereOutsideTransaction = new AtomicBoolean(true); + when(repository.read(SOURCE_OPERATION_ID)) + .thenAnswer( + invocation -> { + if (reads.incrementAndGet() == 1) { + return Optional.of(pending); + } + readbackWasOutsideTransaction.set( + !TransactionSynchronizationManager.isActualTransactionActive()); + return Optional.of(acknowledged); + }); + when(worldClient.intake(pending.request())) + .thenAnswer( + invocation -> { + worldCallsWereOutsideTransaction.compareAndSet( + true, !TransactionSynchronizationManager.isActualTransactionActive()); + return worldReceipt; + }); + when(worldClient.read(any(ReadRequest.class))) + .thenAnswer( + invocation -> { + worldCallsWereOutsideTransaction.compareAndSet( + true, !TransactionSynchronizationManager.isActualTransactionActive()); + return worldReceipt; + }); + when(repository.acknowledge(pending, worldReceipt)) + .thenAnswer( + invocation -> { + acknowledgementWasTransactional.set( + TransactionSynchronizationManager.isActualTransactionActive()); + return acknowledged; + }); + + DeliveryClaim result = service.deliver(SOURCE_OPERATION_ID); + + assertThat(result).isEqualTo(acknowledged); + assertThat(reads).hasValue(2); + assertThat(acknowledgementWasTransactional).isTrue(); + assertThat(readbackWasOutsideTransaction).isTrue(); + assertThat(worldCallsWereOutsideTransaction).isTrue(); + assertThat(transactionManager.definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.definition.isReadOnly()).isFalse(); + ArgumentCaptor readRequest = ArgumentCaptor.forClass(ReadRequest.class); + InOrder remoteOrder = inOrder(worldClient); + remoteOrder.verify(worldClient).intake(pending.request()); + remoteOrder.verify(worldClient).read(readRequest.capture()); + assertThat(readRequest.getValue().binding()).isEqualTo(pending.request()); + assertThat(readRequest.getValue().requestId()) + .isNotEqualTo(pending.request().intakeRequestId()) + .isNotEqualTo(pending.source().operationId()); + verify(repository).acknowledge(pending, worldReceipt); + } + + @Test + void lostAcknowledgementRecoversDurablePriorBeforeAnyRedelivery() { + DeliveryClaim pending = claim(Optional.empty()); + CommittedReceipt worldReceipt = receipt(pending.request(), WORLD_OPERATION_ID, 'a'); + DeliveryClaim acknowledged = claim(Optional.of(worldReceipt)); + AtomicInteger reads = new AtomicInteger(); + when(repository.read(SOURCE_OPERATION_ID)) + .thenAnswer( + invocation -> Optional.of(reads.incrementAndGet() == 1 ? pending : acknowledged)); + when(worldClient.intake(pending.request())).thenReturn(worldReceipt); + when(worldClient.read(any(ReadRequest.class))).thenReturn(worldReceipt); + when(repository.acknowledge(pending, worldReceipt)) + .thenThrow(new IllegalStateException("commit acknowledgement was lost")); + + DeliveryClaim recovered = service.deliver(SOURCE_OPERATION_ID); + assertThat(recovered).isEqualTo(acknowledged); + DeliveryClaim retry = service.deliver(SOURCE_OPERATION_ID); + + assertThat(retry).isEqualTo(acknowledged); + verify(worldClient).intake(pending.request()); + verify(worldClient).read(any(ReadRequest.class)); + verify(repository).acknowledge(pending, worldReceipt); + } + + @Test + void matchingConcurrentReceiptIsReturnedAndChangedReceiptIsDenied() { + DeliveryClaim pending = claim(Optional.empty()); + CommittedReceipt worldReceipt = receipt(pending.request(), WORLD_OPERATION_ID, 'a'); + DeliveryClaim concurrentWinner = claim(Optional.of(worldReceipt)); + when(repository.read(SOURCE_OPERATION_ID)) + .thenReturn(Optional.of(pending), Optional.of(concurrentWinner)); + when(worldClient.intake(pending.request())).thenReturn(worldReceipt); + when(worldClient.read(any(ReadRequest.class))).thenReturn(worldReceipt); + when(repository.acknowledge(pending, worldReceipt)).thenReturn(concurrentWinner); + + assertThat(service.deliver(SOURCE_OPERATION_ID)).isEqualTo(concurrentWinner); + + org.mockito.Mockito.reset(repository, worldClient); + CommittedReceipt otherReceipt = receipt(pending.request(), WORLD_OPERATION_ID, 'b'); + DeliveryClaim changedWinner = claim(Optional.of(otherReceipt)); + when(repository.read(SOURCE_OPERATION_ID)) + .thenReturn(Optional.of(pending), Optional.of(changedWinner)); + when(worldClient.intake(pending.request())).thenReturn(worldReceipt); + when(worldClient.read(any(ReadRequest.class))).thenReturn(worldReceipt); + when(repository.acknowledge(pending, worldReceipt)) + .thenThrow(new IllegalStateException("different World receipt is already acknowledged")); + + assertThat(otherReceipt).isNotEqualTo(worldReceipt); + assertThatThrownBy(() -> service.deliver(SOURCE_OPERATION_ID)) + .isInstanceOf(GameAuthoredWorldSourceDeliveryService.DeliveryConflictException.class) + .hasMessageContaining("different World receipt won"); + verify(repository).acknowledge(pending, worldReceipt); + } + + private static DeliveryClaim claim(Optional acknowledgedReceipt) { + return claim(NAMESPACE, acknowledgedReceipt); + } + + private static DeliveryClaim claim( + String namespace, Optional acknowledgedReceipt) { + AuthoredWorldSourceEvidence source = source(namespace); + IntakeRequest request = + new IntakeRequest( + 1, + namespace, + INTAKE_REQUEST_ID, + TENANT_ID, + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + return new DeliveryClaim(source, request, acknowledgedReceipt); + } + + private static AuthoredWorldSourceEvidence source(String namespace) { + String tenantSlug = "authored-tenant"; + String worldSlug = "violet-wilds"; + String displayName = "Violet Wilds"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, REGISTRATION_REQUEST_ID, TENANT_ID, tenantSlug, worldSlug, displayName); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 17L, + "authored-tenant-key", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 17L, + "authored-tenant-key", + "NEW_GAME_ROW")); + } + + private static IntakeRequest request() { + AuthoredWorldSourceEvidence source = source(NAMESPACE); + return new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + TENANT_ID, + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + } + + private static CommittedReceipt receipt( + IntakeRequest request, UUID operationId, char receiptMarker) { + return new CommittedReceipt( + request.schemaVersion(), + request.targetNamespace(), + request.intakeRequestId(), + operationId, + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(request), + digest(receiptMarker)); + } + + private static String digest(char marker) { + return "sha256:" + String.valueOf(marker).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class RecordingTransactionManager + extends AbstractPlatformTransactionManager { + private TransactionDefinition definition; + private final AtomicInteger beginCount = new AtomicInteger(); + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition transactionDefinition) { + definition = transactionDefinition; + beginCount.incrementAndGet(); + } + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index 3a0a45eaf5..4d8ed22e7b 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 @@ -13,6 +13,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -21,6 +22,7 @@ import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import net.firedevops.firemud.gamedesign.service.VersionService; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; @@ -51,6 +53,7 @@ void adminMethodsReturnPermissionDeniedErrorDetail() { Mockito.mock(RevisionService.class), Mockito.mock(VersionService.class), Mockito.mock(LaunchDescriptorService.class), + Mockito.mock(CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -83,6 +86,8 @@ public void onCompleted() {} void launchDescriptorRejectsJwtOnlyInternalServiceIdentity() { VersionService versionService = Mockito.mock(VersionService.class); LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); + CompleteLaunchBindingService completeLaunchBindingService = + Mockito.mock(CompleteLaunchBindingService.class); Mockito.when(versionService.getPublishedReleaseBundle("1", 7L)) .thenReturn( new PublishedReleaseBundleDto( @@ -110,6 +115,7 @@ void launchDescriptorRejectsJwtOnlyInternalServiceIdentity() { Mockito.mock(RevisionService.class), versionService, launchDescriptorService, + completeLaunchBindingService, Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -165,7 +171,10 @@ public void onCompleted() {} assertEquals("", bundleRef.get().getBundle().getPublishedReleaseBundleRef()); assertNotNull(descriptorRef.get()); assertEquals("PERMISSION_DENIED", descriptorRef.get().getError().getCode()); + GetCompleteLaunchBindingResponse completeBindingResponse = readCompleteBinding(service, null); + assertEquals("PERMISSION_DENIED", completeBindingResponse.getError().getCode()); Mockito.verifyNoInteractions(launchDescriptorService); + Mockito.verifyNoInteractions(completeLaunchBindingService); } @Test @@ -178,6 +187,7 @@ public void onCompleted() {} Mockito.mock(RevisionService.class), Mockito.mock(VersionService.class), launchDescriptorService, + Mockito.mock(CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -202,12 +212,15 @@ public void onCompleted() {} @Test void launchDescriptorReadRejectsWrongWorkloadAndNamespacePeersBeforeServiceAccess() { LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); + CompleteLaunchBindingService completeLaunchBindingService = + Mockito.mock(CompleteLaunchBindingService.class); GameDesignGrpcService service = new GameDesignGrpcService( Mockito.mock(PingService.class), Mockito.mock(RevisionService.class), Mockito.mock(VersionService.class), launchDescriptorService, + completeLaunchBindingService, Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -227,7 +240,18 @@ void launchDescriptorReadRejectsWrongWorkloadAndNamespacePeersBeforeServiceAcces readDescriptor(service, "spiffe://firemud/ns/other/sa/world-management-service") .getError() .getCode()); + assertEquals( + "PERMISSION_DENIED", + readCompleteBinding(service, "spiffe://firemud/ns/test/sa/game-design-service") + .getError() + .getCode()); + assertEquals( + "PERMISSION_DENIED", + readCompleteBinding(service, "spiffe://firemud/ns/other/sa/world-management-service") + .getError() + .getCode()); Mockito.verifyNoInteractions(launchDescriptorService); + Mockito.verifyNoInteractions(completeLaunchBindingService); } private ResolveLaunchDescriptorResponse resolve(GameDesignGrpcService service, String peerUri) { @@ -267,6 +291,25 @@ private GetLaunchDescriptorResponse readDescriptor( return response.get(); } + private GetCompleteLaunchBindingResponse readCompleteBinding( + GameDesignGrpcService service, String peerUri) { + AtomicReference response = new AtomicReference<>(); + Runnable call = + () -> + service.getCompleteLaunchBinding( + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId("12345678-1234-4234-8234-123456789abc") + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-auth") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .build(), + observerFor(response)); + runAsPeer(peerUri, call); + return response.get(); + } + private void runAsPeer(String peerUri, Runnable call) { if (peerUri == null) { call.run(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java index 9c8499397d..c331104be2 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java @@ -11,6 +11,7 @@ import java.util.Optional; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.dto.HelpTopicDto; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -38,6 +39,7 @@ class GameDesignGrpcServiceHelpTopicTest { Mockito.mock(RevisionService.class), Mockito.mock(VersionService.class), Mockito.mock(LaunchDescriptorService.class), + Mockito.mock(CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java index 95018adc29..56f2f87850 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.settings.ScopedSettingsOverrides; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -39,6 +40,8 @@ class GameDesignGrpcServiceSettingsAuthorityTest { private final VersionService versionService = Mockito.mock(VersionService.class); private final LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); + private final CompleteLaunchBindingService completeLaunchBindingService = + Mockito.mock(CompleteLaunchBindingService.class); private final TemplateRemapSetService templateRemapSetService = Mockito.mock(TemplateRemapSetService.class); private final VersionAssetArtifactService versionAssetArtifactService = @@ -59,6 +62,7 @@ void setUp() { revisionService, versionService, launchDescriptorService, + completeLaunchBindingService, templateRemapSetService, versionAssetArtifactService, settingsAuthorityService, 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 f5e5f83f8f..56bf298d40 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 @@ -31,6 +31,7 @@ import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -103,6 +104,8 @@ class GameDesignGrpcServiceTest { private final VersionService versionService = Mockito.mock(VersionService.class); private final LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); + private final CompleteLaunchBindingService completeLaunchBindingService = + Mockito.mock(CompleteLaunchBindingService.class); private final TemplateRemapSetService templateRemapSetService = Mockito.mock(TemplateRemapSetService.class); private final VersionAssetArtifactService versionAssetArtifactService = @@ -119,6 +122,7 @@ class GameDesignGrpcServiceTest { revisionService, versionService, launchDescriptorService, + completeLaunchBindingService, templateRemapSetService, versionAssetArtifactService, settingsAuthorityService, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/controller/GenerationRuleController.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/controller/GenerationRuleController.java index 33f4df19ff..f13adac7a2 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/controller/GenerationRuleController.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/controller/GenerationRuleController.java @@ -2,11 +2,13 @@ import lombok.RequiredArgsConstructor; import net.firedevops.firemud.common.ApiResponse; +import net.firedevops.firemud.common.ErrorDetail; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.worldmanagement.dto.GenerationRuleDto; import net.firedevops.firemud.worldmanagement.service.GenerationRuleService; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @@ -24,8 +26,12 @@ public class GenerationRuleController { @PostMapping public ResponseEntity> save(@RequestBody GenerationRuleDto dto) { SessionContext.requireTenantAccess(dto.tenantId()); - GenerationRuleDto result = generationRuleService.saveRule(dto); - return ResponseEntity.ok(ApiResponse.success(result)); + return ResponseEntity.status(HttpStatus.PRECONDITION_FAILED) + .body( + ApiResponse.error( + new ErrorDetail( + "FAILED_PRECONDITION", + "Generation rule writes are unavailable without canonical Draft and Account commit authorization"))); } @GetMapping diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldDesignAggregateEpochRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldDesignAggregateEpochRepository.java index dab8cc6563..8a42363fcd 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldDesignAggregateEpochRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldDesignAggregateEpochRepository.java @@ -42,6 +42,56 @@ public Optional findById(Long id) { .fetchOptional(this::toEntity); } + public boolean compareAndAdvance( + Long tenantId, + Long versionId, + String aggregateType, + Long aggregateId, + Long expectedEpoch, + LocalDateTime updatedAt) { + if (expectedEpoch == null || expectedEpoch < 0L || expectedEpoch == Long.MAX_VALUE) { + return false; + } + + long nextEpoch = expectedEpoch + 1L; + LocalDateTime advancementTime = updatedAt == null ? LocalDateTime.now() : updatedAt; + int updated = + dsl.update(WORLD_DESIGN_AGGREGATE_EPOCH) + .set(WORLD_DESIGN_AGGREGATE_EPOCH.DRAFT_REVISION_EPOCH, nextEpoch) + .set(WORLD_DESIGN_AGGREGATE_EPOCH.UPDATED_AT, advancementTime) + .where( + WORLD_DESIGN_AGGREGATE_EPOCH + .TENANT_ID + .eq(tenantId) + .and(WORLD_DESIGN_AGGREGATE_EPOCH.VERSION_ID.eq(versionId)) + .and(WORLD_DESIGN_AGGREGATE_EPOCH.AGGREGATE_TYPE.eq(aggregateType)) + .and(WORLD_DESIGN_AGGREGATE_EPOCH.AGGREGATE_ID.eq(aggregateId)) + .and(WORLD_DESIGN_AGGREGATE_EPOCH.DRAFT_REVISION_EPOCH.eq(expectedEpoch))) + .execute(); + if (updated == 1) { + return true; + } + if (expectedEpoch != 0L) { + return false; + } + + return dsl.insertInto(WORLD_DESIGN_AGGREGATE_EPOCH) + .set(WORLD_DESIGN_AGGREGATE_EPOCH.TENANT_ID, tenantId) + .set(WORLD_DESIGN_AGGREGATE_EPOCH.VERSION_ID, versionId) + .set(WORLD_DESIGN_AGGREGATE_EPOCH.AGGREGATE_TYPE, aggregateType) + .set(WORLD_DESIGN_AGGREGATE_EPOCH.AGGREGATE_ID, aggregateId) + .set(WORLD_DESIGN_AGGREGATE_EPOCH.DRAFT_REVISION_EPOCH, nextEpoch) + .set(WORLD_DESIGN_AGGREGATE_EPOCH.UPDATED_AT, advancementTime) + .onConflict( + WORLD_DESIGN_AGGREGATE_EPOCH.TENANT_ID, + WORLD_DESIGN_AGGREGATE_EPOCH.VERSION_ID, + WORLD_DESIGN_AGGREGATE_EPOCH.AGGREGATE_TYPE, + WORLD_DESIGN_AGGREGATE_EPOCH.AGGREGATE_ID) + .doNothing() + .execute() + == 1; + } + public WorldDesignAggregateEpoch save(WorldDesignAggregateEpoch entity) { if (entity.getId() == null) { WorldDesignAggregateEpochRecord record = dsl.newRecord(WORLD_DESIGN_AGGREGATE_EPOCH); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldDesignScopeEpochRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldDesignScopeEpochRepository.java index 5cab979244..bbde37ea81 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldDesignScopeEpochRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldDesignScopeEpochRepository.java @@ -41,6 +41,56 @@ public Optional findById(Long id) { .fetchOptional(this::toEntity); } + public boolean compareAndAdvance( + Long tenantId, + Long versionId, + String scopeType, + String scopeId, + Long expectedEpoch, + LocalDateTime updatedAt) { + if (expectedEpoch == null || expectedEpoch < 0L || expectedEpoch == Long.MAX_VALUE) { + return false; + } + + long nextEpoch = expectedEpoch + 1L; + LocalDateTime advancementTime = updatedAt == null ? LocalDateTime.now() : updatedAt; + int updated = + dsl.update(WORLD_DESIGN_SCOPE_EPOCH) + .set(WORLD_DESIGN_SCOPE_EPOCH.DRAFT_SCOPE_REVISION_EPOCH, nextEpoch) + .set(WORLD_DESIGN_SCOPE_EPOCH.UPDATED_AT, advancementTime) + .where( + WORLD_DESIGN_SCOPE_EPOCH + .TENANT_ID + .eq(tenantId) + .and(WORLD_DESIGN_SCOPE_EPOCH.VERSION_ID.eq(versionId)) + .and(WORLD_DESIGN_SCOPE_EPOCH.SCOPE_TYPE.eq(scopeType)) + .and(WORLD_DESIGN_SCOPE_EPOCH.SCOPE_ID.eq(scopeId)) + .and(WORLD_DESIGN_SCOPE_EPOCH.DRAFT_SCOPE_REVISION_EPOCH.eq(expectedEpoch))) + .execute(); + if (updated == 1) { + return true; + } + if (expectedEpoch != 0L) { + return false; + } + + return dsl.insertInto(WORLD_DESIGN_SCOPE_EPOCH) + .set(WORLD_DESIGN_SCOPE_EPOCH.TENANT_ID, tenantId) + .set(WORLD_DESIGN_SCOPE_EPOCH.VERSION_ID, versionId) + .set(WORLD_DESIGN_SCOPE_EPOCH.SCOPE_TYPE, scopeType) + .set(WORLD_DESIGN_SCOPE_EPOCH.SCOPE_ID, scopeId) + .set(WORLD_DESIGN_SCOPE_EPOCH.DRAFT_SCOPE_REVISION_EPOCH, nextEpoch) + .set(WORLD_DESIGN_SCOPE_EPOCH.UPDATED_AT, advancementTime) + .onConflict( + WORLD_DESIGN_SCOPE_EPOCH.TENANT_ID, + WORLD_DESIGN_SCOPE_EPOCH.VERSION_ID, + WORLD_DESIGN_SCOPE_EPOCH.SCOPE_TYPE, + WORLD_DESIGN_SCOPE_EPOCH.SCOPE_ID) + .doNothing() + .execute() + == 1; + } + public WorldDesignScopeEpoch save(WorldDesignScopeEpoch entity) { if (entity.getId() == null) { WorldDesignScopeEpochRecord record = dsl.newRecord(WORLD_DESIGN_SCOPE_EPOCH); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java index 56116505a8..1b83df4777 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java @@ -91,14 +91,20 @@ public WorldDesignMutationResultDto applyMutation(WorldDesignMutationRequestDto validateExpectedAggregateEpochBeforeMutation(request); Long aggregateId = applyAggregateMutation(request); - WorldDesignAggregateEpoch aggregateEpoch = - aggregateEpochRepository - .findByTenantIdAndVersionIdAndAggregateTypeAndAggregateId( - request.tenantId(), request.versionId(), request.aggregateType(), aggregateId) - .orElseGet(() -> newAggregateEpoch(request, aggregateId)); - aggregateEpoch.setDraftRevisionEpoch(aggregateEpoch.getDraftRevisionEpoch() + 1L); - aggregateEpoch.setUpdatedAt(LocalDateTime.now()); - aggregateEpochRepository.save(aggregateEpoch); + long aggregateEpochAfter = request.expectedDraftRevisionEpoch() + 1L; + if (!aggregateEpochRepository.compareAndAdvance( + request.tenantId(), + request.versionId(), + request.aggregateType(), + aggregateId, + request.expectedDraftRevisionEpoch(), + LocalDateTime.now())) { + throw appError( + "DRAFT_WRITE_CONFLICT", + "expected Draft aggregate epoch " + + request.expectedDraftRevisionEpoch() + + " changed before the mutation could commit"); + } Long scopeEpochAfter = advanceScopeEpoch(request); @@ -112,7 +118,7 @@ public WorldDesignMutationResultDto applyMutation(WorldDesignMutationRequestDto ledger.setRequestedAggregateId(requestedAggregateId); ledger.setAppliedAggregateId(aggregateId); ledger.setResult(RESULT_APPLIED); - ledger.setAggregateEpochAfter(aggregateEpoch.getDraftRevisionEpoch()); + ledger.setAggregateEpochAfter(aggregateEpochAfter); ledger.setScopeEpochAfter(scopeEpochAfter); ledgerRepository.save(ledger); @@ -121,7 +127,7 @@ public WorldDesignMutationResultDto applyMutation(WorldDesignMutationRequestDto request.tenantId(), request.versionId(), aggregateId, - aggregateEpoch.getDraftRevisionEpoch(), + aggregateEpochAfter, scopeEpochAfter); } @@ -374,6 +380,10 @@ private Long applyWorldGenerationSubtree(WorldDesignMutationRequestDto request) } private void validateExpectedAggregateEpochBeforeMutation(WorldDesignMutationRequestDto request) { + if (!isAdvanceableEpoch(request.expectedDraftRevisionEpoch())) { + throw appError( + "DRAFT_WRITE_CONFLICT", "expected Draft aggregate epoch cannot be advanced safely"); + } if (StringUtils.hasText(request.aggregateId())) { validateExpectedAggregateEpoch(request, parseId(request.aggregateId(), "aggregate_id")); return; @@ -409,6 +419,10 @@ private void validateExpectedScopeEpochBeforeMutation(WorldDesignMutationRequest if (!StringUtils.hasText(request.scopeType()) && !StringUtils.hasText(request.scopeId())) { return; } + if (!isAdvanceableEpoch(request.expectedDraftScopeRevisionEpoch())) { + throw appError( + "DRAFT_WRITE_CONFLICT", "expected Draft scope epoch cannot be advanced safely"); + } String scopeType = requireText(request.scopeType(), "scope_type"); String scopeId = requireNormalizedScopeId(request); Long currentEpoch = @@ -733,24 +747,20 @@ private Long advanceScopeEpoch(WorldDesignMutationRequestDto request) { } String scopeType = requireText(request.scopeType(), "scope_type"); String scopeId = requireNormalizedScopeId(request); - WorldDesignScopeEpoch scopeEpoch = - scopeEpochRepository - .findByTenantIdAndVersionIdAndScopeTypeAndScopeId( - request.tenantId(), request.versionId(), scopeType, scopeId) - .orElseGet(() -> newScopeEpoch(request, scopeType, scopeId)); - if (!scopeEpoch - .getDraftScopeRevisionEpoch() - .equals(request.expectedDraftScopeRevisionEpoch())) { + if (!scopeEpochRepository.compareAndAdvance( + request.tenantId(), + request.versionId(), + scopeType, + scopeId, + request.expectedDraftScopeRevisionEpoch(), + LocalDateTime.now())) { throw appError( "DRAFT_WRITE_CONFLICT", "expected Draft scope epoch " + request.expectedDraftScopeRevisionEpoch() - + " but found " - + scopeEpoch.getDraftScopeRevisionEpoch()); + + " changed before the mutation could commit"); } - scopeEpoch.setDraftScopeRevisionEpoch(scopeEpoch.getDraftScopeRevisionEpoch() + 1L); - scopeEpoch.setUpdatedAt(LocalDateTime.now()); - return scopeEpochRepository.save(scopeEpoch).getDraftScopeRevisionEpoch(); + return request.expectedDraftScopeRevisionEpoch() + 1L; } private void requireDraftVersion(long tenantId, long versionId) { @@ -817,24 +827,8 @@ private void failIfSeedAppendOnlyUpdate(WorldDesignMutationRequestDto request) { } } - private WorldDesignAggregateEpoch newAggregateEpoch( - WorldDesignMutationRequestDto request, Long aggregateId) { - WorldDesignAggregateEpoch epoch = new WorldDesignAggregateEpoch(); - epoch.setTenantId(request.tenantId()); - epoch.setVersionId(request.versionId()); - epoch.setAggregateType(request.aggregateType()); - epoch.setAggregateId(aggregateId); - return epoch; - } - - private WorldDesignScopeEpoch newScopeEpoch( - WorldDesignMutationRequestDto request, String scopeType, String scopeId) { - WorldDesignScopeEpoch epoch = new WorldDesignScopeEpoch(); - epoch.setTenantId(request.tenantId()); - epoch.setVersionId(request.versionId()); - epoch.setScopeType(scopeType); - epoch.setScopeId(scopeId); - return epoch; + private boolean isAdvanceableEpoch(long epoch) { + return epoch >= 0L && epoch < Long.MAX_VALUE; } private Region existingRegion(WorldDesignMutationRequestDto request) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java index 39566abf51..cf4e5eee5e 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java @@ -3,7 +3,6 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; -import java.util.List; import java.util.Optional; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; @@ -21,7 +20,6 @@ import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto.RoomExitSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RuntimeRoomDto; -import net.firedevops.firemud.worldmanagement.dto.WorldDesignMutationRequestDto; import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; import net.firedevops.firemud.worldmanagement.service.PingService; import net.firedevops.firemud.worldmanagement.service.RoomService; @@ -37,10 +35,6 @@ import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationResponse; import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse; -import net.firedevops.firemud.worldmanagement.v1.GeneratedRoomDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.GeneratedRoomExitDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.GeneratedWorldEntitySpawnBindingDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestRequest; import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestResponse; import net.firedevops.firemud.worldmanagement.v1.GetRoomRequest; @@ -54,9 +48,6 @@ import net.firedevops.firemud.worldmanagement.v1.PingResponse; import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse; -import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomExitSnapshot; import net.firedevops.firemud.worldmanagement.v1.RoomSnapshot; import net.firedevops.firemud.worldmanagement.v1.RuntimeRoom; @@ -65,13 +56,9 @@ import net.firedevops.firemud.worldmanagement.v1.UpgradeValidationResult; import net.firedevops.firemud.worldmanagement.v1.ValidateWorldUpgradeMappingsRequest; import net.firedevops.firemud.worldmanagement.v1.ValidateWorldUpgradeMappingsResponse; -import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; -import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.WorldGenerationSubtreeDesignMutation; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; -import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -89,7 +76,6 @@ public class WorldManagementGrpcService private final RoomService roomService; private final WorldInstanceActivationService worldInstanceActivationService; private final WorldDraftDesignDigestService worldDraftDesignDigestService; - private final WorldDesignMutationService worldDesignMutationService; private final WorldUpgradeValidationService worldUpgradeValidationService; private final GameplaySessionAttestationService gameplaySessionAttestationService; private final MeterRegistry meterRegistry; @@ -113,7 +99,6 @@ private WorldManagementGrpcService( this.roomService = roomService; this.worldInstanceActivationService = worldInstanceActivationService; this.worldDraftDesignDigestService = worldDraftDesignDigestService; - this.worldDesignMutationService = worldDesignMutationService; this.worldUpgradeValidationService = worldUpgradeValidationService; this.gameplaySessionAttestationService = gameplaySessionAttestationService; this.meterRegistry = meterRegistry; @@ -523,33 +508,13 @@ public void applyWorldDesignMutation( StreamObserver responseObserver) { ApplyWorldDesignMutationResponse.Builder builder = ApplyWorldDesignMutationResponse.newBuilder(); - try { - var result = worldDesignMutationService.applyMutation(toDto(request)); - builder - .setResult(toProtoMutationResult(result.result())) - .setTenantId(Long.toString(result.tenantId())) - .setVersionId(Long.toString(result.versionId())) - .setAggregateId(Long.toString(result.aggregateId())) - .setDraftRevisionEpoch(result.draftRevisionEpoch()); - if (result.draftScopeRevisionEpoch() != null) { - builder.setDraftScopeRevisionEpoch(result.draftScopeRevisionEpoch()); - } - } catch (NumberFormatException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, logger, "ApplyWorldDesignMutation", "INVALID_ARGUMENT", "invalid id")); - } catch (IllegalArgumentException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ApplyWorldDesignMutation", - errorCodeFor(ex), - errorMessageFor(ex))); - } catch (Exception ex) { - builder.setError( - GrpcAppErrors.internal(meterRegistry, logger, "ApplyWorldDesignMutation", ex)); - } + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ApplyWorldDesignMutation", + "FAILED_PRECONDITION", + "Canonical World Draft writes are unavailable until current Account commit authorization is verified.")); responseObserver.onNext(builder.build()); responseObserver.onCompleted(); } @@ -880,163 +845,6 @@ private String errorMessageFor(IllegalArgumentException ex) { return message; } - private WorldDesignMutationRequestDto toDto(ApplyWorldDesignMutationRequest request) { - return new WorldDesignMutationRequestDto( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getVersionId(), "versionId"), - request.getCommitId(), - request.getRevisionId(), - operationName(request), - aggregateTypeName(request), - request.getAggregateId(), - request.getExpectedDraftRevisionEpoch(), - request.getScopeType() - == net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType - .WORLD_DESIGN_SCOPE_TYPE_UNSPECIFIED - ? "" - : request.getScopeType().name().replace("WORLD_DESIGN_SCOPE_TYPE_", ""), - request.getScopeId(), - request.getExpectedDraftScopeRevisionEpoch(), - request.getScopeMutationPolicy() - == net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy - .WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED - ? "" - : request - .getScopeMutationPolicy() - .name() - .replace("WORLD_DESIGN_SCOPE_MUTATION_POLICY_", ""), - request.hasRegion() ? toDto(request.getRegion()) : null, - request.hasZone() ? toDto(request.getZone()) : null, - request.hasRoom() ? toDto(request.getRoom()) : null, - request.hasRoomExit() ? toDto(request.getRoomExit()) : null, - request.hasGenerationRule() ? toDto(request.getGenerationRule()) : null, - request.hasWorldEntitySpawnBinding() ? toDto(request.getWorldEntitySpawnBinding()) : null, - request.hasWorldGenerationSubtree() ? toDto(request.getWorldGenerationSubtree()) : null); - } - - private String operationName(ApplyWorldDesignMutationRequest request) { - return switch (request.getOperation()) { - case WORLD_DESIGN_MUTATION_OPERATION_UPSERT -> "UPSERT"; - case WORLD_DESIGN_MUTATION_OPERATION_DELETE -> "DELETE"; - default -> ""; - }; - } - - private String aggregateTypeName(ApplyWorldDesignMutationRequest request) { - return switch (request.getAggregateType()) { - case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> "REGION"; - case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> "ZONE"; - case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> "ROOM"; - case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> "ROOM_EXIT"; - case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> "GENERATION_RULE"; - case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> "WORLD_ENTITY_SPAWN_BINDING"; - case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_GENERATION_SUBTREE -> "WORLD_GENERATION_SUBTREE"; - default -> ""; - }; - } - - private WorldDesignMutationRequestDto.RegionMutationDto toDto(RegionDesignMutation mutation) { - return new WorldDesignMutationRequestDto.RegionMutationDto( - mutation.getName(), - mutation.getWeather(), - mutation.getShardId(), - mutation.getGenerationSeed(), - mutation.getGeneratorType(), - mutation.getGeneratorParams(), - mutation.getSpacingMultiplier()); - } - - private WorldDesignMutationRequestDto.ZoneMutationDto toDto(ZoneDesignMutation mutation) { - return new WorldDesignMutationRequestDto.ZoneMutationDto( - mutation.getName(), mutation.getRegionId()); - } - - private WorldDesignMutationRequestDto.RoomMutationDto toDto(RoomDesignMutation mutation) { - return new WorldDesignMutationRequestDto.RoomMutationDto( - mutation.getName(), - mutation.getDescription(), - mutation.getZoneId(), - mutation.getNameLocalizedVariantsJson(), - mutation.getDescriptionLocalizedVariantsJson()); - } - - private WorldDesignMutationRequestDto.RoomExitMutationDto toDto(RoomExitDesignMutation mutation) { - return new WorldDesignMutationRequestDto.RoomExitMutationDto( - mutation.getFromRoomId(), - mutation.getToRoomId(), - mutation.getDirection(), - mutation.getCost()); - } - - private WorldDesignMutationRequestDto.GenerationRuleMutationDto toDto( - GenerationRuleDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GenerationRuleMutationDto( - mutation.getName(), mutation.getValue()); - } - - private WorldDesignMutationRequestDto.WorldEntitySpawnBindingMutationDto toDto( - WorldEntitySpawnBindingDesignMutation mutation) { - return new WorldDesignMutationRequestDto.WorldEntitySpawnBindingMutationDto( - mutation.getRoomId(), - mutation.getEntityTemplateType().name().replace("ENTITY_TEMPLATE_REFERENCE_TYPE_", ""), - mutation.getEntityTemplateId(), - mutation.getSpawnCount(), - mutation.getRespawnDelaySeconds()); - } - - private WorldDesignMutationRequestDto.WorldGenerationSubtreeMutationDto toDto( - WorldGenerationSubtreeDesignMutation mutation) { - List generationRules = - mutation.getGenerationRulesList().stream().map(this::toDto).toList(); - List rooms = - mutation.getRoomsList().stream().map(this::toDto).toList(); - List roomExits = - mutation.getRoomExitsList().stream().map(this::toDto).toList(); - List spawnBindings = - mutation.getWorldEntitySpawnBindingsList().stream().map(this::toDto).toList(); - return new WorldDesignMutationRequestDto.WorldGenerationSubtreeMutationDto( - generationRules, rooms, roomExits, spawnBindings); - } - - private WorldDesignMutationRequestDto.GeneratedRoomMutationDto toDto( - GeneratedRoomDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GeneratedRoomMutationDto( - mutation.getClientRef(), - mutation.getName(), - mutation.getDescription(), - mutation.getZoneId(), - mutation.getNameLocalizedVariantsJson(), - mutation.getDescriptionLocalizedVariantsJson()); - } - - private WorldDesignMutationRequestDto.GeneratedRoomExitMutationDto toDto( - GeneratedRoomExitDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GeneratedRoomExitMutationDto( - mutation.getFromRoomRef(), - mutation.getToRoomRef(), - mutation.getDirection(), - mutation.getCost()); - } - - private WorldDesignMutationRequestDto.GeneratedWorldEntitySpawnBindingMutationDto toDto( - GeneratedWorldEntitySpawnBindingDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GeneratedWorldEntitySpawnBindingMutationDto( - mutation.getRoomRef(), - mutation.getEntityTemplateType().name().replace("ENTITY_TEMPLATE_REFERENCE_TYPE_", ""), - mutation.getEntityTemplateId(), - mutation.getSpawnCount(), - mutation.getRespawnDelaySeconds()); - } - - private WorldDesignMutationResult toProtoMutationResult(String result) { - return switch (result) { - case "APPLIED" -> WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_APPLIED; - case "NO_OP_ALREADY_APPLIED" -> - WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_NO_OP_ALREADY_APPLIED; - default -> WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED; - }; - } - private UpgradeValidationResult toUpgradeValidationResult(String result) { return switch (result) { case "COMPATIBLE" -> UpgradeValidationResult.UPGRADE_VALIDATION_RESULT_COMPATIBLE; diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityReceipt.java new file mode 100644 index 0000000000..2d70ec8b9d --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityReceipt.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; + +/** + * Immutable World-local identity association for one fresh authored Version. + * + *

This retains source-qualified identity evidence and allocates a private World version key. It + * does not materialize content, authorize a Draft write, or permit lifecycle preparation. + */ +public record WorldAuthoredVersionIdentityReceipt( + int schemaVersion, + UUID operationId, + long localVersionKey, + WorldAuthoredSourceIntakeReceipt sourceIntakeReceipt, + AuthoredWorldVersionStateEvidence versionStateEvidence) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public WorldAuthoredVersionIdentityReceipt { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-Version identity version"); + } + requireNonNil(operationId, "operationId"); + if (localVersionKey <= 0) { + throw new IllegalArgumentException("localVersionKey must be positive"); + } + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(versionStateEvidence, "versionStateEvidence"); + versionStateEvidence.requireValid(); + + var source = sourceIntakeReceipt.source(); + var request = versionStateEvidence.request(); + if (!"NEW_GAME_ROW".equals(source.provenanceKind()) + || !sourceIntakeReceipt.targetNamespace().equals(request.targetNamespace()) + || !sourceIntakeReceipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !sourceIntakeReceipt.worldSlug().equals(request.worldSlug()) + || !sourceIntakeReceipt.sourceOperationId().equals(request.sourceOperationId()) + || !sourceIntakeReceipt + .sourceEvidenceDigest() + .equals(request.expectedSourceEvidenceDigest()) + || !source.equals(versionStateEvidence.sourceEvidence())) { + throw new IllegalArgumentException( + "World Version identity differs from its exact fresh source intake"); + } + UUID readRequestId = request.readRequestId(); + if (readRequestId.equals(versionStateEvidence.canonicalVersionId()) + || readRequestId.equals(operationId) + || readRequestId.equals(sourceIntakeReceipt.operationId()) + || readRequestId.equals(sourceIntakeReceipt.intakeRequestId()) + || readRequestId.equals(sourceIntakeReceipt.sourceOperationId()) + || readRequestId.equals(source.registrationRequestId())) { + throw new IllegalArgumentException( + "Version-state readRequestId must be separate from source and owner identities"); + } + if (versionStateEvidence.versionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT + && versionStateEvidence.versionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && versionStateEvidence.versionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new IllegalArgumentException( + "World Version identity requires DRAFT, PUBLISHED, or ACTIVE owner evidence"); + } + } + + public UUID canonicalVersionId() { + return versionStateEvidence.canonicalVersionId(); + } + + public long gameDesignVersionId() { + return versionStateEvidence.request().versionId(); + } + + public String targetNamespace() { + return sourceIntakeReceipt.targetNamespace(); + } + + public UUID canonicalTenantId() { + return sourceIntakeReceipt.canonicalTenantId(); + } + + public String worldSlug() { + return sourceIntakeReceipt.worldSlug(); + } + + 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/WorldAuthoredVersionIdentityRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java new file mode 100644 index 0000000000..94902a39ef --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java @@ -0,0 +1,386 @@ +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 net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.gamedesign.v1.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.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Owner-local immutable association between a fresh authored Version UUID and a World key. */ +public class WorldAuthoredVersionIdentityRepository { + private static final Table VERSION_IDENTITY = + DSL.table(DSL.name("world_authored_version_identity")); + private static final JsonMapper CLOSED_JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + 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 WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field GAME_DESIGN_VERSION_ID = + DSL.field(DSL.name("game_design_version_id"), Long.class); + private static final Field LOCAL_VERSION_KEY = + DSL.field(DSL.name("local_version_key"), 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 LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_digest"), String.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 VERSION_STATE_SCHEMA_VERSION = + DSL.field(DSL.name("version_state_schema_version"), Short.class); + private static final Field VERSION_STATE_READ_REQUEST_ID = + DSL.field(DSL.name("version_state_read_request_id"), UUID.class); + private static final Field VERSION_STATE_STATE = + DSL.field(DSL.name("version_state_state"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final Field VERSION_STATE_EVIDENCE_DIGEST = + DSL.field(DSL.name("version_state_evidence_digest"), String.class); + private static final Field VERSION_STATE_EVIDENCE_JSON = + DSL.field(DSL.name("version_state_evidence_json"), String.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The injected DSLContext is an internal collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldAuthoredVersionIdentityRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** Reads the immutable identity by canonical Version UUID after the owner transaction commits. */ + public Optional readByCanonicalVersion( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + requireNoActiveTransaction("World authored-Version identity read"); + validateIdentityKey(namespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + Record row = + findByCanonicalVersion(namespace, canonicalTenantId, worldSlug, canonicalVersionId); + return row == null ? Optional.empty() : Optional.of(toReceipt(row)); + } + + /** Reads an immutable identity by the exact Game Design-owned numeric Version selector. */ + public Optional readByGameDesignVersion( + String namespace, UUID canonicalTenantId, String worldSlug, long gameDesignVersionId) { + requireNoActiveTransaction("World authored-Version identity read"); + validateIdentityKey(namespace, canonicalTenantId, worldSlug); + requirePositive(gameDesignVersionId, "gameDesignVersionId"); + Record row = + findByGameDesignVersion(namespace, canonicalTenantId, worldSlug, gameDesignVersionId); + return row == null ? Optional.empty() : Optional.of(toReceipt(row)); + } + + /** + * Atomically claims the source-qualified Version identity with a World-allocated local key. + * + *

Concurrent requests for the same stable source, canonical UUID, and Game Design selector + * return the first stored receipt even when their transport read IDs or current state epochs + * differ. Changed source or selector evidence conflicts without replacing that receipt. + */ + public WorldAuthoredVersionIdentityReceipt acceptFresh( + WorldAuthoredSourceIntakeReceipt sourceReceipt, + AuthoredWorldVersionStateEvidence versionStateEvidence) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + Objects.requireNonNull(versionStateEvidence, "versionStateEvidence"); + validateFreshEvidence(sourceReceipt, versionStateEvidence); + + AuthoredWorldVersionStateEvidence.Request request = versionStateEvidence.request(); + UUID operationId = newNonNilUuid(); + int inserted = + dsl.insertInto(VERSION_IDENTITY) + .set(OPERATION_ID, operationId) + .set(TARGET_NAMESPACE, sourceReceipt.targetNamespace()) + .set(CANONICAL_TENANT_ID, sourceReceipt.canonicalTenantId()) + .set(WORLD_SLUG, sourceReceipt.worldSlug()) + .set(CANONICAL_VERSION_ID, versionStateEvidence.canonicalVersionId()) + .set(GAME_DESIGN_VERSION_ID, request.versionId()) + .set(INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(LOCAL_TENANT_KEY, sourceReceipt.localTenantKey()) + .set(INTAKE_REQUEST_DIGEST, sourceReceipt.requestDigest()) + .set(SOURCE_OPERATION_ID, sourceReceipt.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, sourceReceipt.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(VERSION_STATE_SCHEMA_VERSION, (short) request.schemaVersion()) + .set(VERSION_STATE_READ_REQUEST_ID, request.readRequestId()) + .set(VERSION_STATE_STATE, lifecycleToken(versionStateEvidence.versionState())) + .set(VERSION_STATE_EPOCH, versionStateEvidence.versionStateEpoch()) + .set(VERSION_STATE_EVIDENCE_DIGEST, versionStateEvidence.evidenceDigest()) + .set(VERSION_STATE_EVIDENCE_JSON, writeJson(versionStateEvidence)) + .onConflictDoNothing() + .execute(); + + Record row = + findByCanonicalVersion( + sourceReceipt.targetNamespace(), + sourceReceipt.canonicalTenantId(), + sourceReceipt.worldSlug(), + versionStateEvidence.canonicalVersionId()); + if (row == null) { + row = + findByGameDesignVersion( + sourceReceipt.targetNamespace(), + sourceReceipt.canonicalTenantId(), + sourceReceipt.worldSlug(), + request.versionId()); + } + if (row == null) { + throw new InvalidIdentityEvidenceException( + "World authored-Version identity is missing after its owner claim"); + } + + WorldAuthoredVersionIdentityReceipt receipt = toReceipt(row); + requireSameIdentity(receipt, sourceReceipt, versionStateEvidence); + if (inserted == 0) { + // A duplicate request resolves only to the original immutable receipt; never rewrite it. + return receipt; + } + return receipt; + } + + private Record findByCanonicalVersion( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + return dsl.selectFrom(VERSION_IDENTITY) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(CANONICAL_VERSION_ID.eq(canonicalVersionId))) + .fetchOne(); + } + + private Record findByGameDesignVersion( + String namespace, UUID canonicalTenantId, String worldSlug, long gameDesignVersionId) { + return dsl.selectFrom(VERSION_IDENTITY) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(GAME_DESIGN_VERSION_ID.eq(gameDesignVersionId))) + .fetchOne(); + } + + private WorldAuthoredVersionIdentityReceipt toReceipt(Record row) { + try { + UUID operationId = required(row, OPERATION_ID); + String namespace = required(row, TARGET_NAMESPACE); + UUID canonicalTenantId = required(row, CANONICAL_TENANT_ID); + String worldSlug = required(row, WORLD_SLUG); + UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); + Long gameDesignVersionId = required(row, GAME_DESIGN_VERSION_ID); + Long localVersionKey = required(row, LOCAL_VERSION_KEY); + UUID intakeOperationId = required(row, INTAKE_OPERATION_ID); + UUID intakeRequestId = required(row, INTAKE_REQUEST_ID); + Long localTenantKey = required(row, LOCAL_TENANT_KEY); + String intakeRequestDigest = required(row, INTAKE_REQUEST_DIGEST); + UUID sourceOperationId = required(row, SOURCE_OPERATION_ID); + String sourceEvidenceDigest = required(row, SOURCE_EVIDENCE_DIGEST); + String intakeReceiptDigest = required(row, INTAKE_RECEIPT_DIGEST); + Short versionStateSchemaVersion = required(row, VERSION_STATE_SCHEMA_VERSION); + UUID readRequestId = required(row, VERSION_STATE_READ_REQUEST_ID); + String versionStateToken = required(row, VERSION_STATE_STATE); + Long versionStateEpoch = required(row, VERSION_STATE_EPOCH); + String versionStateEvidenceDigest = required(row, VERSION_STATE_EVIDENCE_DIGEST); + AuthoredWorldVersionStateEvidence evidence = + readJson(required(row, VERSION_STATE_EVIDENCE_JSON)); + + if (versionStateSchemaVersion != evidence.request().schemaVersion() + || !readRequestId.equals(evidence.request().readRequestId()) + || !versionStateToken.equals(lifecycleToken(evidence.versionState())) + || !versionStateEpoch.equals(evidence.versionStateEpoch()) + || !versionStateEvidenceDigest.equals(evidence.evidenceDigest()) + || !canonicalVersionId.equals(evidence.canonicalVersionId()) + || gameDesignVersionId != evidence.request().versionId()) { + throw new IllegalArgumentException( + "Persisted World Version identity columns differ from their closed evidence"); + } + + WorldAuthoredSourceIntakeReceipt sourceReceipt = + new WorldAuthoredSourceIntakeReceipt( + 1, + namespace, + intakeRequestId, + intakeOperationId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + intakeRequestDigest, + intakeReceiptDigest, + localTenantKey, + evidence.sourceEvidence()); + return new WorldAuthoredVersionIdentityReceipt( + 1, operationId, localVersionKey, sourceReceipt, evidence); + } catch (RuntimeException exception) { + if (exception instanceof InvalidIdentityEvidenceException) { + throw exception; + } + throw new InvalidIdentityEvidenceException( + "Persisted World authored-Version identity evidence is invalid", exception); + } + } + + private static void validateFreshEvidence( + WorldAuthoredSourceIntakeReceipt sourceReceipt, AuthoredWorldVersionStateEvidence evidence) { + evidence.requireValid(); + AuthoredWorldVersionStateEvidence.Request request = evidence.request(); + if (!"NEW_GAME_ROW".equals(sourceReceipt.source().provenanceKind()) + || !sourceReceipt.targetNamespace().equals(request.targetNamespace()) + || !sourceReceipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !sourceReceipt.worldSlug().equals(request.worldSlug()) + || !sourceReceipt.sourceOperationId().equals(request.sourceOperationId()) + || !sourceReceipt.sourceEvidenceDigest().equals(request.expectedSourceEvidenceDigest()) + || !sourceReceipt.source().equals(evidence.sourceEvidence())) { + throw new RegistrationConflictException( + "World Version identity evidence differs from the exact fresh source intake"); + } + } + + private static void requireSameIdentity( + WorldAuthoredVersionIdentityReceipt receipt, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + AuthoredWorldVersionStateEvidence candidate) { + if (!receipt.sourceIntakeReceipt().equals(sourceReceipt) + || !receipt.canonicalVersionId().equals(candidate.canonicalVersionId()) + || receipt.gameDesignVersionId() != candidate.request().versionId()) { + throw new RegistrationConflictException( + "World Version identity scope, source intake, or Game Design selector conflicts"); + } + } + + private static String writeJson(Object value) { + try { + return CLOSED_JSON.writeValueAsString(value); + } catch (Exception exception) { + throw new InvalidIdentityEvidenceException( + "World Version identity evidence could not be encoded", exception); + } + } + + private static AuthoredWorldVersionStateEvidence readJson(String json) { + try { + AuthoredWorldVersionStateEvidence evidence = + CLOSED_JSON.readValue(json, AuthoredWorldVersionStateEvidence.class); + if (!writeJson(evidence).equals(json)) { + throw new IllegalArgumentException( + "Persisted Version-state evidence JSON is not in its closed form"); + } + evidence.requireValid(); + return evidence; + } catch (Exception exception) { + throw new InvalidIdentityEvidenceException( + "Persisted Version-state JSON is not closed evidence", exception); + } + } + + private static String lifecycleToken(VersionLifecycleState state) { + return switch (state) { + case VERSION_LIFECYCLE_STATE_DRAFT -> "DRAFT"; + case VERSION_LIFECYCLE_STATE_PUBLISHED -> "PUBLISHED"; + case VERSION_LIFECYCLE_STATE_ACTIVE -> "ACTIVE"; + default -> + throw new InvalidIdentityEvidenceException( + "World Version identity requires DRAFT, PUBLISHED, or ACTIVE owner evidence"); + }; + } + + private static T required(Record row, Field field) { + return Objects.requireNonNull(row.get(field), "Persisted " + field.getName() + " is null"); + } + + private static void validateIdentityKey( + String namespace, UUID canonicalTenantId, String worldSlug) { + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " requires an independent committed owner read"); + } + } + + private static void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-Version identity requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World authored-Version identity requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World authored-Version identity requires READ COMMITTED isolation"); + } + } + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidIdentityEvidenceException extends IllegalStateException { + public InvalidIdentityEvidenceException(String message) { + super(message); + } + + public InvalidIdentityEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java new file mode 100644 index 0000000000..45355f38ed --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java @@ -0,0 +1,340 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired World owner step that associates a fresh source-owned Version UUID with a + * private World identity key. + * + *

This identity receipt is non-admitting. It does not materialize content or authorize Draft + * writes, publication, lifecycle preparation, or runtime activation. + */ +public final class WorldAuthoredVersionIdentityService { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AuthoredWorldVersionStateClient versionStateClient; + private final WorldAuthoredVersionIdentityRepository repository; + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public WorldAuthoredVersionIdentityService( + AuthoredWorldVersionStateClient versionStateClient, + WorldAuthoredVersionIdentityRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.versionStateClient = Objects.requireNonNull(versionStateClient, "versionStateClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + this.sourceIntakeRepository = + Objects.requireNonNull(sourceIntakeRepository, "sourceIntakeRepository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Associates one source-owned Version selector and canonical UUID with a World-local key. + * + *

The stable identity is `(namespace, canonical tenant, world, canonical Version UUID)`. + * `readRequestId` is transport correlation only. Exact retries read the original stored receipt + * before calling Game Design again. + */ + public WorldAuthoredVersionIdentityReceipt associate( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + UUID expectedCanonicalVersionId, + long gameDesignVersionId, + UUID readRequestId) { + requireAuthenticatedGameDesignCaller(); + requireNoAmbientTransaction(); + validateRequest( + targetNamespace, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + expectedCanonicalVersionId, + gameDesignVersionId, + readRequestId); + + WorldAuthoredSourceIntakeReceipt sourceReceipt = + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest); + requireFreshReadRequestId(readRequestId, expectedCanonicalVersionId, sourceReceipt); + + Optional prior = + repository.readByCanonicalVersion( + workloadNamespace, canonicalTenantId, worldSlug, expectedCanonicalVersionId); + if (prior.isPresent()) { + return requireSameIdentity( + prior.orElseThrow(), sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + } + Optional priorByGameDesignVersion = + repository.readByGameDesignVersion( + workloadNamespace, canonicalTenantId, worldSlug, gameDesignVersionId); + if (priorByGameDesignVersion.isPresent()) { + return requireSameIdentity( + priorByGameDesignVersion.orElseThrow(), + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId); + } + + AuthoredWorldVersionStateEvidence.Request currentRequest = + new AuthoredWorldVersionStateEvidence.Request( + SCHEMA_VERSION, + workloadNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + gameDesignVersionId); + AuthoredWorldVersionStateEvidence current; + try { + current = versionStateClient.read(currentRequest); + } catch (RuntimeException exception) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design source-qualified Version identity evidence is unavailable or invalid", + exception); + } + requireCurrentEvidence(current, currentRequest, sourceReceipt, expectedCanonicalVersionId); + + WorldAuthoredVersionIdentityReceipt accepted; + try { + accepted = ownerTransaction.execute(status -> repository.acceptFresh(sourceReceipt, current)); + } catch (RuntimeException ownerFailure) { + Optional committed = + repository.readByCanonicalVersion( + workloadNamespace, canonicalTenantId, worldSlug, expectedCanonicalVersionId); + if (committed.isPresent()) { + requireSameSourceIntake( + sourceReceipt, + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest)); + return requireSameIdentity( + committed.orElseThrow(), + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId); + } + Optional claimedSelector = + repository.readByGameDesignVersion( + workloadNamespace, canonicalTenantId, worldSlug, gameDesignVersionId); + if (claimedSelector.isPresent()) { + requireSameSourceIntake( + sourceReceipt, + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest)); + return requireSameIdentity( + claimedSelector.orElseThrow(), + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId); + } + throw ownerFailure; + } + if (accepted == null) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World owner transaction returned no Version identity receipt"); + } + requireSameIdentity(accepted, sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + + Optional committed = + repository.readByCanonicalVersion( + workloadNamespace, canonicalTenantId, worldSlug, expectedCanonicalVersionId); + if (committed.isEmpty()) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World Version identity is missing after its owner commit"); + } + WorldAuthoredVersionIdentityReceipt readback = committed.orElseThrow(); + requireSameSourceIntake( + sourceReceipt, + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest)); + requireSameIdentity(readback, sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + if (!accepted.equals(readback)) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World Version identity changed during independent commit readback"); + } + return readback; + } + + private WorldAuthoredVersionIdentityReceipt requireSameIdentity( + WorldAuthoredVersionIdentityReceipt receipt, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + UUID expectedCanonicalVersionId, + long gameDesignVersionId) { + if (!receipt.targetNamespace().equals(workloadNamespace) + || !receipt.sourceIntakeReceipt().equals(sourceReceipt) + || !receipt.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !receipt.worldSlug().equals(sourceReceipt.worldSlug()) + || !receipt.canonicalVersionId().equals(expectedCanonicalVersionId) + || receipt.gameDesignVersionId() != gameDesignVersionId) { + throw new WorldAuthoredVersionIdentityRepository.RegistrationConflictException( + "World Version identity scope, source intake, or selector conflicts with its first claim"); + } + return receipt; + } + + private void requireCurrentEvidence( + AuthoredWorldVersionStateEvidence evidence, + AuthoredWorldVersionStateEvidence.Request expectedRequest, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + UUID expectedCanonicalVersionId) { + if (evidence == null) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design returned no source-qualified Version identity evidence"); + } + try { + evidence.requireValid(); + } catch (RuntimeException exception) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design source-qualified Version identity evidence is invalid", exception); + } + if (!expectedRequest.equals(evidence.request()) + || !sourceReceipt.source().equals(evidence.sourceEvidence()) + || !expectedCanonicalVersionId.equals(evidence.canonicalVersionId())) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design Version identity evidence differs from the exact source and expected UUID"); + } + VersionLifecycleState state = evidence.versionState(); + if (state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT + && state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design Version identity evidence must be DRAFT, PUBLISHED, or ACTIVE"); + } + } + + private void requireExactFreshSourceIntake( + WorldAuthoredSourceIntakeReceipt sourceReceipt, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + if (!workloadNamespace.equals(sourceReceipt.targetNamespace()) + || !canonicalTenantId.equals(sourceReceipt.canonicalTenantId()) + || !worldSlug.equals(sourceReceipt.worldSlug()) + || !sourceOperationId.equals(sourceReceipt.sourceOperationId()) + || !sourceEvidenceDigest.equals(sourceReceipt.sourceEvidenceDigest()) + || !"NEW_GAME_ROW".equals(sourceReceipt.source().provenanceKind())) { + throw new WorldAuthoredVersionIdentityRepository.RegistrationConflictException( + "World Version identity requires the exact fresh NEW_GAME_ROW source intake"); + } + } + + private WorldAuthoredSourceIntakeReceipt readExactSourceIntake( + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + WorldAuthoredSourceIntakeReceipt sourceReceipt = + sourceIntakeRepository + .readBySource( + workloadNamespace, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest) + .orElseThrow( + () -> + new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World Version identity requires an exact committed fresh source intake")); + requireExactFreshSourceIntake( + sourceReceipt, canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest); + return sourceReceipt; + } + + private static void requireSameSourceIntake( + WorldAuthoredSourceIntakeReceipt expected, WorldAuthoredSourceIntakeReceipt actual) { + if (!expected.equals(actual)) { + throw new WorldAuthoredVersionIdentityRepository.RegistrationConflictException( + "World source intake changed during Version identity readback"); + } + } + + private void requireAuthenticatedGameDesignCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(workloadNamespace)) { + throw new SecurityException( + "World Version identity requires the authenticated same-namespace Game Design workload"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World Version identity cannot enter from an ambient transaction"); + } + } + + private void validateRequest( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + UUID expectedCanonicalVersionId, + long gameDesignVersionId, + UUID readRequestId) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new SecurityException("World Version identity namespace does not match this workload"); + } + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(sourceOperationId, "sourceOperationId"); + requireNonNil(expectedCanonicalVersionId, "expectedCanonicalVersionId"); + requireNonNil(readRequestId, "readRequestId"); + if (!GameTenantCreationDigest.isDigest(sourceEvidenceDigest)) { + throw new IllegalArgumentException("sourceEvidenceDigest must be a canonical SHA-256 digest"); + } + if (gameDesignVersionId <= 0) { + throw new IllegalArgumentException("gameDesignVersionId must be positive"); + } + } + + private static void requireFreshReadRequestId( + UUID readRequestId, + UUID expectedCanonicalVersionId, + WorldAuthoredSourceIntakeReceipt sourceReceipt) { + if (readRequestId.equals(expectedCanonicalVersionId) + || readRequestId.equals(sourceReceipt.operationId()) + || readRequestId.equals(sourceReceipt.intakeRequestId()) + || readRequestId.equals(sourceReceipt.sourceOperationId()) + || readRequestId.equals(sourceReceipt.source().registrationRequestId())) { + throw new IllegalArgumentException( + "Version-state readRequestId must be fresh and separate from source identities"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(NIL_UUID)) { + 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/WorldCompleteLaunchBindingReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingReceipt.java new file mode 100644 index 0000000000..a3b3c44f5e --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingReceipt.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; + +/** + * Internal World receipt for a retained authored-world descriptor and complete release pair. + * + *

This is non-admitting released-content evidence. It does not represent local content, + * PREPARING, ACTIVE/current authority, or activation. + */ +public record WorldCompleteLaunchBindingReceipt( + int schemaVersion, + UUID operationId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + WorldAuthoredSourceIntakeReceipt sourceIntakeReceipt, + CompleteLaunchBindingEvidence evidence) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public WorldCompleteLaunchBindingReceipt { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World complete launch binding version"); + } + requireNonNil(operationId, "operationId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(evidence, "evidence"); + + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !targetNamespace.equals(sourceIntakeReceipt.targetNamespace()) + || !canonicalTenantId.equals(sourceIntakeReceipt.canonicalTenantId()) + || !worldSlug.equals(sourceIntakeReceipt.worldSlug()) + || !descriptor + .authoredWorldSourceOperationId() + .equals(sourceIntakeReceipt.sourceOperationId()) + || !descriptor + .authoredWorldSourceEvidenceDigest() + .equals(sourceIntakeReceipt.sourceEvidenceDigest())) { + throw new IllegalArgumentException( + "World complete launch binding differs from its exact authored-source intake"); + } + } + + public AuthoredWorldLaunchDescriptorEvidence descriptor() { + return evidence.descriptor(); + } + + 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/WorldCompleteLaunchBindingRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingRepository.java new file mode 100644 index 0000000000..79abf22cb8 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingRepository.java @@ -0,0 +1,427 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Owner-local immutable persistence for complete authored-world launch evidence. */ +public class WorldCompleteLaunchBindingRepository { + private static final Table BINDING = DSL.table(DSL.name("world_complete_launch_binding")); + private static final JsonMapper CLOSED_JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private static final Field BINDING_OPERATION_ID = + DSL.field(DSL.name("binding_operation_id"), UUID.class); + 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 CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.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 LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.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 DESCRIPTOR_REQUEST_DIGEST = + DSL.field(DSL.name("descriptor_request_digest"), String.class); + private static final Field DESCRIPTOR_RESULT_DIGEST = + DSL.field(DSL.name("descriptor_result_digest"), String.class); + private static final Field RELEASE_ATTESTATION_DIGEST = + DSL.field(DSL.name("release_attestation_digest"), String.class); + private static final Field DESCRIPTOR_JSON = + DSL.field(DSL.name("descriptor_json"), String.class); + private static final Field RELEASE_ATTESTATION_JSON = + DSL.field(DSL.name("release_attestation_json"), String.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The injected DSLContext is an internal collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldCompleteLaunchBindingRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** Reads the immutable owner row by its stable namespace/tenant/control-plane request key. */ + public Optional read( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + requireNoActiveTransaction("World complete launch binding read"); + validateKey(namespace, canonicalTenantId, controlPlaneRequestId); + Record row = find(namespace, canonicalTenantId, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(toStoredBinding(row)); + } + + /** + * Retains one complete pair against the exact committed local source receipt. + * + *

The caller must authenticate Game Session, perform all remote and committed reads outside + * the owner transaction, then invoke this method in a fresh writable READ COMMITTED transaction. + */ + public WorldCompleteLaunchBindingReceipt acceptFresh( + String namespace, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + CompleteLaunchBindingEvidence evidence) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + Objects.requireNonNull(evidence, "evidence"); + requireSourceBinding(namespace, sourceReceipt, evidence); + + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + String descriptorJson = writeJson(descriptor); + String attestationJson = writeJson(evidence.releaseAttestation()); + UUID operationId = newNonNilUuid(); + int inserted = + dsl.insertInto(BINDING) + .set(BINDING_OPERATION_ID, operationId) + .set(TARGET_NAMESPACE, namespace) + .set(CANONICAL_TENANT_ID, descriptor.canonicalTenantId()) + .set(CANONICAL_VERSION_ID, evidence.releaseAttestation().canonicalVersionId()) + .set(WORLD_SLUG, descriptor.worldSlug()) + .set(CONTROL_PLANE_REQUEST_ID, descriptor.controlPlaneRequestId()) + .set(INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(LOCAL_TENANT_KEY, sourceReceipt.localTenantKey()) + .set(SOURCE_OPERATION_ID, sourceReceipt.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, sourceReceipt.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(DESCRIPTOR_REQUEST_DIGEST, descriptor.requestDigest()) + .set(DESCRIPTOR_RESULT_DIGEST, descriptor.resultDigest()) + .set(RELEASE_ATTESTATION_DIGEST, evidence.releaseAttestation().evidenceDigest()) + .set(DESCRIPTOR_JSON, descriptorJson) + .set(RELEASE_ATTESTATION_JSON, attestationJson) + .onConflictDoNothing() + .execute(); + + Record row = + find(namespace, descriptor.canonicalTenantId(), descriptor.controlPlaneRequestId()); + if (row == null) { + throw new InvalidBindingEvidenceException( + "World complete launch binding is missing after its owner claim"); + } + StoredBinding stored = toStoredBinding(row); + WorldCompleteLaunchBindingReceipt receipt = toReceipt(stored, sourceReceipt); + requireExactEvidence(receipt, evidence); + if (inserted == 0) { + throwIfInsertDidNotSelectOriginal(receipt, sourceReceipt, evidence); + } + return receipt; + } + + /** + * Rehydrates the internal receipt only after the exact local intake has been read independently. + */ + WorldCompleteLaunchBindingReceipt toReceipt( + StoredBinding stored, WorldAuthoredSourceIntakeReceipt sourceReceipt) { + Objects.requireNonNull(stored, "stored"); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + if (!stored.targetNamespace().equals(sourceReceipt.targetNamespace()) + || !stored.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !stored.worldSlug().equals(sourceReceipt.worldSlug()) + || !stored.intakeOperationId().equals(sourceReceipt.operationId()) + || !stored.intakeRequestId().equals(sourceReceipt.intakeRequestId()) + || stored.localTenantKey() != sourceReceipt.localTenantKey() + || !stored.sourceOperationId().equals(sourceReceipt.sourceOperationId()) + || !stored.sourceEvidenceDigest().equals(sourceReceipt.sourceEvidenceDigest()) + || !stored.intakeReceiptDigest().equals(sourceReceipt.receiptDigest())) { + throw new InvalidBindingEvidenceException( + "World complete launch binding differs from its exact local source receipt"); + } + try { + return new WorldCompleteLaunchBindingReceipt( + 1, + stored.operationId(), + stored.targetNamespace(), + stored.canonicalTenantId(), + stored.worldSlug(), + stored.controlPlaneRequestId(), + sourceReceipt, + stored.evidence()); + } catch (RuntimeException exception) { + if (exception instanceof InvalidBindingEvidenceException) { + throw exception; + } + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding conflicts with its local source", exception); + } + } + + void requireExactEvidence( + WorldCompleteLaunchBindingReceipt receipt, CompleteLaunchBindingEvidence expected) { + AuthoredWorldLaunchDescriptorEvidence descriptor = expected.descriptor(); + if (!receipt.evidence().equals(expected) + || !receipt.targetNamespace().equals(descriptor.targetNamespace()) + || !receipt.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !receipt.worldSlug().equals(descriptor.worldSlug()) + || !receipt.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId())) { + throw new RegistrationConflictException( + "World complete launch binding request identity was reused with changed evidence"); + } + } + + private void throwIfInsertDidNotSelectOriginal( + WorldCompleteLaunchBindingReceipt receipt, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + CompleteLaunchBindingEvidence expected) { + if (!receipt.sourceIntakeReceipt().equals(sourceReceipt)) { + throw new RegistrationConflictException( + "World complete launch binding request identity changed its source intake"); + } + requireExactEvidence(receipt, expected); + } + + private Record find(String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + return dsl.selectFrom(BINDING) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) + .fetchOne(); + } + + private StoredBinding toStoredBinding(Record row) { + try { + UUID operationId = required(row, BINDING_OPERATION_ID); + String namespace = required(row, TARGET_NAMESPACE); + UUID canonicalTenantId = required(row, CANONICAL_TENANT_ID); + UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); + String worldSlug = required(row, WORLD_SLUG); + String controlPlaneRequestId = required(row, CONTROL_PLANE_REQUEST_ID); + UUID intakeOperationId = required(row, INTAKE_OPERATION_ID); + UUID intakeRequestId = required(row, INTAKE_REQUEST_ID); + Long localTenantKey = required(row, LOCAL_TENANT_KEY); + UUID sourceOperationId = required(row, SOURCE_OPERATION_ID); + String sourceEvidenceDigest = required(row, SOURCE_EVIDENCE_DIGEST); + String intakeReceiptDigest = required(row, INTAKE_RECEIPT_DIGEST); + String descriptorRequestDigest = required(row, DESCRIPTOR_REQUEST_DIGEST); + String descriptorResultDigest = required(row, DESCRIPTOR_RESULT_DIGEST); + String attestationDigest = required(row, RELEASE_ATTESTATION_DIGEST); + AuthoredWorldLaunchDescriptorEvidence descriptor = + readJson(required(row, DESCRIPTOR_JSON), AuthoredWorldLaunchDescriptorEvidence.class); + AuthoredWorldReleaseAttestationEvidence attestation = + readJson( + required(row, RELEASE_ATTESTATION_JSON), + AuthoredWorldReleaseAttestationEvidence.class); + descriptor.requireValid(); + CompleteLaunchBindingEvidence evidence = + new CompleteLaunchBindingEvidence(descriptor, attestation); + requireStoredColumns( + namespace, + canonicalTenantId, + canonicalVersionId, + worldSlug, + controlPlaneRequestId, + sourceOperationId, + sourceEvidenceDigest, + descriptorRequestDigest, + descriptorResultDigest, + attestationDigest, + descriptor, + attestation); + if (localTenantKey <= 0) { + throw new IllegalArgumentException("Stored local tenant key must be positive"); + } + return new StoredBinding( + operationId, + namespace, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + intakeOperationId, + intakeRequestId, + localTenantKey, + sourceOperationId, + sourceEvidenceDigest, + intakeReceiptDigest, + descriptorRequestDigest, + descriptorResultDigest, + attestationDigest, + evidence); + } catch (RuntimeException exception) { + if (exception instanceof InvalidBindingEvidenceException) { + throw exception; + } + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding evidence is invalid", exception); + } + } + + private static void requireStoredColumns( + String namespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + String controlPlaneRequestId, + UUID sourceOperationId, + String sourceEvidenceDigest, + String descriptorRequestDigest, + String descriptorResultDigest, + String attestationDigest, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence attestation) { + if (!namespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !sourceOperationId.equals(descriptor.authoredWorldSourceOperationId()) + || !sourceEvidenceDigest.equals(descriptor.authoredWorldSourceEvidenceDigest()) + || !descriptorRequestDigest.equals(descriptor.requestDigest()) + || !descriptorResultDigest.equals(descriptor.resultDigest()) + || !canonicalVersionId.equals(attestation.canonicalVersionId()) + || !attestationDigest.equals(attestation.evidenceDigest())) { + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding columns differ from their closed evidence"); + } + } + + private static void requireSourceBinding( + String namespace, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + CompleteLaunchBindingEvidence evidence) { + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + if (!namespace.equals(descriptor.targetNamespace()) + || !namespace.equals(sourceReceipt.targetNamespace()) + || !descriptor.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !descriptor.worldSlug().equals(sourceReceipt.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(sourceReceipt.sourceOperationId()) + || !descriptor + .authoredWorldSourceEvidenceDigest() + .equals(sourceReceipt.sourceEvidenceDigest())) { + throw new RegistrationConflictException( + "Complete launch binding does not match the exact World source intake"); + } + } + + private static T required(Record row, Field field) { + return Objects.requireNonNull(row.get(field), "Persisted " + field.getName() + " is null"); + } + + private static String writeJson(Object value) { + try { + return CLOSED_JSON.writeValueAsString(value); + } catch (Exception exception) { + throw new InvalidBindingEvidenceException( + "World complete launch binding evidence could not be encoded", exception); + } + } + + private static T readJson(String json, Class type) { + try { + T value = CLOSED_JSON.readValue(json, type); + if (!writeJson(value).equals(json)) { + throw new IllegalArgumentException("Persisted evidence JSON is not in its closed form"); + } + return value; + } catch (Exception exception) { + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding JSON is not closed evidence", exception); + } + } + + private static void validateKey( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("namespace must be one canonical DNS label"); + } + if (canonicalTenantId == null || canonicalTenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("canonicalTenantId must be a non-nil UUID"); + } + if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId must be nonblank"); + } + } + + private static UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " requires an independent committed owner read"); + } + } + + private static void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World complete launch binding requires an active World owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World complete launch binding requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null + && declaredIsolation != java.sql.Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World complete launch binding requires READ COMMITTED isolation"); + } + } + + static record StoredBinding( + UUID operationId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + UUID intakeOperationId, + UUID intakeRequestId, + long localTenantKey, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest, + String descriptorRequestDigest, + String descriptorResultDigest, + String releaseAttestationDigest, + CompleteLaunchBindingEvidence evidence) {} + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidBindingEvidenceException extends IllegalStateException { + public InvalidBindingEvidenceException(String message) { + super(message); + } + + public InvalidBindingEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java new file mode 100644 index 0000000000..98c3f37014 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java @@ -0,0 +1,340 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired World owner step for retaining the complete released-content launch binding. + * + *

Neither binding nor its current-Version read proves local content, commit fencing, lifecycle + * preparation, or runtime admission. + */ +public final class WorldCompleteLaunchBindingService { + private final AuthoredWorldLaunchDescriptorClient client; + private final AuthoredWorldVersionStateClient versionStateClient; + private final WorldCompleteLaunchBindingRepository repository; + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public WorldCompleteLaunchBindingService( + AuthoredWorldLaunchDescriptorClient client, + WorldCompleteLaunchBindingRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this(client, repository, sourceIntakeRepository, transactionManager, workloadNamespace, null); + } + + /** + * Constructs the explicitly unwired binding verifier with its separately authenticated Game + * Design current-version reader. + */ + public WorldCompleteLaunchBindingService( + AuthoredWorldLaunchDescriptorClient client, + WorldCompleteLaunchBindingRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace, + AuthoredWorldVersionStateClient versionStateClient) { + this.client = Objects.requireNonNull(client, "client"); + this.versionStateClient = versionStateClient; + this.repository = Objects.requireNonNull(repository, "repository"); + this.sourceIntakeRepository = + Objects.requireNonNull(sourceIntakeRepository, "sourceIntakeRepository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Binds the exact immutable Game Design read selector to the already committed local source. + * + *

The verified same-namespace Game Session workload is required before any owner read or Game + * Design call. Existing claims are resolved first so retries cannot select newer defaults. + */ + public WorldCompleteLaunchBindingReceipt bind(GetRequest request) { + requireAuthenticatedGameSessionCaller(); + requireNoAmbientTransaction(); + validateRequest(request); + + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + Optional prior = + repository.read( + workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()); + if (prior.isPresent()) { + WorldCompleteLaunchBindingRepository.StoredBinding stored = prior.orElseThrow(); + requireStoredRequest(stored, request); + WorldCompleteLaunchBindingReceipt receipt = loadExactSourceReceipt(stored); + return receipt; + } + + CompleteLaunchBindingEvidence fetched = + client.getComplete(AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(request)); + requireFetchedEvidence(fetched, request); + WorldAuthoredSourceIntakeReceipt sourceReceipt = readExactSourceReceipt(fetched); + + WorldCompleteLaunchBindingReceipt accepted; + try { + accepted = + ownerTransaction.execute( + status -> repository.acceptFresh(workloadNamespace, sourceReceipt, fetched)); + } catch (RuntimeException ownerFailure) { + // A commit acknowledgment can be lost after PostgreSQL made the immutable claim durable. + Optional uncertainCommit = + repository.read( + workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()); + if (uncertainCommit.isEmpty()) { + throw ownerFailure; + } + WorldCompleteLaunchBindingReceipt recovered = + recoverExactSourceReceipt(uncertainCommit.orElseThrow(), request); + requireSamePair(recovered, fetched); + return recovered; + } + if (accepted == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World owner transaction returned no complete launch binding receipt"); + } + requireStoredRequest(accepted, request); + requireSamePair(accepted, fetched); + + Optional committed = + repository.read( + workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()); + if (committed.isEmpty()) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World complete launch binding is missing after its owner commit"); + } + WorldCompleteLaunchBindingRepository.StoredBinding stored = committed.orElseThrow(); + requireStoredRequest(stored, request); + WorldCompleteLaunchBindingReceipt readback = loadExactSourceReceipt(stored); + if (!accepted.equals(readback)) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World complete launch binding changed during independent commit readback"); + } + return readback; + } + + /** + * Reads current Game Design version evidence for an already committed, exact World binding. + * + *

This read never creates or changes the historical binding. It establishes only current + * source-owned Version eligibility at the descriptor epoch; it does not prove World content, + * commit fencing, preparation, or admission. + */ + public AuthoredWorldVersionStateEvidence readCurrentVersionState( + GetRequest request, UUID currentReadId) { + requireAuthenticatedGameSessionCaller(); + requireNoAmbientTransaction(); + validateRequest(request); + requireNonNilCurrentReadId(currentReadId); + if (versionStateClient == null) { + throw new IllegalStateException( + "World current-version verification has no configured Game Design reader"); + } + + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + WorldCompleteLaunchBindingRepository.StoredBinding stored = + repository + .read(workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()) + .orElseThrow( + () -> + new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World current-version verification requires a committed launch binding")); + requireStoredRequest(stored, request); + WorldCompleteLaunchBindingReceipt committed = loadExactSourceReceipt(stored); + requireStoredRequest(committed, request); + requireFreshCurrentReadId(currentReadId, request, committed); + + AuthoredWorldLaunchDescriptorEvidence descriptor = committed.descriptor(); + // This is the Game Design-owned Version selector, never World's private local tenant key. + AuthoredWorldVersionStateEvidence.Request currentRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + descriptor.targetNamespace(), + currentReadId, + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.versionId()); + AuthoredWorldVersionStateEvidence current; + try { + current = versionStateClient.read(currentRequest); + } catch (RuntimeException exception) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Current Game Design version-state evidence is unavailable or invalid", exception); + } + if (current == null + || !currentRequest.equals(current.request()) + || !committed.sourceIntakeReceipt().source().equals(current.sourceEvidence())) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current-version evidence differs from the exact committed World source"); + } + UUID committedCanonicalVersionId = + committed.evidence().releaseAttestation().canonicalVersionId(); + if (!committedCanonicalVersionId.equals(current.canonicalVersionId())) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current canonical version UUID differs from the committed release attestation"); + } + if (current.versionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && current.versionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current Version is not PUBLISHED or ACTIVE"); + } + if (current.versionStateEpoch() != descriptor.versionStateEpoch()) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current Version epoch differs from the immutable launch descriptor"); + } + return current; + } + + private WorldCompleteLaunchBindingReceipt loadExactSourceReceipt( + WorldCompleteLaunchBindingRepository.StoredBinding stored) { + CompleteLaunchBindingEvidence evidence = stored.evidence(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = readExactSourceReceipt(evidence); + return repository.toReceipt(stored, sourceReceipt); + } + + private WorldCompleteLaunchBindingReceipt recoverExactSourceReceipt( + WorldCompleteLaunchBindingRepository.StoredBinding stored, GetRequest request) { + requireStoredRequest(stored, request); + return loadExactSourceReceipt(stored); + } + + private WorldAuthoredSourceIntakeReceipt readExactSourceReceipt( + CompleteLaunchBindingEvidence evidence) { + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + return sourceIntakeRepository + .readBySource( + workloadNamespace, + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest()) + .orElseThrow( + () -> + new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Complete launch binding has no exact committed World source intake")); + } + + private void requireStoredRequest(WorldCompleteLaunchBindingReceipt receipt, GetRequest request) { + requireStoredRequest(receipt.descriptor(), receipt.targetNamespace(), request); + } + + private void requireStoredRequest( + WorldCompleteLaunchBindingRepository.StoredBinding stored, GetRequest request) { + requireStoredRequest(stored.evidence().descriptor(), stored.targetNamespace(), request); + if (!stored.canonicalTenantId().equals(request.expectedRequest().canonicalTenantId()) + || !stored + .controlPlaneRequestId() + .equals(request.expectedRequest().controlPlaneRequestId())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World complete launch binding stable request identity changed"); + } + } + + private void requireStoredRequest( + AuthoredWorldLaunchDescriptorEvidence descriptor, + String targetNamespace, + GetRequest request) { + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + if (!descriptor.request().equals(expected) + || !descriptor.resultDigest().equals(request.expectedResultDigest()) + || !workloadNamespace.equals(descriptor.targetNamespace()) + || !workloadNamespace.equals(targetNamespace)) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World complete launch binding request identity was reused with changed request or result"); + } + } + + private void requireFetchedEvidence(CompleteLaunchBindingEvidence evidence, GetRequest request) { + if (evidence == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design returned no complete launch binding evidence"); + } + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + if (!descriptor.request().equals(request.expectedRequest()) + || !descriptor.resultDigest().equals(request.expectedResultDigest()) + || !workloadNamespace.equals(descriptor.targetNamespace())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "Game Design complete launch binding differs from the exact read request"); + } + } + + private void requireSamePair( + WorldCompleteLaunchBindingReceipt receipt, CompleteLaunchBindingEvidence expected) { + if (!receipt.evidence().equals(expected)) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World complete launch binding request identity was reused with another release pair"); + } + } + + private void validateRequest(GetRequest request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.expectedRequest().targetNamespace())) { + throw new SecurityException( + "Complete launch binding request namespace does not match this World workload"); + } + } + + private static void requireNonNilCurrentReadId(UUID currentReadId) { + if (currentReadId == null || currentReadId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Current version-state read ID must be a non-nil UUID"); + } + } + + private static void requireFreshCurrentReadId( + UUID currentReadId, GetRequest request, WorldCompleteLaunchBindingReceipt committed) { + WorldAuthoredSourceIntakeReceipt intake = committed.sourceIntakeReceipt(); + if (currentReadId.equals(request.requestId()) + || currentReadId.equals(committed.operationId()) + || currentReadId.equals(intake.operationId()) + || currentReadId.equals(intake.intakeRequestId()) + || currentReadId.equals(intake.sourceOperationId()) + || currentReadId.equals(intake.source().registrationRequestId())) { + throw new IllegalArgumentException( + "Current version-state read ID must be separate from source and registration IDs"); + } + } + + private void requireAuthenticatedGameSessionCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-session-service") + || !peer.isInNamespace(workloadNamespace)) { + throw new SecurityException( + "World complete launch binding requires the authenticated same-namespace Game Session workload"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World complete launch binding cannot enter from an ambient transaction"); + } + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql b/services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql new file mode 100644 index 0000000000..28f26a6f8f --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql @@ -0,0 +1,72 @@ +CREATE TABLE world_complete_launch_binding ( + binding_operation_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + control_plane_request_id TEXT NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + descriptor_request_digest VARCHAR(71) NOT NULL, + descriptor_result_digest VARCHAR(71) NOT NULL, + release_attestation_digest VARCHAR(71) NOT NULL, + descriptor_json TEXT NOT NULL, + release_attestation_json TEXT NOT NULL, + CONSTRAINT pk_world_complete_launch_binding PRIMARY KEY (binding_operation_id), + CONSTRAINT fk_world_complete_launch_binding_source + 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_complete_launch_binding_ids CHECK ( + binding_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_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_complete_launch_binding_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_complete_launch_binding_world CHECK ( + world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT ck_world_complete_launch_binding_request CHECK ( + length(btrim(control_plane_request_id)) > 0 + ), + CONSTRAINT ck_world_complete_launch_binding_digests CHECK ( + source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND release_attestation_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_complete_launch_binding_components CHECK ( + length(descriptor_json) > 0 AND length(release_attestation_json) > 0 + ) +); + +-- [jooq ignore start] +-- The DDL export backend cannot index TEXT. PostgreSQL still enforces this exact +-- unbounded request identity; the runtime repository does not use generated keys. +ALTER TABLE world_complete_launch_binding + ADD CONSTRAINT uq_world_complete_launch_binding_request + UNIQUE (target_namespace, canonical_tenant_id, control_plane_request_id); + +CREATE TRIGGER trg_world_complete_launch_binding_immutable + BEFORE UPDATE OR DELETE ON world_complete_launch_binding + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_complete_launch_binding_no_truncate + BEFORE TRUNCATE ON world_complete_launch_binding + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql b/services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql new file mode 100644 index 0000000000..d6465727fe --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql @@ -0,0 +1,80 @@ +CREATE TABLE world_authored_version_identity ( + operation_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_id BIGINT NOT NULL, + local_version_key BIGINT GENERATED ALWAYS AS IDENTITY NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + intake_request_digest VARCHAR(71) NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + version_state_schema_version SMALLINT NOT NULL, + version_state_read_request_id UUID NOT NULL, + version_state_state VARCHAR(32) NOT NULL, + version_state_epoch BIGINT NOT NULL, + version_state_evidence_digest VARCHAR(71) NOT NULL, + version_state_evidence_json TEXT NOT NULL, + CONSTRAINT pk_world_authored_version_identity PRIMARY KEY (operation_id), + CONSTRAINT uq_world_authored_version_identity_local_key UNIQUE (local_version_key), + CONSTRAINT uq_world_authored_version_identity_canonical UNIQUE ( + target_namespace, canonical_tenant_id, world_slug, canonical_version_id + ), + CONSTRAINT uq_world_authored_version_identity_game_design_version UNIQUE ( + target_namespace, canonical_tenant_id, world_slug, game_design_version_id + ), + CONSTRAINT fk_world_authored_version_identity_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_authored_version_identity_scope CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(world_slug) BETWEEN 1 AND 120 + ), + CONSTRAINT ck_world_authored_version_identity_counters CHECK ( + game_design_version_id > 0 + AND local_version_key > 0 + AND local_tenant_key > 0 + AND version_state_epoch > 0 + AND version_state_schema_version = 1 + ), + CONSTRAINT ck_world_authored_version_identity_ids CHECK ( + operation_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 version_state_read_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_authored_version_identity_state CHECK ( + version_state_state IN ('DRAFT', 'PUBLISHED', 'ACTIVE') + ), + CONSTRAINT ck_world_authored_version_identity_digests CHECK ( + intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND version_state_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_authored_version_identity_json CHECK ( + octet_length(version_state_evidence_json) > 0 + ) +); + +-- [jooq ignore start] +CREATE TRIGGER trg_world_authored_version_identity_immutable + BEFORE UPDATE OR DELETE ON world_authored_version_identity + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_version_identity_no_truncate + BEFORE TRUNCATE ON world_authored_version_identity + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +-- [jooq ignore stop] 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 8629d03b79..013b3bdbc0 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 @@ -12,6 +12,7 @@ import com.google.protobuf.Message; import io.grpc.ForwardingServerCall; +import io.grpc.ManagedChannel; import io.grpc.Metadata; import io.grpc.Server; import io.grpc.ServerCall; @@ -36,6 +37,9 @@ import java.time.Instant; import java.util.Base64; import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.ConcurrentLinkedQueue; @@ -56,12 +60,21 @@ 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.service.impl.WorldManagementGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; +import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationRequest; +import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationResponse; import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.ExtendedKeyUsage; @@ -103,6 +116,32 @@ properties = "spring.grpc.server.port=0") class WorldAuthoredSourceIntakeMtlsIntegrationTest { private static final String NAMESPACE = "firemud"; + private static final List WORLD_MUTATION_SNAPSHOT_TABLES = + List.of( + "region", + "zone", + "room", + "instance", + "room_exit", + "generation_rule", + "world_instance", + "region_instance", + "zone_instance", + "room_instance", + "room_instance_exit", + "world_event", + "world_design_revision_ledger", + "world_design_aggregate_epoch", + "world_design_scope_epoch", + "world_entity_spawn_binding", + "initial_admission_bind_hold", + "world_authored_source_tenant_association", + "world_authored_source_tenant_key_reservation", + "world_authored_source_intake", + "world_design_publication_fence_attempt", + "world_design_publication_fence_owner", + "world_complete_launch_binding", + "world_authored_version_identity"); private static final String WORLD_SERVER_URI = "spiffe://firemud/ns/firemud/sa/world-management-service"; private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); @@ -120,6 +159,7 @@ class WorldAuthoredSourceIntakeMtlsIntegrationTest { @Autowired private WorldAuthoredSourceIntakeRepository repository; @Autowired private DSLContext dsl; @Autowired private PlatformTransactionManager transactionManager; + @Autowired private WorldManagementGrpcService worldManagementGrpcService; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; @@ -289,6 +329,37 @@ void deniesWrongWorkloadAndChangedBindingWithoutOwnerMutation() throws Exception } } + @Test + void registeredDraftMutationDeniesGameDesignPeerWithoutAccountCommitAuthorization() + throws Exception { + startRegisteredWorldManagementReceiver(); + Map> before = worldMutationRowSnapshot(); + + ApplyWorldDesignMutationResponse response = + applyWorldDesignMutation( + pki.gameDesignClient(), "gd-draft-denial", canonicalLookingDraftMutation()); + + assertDraftMutationDenied(response); + assertThat(worldMutationRowSnapshot()) + .as("World content, source, association, lifecycle and publication rows stay unchanged") + .isEqualTo(before); + } + + @Test + void registeredDraftMutationDeniesOtherAuthenticatedPeerBeforeOwnerMutation() throws Exception { + startRegisteredWorldManagementReceiver(); + Map> before = worldMutationRowSnapshot(); + + ApplyWorldDesignMutationResponse response = + applyWorldDesignMutation( + pki.accountClient(), "account-draft-denial", canonicalLookingDraftMutation()); + + assertDraftMutationDenied(response); + assertThat(worldMutationRowSnapshot()) + .as("World content, source, association, lifecycle and publication rows stay unchanged") + .isEqualTo(before); + } + private AuthoredWorldSourceClient sourceBoundary(Scenario scenario) { AuthoredWorldSourceClient syntheticSource = mock(AuthoredWorldSourceClient.class); when(syntheticSource.read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class))) @@ -333,6 +404,43 @@ private void startReceiver( .start(); } + private void startRegisteredWorldManagementReceiver() throws Exception { + var withPeerIdentity = + ServerInterceptors.intercept(worldManagementGrpcService, new GrpcPeerIdentityInterceptor()); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.worldServer().privateKey(), pki.worldServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(withPeerIdentity) + .build() + .start(); + } + + private ApplyWorldDesignMutationResponse applyWorldDesignMutation( + TestCertificate certificate, String label, ApplyWorldDesignMutationRequest request) + throws Exception { + ManagedChannel channel = + new GrpcChannelFactory() + .buildChannel( + "127.0.0.1:" + server.getPort(), + server.getPort(), + tlsProperties(certificate, label), + false); + try { + return WorldManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .applyWorldDesignMutation(request); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + private WorldAuthoredSourceIntakeClient intakeClient(TestCertificate certificate, String label) throws Exception { WorldAuthoredSourceIntakeClient client = @@ -442,6 +550,17 @@ private DbCounts dbCounts(Scenario scenario) { scenario.canonicalTenantId())); } + private Map> worldMutationRowSnapshot() { + Map> snapshot = new LinkedHashMap<>(); + for (String table : WORLD_MUTATION_SNAPSHOT_TABLES) { + snapshot.put( + table, + dsl.fetch("SELECT to_jsonb(world_row)::text FROM " + table + " AS world_row ORDER BY 1") + .getValues(0, String.class)); + } + return snapshot; + } + private long count(String query, Object... bindings) { return Objects.requireNonNull( dsl.fetchOne(query, bindings), "World intake count query returned no row") @@ -514,6 +633,37 @@ private static void assertStatus(Status.Code expected, ThrowingAction action) { failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); } + private static ApplyWorldDesignMutationRequest canonicalLookingDraftMutation() { + return ApplyWorldDesignMutationRequest.newBuilder() + .setTenantId("11111111-1111-4111-8111-111111111111") + .setVersionId("22222222-2222-4222-8222-222222222222") + .setCommitId("commit-1") + .setRevisionId("revision-1") + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId("44") + .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) + .build(); + } + + private static void assertDraftMutationDenied(ApplyWorldDesignMutationResponse response) { + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("FAILED_PRECONDITION"); + assertThat(response.getError().getMessage()) + .isEqualTo( + "Canonical World Draft writes are unavailable until current Account commit authorization is verified."); + assertThat(response.getResult()) + .isEqualTo(WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED); + assertThat(response.getTenantId()).isEmpty(); + assertThat(response.getVersionId()).isEmpty(); + assertThat(response.getAggregateId()).isEmpty(); + assertThat(response.getDraftRevisionEpoch()).isZero(); + assertThat(response.getDraftScopeRevisionEpoch()).isZero(); + assertThat(response.getAllFields().keySet()) + .containsExactly(ApplyWorldDesignMutationResponse.getDescriptor().findFieldByName("error")); + } + private static String pem(String type, byte[] bytes) { String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); return "-----BEGIN " + type + "-----\n" + body + "\n-----END " + type + "-----\n"; diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java new file mode 100644 index 0000000000..aa47730226 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java @@ -0,0 +1,957 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import 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.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +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.VersionLifecycleState; +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.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository.RegistrationConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +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.TransactionStatus; +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 WorldAuthoredVersionIdentityIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final UUID OTHER_CANONICAL_VERSION = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final List WORLD_CONTENT_AND_LIFECYCLE_TABLES = + List.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"); + + @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 DSLContext dsl; + @Autowired private WorldAuthoredSourceIntakeRepository sourceRepository; + @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 persistsExactIdentityAndPrivateKeyWithoutContentOrLifecycleWrites() { + long legacyTenantKey = + 6_900_000_000L + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 100_000L); + String legacyRegionName = "unmapped-legacy-region-" + UUID.randomUUID(); + long legacyRegionId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", + legacyTenantKey, + legacyRegionName), + "legacy region insert returned no row") + .get(0, Long.class); + long legacyGameInstanceId = positiveLong(); + String legacyControlRequest = "retained-legacy-" + UUID.randomUUID(); + long legacyWorldInstanceId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, " + + "generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, status) " + + "VALUES (?, ?, 17, ?, 'retained-descriptor', 29, 'legacy-config', " + + "31, 'retained-release', 3, 'ACTIVE') RETURNING id", + legacyTenantKey, + legacyGameInstanceId, + legacyControlRequest), + "legacy world-instance insert returned no row") + .get(0, Long.class); + + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + Map rowsBeforeIdentity = worldContentAndLifecycleCounts(); + assertThat(sourceReceipt.localTenantKey()).isNotEqualTo(legacyTenantKey); + + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 103L; + AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + return versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 5L); + }); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService service = service(client, repository, transactionManager); + UUID readRequestId = UUID.randomUUID(); + + WorldAuthoredVersionIdentityReceipt receipt = + withGameDesign( + () -> + service.associate( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + canonicalVersionId, + gameDesignVersionId, + readRequestId)); + WorldAuthoredVersionIdentityReceipt independentReadback = + repository + .readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId) + .orElseThrow(); + + assertThat(receipt).isEqualTo(independentReadback); + assertThat(receipt.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(receipt.canonicalVersionId()).isEqualTo(canonicalVersionId); + assertThat(receipt.gameDesignVersionId()).isEqualTo(gameDesignVersionId); + assertThat(receipt.localVersionKey()).isPositive(); + assertThat(receipt.versionStateEvidence().request().readRequestId()).isEqualTo(readRequestId); + assertThat( + repository.readByGameDesignVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), gameDesignVersionId)) + .contains(receipt); + assertThat(identityCount(source)).isEqualTo(1L); + assertThat(worldContentAndLifecycleCounts()).isEqualTo(rowsBeforeIdentity); + + var storedRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM world_authored_version_identity WHERE operation_id = ?", + receipt.operationId()), + "World authored-Version identity row was not persisted"); + assertThat(storedRow.get("operation_id", UUID.class)).isEqualTo(receipt.operationId()); + assertThat(storedRow.get("target_namespace", String.class)).isEqualTo(NAMESPACE); + assertThat(storedRow.get("canonical_tenant_id", UUID.class)) + .isEqualTo(source.canonicalTenantId()); + assertThat(storedRow.get("world_slug", String.class)).isEqualTo(source.worldSlug()); + assertThat(storedRow.get("canonical_version_id", UUID.class)).isEqualTo(canonicalVersionId); + assertThat(storedRow.get("game_design_version_id", Long.class)).isEqualTo(gameDesignVersionId); + assertThat(storedRow.get("local_version_key", Long.class)).isEqualTo(receipt.localVersionKey()); + assertThat(storedRow.get("intake_operation_id", UUID.class)) + .isEqualTo(sourceReceipt.operationId()); + assertThat(storedRow.get("intake_request_id", UUID.class)) + .isEqualTo(sourceReceipt.intakeRequestId()); + assertThat(storedRow.get("local_tenant_key", Long.class)) + .isEqualTo(sourceReceipt.localTenantKey()); + assertThat(storedRow.get("intake_request_digest", String.class)) + .isEqualTo(sourceReceipt.requestDigest()); + assertThat(storedRow.get("source_operation_id", UUID.class)).isEqualTo(source.operationId()); + assertThat(storedRow.get("source_evidence_digest", String.class)) + .isEqualTo(source.evidenceDigest()); + assertThat(storedRow.get("intake_receipt_digest", String.class)) + .isEqualTo(sourceReceipt.receiptDigest()); + assertThat(storedRow.get("version_state_read_request_id", UUID.class)).isEqualTo(readRequestId); + assertThat(storedRow.get("version_state_evidence_digest", String.class)) + .isEqualTo(receipt.versionStateEvidence().evidenceDigest()); + assertThat(storedRow.get("version_state_evidence_json", String.class)) + .contains(source.operationId().toString(), canonicalVersionId.toString()); + var localKeyColumn = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT is_identity, identity_generation FROM information_schema.columns " + + "WHERE table_schema = current_schema() " + + "AND table_name = 'world_authored_version_identity' " + + "AND column_name = 'local_version_key'"), + "World local version key identity metadata was not found"); + assertThat(localKeyColumn.get("is_identity", String.class)).isEqualTo("YES"); + assertThat(localKeyColumn.get("identity_generation", String.class)).isEqualTo("ALWAYS"); + + var retainedRegion = + Objects.requireNonNull( + dsl.fetchOne("SELECT tenant_id, name FROM region WHERE id = ?", legacyRegionId), + "unmapped legacy region disappeared"); + assertThat(retainedRegion.get("tenant_id", Long.class)).isEqualTo(legacyTenantKey); + assertThat(retainedRegion.get("name", String.class)).isEqualTo(legacyRegionName); + var retainedWorld = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_id, game_instance_id, control_plane_request_id, version_id, status " + + "FROM world_instance WHERE id = ?", + legacyWorldInstanceId), + "unmapped legacy world-instance row disappeared"); + assertThat(retainedWorld.get("tenant_id", Long.class)).isEqualTo(legacyTenantKey); + assertThat(retainedWorld.get("game_instance_id", Long.class)).isEqualTo(legacyGameInstanceId); + assertThat(retainedWorld.get("control_plane_request_id", String.class)) + .isEqualTo(legacyControlRequest); + assertThat(retainedWorld.get("version_id", Long.class)).isEqualTo(29L); + assertThat(retainedWorld.get("status", String.class)).isEqualTo("ACTIVE"); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_version_identity SET world_slug = ? " + + "WHERE operation_id = ?", + "rewritten-world", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_version_identity WHERE operation_id = ?", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_authored_version_identity")) + .isInstanceOf(DataAccessException.class); + assertThat(identityCount(source)).isEqualTo(1L); + verify(client, times(1)).read(any()); + } + + @Test + void deniesWrongGameDesignIdentitySourceNamespaceAndMissingIntakeBeforeOwnerWrites() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 211L; + + AuthoredWorldVersionStateClient wrongUuidClient = mock(AuthoredWorldVersionStateClient.class); + when(wrongUuidClient.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + invocation.getArgument(0), + source, + OTHER_CANONICAL_VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 8L)); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService wrongUuidService = + service(wrongUuidClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + wrongUuidService, + source, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(InvalidIdentityEvidenceException.class); + assertThat(identityCount(source)).isZero(); + + AuthoredWorldVersionStateClient wrongPeerClient = mock(AuthoredWorldVersionStateClient.class); + WorldAuthoredVersionIdentityService wrongPeerService = + service(wrongPeerClient, repository, transactionManager); + assertThatThrownBy( + () -> + withPeer( + NAMESPACE, + "game-session-service", + () -> + associate( + wrongPeerService, + source, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(SecurityException.class); + verify(wrongPeerClient, never()).read(any()); + assertThat(identityCount(source)).isZero(); + + AuthoredWorldSourceEvidence substitutedSource = source(UUID.randomUUID(), randomWorld()); + AuthoredWorldVersionStateClient wrongSourceClient = mock(AuthoredWorldVersionStateClient.class); + UUID substitutedReadId = UUID.randomUUID(); + when(wrongSourceClient.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + request(substitutedSource, substitutedReadId, gameDesignVersionId), + substitutedSource, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 9L)); + WorldAuthoredVersionIdentityService wrongSourceService = + service(wrongSourceClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + wrongSourceService, + source, + canonicalVersionId, + gameDesignVersionId, + substitutedReadId))) + .isInstanceOf(InvalidIdentityEvidenceException.class); + assertThat(identityCount(source)).isZero(); + assertThat(identityCount(substitutedSource)).isZero(); + + AuthoredWorldVersionStateClient wrongNamespaceClient = + mock(AuthoredWorldVersionStateClient.class); + WorldAuthoredVersionIdentityService wrongNamespaceService = + service(wrongNamespaceClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + wrongNamespaceService.associate( + "other-namespace", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(SecurityException.class); + verify(wrongNamespaceClient, never()).read(any()); + assertThat(identityCount(source)).isZero(); + + AuthoredWorldSourceEvidence missingSource = source(UUID.randomUUID(), randomWorld()); + AuthoredWorldVersionStateClient missingSourceClient = + mock(AuthoredWorldVersionStateClient.class); + when(missingSourceClient.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + invocation.getArgument(0), + missingSource, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 10L)); + WorldAuthoredVersionIdentityService missingSourceService = + service(missingSourceClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + missingSourceService, + missingSource, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(InvalidIdentityEvidenceException.class); + assertThat(identityCount(missingSource)).isZero(); + assertThat( + sourceRepository.readBySource( + NAMESPACE, + missingSource.canonicalTenantId(), + missingSource.worldSlug(), + missingSource.operationId(), + missingSource.evidenceDigest())) + .isEmpty(); + } + + @Test + void concurrentExactStableIdentityReturnsOneOriginalHistoricalReceipt() throws Exception { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 307L; + UUID firstReadId = UUID.randomUUID(); + UUID secondReadId = UUID.randomUUID(); + CountDownLatch bothRead = new CountDownLatch(2); + AtomicReference firstEvidence = new AtomicReference<>(); + AtomicReference secondEvidence = new AtomicReference<>(); + AuthoredWorldVersionStateClient firstClient = mock(AuthoredWorldVersionStateClient.class); + AuthoredWorldVersionStateClient secondClient = mock(AuthoredWorldVersionStateClient.class); + when(firstClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + awaitReadBarrier(bothRead); + AuthoredWorldVersionStateEvidence evidence = + versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 12L); + firstEvidence.set(evidence); + return evidence; + }); + when(secondClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + awaitReadBarrier(bothRead); + AuthoredWorldVersionStateEvidence evidence = + versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + 13L); + secondEvidence.set(evidence); + return evidence; + }); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService firstService = + service(firstClient, repository, transactionManager); + WorldAuthoredVersionIdentityService secondService = + service(secondClient, repository, transactionManager); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> + withGameDesign( + () -> + associate( + firstService, + source, + canonicalVersionId, + gameDesignVersionId, + firstReadId))); + Future second = + executor.submit( + () -> + withGameDesign( + () -> + associate( + secondService, + source, + canonicalVersionId, + gameDesignVersionId, + secondReadId))); + WorldAuthoredVersionIdentityReceipt firstReceipt = first.get(25, TimeUnit.SECONDS); + WorldAuthoredVersionIdentityReceipt secondReceipt = second.get(25, TimeUnit.SECONDS); + + assertThat(firstReceipt).isEqualTo(secondReceipt); + assertThat(firstReceipt.operationId()).isEqualTo(secondReceipt.operationId()); + assertThat(firstReceipt.localVersionKey()).isEqualTo(secondReceipt.localVersionKey()); + assertThat(firstReceipt.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(firstReceipt.versionStateEvidence()) + .isIn(firstEvidence.get(), secondEvidence.get()); + assertThat(firstEvidence.get().evidenceDigest()) + .isNotEqualTo(secondEvidence.get().evidenceDigest()); + assertThat(firstEvidence.get().request().readRequestId()) + .isNotEqualTo(secondEvidence.get().request().readRequestId()); + assertThat( + repository.readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId)) + .contains(firstReceipt); + assertThat(identityCount(source)).isEqualTo(1L); + } + verify(firstClient, times(1)).read(any()); + verify(secondClient, times(1)).read(any()); + } + + @Test + void conflictingUuidOrGameDesignSelectorDoesNotRewriteTheOriginalReceipt() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 401L; + AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + UUID returnedCanonicalId = + request.versionId() == gameDesignVersionId + ? canonicalVersionId + : OTHER_CANONICAL_VERSION; + return versionEvidence( + request, + source, + returnedCanonicalId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 16L); + }); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService service = service(client, repository, transactionManager); + WorldAuthoredVersionIdentityReceipt original = + withGameDesign( + () -> + associate( + service, source, canonicalVersionId, gameDesignVersionId, UUID.randomUUID())); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + service, + source, + canonicalVersionId, + gameDesignVersionId + 1, + UUID.randomUUID()))) + .isInstanceOf(RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + service, + source, + OTHER_CANONICAL_VERSION, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(RegistrationConflictException.class); + + assertThat( + repository.readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId)) + .contains(original); + assertThat(identityCount(source)).isEqualTo(1L); + verify(client, times(1)).read(any()); + } + + @Test + void recoversLostCommitAcknowledgmentAndRetriesWithoutRereadingOrReminting() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 503L; + AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + invocation.getArgument(0), + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 21L)); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService service = + service( + client, repository, new LostCommitAcknowledgmentTransactionManager(transactionManager)); + UUID originalReadId = UUID.randomUUID(); + + WorldAuthoredVersionIdentityReceipt recovered = + withGameDesign( + () -> + associate( + service, source, canonicalVersionId, gameDesignVersionId, originalReadId)); + WorldAuthoredVersionIdentityReceipt retry = + withGameDesign( + () -> + associate( + service, source, canonicalVersionId, gameDesignVersionId, UUID.randomUUID())); + + assertThat(recovered).isEqualTo(retry); + assertThat(retry.versionStateEvidence().request().readRequestId()).isEqualTo(originalReadId); + assertThat(identityCount(source)).isEqualTo(1L); + assertThat( + repository.readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId)) + .contains(recovered); + verify(client, times(1)).read(any()); + } + + @Test + void forwardV27MigrationPreservesRetainedRowsWithoutInferringIdentityAssociations() + throws SQLException { + String schema = "world_version_identity_" + UUID.randomUUID().toString().replace("-", ""); + long legacyTenantKey = + 8_300_000_000L + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 100_000L); + String firstRegionName = "retained-v26-region-a-" + UUID.randomUUID(); + String secondRegionName = "retained-v26-region-b-" + UUID.randomUUID(); + long legacyGameInstanceId = positiveLong(); + try { + migrateFixture(schema, MigrationVersion.fromVersion("26")); + try (Connection connection = fixtureConnection(schema)) { + try (PreparedStatement region = + connection.prepareStatement("INSERT INTO region (tenant_id, name) VALUES (?, ?)")) { + region.setLong(1, legacyTenantKey); + region.setString(2, firstRegionName); + region.executeUpdate(); + region.setLong(1, legacyTenantKey + 1); + region.setString(2, secondRegionName); + region.executeUpdate(); + } + try (PreparedStatement world = + connection.prepareStatement( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, " + + "generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, status) " + + "VALUES (?, ?, 23, 'retained-v26-request', 'retained-v26-descriptor', " + + "37, 'retained-v26-config', 41, 'retained-v26-release', 4, 'ACTIVE')")) { + world.setLong(1, legacyTenantKey); + world.setLong(2, legacyGameInstanceId); + world.executeUpdate(); + } + } + + migrateFixture(schema, null); + + try (Connection connection = fixtureConnection(schema); + Statement statement = connection.createStatement()) { + try (PreparedStatement regions = + connection.prepareStatement( + "SELECT tenant_id, name FROM region WHERE tenant_id IN (?, ?) " + + "ORDER BY tenant_id")) { + regions.setLong(1, legacyTenantKey); + regions.setLong(2, legacyTenantKey + 1); + try (ResultSet result = regions.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_id")).isEqualTo(legacyTenantKey); + assertThat(result.getString("name")).isEqualTo(firstRegionName); + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_id")).isEqualTo(legacyTenantKey + 1); + assertThat(result.getString("name")).isEqualTo(secondRegionName); + assertThat(result.next()).isFalse(); + } + } + try (PreparedStatement worlds = + connection.prepareStatement( + "SELECT tenant_id, game_instance_id, version_id, status FROM world_instance " + + "WHERE tenant_id = ?")) { + worlds.setLong(1, legacyTenantKey); + try (ResultSet result = worlds.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_id")).isEqualTo(legacyTenantKey); + assertThat(result.getLong("game_instance_id")).isEqualTo(legacyGameInstanceId); + assertThat(result.getLong("version_id")).isEqualTo(37L); + assertThat(result.getString("status")).isEqualTo("ACTIVE"); + assertThat(result.next()).isFalse(); + } + } + assertCount(statement, "world_authored_version_identity", 0L); + assertCount(statement, "world_authored_source_tenant_association", 0L); + try (PreparedStatement reservations = + connection.prepareStatement( + "SELECT tenant_key, claim_kind, target_namespace, canonical_tenant_id " + + "FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key IN (?, ?) ORDER BY tenant_key")) { + reservations.setLong(1, legacyTenantKey); + reservations.setLong(2, legacyTenantKey + 1); + try (ResultSet result = reservations.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_key")).isEqualTo(legacyTenantKey); + assertThat(result.getString("claim_kind")).isEqualTo("LEGACY_NUMERIC"); + assertThat(result.getString("target_namespace")).isNull(); + assertThat(result.getObject("canonical_tenant_id")).isNull(); + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_key")).isEqualTo(legacyTenantKey + 1); + assertThat(result.getString("claim_kind")).isEqualTo("LEGACY_NUMERIC"); + assertThat(result.getString("target_namespace")).isNull(); + assertThat(result.getObject("canonical_tenant_id")).isNull(); + assertThat(result.next()).isFalse(); + } + } + } + } finally { + dropFixtureSchema(schema); + } + } + + private WorldAuthoredSourceIntakeReceipt acceptSource(AuthoredWorldSourceEvidence source) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + return Objects.requireNonNull( + transaction.execute( + status -> sourceRepository.acceptFresh(NAMESPACE, UUID.randomUUID(), source)), + "World source intake returned no receipt"); + } + + private WorldAuthoredVersionIdentityService service( + AuthoredWorldVersionStateClient client, + WorldAuthoredVersionIdentityRepository repository, + PlatformTransactionManager manager) { + return new WorldAuthoredVersionIdentityService( + client, repository, sourceRepository, manager, NAMESPACE); + } + + private static WorldAuthoredVersionIdentityReceipt associate( + WorldAuthoredVersionIdentityService service, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + long gameDesignVersionId, + UUID readRequestId) { + return service.associate( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + canonicalVersionId, + gameDesignVersionId, + readRequestId); + } + + private Map worldContentAndLifecycleCounts() { + Map counts = new LinkedHashMap<>(); + for (String table : WORLD_CONTENT_AND_LIFECYCLE_TABLES) { + counts.put( + table, + Objects.requireNonNull( + dsl.fetchOne("SELECT COUNT(*) FROM " + table), + "World content count query returned no row") + .get(0, Long.class)); + } + return Map.copyOf(counts); + } + + private long identityCount(AuthoredWorldSourceEvidence source) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_version_identity WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND world_slug = ?", + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug()), + "World authored-Version identity count query returned no row") + .get(0, Long.class); + } + + private static AuthoredWorldSourceEvidence source(UUID tenant, String worldSlug) { + UUID registrationRequest = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String displayName = "Source " + tenant.toString().substring(0, 8); + long sourceGameRowId = Math.max(1L, tenant.getLeastSignificantBits() & Long.MAX_VALUE); + String sourceGameTenantKey = "source-" + tenant.toString().replace("-", "").substring(0, 24); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequest, tenant, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static AuthoredWorldVersionStateEvidence.Request request( + AuthoredWorldSourceEvidence source, UUID readRequestId, long gameDesignVersionId) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + readRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gameDesignVersionId); + } + + private static AuthoredWorldVersionStateEvidence versionEvidence( + AuthoredWorldVersionStateEvidence.Request request, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + VersionLifecycleState state, + long epoch) { + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, state, epoch); + } + + private static String randomWorld() { + return "world-" + UUID.randomUUID().toString().replace("-", "").substring(0, 18); + } + + private static long positiveLong() { + return Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + } + + private static T withGameDesign(java.util.function.Supplier action) { + return withPeer(NAMESPACE, "game-design-service", action); + } + + private static T withPeer( + String namespace, String service, java.util.function.Supplier action) { + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static void awaitReadBarrier(CountDownLatch latch) { + latch.countDown(); + try { + if (!latch.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent Version identity read barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent Version identity read was interrupted", exception); + } + } + + 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 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 assertCount(Statement statement, String table, long expected) + throws SQLException { + try (ResultSet result = statement.executeQuery("SELECT COUNT(*) FROM " + table)) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong(1)).isEqualTo(expected); + } + } + + private static final class LostCommitAcknowledgmentTransactionManager + implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private boolean firstCommit = true; + + private LostCommitAcknowledgmentTransactionManager(PlatformTransactionManager delegate) { + this.delegate = delegate; + } + + @Override + public TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + return delegate.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + delegate.commit(status); + if (firstCommit) { + firstCommit = false; + throw new IllegalStateException("simulated lost World identity commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + if (!status.isCompleted()) { + delegate.rollback(status); + } + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java new file mode 100644 index 0000000000..acdfd1a4ae --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java @@ -0,0 +1,1148 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +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.VersionLifecycleState; +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.WorldCompleteLaunchBindingReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository.RegistrationConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingService; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +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.TransactionStatus; +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 WorldCompleteLaunchBindingIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final UUID VERSION = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID OTHER_CANONICAL_VERSION = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + + @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 DSLContext dsl; + @Autowired private DataSource dataSource; + @Autowired private WorldAuthoredSourceIntakeRepository sourceRepository; + @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 persistsCompletePairReadsItBackAndLeavesUnmappedRetainedRowsUntouched() { + long retainedLegacyKey = + 7_900_000_000L + Math.abs(UUID.randomUUID().getLeastSignificantBits() % 100_000L); + String retainedName = "unmapped-retained-" + UUID.randomUUID(); + Long retainedRegionId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", + retainedLegacyKey, + retainedName), + "retained region insert returned no row") + .get(0, Long.class); + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 41L); + GetRequest request = request(evidence); + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.getComplete(any())).thenReturn(evidence); + WorldCompleteLaunchBindingService service = service(client, transactionManager); + + WorldCompleteLaunchBindingReceipt first = withGameSession(() -> service.bind(request)); + WorldCompleteLaunchBindingReceipt retry = + withGameSession(() -> service.bind(request(evidence))); + + assertThat(first).isEqualTo(retry); + assertThat(first.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(first.evidence()).isEqualTo(evidence); + assertThat(first.operationId()).isNotEqualTo(sourceReceipt.operationId()); + verify(client).getComplete(any()); + Record bindingRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT binding_operation_id, intake_operation_id, intake_request_id, " + + "local_tenant_key, source_operation_id, source_evidence_digest, " + + "intake_receipt_digest, descriptor_request_digest, descriptor_result_digest, " + + "release_attestation_digest, descriptor_json, release_attestation_json " + + "FROM world_complete_launch_binding WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND control_plane_request_id = ?", + NAMESPACE, + source.canonicalTenantId(), + evidence.descriptor().controlPlaneRequestId()), + "complete launch binding row was not persisted"); + assertThat(bindingRow.get("binding_operation_id", UUID.class)).isEqualTo(first.operationId()); + assertThat(bindingRow.get("intake_operation_id", UUID.class)) + .isEqualTo(sourceReceipt.operationId()); + assertThat(bindingRow.get("intake_request_id", UUID.class)) + .isEqualTo(sourceReceipt.intakeRequestId()); + assertThat(bindingRow.get("local_tenant_key", Long.class)) + .isEqualTo(sourceReceipt.localTenantKey()); + assertThat(bindingRow.get("source_operation_id", UUID.class)).isEqualTo(source.operationId()); + assertThat(bindingRow.get("source_evidence_digest", String.class)) + .isEqualTo(source.evidenceDigest()); + assertThat(bindingRow.get("intake_receipt_digest", String.class)) + .isEqualTo(sourceReceipt.receiptDigest()); + assertThat(bindingRow.get("descriptor_request_digest", String.class)) + .isEqualTo(evidence.descriptor().requestDigest()); + assertThat(bindingRow.get("descriptor_result_digest", String.class)) + .isEqualTo(evidence.descriptor().resultDigest()); + assertThat(bindingRow.get("release_attestation_digest", String.class)) + .isEqualTo(evidence.releaseAttestation().evidenceDigest()); + assertThat(bindingRow.get("descriptor_json", String.class)) + .contains(evidence.descriptor().resultDigest()); + assertThat(bindingRow.get("release_attestation_json", String.class)) + .contains(evidence.releaseAttestation().evidenceDigest()); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_id, name FROM region WHERE id = ?", retainedRegionId), + "retained region readback returned no row") + .get("tenant_id", Long.class)) + .isEqualTo(retainedLegacyKey); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT name FROM region WHERE id = ?", retainedRegionId), + "retained region name readback returned no row") + .get("name", String.class)) + .isEqualTo(retainedName); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_complete_launch_binding SET world_slug = ? " + + "WHERE binding_operation_id = ?", + "changed-world", + first.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_complete_launch_binding WHERE binding_operation_id = ?", + first.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_complete_launch_binding")) + .isInstanceOf(DataAccessException.class); + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + } + + @Test + void forwardV26MigrationPreservesUnmappedRetainedWorldRows() throws SQLException { + String schema = + "world_complete_launch_binding_" + UUID.randomUUID().toString().replace("-", ""); + long retainedLegacyKey = + 8_700_000_000L + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 1_000_000L); + String retainedName = "retained-before-v26-" + UUID.randomUUID(); + try { + migrateFixture(schema, MigrationVersion.fromVersion("25")); + try (Connection connection = fixtureConnection(schema); + PreparedStatement statement = + connection.prepareStatement("INSERT INTO region (tenant_id, name) VALUES (?, ?)")) { + statement.setLong(1, retainedLegacyKey); + statement.setString(2, retainedName); + statement.executeUpdate(); + } + migrateFixture(schema, null); + + try (Connection connection = fixtureConnection(schema); + Statement statement = connection.createStatement()) { + try (PreparedStatement retainedQuery = + connection.prepareStatement("SELECT tenant_id, name FROM region WHERE tenant_id = ?")) { + retainedQuery.setLong(1, retainedLegacyKey); + try (ResultSet retained = retainedQuery.executeQuery()) { + assertThat(retained.next()).isTrue(); + assertThat(retained.getLong("tenant_id")).isEqualTo(retainedLegacyKey); + assertThat(retained.getString("name")).isEqualTo(retainedName); + assertThat(retained.next()).isFalse(); + } + } + try (ResultSet bindingTable = + statement.executeQuery("SELECT COUNT(*) FROM world_complete_launch_binding")) { + assertThat(bindingTable.next()).isTrue(); + assertThat(bindingTable.getLong(1)).isZero(); + } + } + } finally { + dropFixtureSchema(schema); + } + } + + @Test + void deniesMissingOrSubstitutedSourceBeforeAnyWorldOwnerWrite() { + AuthoredWorldSourceEvidence retainedSource = source(UUID.randomUUID(), randomWorld()); + acceptSource(retainedSource); + AuthoredWorldSourceEvidence substitutedSource = source(UUID.randomUUID(), randomWorld()); + CompleteLaunchBindingEvidence substituted = evidence(substitutedSource, controlRequest(), 43L); + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.getComplete(any())).thenReturn(substituted); + WorldCompleteLaunchBindingService service = service(client, transactionManager); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(request(substituted)))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class); + assertThat(countBindings(substitutedSource.canonicalTenantId())).isZero(); + verify(client).getComplete(any()); + } + + @Test + void simultaneousExactRetriesReturnTheSameDurableReceiptAndOwnerOperation() throws Exception { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 50L); + CountDownLatch bothFetched = new CountDownLatch(2); + AuthoredWorldLaunchDescriptorClient firstClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + AuthoredWorldLaunchDescriptorClient secondClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(firstClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return evidence; + }); + when(secondClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return evidence; + }); + WorldCompleteLaunchBindingService firstService = service(firstClient, transactionManager); + WorldCompleteLaunchBindingService secondService = service(secondClient, transactionManager); + GetRequest firstRequest = request(evidence); + GetRequest secondRequest = request(evidence); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit(() -> withGameSession(() -> firstService.bind(firstRequest))); + Future second = + executor.submit(() -> withGameSession(() -> secondService.bind(secondRequest))); + WorldCompleteLaunchBindingReceipt firstReceipt = first.get(20, TimeUnit.SECONDS); + WorldCompleteLaunchBindingReceipt secondReceipt = second.get(20, TimeUnit.SECONDS); + + assertThat(firstReceipt).isEqualTo(secondReceipt); + assertThat(firstReceipt.operationId()).isEqualTo(secondReceipt.operationId()); + assertThat(firstReceipt.evidence()).isEqualTo(evidence); + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT binding_operation_id FROM world_complete_launch_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND control_plane_request_id = ?", + NAMESPACE, + source.canonicalTenantId(), + evidence.descriptor().controlPlaneRequestId()), + "complete launch binding operation readback returned no row") + .get("binding_operation_id", UUID.class)) + .isEqualTo(firstReceipt.operationId()); + } + verify(firstClient).getComplete(any()); + verify(secondClient).getComplete(any()); + } + + @Test + void concurrentExactAndChangedClaimsKeepOneImmutableBinding() throws Exception { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + String stableControlRequest = controlRequest(); + CompleteLaunchBindingEvidence original = evidence(source, stableControlRequest, 51L); + CompleteLaunchBindingEvidence changed = evidence(source, stableControlRequest, 52L); + CountDownLatch bothFetched = new CountDownLatch(2); + AuthoredWorldLaunchDescriptorClient originalClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + AuthoredWorldLaunchDescriptorClient changedClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(originalClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return original; + }); + when(changedClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return changed; + }); + WorldCompleteLaunchBindingService originalService = service(originalClient, transactionManager); + WorldCompleteLaunchBindingService changedService = service(changedClient, transactionManager); + GetRequest originalRequest = request(original); + GetRequest changedRequest = request(changed); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(() -> attempt(originalService, originalRequest)); + Future second = executor.submit(() -> attempt(changedService, changedRequest)); + Object firstResult = first.get(20, TimeUnit.SECONDS); + Object secondResult = second.get(20, TimeUnit.SECONDS); + WorldCompleteLaunchBindingReceipt receipt; + if (firstResult instanceof WorldCompleteLaunchBindingReceipt firstReceipt) { + receipt = firstReceipt; + assertThat(secondResult).isInstanceOf(RegistrationConflictException.class); + } else { + assertThat(firstResult).isInstanceOf(RegistrationConflictException.class); + assertThat(secondResult).isInstanceOf(WorldCompleteLaunchBindingReceipt.class); + receipt = (WorldCompleteLaunchBindingReceipt) secondResult; + } + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT binding_operation_id FROM world_complete_launch_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND control_plane_request_id = ?", + NAMESPACE, + source.canonicalTenantId(), + stableControlRequest), + "complete launch binding operation readback returned no row") + .get("binding_operation_id", UUID.class)) + .isEqualTo(receipt.operationId()); + } + } + + @Test + void recoversCommittedBindingWhenOwnerCommitAcknowledgmentIsLost() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 61L); + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.getComplete(any())).thenReturn(evidence); + LostCommitAcknowledgmentTransactionManager manager = + new LostCommitAcknowledgmentTransactionManager(transactionManager); + WorldCompleteLaunchBindingService service = service(client, manager); + + WorldCompleteLaunchBindingReceipt recovered = + withGameSession(() -> service.bind(request(evidence))); + + assertThat(recovered.evidence()).isEqualTo(evidence); + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + verify(client).getComplete(any()); + LostCommitAcknowledgmentTransactionManager retryManager = + new LostCommitAcknowledgmentTransactionManager(transactionManager); + AuthoredWorldLaunchDescriptorClient retryClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + WorldCompleteLaunchBindingReceipt retry = + withGameSession(() -> service(retryClient, retryManager).bind(request(evidence))); + assertThat(retry.operationId()).isEqualTo(recovered.operationId()); + verify(retryClient, never()).getComplete(any()); + } + + @Test + void readsCurrentVersionForExactCommittedBindingAndPreservesOriginalReceipt() + throws SQLException { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 71L); + GetRequest bindingRequest = request(evidence); + AuthoredWorldLaunchDescriptorClient descriptorClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(descriptorClient.getComplete(any())).thenReturn(evidence); + AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + UUID firstReadId = UUID.randomUUID(); + UUID retiredReadId = UUID.randomUUID(); + when(versionStateClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request currentRequest = invocation.getArgument(0); + if (currentRequest.readRequestId().equals(firstReadId)) { + return currentVersionState( + currentRequest, + source, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.descriptor().versionStateEpoch()); + } + if (currentRequest.readRequestId().equals(retiredReadId)) { + return currentVersionState( + currentRequest, + source, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + evidence.descriptor().versionStateEpoch() + 1); + } + throw new IllegalArgumentException("Unexpected synthetic current-read request"); + }); + WorldCompleteLaunchBindingService service = + service(descriptorClient, versionStateClient, transactionManager); + + WorldCompleteLaunchBindingReceipt original = + withGameSession(() -> service.bind(bindingRequest)); + Map>> ownerRowsBeforeRead = + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId()); + + AuthoredWorldVersionStateEvidence eligible = + withGameSession(() -> service.readCurrentVersionState(bindingRequest, firstReadId)); + + assertThat(eligible.versionState()) + .isEqualTo(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED); + assertThat(eligible.versionStateEpoch()).isEqualTo(evidence.descriptor().versionStateEpoch()); + assertThat(eligible.request().versionId()).isEqualTo(evidence.descriptor().versionId()); + assertThat( + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId())) + .isEqualTo(ownerRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(bindingRequest, retiredReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("epoch differs"); + assertThat( + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId())) + .isEqualTo(ownerRowsBeforeRead); + + WorldCompleteLaunchBindingReceipt retry = withGameSession(() -> service.bind(bindingRequest)); + assertThat(retry).isEqualTo(original); + assertThat(retry.operationId()).isEqualTo(original.operationId()); + assertThat(retry.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(retry.evidence()).isEqualTo(evidence); + assertThat( + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId())) + .isEqualTo(ownerRowsBeforeRead); + verify(descriptorClient).getComplete(any()); + verify(versionStateClient, times(2)).read(any()); + } + + @Test + void deniesMixedCurrentVersionEvidenceWithoutChangingCommittedBinding() throws SQLException { + AuthoredWorldSourceEvidence boundSource = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt boundSourceReceipt = acceptSource(boundSource); + CompleteLaunchBindingEvidence bindingEvidence = evidence(boundSource, controlRequest(), 73L); + GetRequest bindingRequest = request(bindingEvidence); + AuthoredWorldLaunchDescriptorClient descriptorClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(descriptorClient.getComplete(any())).thenReturn(bindingEvidence); + AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + + AuthoredWorldSourceEvidence otherSource = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt otherSourceReceipt = acceptSource(otherSource); + AuthoredWorldSourceEvidence missingBindingSource = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt missingBindingReceipt = acceptSource(missingBindingSource); + String otherControlPlaneRequestId = controlRequest(); + UUID mixedReadId = UUID.randomUUID(); + UUID changedSelectorReadId = UUID.randomUUID(); + UUID changedCanonicalVersionReadId = UUID.randomUUID(); + UUID unavailableReadId = UUID.randomUUID(); + UUID missingBindingReadId = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence mixedEvidence = + currentVersionState( + otherSource, + mixedReadId, + bindingEvidence.descriptor().versionId() + 1, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence changedSelectorEvidence = + currentVersionState( + boundSource, + changedSelectorReadId, + bindingEvidence.descriptor().versionId() + 1, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence expectedCanonicalVersionEvidence = + currentVersionState( + boundSource, + changedCanonicalVersionReadId, + bindingEvidence.descriptor().versionId(), + bindingEvidence.releaseAttestation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence changedCanonicalVersionEvidence = + currentVersionState( + boundSource, + changedCanonicalVersionReadId, + bindingEvidence.descriptor().versionId(), + OTHER_CANONICAL_VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + mixedEvidence.requireValid(); + changedSelectorEvidence.requireValid(); + changedCanonicalVersionEvidence.requireValid(); + when(versionStateClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request currentRequest = invocation.getArgument(0); + if (currentRequest.readRequestId().equals(mixedReadId)) { + return mixedEvidence; + } + if (currentRequest.readRequestId().equals(changedSelectorReadId)) { + return changedSelectorEvidence; + } + if (currentRequest.readRequestId().equals(changedCanonicalVersionReadId)) { + return changedCanonicalVersionEvidence; + } + if (currentRequest.readRequestId().equals(unavailableReadId)) { + throw new IllegalStateException("Synthetic current-version source is unavailable"); + } + throw new IllegalArgumentException("Unexpected synthetic current-read request"); + }); + WorldCompleteLaunchBindingService service = + service(descriptorClient, versionStateClient, transactionManager); + WorldCompleteLaunchBindingReceipt committed = + withGameSession(() -> service.bind(bindingRequest)); + GetRequest missingBindingRequest = + request(evidence(missingBindingSource, controlRequest(), 74L)); + Map>> committedRowsBeforeRead = + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId()); + Map>> otherSourceRowsBeforeRead = + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId); + Map>> missingBindingRowsBeforeRead = + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId()); + assertThat(mixedEvidence.request().sourceOperationId()).isEqualTo(otherSource.operationId()); + assertThat(mixedEvidence.request().versionId()) + .isNotEqualTo(bindingEvidence.descriptor().versionId()); + assertThat(changedSelectorEvidence.sourceEvidence()).isEqualTo(boundSource); + assertThat(changedSelectorEvidence.request().versionId()) + .isNotEqualTo(bindingEvidence.descriptor().versionId()); + assertThat(changedCanonicalVersionEvidence.request()) + .isEqualTo(expectedCanonicalVersionEvidence.request()); + assertThat(changedCanonicalVersionEvidence.sourceEvidence()) + .isEqualTo(expectedCanonicalVersionEvidence.sourceEvidence()); + assertThat(changedCanonicalVersionEvidence.versionState()) + .isEqualTo(expectedCanonicalVersionEvidence.versionState()); + assertThat(changedCanonicalVersionEvidence.versionStateEpoch()) + .isEqualTo(expectedCanonicalVersionEvidence.versionStateEpoch()); + assertThat(changedCanonicalVersionEvidence.canonicalVersionId()) + .isNotEqualTo(bindingEvidence.releaseAttestation().canonicalVersionId()); + + assertThatThrownBy( + () -> + withGameSession(() -> service.readCurrentVersionState(bindingRequest, mixedReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + assertThat( + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId)) + .isEqualTo(otherSourceRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(bindingRequest, changedSelectorReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + bindingRequest, changedCanonicalVersionReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("canonical version UUID differs"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + assertThat( + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId)) + .isEqualTo(otherSourceRowsBeforeRead); + assertThat( + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId())) + .isEqualTo(missingBindingRowsBeforeRead); + assertThat(committed.evidence()).isEqualTo(bindingEvidence); + assertThat(committed.sourceIntakeReceipt()).isEqualTo(boundSourceReceipt); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(bindingRequest, unavailableReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("unavailable or invalid"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + missingBindingRequest, missingBindingReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("requires a committed launch binding"); + assertThat( + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId())) + .isEqualTo(missingBindingRowsBeforeRead); + assertThat(missingBindingRowsBeforeRead.get("binding")).isEmpty(); + assertThat(committed.operationId()) + .isEqualTo(committedRowsBeforeRead.get("binding").get(0).get("binding_operation_id")); + assertThat( + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId)) + .isEqualTo(otherSourceRowsBeforeRead); + assertThat( + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId())) + .isEqualTo(missingBindingRowsBeforeRead); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + WorldCompleteLaunchBindingReceipt retried = withGameSession(() -> service.bind(bindingRequest)); + assertThat(retried).isEqualTo(committed); + assertThat(retried.evidence()).isEqualTo(bindingEvidence); + assertThat(retried.sourceIntakeReceipt()).isEqualTo(boundSourceReceipt); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + verify(descriptorClient).getComplete(any()); + verify(versionStateClient, times(4)).read(any()); + } + + private WorldAuthoredSourceIntakeReceipt acceptSource(AuthoredWorldSourceEvidence source) { + UUID intakeRequestId = UUID.randomUUID(); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + return Objects.requireNonNull( + transaction.execute( + status -> sourceRepository.acceptFresh(NAMESPACE, intakeRequestId, source)), + "World source intake returned no receipt"); + } + + private WorldCompleteLaunchBindingService service( + AuthoredWorldLaunchDescriptorClient client, PlatformTransactionManager manager) { + return new WorldCompleteLaunchBindingService( + client, + new WorldCompleteLaunchBindingRepository(dsl), + sourceRepository, + manager, + NAMESPACE); + } + + private WorldCompleteLaunchBindingService service( + AuthoredWorldLaunchDescriptorClient descriptorClient, + AuthoredWorldVersionStateClient versionStateClient, + PlatformTransactionManager manager) { + return new WorldCompleteLaunchBindingService( + descriptorClient, + new WorldCompleteLaunchBindingRepository(dsl), + sourceRepository, + manager, + NAMESPACE, + versionStateClient); + } + + private Map>> worldOwnerRows( + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + long localTenantKey, + String controlPlaneRequestId) + throws SQLException { + try (Connection connection = dataSource.getConnection()) { + Map>> rows = new LinkedHashMap<>(); + rows.put( + "association", + readOwnerRows( + connection, + "SELECT * FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + canonicalTenantId)); + rows.put( + "reservation", + readOwnerRows( + connection, + "SELECT * FROM world_authored_source_tenant_key_reservation WHERE tenant_key = ?", + localTenantKey)); + rows.put( + "sourceIntake", + readOwnerRows( + connection, + "SELECT * FROM world_authored_source_intake WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND operation_id = ?", + NAMESPACE, + canonicalTenantId, + sourceIntakeOperationId)); + rows.put( + "binding", + readOwnerRows( + connection, + "SELECT * FROM world_complete_launch_binding WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND control_plane_request_id = ?", + NAMESPACE, + canonicalTenantId, + controlPlaneRequestId)); + return Collections.unmodifiableMap(rows); + } + } + + private static List> readOwnerRows( + Connection connection, String query, Object... parameters) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(query)) { + for (int index = 0; index < parameters.length; index++) { + statement.setObject(index + 1, parameters[index]); + } + try (ResultSet resultSet = statement.executeQuery()) { + ResultSetMetaData metadata = resultSet.getMetaData(); + List> rows = new ArrayList<>(); + while (resultSet.next()) { + Map row = new LinkedHashMap<>(); + for (int index = 1; index <= metadata.getColumnCount(); index++) { + row.put(metadata.getColumnLabel(index), resultSet.getObject(index)); + } + rows.add(Collections.unmodifiableMap(row)); + } + return List.copyOf(rows); + } + } + } + + private long countBindings(UUID tenant) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_complete_launch_binding WHERE target_namespace = ? " + + "AND canonical_tenant_id = ?", + NAMESPACE, + tenant), + "complete launch binding count query returned no row") + .get(0, Long.class); + } + + private static AuthoredWorldSourceEvidence source(UUID tenant, String worldSlug) { + UUID registrationRequest = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String displayName = "Source " + tenant.toString().substring(0, 8); + long sourceGameRowId = Math.max(1L, tenant.getLeastSignificantBits() & Long.MAX_VALUE); + String sourceGameTenantKey = "source-" + tenant.toString().replace("-", "").substring(0, 24); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequest, tenant, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static CompleteLaunchBindingEvidence evidence( + AuthoredWorldSourceEvidence source, String controlPlaneRequestId, long gameTemplateId) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "launch-descriptor-" + gameTemplateId, + 42L, + false, + null, + "{}", + "generation-config-42", + 17L, + 51L, + "release-bundle-51", + false, + null); + String commit = "commit-launch-binding"; + List participants = + List.of( + participant("WORLD_MANAGEMENT", 2, "a", false, commit), + participant("ENTITY_MANAGEMENT", 2, "b", false, commit), + participant("GAME_LOGIC", 1, "c", true, commit), + participant("AUTOMATION_SCRIPTING", 5, "d", false, commit), + participant("GAME_DESIGN_CONTROL_PLANE", 1, "e", false, commit)); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + VERSION, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:owner:launch-binding", + commit, + participants, + digest('f'), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldVersionStateEvidence.Request request, + AuthoredWorldSourceEvidence source, + VersionLifecycleState versionState, + long versionStateEpoch) { + return currentVersionState(request, source, VERSION, versionState, versionStateEpoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldVersionStateEvidence.Request request, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, versionState, versionStateEpoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID readRequestId, + long versionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + return currentVersionState( + source, readRequestId, versionId, VERSION, versionState, versionStateEpoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID readRequestId, + long versionId, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + source.targetNamespace(), + readRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + versionId); + return currentVersionState( + request, source, canonicalVersionId, versionState, versionStateEpoch); + } + + private static AuthoredWorldReleaseAttestationEvidence.Participant participant( + String owner, int schema, String contentHex, boolean hasAbilityDigest, String commit) { + return new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "42", + false, + null, + commit, + contentHex.repeat(64), + schema, + hasAbilityDigest, + hasAbilityDigest ? digest('c') : null); + } + + private static GetRequest request(CompleteLaunchBindingEvidence evidence) { + UUID requestId; + do { + requestId = UUID.randomUUID(); + } while (requestId.equals(evidence.descriptor().authoredWorldSourceOperationId())); + return new GetRequest( + requestId, evidence.descriptor().request(), evidence.descriptor().resultDigest()); + } + + private static String randomWorld() { + return "world-" + UUID.randomUUID().toString().replace("-", "").substring(0, 18); + } + + private static String controlRequest() { + return "world-control-" + UUID.randomUUID(); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static GrpcPeerIdentity peer() { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service", + NAMESPACE, + "game-session-service"); + } + + private static T withGameSession(java.util.function.Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer()); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static void awaitFetchBarrier(CountDownLatch latch) { + latch.countDown(); + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent launch-binding fetch barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent launch-binding fetch was interrupted", exception); + } + } + + private static Object attempt(WorldCompleteLaunchBindingService service, GetRequest request) { + return withGameSession( + () -> { + try { + return service.bind(request); + } catch (RegistrationConflictException exception) { + return exception; + } + }); + } + + 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 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 final class LostCommitAcknowledgmentTransactionManager + implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private boolean firstCommit = true; + + private LostCommitAcknowledgmentTransactionManager(PlatformTransactionManager delegate) { + this.delegate = delegate; + } + + @Override + public TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + return delegate.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + delegate.commit(status); + if (firstCommit) { + firstCommit = false; + throw new IllegalStateException("simulated lost owner commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + if (!status.isCompleted()) { + delegate.rollback(status); + } + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignEpochCasPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignEpochCasPostgresIntegrationTest.java new file mode 100644 index 0000000000..0fe35fc873 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignEpochCasPostgresIntegrationTest.java @@ -0,0 +1,713 @@ +package net.firedevops.firemud.worldmanagement; + +import static net.firedevops.firemud.worldmanagement.jooq.tables.WorldDesignAggregateEpoch.WORLD_DESIGN_AGGREGATE_EPOCH; +import static net.firedevops.firemud.worldmanagement.jooq.tables.WorldDesignScopeEpoch.WORLD_DESIGN_SCOPE_EPOCH; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.when; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BooleanSupplier; +import java.util.function.LongSupplier; +import net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +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.dto.WorldDesignMutationRequestDto; +import net.firedevops.firemud.worldmanagement.entity.Region; +import net.firedevops.firemud.worldmanagement.entity.WorldDesignAggregateEpoch; +import net.firedevops.firemud.worldmanagement.entity.WorldDesignScopeEpoch; +import net.firedevops.firemud.worldmanagement.entity.Zone; +import net.firedevops.firemud.worldmanagement.repository.RegionRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldDesignAggregateEpochRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldDesignScopeEpochRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService; +import org.jooq.DSLContext; +import org.jooq.Record; +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.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 WorldDesignEpochCasPostgresIntegrationTest { + private static final LocalDateTime INITIAL_EPOCH_TIME = LocalDateTime.of(2026, 10, 1, 12, 0); + private static final LocalDateTime ADVANCED_EPOCH_TIME = LocalDateTime.of(2026, 10, 2, 12, 0); + + @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 DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private RegionRepository regionRepository; + @Autowired private ZoneRepository zoneRepository; + @Autowired private WorldDesignAggregateEpochRepository aggregateEpochRepository; + @Autowired private WorldDesignScopeEpochRepository scopeEpochRepository; + @Autowired private WorldDesignMutationService mutationService; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void concurrentFirstZeroClaimsHaveExactlyOneWinnerForEachEpochTable() throws Exception { + long tenantId = uniquePositiveLong(); + long versionId = uniquePositiveLong(); + long aggregateId = uniquePositiveLong(); + String scopeId = Long.toString(uniquePositiveLong()); + + assertSingleConcurrentWinner( + "first aggregate epoch claim", + () -> + aggregateEpochRepository.compareAndAdvance( + tenantId, versionId, "ROOM", aggregateId, 0L, ADVANCED_EPOCH_TIME), + () -> + aggregateEpochRepository + .findByTenantIdAndVersionIdAndAggregateTypeAndAggregateId( + tenantId, versionId, "ROOM", aggregateId) + .orElseThrow() + .getDraftRevisionEpoch(), + () -> countAggregateRows(tenantId, versionId, "ROOM", aggregateId), + 1L); + assertSingleConcurrentWinner( + "first scope epoch claim", + () -> + scopeEpochRepository.compareAndAdvance( + tenantId, versionId, "ZONE_SUBTREE", scopeId, 0L, ADVANCED_EPOCH_TIME), + () -> + scopeEpochRepository + .findByTenantIdAndVersionIdAndScopeTypeAndScopeId( + tenantId, versionId, "ZONE_SUBTREE", scopeId) + .orElseThrow() + .getDraftScopeRevisionEpoch(), + () -> countScopeRows(tenantId, versionId, "ZONE_SUBTREE", scopeId), + 1L); + } + + @Test + void concurrentExistingEpochClaimsHaveExactlyOneWinnerForEachEpochTable() throws Exception { + long tenantId = uniquePositiveLong(); + long versionId = uniquePositiveLong(); + long aggregateId = uniquePositiveLong(); + String scopeId = Long.toString(uniquePositiveLong()); + saveAggregateEpoch(tenantId, versionId, "ROOM", aggregateId, 6L, INITIAL_EPOCH_TIME); + saveScopeEpoch(tenantId, versionId, "ZONE_SUBTREE", scopeId, 6L, INITIAL_EPOCH_TIME); + + assertSingleConcurrentWinner( + "existing aggregate epoch advance", + () -> + aggregateEpochRepository.compareAndAdvance( + tenantId, versionId, "ROOM", aggregateId, 6L, ADVANCED_EPOCH_TIME), + () -> + aggregateEpochRepository + .findByTenantIdAndVersionIdAndAggregateTypeAndAggregateId( + tenantId, versionId, "ROOM", aggregateId) + .orElseThrow() + .getDraftRevisionEpoch(), + () -> countAggregateRows(tenantId, versionId, "ROOM", aggregateId), + 7L); + assertSingleConcurrentWinner( + "existing scope epoch advance", + () -> + scopeEpochRepository.compareAndAdvance( + tenantId, versionId, "ZONE_SUBTREE", scopeId, 6L, ADVANCED_EPOCH_TIME), + () -> + scopeEpochRepository + .findByTenantIdAndVersionIdAndScopeTypeAndScopeId( + tenantId, versionId, "ZONE_SUBTREE", scopeId) + .orElseThrow() + .getDraftScopeRevisionEpoch(), + () -> countScopeRows(tenantId, versionId, "ZONE_SUBTREE", scopeId), + 7L); + } + + @Test + void tupleDimensionsAndInvalidEpochsCannotChangeNeighboringRows() { + long tenantId = uniquePositiveLong(); + long otherTenantId = tenantId + 1L; + long versionId = uniquePositiveLong(); + long otherVersionId = versionId + 1L; + long aggregateId = uniquePositiveLong(); + String scopeId = Long.toString(uniquePositiveLong()); + + List aggregateRows = + List.of( + saveAggregateEpoch(tenantId, versionId, "ROOM", aggregateId, 3L, INITIAL_EPOCH_TIME), + saveAggregateEpoch( + otherTenantId, versionId, "ROOM", aggregateId, 3L, INITIAL_EPOCH_TIME), + saveAggregateEpoch( + tenantId, otherVersionId, "ROOM", aggregateId, 3L, INITIAL_EPOCH_TIME), + saveAggregateEpoch(tenantId, versionId, "ZONE", aggregateId, 3L, INITIAL_EPOCH_TIME), + saveAggregateEpoch( + tenantId, versionId, "ROOM", aggregateId + 1L, 3L, INITIAL_EPOCH_TIME), + saveAggregateEpoch( + tenantId, versionId, "ROOM", aggregateId + 2L, Long.MAX_VALUE, INITIAL_EPOCH_TIME)); + List aggregateIds = aggregateRows.stream().map(WorldDesignAggregateEpoch::getId).toList(); + String aggregateSnapshotBeforeInvalidCalls = aggregateSnapshot(aggregateIds); + String aggregateSiblingsBeforeAdvance = + aggregateSnapshot(aggregateIds.subList(1, aggregateIds.size())); + + assertThat( + aggregateEpochRepository.compareAndAdvance( + tenantId, versionId, "ROOM", aggregateId, -1L, ADVANCED_EPOCH_TIME)) + .isFalse(); + assertThat( + aggregateEpochRepository.compareAndAdvance( + tenantId, versionId, "ROOM", aggregateId + 2L, Long.MAX_VALUE, ADVANCED_EPOCH_TIME)) + .isFalse(); + assertThat( + aggregateEpochRepository.compareAndAdvance( + tenantId, versionId, "ROOM", aggregateId, 2L, ADVANCED_EPOCH_TIME)) + .isFalse(); + assertThat( + aggregateEpochRepository.compareAndAdvance( + tenantId, versionId, "ROOM", aggregateId + 3L, 3L, ADVANCED_EPOCH_TIME)) + .isFalse(); + assertThat(aggregateSnapshot(aggregateIds)).isEqualTo(aggregateSnapshotBeforeInvalidCalls); + + assertThat( + aggregateEpochRepository.compareAndAdvance( + tenantId, versionId, "ROOM", aggregateId, 3L, ADVANCED_EPOCH_TIME)) + .isTrue(); + assertThat( + aggregateEpochRepository + .findByTenantIdAndVersionIdAndAggregateTypeAndAggregateId( + tenantId, versionId, "ROOM", aggregateId) + .orElseThrow()) + .satisfies( + epoch -> { + assertThat(epoch.getDraftRevisionEpoch()).isEqualTo(4L); + assertThat(epoch.getUpdatedAt()).isEqualTo(ADVANCED_EPOCH_TIME); + }); + assertThat(aggregateSnapshot(aggregateIds.subList(1, aggregateIds.size()))) + .isEqualTo(aggregateSiblingsBeforeAdvance); + + List scopeRows = + List.of( + saveScopeEpoch(tenantId, versionId, "ZONE_SUBTREE", scopeId, 3L, INITIAL_EPOCH_TIME), + saveScopeEpoch( + otherTenantId, versionId, "ZONE_SUBTREE", scopeId, 3L, INITIAL_EPOCH_TIME), + saveScopeEpoch( + tenantId, otherVersionId, "ZONE_SUBTREE", scopeId, 3L, INITIAL_EPOCH_TIME), + saveScopeEpoch(tenantId, versionId, "REGION_SUBTREE", scopeId, 3L, INITIAL_EPOCH_TIME), + saveScopeEpoch( + tenantId, + versionId, + "ZONE_SUBTREE", + Long.toString(Long.parseLong(scopeId) + 1L), + 3L, + INITIAL_EPOCH_TIME), + saveScopeEpoch( + tenantId, + versionId, + "ZONE_SUBTREE", + Long.toString(Long.parseLong(scopeId) + 2L), + Long.MAX_VALUE, + INITIAL_EPOCH_TIME)); + List scopeIds = scopeRows.stream().map(WorldDesignScopeEpoch::getId).toList(); + String scopeSnapshotBeforeInvalidCalls = scopeSnapshot(scopeIds); + String scopeSiblingsBeforeAdvance = scopeSnapshot(scopeIds.subList(1, scopeIds.size())); + + assertThat( + scopeEpochRepository.compareAndAdvance( + tenantId, versionId, "ZONE_SUBTREE", scopeId, -1L, ADVANCED_EPOCH_TIME)) + .isFalse(); + WorldDesignScopeEpoch overflowScope = scopeRows.get(scopeRows.size() - 1); + assertThat( + scopeEpochRepository.compareAndAdvance( + overflowScope.getTenantId(), + overflowScope.getVersionId(), + overflowScope.getScopeType(), + overflowScope.getScopeId(), + Long.MAX_VALUE, + ADVANCED_EPOCH_TIME)) + .isFalse(); + assertThat( + scopeEpochRepository.compareAndAdvance( + tenantId, versionId, "ZONE_SUBTREE", scopeId, 2L, ADVANCED_EPOCH_TIME)) + .isFalse(); + assertThat( + scopeEpochRepository.compareAndAdvance( + tenantId, versionId, "ZONE_SUBTREE", scopeId + "-missing", 3L, ADVANCED_EPOCH_TIME)) + .isFalse(); + assertThat(scopeSnapshot(scopeIds)).isEqualTo(scopeSnapshotBeforeInvalidCalls); + + assertThat( + scopeEpochRepository.compareAndAdvance( + tenantId, versionId, "ZONE_SUBTREE", scopeId, 3L, ADVANCED_EPOCH_TIME)) + .isTrue(); + assertThat( + scopeEpochRepository + .findByTenantIdAndVersionIdAndScopeTypeAndScopeId( + tenantId, versionId, "ZONE_SUBTREE", scopeId) + .orElseThrow()) + .satisfies( + epoch -> { + assertThat(epoch.getDraftScopeRevisionEpoch()).isEqualTo(4L); + assertThat(epoch.getUpdatedAt()).isEqualTo(ADVANCED_EPOCH_TIME); + }); + assertThat(scopeSnapshot(scopeIds.subList(1, scopeIds.size()))) + .isEqualTo(scopeSiblingsBeforeAdvance); + } + + @Test + void lateScopeConflictRollsBackServiceAuthoredRowAndPriorAggregateAdvance() throws Exception { + WorldFixture fixture = worldFixture(); + WorldDesignScopeEpoch scopeEpoch = + saveScopeEpoch( + fixture.tenantId(), + fixture.versionId(), + "ZONE_SUBTREE", + Long.toString(fixture.zoneId()), + 0L, + INITIAL_EPOCH_TIME); + stubDraftVersion(fixture.tenantId(), fixture.versionId()); + WorldDesignMutationRequestDto request = roomMutation(fixture, "late-conflict"); + + CountDownLatch blockerChangedScope = new CountDownLatch(1); + CountDownLatch releaseBlocker = new CountDownLatch(1); + CountDownLatch mutationStarted = new CountDownLatch(1); + AtomicInteger blockerBackendPid = new AtomicInteger(); + AtomicInteger mutationBackendPid = new AtomicInteger(); + + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future blocker = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + blockerBackendPid.set(backendPid()); + int updated = + dsl.execute( + "UPDATE world_design_scope_epoch SET " + + "draft_scope_revision_epoch = ?, updated_at = ? " + + "WHERE id = ? AND draft_scope_revision_epoch = ?", + 1L, + ADVANCED_EPOCH_TIME, + scopeEpoch.getId(), + 0L); + assertThat(updated).isEqualTo(1); + blockerChangedScope.countDown(); + await(releaseBlocker); + return null; + })); + await(blockerChangedScope); + + Future mutation = + executor.submit( + () -> { + try { + ownerTransaction() + .execute( + status -> { + mutationBackendPid.set(backendPid()); + mutationStarted.countDown(); + return mutationService.applyMutation(request); + }); + return null; + } catch (RuntimeException exception) { + return exception; + } + }); + await(mutationStarted); + awaitBackendBlockedBy(mutationBackendPid.get(), blockerBackendPid.get()); + releaseBlocker.countDown(); + + blocker.get(10, TimeUnit.SECONDS); + Throwable conflict = mutation.get(10, TimeUnit.SECONDS); + assertThat(conflict) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("DRAFT_WRITE_CONFLICT:"); + } finally { + releaseBlocker.countDown(); + executor.shutdownNow(); + } + + assertThat(roomSnapshot(fixture)).isEmpty(); + assertThat(countRows("world_design_aggregate_epoch", fixture.tenantId(), fixture.versionId())) + .isZero(); + assertThat(countLedgerRows(fixture.tenantId(), fixture.versionId(), request.commitId())) + .isZero(); + assertThat( + scopeEpochRepository + .findByTenantIdAndVersionIdAndScopeTypeAndScopeId( + fixture.tenantId(), + fixture.versionId(), + "ZONE_SUBTREE", + Long.toString(fixture.zoneId())) + .orElseThrow()) + .satisfies( + epoch -> { + assertThat(epoch.getDraftScopeRevisionEpoch()).isEqualTo(1L); + assertThat(epoch.getUpdatedAt()).isEqualTo(ADVANCED_EPOCH_TIME); + }); + } + + @Test + void authoredRowAggregateScopeAndLedgerShareTheOwnerTransaction() { + WorldFixture fixture = worldFixture(); + stubDraftVersion(fixture.tenantId(), fixture.versionId()); + WorldDesignMutationRequestDto request = roomMutation(fixture, "forced-rollback"); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + var result = mutationService.applyMutation(request); + assertThat(result.result()).isEqualTo("APPLIED"); + assertThat(result.aggregateId()).isPositive(); + List authoredRows = roomSnapshot(fixture); + assertThat(authoredRows).hasSize(1); + assertThat(authoredRows.get(0)) + .contains("epoch-cas-room-forced-rollback"); + assertThat(countRows("room", fixture.tenantId(), fixture.versionId())) + .isEqualTo(1L); + assertThat( + aggregateEpochRepository + .findByTenantIdAndVersionIdAndAggregateTypeAndAggregateId( + fixture.tenantId(), + fixture.versionId(), + "ROOM", + result.aggregateId()) + .orElseThrow() + .getDraftRevisionEpoch()) + .isEqualTo(1L); + assertThat( + scopeEpochRepository + .findByTenantIdAndVersionIdAndScopeTypeAndScopeId( + fixture.tenantId(), + fixture.versionId(), + "ZONE_SUBTREE", + Long.toString(fixture.zoneId())) + .orElseThrow() + .getDraftScopeRevisionEpoch()) + .isEqualTo(1L); + assertThat( + countLedgerRows( + fixture.tenantId(), fixture.versionId(), request.commitId())) + .isEqualTo(1L); + throw new ForcedRollbackException(); + })) + .isInstanceOf(ForcedRollbackException.class); + + assertThat(roomSnapshot(fixture)).isEmpty(); + assertThat(countRows("world_design_aggregate_epoch", fixture.tenantId(), fixture.versionId())) + .isZero(); + assertThat(countRows("world_design_scope_epoch", fixture.tenantId(), fixture.versionId())) + .isZero(); + assertThat(countLedgerRows(fixture.tenantId(), fixture.versionId(), request.commitId())) + .isZero(); + } + + private void assertSingleConcurrentWinner( + String description, + BooleanSupplier advance, + LongSupplier storedEpoch, + LongSupplier matchingRowCount, + long expectedFinalEpoch) + throws Exception { + CountDownLatch firstAdvanced = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + AtomicInteger firstBackendPid = new AtomicInteger(); + AtomicInteger secondBackendPid = new AtomicInteger(); + + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + firstBackendPid.set(backendPid()); + boolean advanced = advance.getAsBoolean(); + assertThat(advanced).as(description).isTrue(); + firstAdvanced.countDown(); + await(releaseFirst); + return advanced; + })); + await(firstAdvanced); + + Future second = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + secondBackendPid.set(backendPid()); + secondStarted.countDown(); + return advance.getAsBoolean(); + })); + await(secondStarted); + awaitBackendBlockedBy(secondBackendPid.get(), firstBackendPid.get()); + releaseFirst.countDown(); + + assertThat(first.get(10, TimeUnit.SECONDS)).as(description).isTrue(); + assertThat(second.get(10, TimeUnit.SECONDS)).as(description).isFalse(); + assertThat(storedEpoch.getAsLong()).as(description).isEqualTo(expectedFinalEpoch); + assertThat(matchingRowCount.getAsLong()).as(description).isEqualTo(1L); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + } + } + + private WorldFixture worldFixture() { + long tenantId = uniquePositiveLong(); + long versionId = uniquePositiveLong(); + Region region = new Region(); + region.setTenantId(tenantId); + region.setVersionId(versionId); + region.setShardId(0); + region.setName("epoch-cas-region-" + UUID.randomUUID()); + region.setGenerationSeed(0L); + region.setSpacingMultiplier(1.0); + Region savedRegion = regionRepository.save(region); + + Zone zone = new Zone(); + zone.setTenantId(tenantId); + zone.setVersionId(versionId); + zone.setRegion(savedRegion); + zone.setName("epoch-cas-zone-" + UUID.randomUUID()); + Zone savedZone = zoneRepository.save(zone); + return new WorldFixture(tenantId, versionId, savedZone.getId()); + } + + private WorldDesignMutationRequestDto roomMutation(WorldFixture fixture, String suffix) { + return new WorldDesignMutationRequestDto( + fixture.tenantId(), + fixture.versionId(), + "epoch-cas-commit-" + suffix + "-" + UUID.randomUUID(), + "epoch-cas-revision-" + UUID.randomUUID(), + "UPSERT", + "ROOM", + "", + 0L, + "ZONE_SUBTREE", + Long.toString(fixture.zoneId()), + 0L, + "SEED_APPEND_ONLY", + null, + null, + new WorldDesignMutationRequestDto.RoomMutationDto( + "epoch-cas-room-" + suffix, + "Authored by the mutation service", + Long.toString(fixture.zoneId()), + null, + null), + null, + null, + null, + null); + } + + private void stubDraftVersion(long tenantId, long versionId) { + when(gameDesignClient.getVersionState(tenantId, versionId)) + .thenReturn( + GetVersionStateResponse.newBuilder() + .setVersionState( + VersionStateSnapshot.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setVersionId(versionId) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT) + .setVersionStateEpoch(1L) + .build()) + .build()); + } + + private WorldDesignAggregateEpoch saveAggregateEpoch( + long tenantId, + long versionId, + String aggregateType, + long aggregateId, + long epoch, + LocalDateTime updatedAt) { + WorldDesignAggregateEpoch row = new WorldDesignAggregateEpoch(); + row.setTenantId(tenantId); + row.setVersionId(versionId); + row.setAggregateType(aggregateType); + row.setAggregateId(aggregateId); + row.setDraftRevisionEpoch(epoch); + row.setUpdatedAt(updatedAt); + return aggregateEpochRepository.save(row); + } + + private WorldDesignScopeEpoch saveScopeEpoch( + long tenantId, + long versionId, + String scopeType, + String scopeId, + long epoch, + LocalDateTime updatedAt) { + WorldDesignScopeEpoch row = new WorldDesignScopeEpoch(); + row.setTenantId(tenantId); + row.setVersionId(versionId); + row.setScopeType(scopeType); + row.setScopeId(scopeId); + row.setDraftScopeRevisionEpoch(epoch); + row.setUpdatedAt(updatedAt); + return scopeEpochRepository.save(row); + } + + private String aggregateSnapshot(List ids) { + return dsl.selectFrom(WORLD_DESIGN_AGGREGATE_EPOCH) + .where(WORLD_DESIGN_AGGREGATE_EPOCH.ID.in(ids)) + .orderBy(WORLD_DESIGN_AGGREGATE_EPOCH.ID.asc()) + .fetch() + .formatJSON(); + } + + private String scopeSnapshot(List ids) { + return dsl.selectFrom(WORLD_DESIGN_SCOPE_EPOCH) + .where(WORLD_DESIGN_SCOPE_EPOCH.ID.in(ids)) + .orderBy(WORLD_DESIGN_SCOPE_EPOCH.ID.asc()) + .fetch() + .formatJSON(); + } + + private List roomSnapshot(WorldFixture fixture) { + return dsl.fetch( + "SELECT * FROM room WHERE tenant_id = ? AND version_id = ? ORDER BY id", + fixture.tenantId(), + fixture.versionId()) + .map(Record::formatJSON); + } + + private long countRows(String table, long tenantId, long versionId) { + Record row = + dsl.fetchOne( + "SELECT COUNT(*) FROM " + table + " WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId); + return Objects.requireNonNull(row, "count query returned no row").get(0, Long.class); + } + + private long countLedgerRows(long tenantId, long versionId, String commitId) { + Record row = + dsl.fetchOne( + "SELECT COUNT(*) FROM world_design_revision_ledger " + + "WHERE tenant_id = ? AND version_id = ? AND commit_id = ?", + tenantId, + versionId, + commitId); + return Objects.requireNonNull(row, "ledger count query returned no row").get(0, Long.class); + } + + private long countAggregateRows( + long tenantId, long versionId, String aggregateType, long aggregateId) { + Record row = + dsl.fetchOne( + "SELECT COUNT(*) FROM world_design_aggregate_epoch " + + "WHERE tenant_id = ? AND version_id = ? AND aggregate_type = ? AND aggregate_id = ?", + tenantId, + versionId, + aggregateType, + aggregateId); + return Objects.requireNonNull(row, "aggregate epoch count query returned no row") + .get(0, Long.class); + } + + private long countScopeRows(long tenantId, long versionId, String scopeType, String scopeId) { + Record row = + dsl.fetchOne( + "SELECT COUNT(*) FROM world_design_scope_epoch " + + "WHERE tenant_id = ? AND version_id = ? AND scope_type = ? AND scope_id = ?", + tenantId, + versionId, + scopeType, + scopeId); + return Objects.requireNonNull(row, "scope epoch count query returned no row") + .get(0, Long.class); + } + + private int backendPid() { + Record row = Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")); + return Objects.requireNonNull(row.get(0, Integer.class)); + } + + private void awaitBackendBlockedBy(int blockedPid, int blockerPid) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + Record row = + dsl.fetchOne( + "SELECT wait_event_type = 'Lock' AND ? = ANY(pg_blocking_pids(pid)) " + + "FROM pg_stat_activity WHERE pid = ?", + blockerPid, + blockedPid); + if (row != null && Boolean.TRUE.equals(row.get(0, Boolean.class))) { + return; + } + Thread.sleep(25L); + } + throw new AssertionError( + "PostgreSQL backend " + blockedPid + " was not observed blocked by " + blockerPid); + } + + private TransactionTemplate ownerTransaction() { + return new TransactionTemplate(transactionManager); + } + + private static long uniquePositiveLong() { + return ((UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE) / 1_000_000L) + 10_000L; + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new AssertionError("Timed out coordinating the PostgreSQL epoch CAS test"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new AssertionError( + "Interrupted while coordinating the PostgreSQL epoch CAS test", exception); + } + } + + private record WorldFixture(long tenantId, long versionId, long zoneId) {} + + private static final class ForcedRollbackException extends RuntimeException {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java index be9dd02290..0544de102b 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.worldmanagement; +import static net.firedevops.firemud.worldmanagement.jooq.tables.GenerationRule.GENERATION_RULE; import static net.firedevops.firemud.worldmanagement.jooq.tables.RegionInstance.REGION_INSTANCE; import static net.firedevops.firemud.worldmanagement.jooq.tables.WorldEvent.WORLD_EVENT; import static net.firedevops.firemud.worldmanagement.jooq.tables.WorldInstance.WORLD_INSTANCE; @@ -17,7 +18,10 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.security.HttpAuthProperties; +import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.test.FiremudAuthTestProperties; import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; @@ -34,23 +38,34 @@ import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; import org.springframework.http.HttpHeaders; +import org.springframework.mock.web.MockHttpServletRequest; 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.annotation.Transactional; import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerExecutionChain; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, classes = WorldManagementServiceApplication.class, - properties = "spring.grpc.server.port=0") + properties = { + "spring.grpc.server.port=0", + FiremudAuthTestProperties.HTTP_ENABLED, + "firemud.auth.http.public-routes[0].method=GET", + "firemud.auth.http.public-routes[0].path-pattern=/ping" + }) class WorldManagementServiceApplicationIntegrationTest { private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); @@ -70,7 +85,10 @@ static void configure(DynamicPropertyRegistry registry) { @LocalServerPort private int port; @Autowired private JwtUtil jwtUtil; + @Autowired private HttpAuthProperties httpAuthProperties; + @Autowired private ObjectMapper objectMapper; @Autowired private DSLContext dsl; + @Autowired private RequestMappingHandlerMapping requestMappingHandlerMapping; @Autowired private WorldEventRepository worldEventRepository; @Autowired private PlatformTransactionManager transactionManager; @@ -141,6 +159,59 @@ void saveRuleRejectsMalformedBodyWithInvalidArgumentEnvelope() throws Exception assertThat(response.body()).contains("\"message\":\"Request body is malformed\""); } + @Test + void saveRuleDeniesAuthenticatedWriteWithoutCanonicalCommitAuthorization() throws Exception { + String token = operatorToken(); + assertThat(httpAuthProperties.isEnabled()).isTrue(); + + MockHttpServletRequest servletRequest = new MockHttpServletRequest("POST", "/generation/rules"); + HandlerExecutionChain handlerExecutionChain = + requestMappingHandlerMapping.getHandler(servletRequest); + assertThat(handlerExecutionChain).isNotNull(); + assertThat(handlerExecutionChain.getHandler()).isInstanceOf(HandlerMethod.class); + assertThat(handlerExecutionChain.getInterceptors()) + .anyMatch(HttpJwtAuthInterceptor.class::isInstance); + + var tokenClaims = jwtUtil.parseToken(token).getPayload(); + assertThat(tokenClaims.get("accountId", String.class)) + .isEqualTo("018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"); + assertThat(tokenClaims.get("globalRoles", List.class)).containsExactly("platformAdmin"); + + dsl.insertInto(GENERATION_RULE) + .set(GENERATION_RULE.TENANT_ID, 1L) + .set(GENERATION_RULE.VERSION_ID, 7L) + .set(GENERATION_RULE.NAME, "retained-denial-proof") + .set(GENERATION_RULE.SCOPE_TYPE, "ZONE_SUBTREE") + .set(GENERATION_RULE.SCOPE_ID, "12") + .set(GENERATION_RULE.VALUE, "{\"retained\":true}") + .execute(); + List> generationRulesBefore = generationRuleRows(); + assertThat(generationRulesBefore).isNotEmpty(); + HttpRequest request = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/generation/rules")) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) + .header(HttpHeaders.CONTENT_TYPE, "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + """ + {"tenantId":1,"name":"denied-rule","scopeType":"ZONE_SUBTREE","scopeId":"12","value":"{}"} + """)) + .build(); + + HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); + + assertThat(response.statusCode()).as("HTTP response body: %s", response.body()).isEqualTo(412); + assertThat(response.body()).contains("\"status\":\"ERROR\""); + assertThat(response.body()).contains("\"code\":\"FAILED_PRECONDITION\""); + assertThat(response.body()) + .contains( + "\"message\":\"Generation rule writes are unavailable without canonical Draft and Account commit authorization\""); + JsonNode responseBody = objectMapper.readTree(response.body()); + assertThat(responseBody.path("status").asText()).isEqualTo("ERROR"); + assertThat(responseBody.hasNonNull("data")).isFalse(); + assertThat(generationRuleRows()).isEqualTo(generationRulesBefore); + } + @Test @Transactional void worldEventDueQueryExcludesWeatherAndEnforcesScope() { @@ -248,6 +319,12 @@ private static void awaitLatch(CountDownLatch latch) { } } + private List> generationRuleRows() { + return dsl.selectFrom(GENERATION_RULE) + .orderBy(GENERATION_RULE.ID.asc()) + .fetch(record -> record.intoMap()); + } + private long insertRegion(long tenantId, long gameInstanceId, long fixtureLabel) { Long worldInstanceId = dsl.insertInto(WORLD_INSTANCE) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/controller/GenerationRuleControllerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/controller/GenerationRuleControllerTest.java index 6c381777af..0ec0c67368 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/controller/GenerationRuleControllerTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/controller/GenerationRuleControllerTest.java @@ -57,15 +57,62 @@ void listEnforcesTenantScopedAccess() throws Exception { } @Test - void saveRejectsCallerWithoutTenantAccess() throws Exception { + void saveRejectsTenantAdminWithoutCanonicalDraftCommitAuthorization() throws Exception { + mockMvc + .perform(validSaveRequest()) + .andExpect(status().isPreconditionFailed()) + .andExpect(jsonPath("$.status").value("ERROR")) + .andExpect(jsonPath("$.error.code").value("FAILED_PRECONDITION")) + .andExpect( + jsonPath("$.error.message") + .value( + "Generation rule writes are unavailable without canonical Draft and Account commit authorization")); + + verifyNoInteractions(generationRuleService); + } + + @Test + void saveRejectsGlobalPlatformAdminWithoutCanonicalDraftCommitAuthorization() throws Exception { + SessionContext.setContext("test-account", List.of("platformAdmin"), Map.of()); + + mockMvc + .perform(validSaveRequest()) + .andExpect(status().isPreconditionFailed()) + .andExpect(jsonPath("$.status").value("ERROR")) + .andExpect(jsonPath("$.error.code").value("FAILED_PRECONDITION")); + + verifyNoInteractions(generationRuleService); + } + + @Test + void saveRejectsDesignerAndPlayerWithoutTenantAccessBeforeDispatch() throws Exception { + for (String role : List.of("designer", "player")) { + installTenantContext(Map.of("1", List.of(role))); + + mockMvc.perform(validSaveRequest()).andExpect(status().isForbidden()); + + verifyNoInteractions(generationRuleService); + } + } + + @Test + void saveRejectsCallerWithoutTenantAccessBeforeDispatch() throws Exception { installTenantContext(Map.of("9", List.of("tenantAdmin"))); + mockMvc.perform(validSaveRequest()).andExpect(status().isForbidden()); + + verifyNoInteractions(generationRuleService); + } + + @Test + void saveKeepsMalformedBodyBindingFailureBeforeDispatch() throws Exception { mockMvc - .perform( - post("/generation/rules") - .contentType(MediaType.APPLICATION_JSON) - .content("{\"id\":7,\"tenantId\":1,\"name\":\"room\",\"value\":\"{}\"}")) - .andExpect(status().isForbidden()); + .perform(post("/generation/rules").contentType(MediaType.APPLICATION_JSON).content("{")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) + .andExpect(jsonPath("$.error.message").value("Request body is malformed")); + + verifyNoInteractions(generationRuleService); } @Test @@ -93,4 +140,11 @@ void listRejectsZeroTenantIdBeforeDispatch() throws Exception { private void installTenantContext(Map> scopedRoles) { SessionContext.setContext("test-account", List.of(), scopedRoles); } + + private org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder + validSaveRequest() { + return post("/generation/rules") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"id\":7,\"tenantId\":1,\"name\":\"room\",\"value\":\"{}\"}"); + } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java index a47957a898..512adade21 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -87,12 +88,13 @@ void setUp() { region.setId(44L); return region; }); - when(aggregateEpochRepository.save(any(WorldDesignAggregateEpoch.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); + when(aggregateEpochRepository.compareAndAdvance(any(), any(), any(), any(), any(), any())) + .thenReturn(true); when(scopeEpochRepository.findByTenantIdAndVersionIdAndScopeTypeAndScopeId( any(Long.class), any(Long.class), any(String.class), any(String.class))) .thenReturn(Optional.empty()); - when(scopeEpochRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); + when(scopeEpochRepository.compareAndAdvance(any(), any(), any(), any(), any(), any())) + .thenReturn(true); when(ledgerRepository.save(any(WorldDesignRevisionLedger.class))) .thenAnswer(invocation -> invocation.getArgument(0)); } @@ -265,6 +267,73 @@ void newAggregateWithNonZeroExpectedEpochFailsBeforeMutation() { verify(regionRepository, never()).save(any(Region.class)); } + @Test + void negativeOrOverflowingAggregateEpochFailsBeforeMutation() { + for (long expectedEpoch : new long[] {-1L, Long.MAX_VALUE}) { + IllegalArgumentException ex = + assertThrows( + IllegalArgumentException.class, + () -> service.applyMutation(regionCreateRequestWithExpectedEpoch(expectedEpoch))); + + assertEquals( + "DRAFT_WRITE_CONFLICT: expected Draft aggregate epoch cannot be advanced safely", + ex.getMessage()); + } + + verify(regionRepository, never()).save(any(Region.class)); + } + + @Test + void negativeOrOverflowingScopeEpochFailsBeforeMutation() { + for (long expectedEpoch : new long[] {-1L, Long.MAX_VALUE}) { + IllegalArgumentException ex = + assertThrows( + IllegalArgumentException.class, + () -> + service.applyMutation( + regionCreateRequestWithScope("REGION_SUBTREE", "12", expectedEpoch))); + + assertEquals( + "DRAFT_WRITE_CONFLICT: expected Draft scope epoch cannot be advanced safely", + ex.getMessage()); + } + + verify(regionRepository, never()).save(any(Region.class)); + } + + @Test + void aggregateEpochCompareAndAdvanceConflictRejectsMutation() { + when(aggregateEpochRepository.compareAndAdvance( + eq(1L), eq(7L), eq("REGION"), eq(44L), eq(0L), any())) + .thenReturn(false); + + IllegalArgumentException ex = + assertThrows( + IllegalArgumentException.class, () -> service.applyMutation(regionCreateRequest())); + + assertEquals(true, ex.getMessage().startsWith("DRAFT_WRITE_CONFLICT:")); + verify(regionRepository).save(any(Region.class)); + verify(ledgerRepository, never()).save(any(WorldDesignRevisionLedger.class)); + } + + @Test + void scopeEpochCompareAndAdvanceConflictRejectsMutation() { + when(scopeEpochRepository.compareAndAdvance( + eq(1L), eq(7L), eq("NEW_EMPTY_REGION"), eq("12"), eq(0L), any())) + .thenReturn(false); + + IllegalArgumentException ex = + assertThrows( + IllegalArgumentException.class, + () -> service.applyMutation(regionCreateRequestWithScope("NEW_EMPTY_REGION", "12"))); + + assertEquals(true, ex.getMessage().startsWith("DRAFT_WRITE_CONFLICT:")); + verify(regionRepository).save(any(Region.class)); + verify(aggregateEpochRepository) + .compareAndAdvance(eq(1L), eq(7L), eq("REGION"), eq(44L), eq(0L), any()); + verify(ledgerRepository, never()).save(any(WorldDesignRevisionLedger.class)); + } + @Test void nonDraftVersionIsRejectedBeforeMutation() { when(gameDesignClient.getVersionState(1L, 7L)) @@ -897,6 +966,11 @@ private WorldDesignMutationRequestDto regionUpdateRequestWithPolicy(String scope private WorldDesignMutationRequestDto regionCreateRequestWithScope( String scopeType, String scopeId) { + return regionCreateRequestWithScope(scopeType, scopeId, 0L); + } + + private WorldDesignMutationRequestDto regionCreateRequestWithScope( + String scopeType, String scopeId, long expectedScopeEpoch) { return new WorldDesignMutationRequestDto( 1L, 7L, @@ -908,7 +982,7 @@ private WorldDesignMutationRequestDto regionCreateRequestWithScope( 0L, scopeType, scopeId, - 0L, + expectedScopeEpoch, "REPLACE_SCOPE", new WorldDesignMutationRequestDto.RegionMutationDto( "North", "rain", 0, 123L, "ROOM_GRAPH", "{}", 1.0d), diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java index efe6e396fb..beec507cdb 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java @@ -23,7 +23,6 @@ import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldDto; import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RuntimeRoomDto; -import net.firedevops.firemud.worldmanagement.dto.WorldDesignMutationResultDto; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; import net.firedevops.firemud.worldmanagement.service.PingService; @@ -113,6 +112,54 @@ public void onCompleted() {} return ref.get(); } + private static ApplyWorldDesignMutationResponse invokeMutation( + WorldManagementGrpcService service, ApplyWorldDesignMutationRequest request) { + AtomicReference ref = new AtomicReference<>(); + service.applyWorldDesignMutation( + request, + new StreamObserver<>() { + @Override + public void onNext(ApplyWorldDesignMutationResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + return ref.get(); + } + + private static ApplyWorldDesignMutationRequest canonicalLookingMutationRequest() { + return ApplyWorldDesignMutationRequest.newBuilder() + .setTenantId("1") + .setVersionId("7") + .setCommitId("commit-1") + .setRevisionId("revision-1") + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId("44") + .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) + .build(); + } + + private static void assertWorldMutationDenied(ApplyWorldDesignMutationResponse response) { + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals( + "Canonical World Draft writes are unavailable until current Account commit authorization is verified.", + response.getError().getMessage()); + assertEquals( + WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED, response.getResult()); + assertEquals("", response.getTenantId()); + assertEquals("", response.getVersionId()); + assertEquals("", response.getAggregateId()); + assertEquals(0L, response.getDraftRevisionEpoch()); + assertEquals(0L, response.getDraftScopeRevisionEpoch()); + } + private static GetDraftDesignDigestResponse invokeDigestWithPeer( WorldManagementGrpcService service, GetDraftDesignDigestRequest request, @@ -587,21 +634,19 @@ void getDraftDesignDigestRejectsOwnerTenantMismatch() { } @Test - void applyWorldDesignMutationReturnsTypedResult() { + void applyWorldDesignMutationDeniesCanonicalWritesWithoutAccountCommitAuthorization() { PingService pingService = Mockito.mock(PingService.class); RoomService roomService = Mockito.mock(RoomService.class); WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); WorldDesignMutationService mutationService = Mockito.mock(WorldDesignMutationService.class); + WorldInstanceActivationService activationService = + Mockito.mock(WorldInstanceActivationService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); - Mockito.when(mutationService.applyMutation(Mockito.any())) - .thenReturn(new WorldDesignMutationResultDto("APPLIED", 1L, 7L, 44L, 1L, null)); - SessionContext.setContext( - "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); WorldManagementGrpcService service = new WorldManagementGrpcService( pingService, roomService, - Mockito.mock(WorldInstanceActivationService.class), + activationService, digestService, mutationService, Mockito.mock(WorldUpgradeValidationService.class), @@ -610,36 +655,22 @@ void applyWorldDesignMutationReturnsTypedResult() { new ObjectMapper(), (PublicationReadGuard) null); - AtomicReference ref = new AtomicReference<>(); - service.applyWorldDesignMutation( - ApplyWorldDesignMutationRequest.newBuilder() - .setTenantId("1") - .setVersionId("7") - .setCommitId("commit-1") - .setRevisionId("revision-1") - .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) - .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) - .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) - .setScopeId("44") - .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) - .build(), - new StreamObserver<>() { - @Override - public void onNext(ApplyWorldDesignMutationResponse value) { - ref.set(value); - } + ApplyWorldDesignMutationRequest request = canonicalLookingMutationRequest(); + SessionContext.clear(); + assertWorldMutationDenied(invokeMutation(service, request)); - @Override - public void onError(Throwable t) {} + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-design-service", "test-instance"); + assertWorldMutationDenied(invokeMutation(service, request)); - @Override - public void onCompleted() {} - }); + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-design-service", "test-instance"); + AtomicReference authenticatedPeerResponse = + new AtomicReference<>(); + runAsGameDesign(() -> authenticatedPeerResponse.set(invokeMutation(service, request))); + assertWorldMutationDenied(authenticatedPeerResponse.get()); - assertEquals( - WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_APPLIED, ref.get().getResult()); - assertEquals("44", ref.get().getAggregateId()); - assertEquals(1L, ref.get().getDraftRevisionEpoch()); + Mockito.verifyNoInteractions(mutationService, digestService, activationService); } @Test @@ -648,6 +679,8 @@ void applyWorldDesignMutationRejectsZeroVersionIdBeforeMutation() { RoomService roomService = Mockito.mock(RoomService.class); WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); WorldDesignMutationService mutationService = Mockito.mock(WorldDesignMutationService.class); + WorldInstanceActivationService activationService = + Mockito.mock(WorldInstanceActivationService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); SessionContext.setContext( "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); @@ -655,7 +688,7 @@ void applyWorldDesignMutationRejectsZeroVersionIdBeforeMutation() { new WorldManagementGrpcService( pingService, roomService, - Mockito.mock(WorldInstanceActivationService.class), + activationService, digestService, mutationService, Mockito.mock(WorldUpgradeValidationService.class), @@ -664,35 +697,23 @@ void applyWorldDesignMutationRejectsZeroVersionIdBeforeMutation() { new ObjectMapper(), (PublicationReadGuard) null); - AtomicReference ref = new AtomicReference<>(); - service.applyWorldDesignMutation( - ApplyWorldDesignMutationRequest.newBuilder() - .setTenantId("1") - .setVersionId("0") - .setCommitId("commit-1") - .setRevisionId("revision-1") - .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) - .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) - .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) - .setScopeId("44") - .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) - .build(), - new StreamObserver<>() { - @Override - public void onNext(ApplyWorldDesignMutationResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("versionId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(mutationService); + ApplyWorldDesignMutationResponse response = + invokeMutation( + service, + ApplyWorldDesignMutationRequest.newBuilder() + .setTenantId("1") + .setVersionId("0") + .setCommitId("commit-1") + .setRevisionId("revision-1") + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId("44") + .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) + .build()); + + assertWorldMutationDenied(response); + Mockito.verifyNoInteractions(mutationService, digestService, activationService); } @Test diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java new file mode 100644 index 0000000000..e697fdf577 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java @@ -0,0 +1,489 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +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.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldAuthoredVersionIdentityServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID SOURCE_REGISTRATION = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID INTAKE_OPERATION = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID READ_REQUEST = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID VERSION = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID OTHER_VERSION = UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final String WORLD = "violet-wilds"; + private static final long GAME_DESIGN_VERSION_ID = 42L; + + private final AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + private final WorldAuthoredVersionIdentityRepository repository = + mock(WorldAuthoredVersionIdentityRepository.class); + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository = + mock(WorldAuthoredSourceIntakeRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final WorldAuthoredVersionIdentityService service = + new WorldAuthoredVersionIdentityService( + versionStateClient, repository, sourceIntakeRepository, transactionManager, NAMESPACE); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresExactSameNamespaceGameDesignPeerBeforeAnyOwnerOrRemoteAccess() { + assertThatThrownBy(() -> withoutPeer(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-design-service"), + () -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.associate( + "other", + TENANT, + WORLD, + SOURCE_OPERATION, + source().evidenceDigest(), + VERSION, + GAME_DESIGN_VERSION_ID, + READ_REQUEST))) + .isInstanceOf(SecurityException.class); + verifyNoInteractions(sourceIntakeRepository, repository, versionStateClient); + } + + @Test + void exactRetryReturnsOriginalReceiptWithoutCallingGameDesignAgain() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence originalState = + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 7L); + WorldAuthoredVersionIdentityReceipt original = identityReceipt(intake, originalState, 91L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.of(original)); + + WorldAuthoredVersionIdentityReceipt result = + withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID)); + + assertThat(result).isEqualTo(original); + verifyNoInteractions(versionStateClient); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + verify(repository, never()) + .readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID); + verify(sourceIntakeRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + } + + @Test + void changedCanonicalUuidForAnAlreadyMappedGameDesignSelectorDeniesBeforeRemoteRead() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence oldState = + versionState( + source, + READ_REQUEST, + OTHER_VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 7L); + WorldAuthoredVersionIdentityReceipt existing = identityReceipt(intake, oldState, 91L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty()); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.of(existing)); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("selector conflicts"); + + verifyNoInteractions(versionStateClient); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void retainsExactSourceQualifiedDraftIdentityInItsOwnReadCommittedTransaction() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence current = + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 3L); + WorldAuthoredVersionIdentityReceipt accepted = identityReceipt(intake, current, 101L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty(), Optional.of(accepted)); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())).thenReturn(current); + when(repository.acceptFresh(intake, current)).thenReturn(accepted); + + WorldAuthoredVersionIdentityReceipt result = + withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID)); + + assertThat(result).isEqualTo(accepted); + assertThat(result.localVersionKey()).isEqualTo(101L); + assertThat(result.canonicalVersionId()).isEqualTo(VERSION); + assertThat(result.gameDesignVersionId()).isEqualTo(GAME_DESIGN_VERSION_ID); + assertThat(result.sourceIntakeReceipt()).isEqualTo(intake); + assertThat(result.versionStateEvidence()).isEqualTo(current); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + + InOrder order = inOrder(sourceIntakeRepository, repository, versionStateClient); + order + .verify(sourceIntakeRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + order.verify(repository).readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION); + order + .verify(repository) + .readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID); + order.verify(versionStateClient).read(current.request()); + order.verify(repository).acceptFresh(intake, current); + order.verify(repository).readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION); + order + .verify(sourceIntakeRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + } + + @Test + void rejectsSubstitutedCanonicalVersionAndUnsupportedLifecycleBeforeMutation() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty()); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())) + .thenReturn( + versionState( + source, + READ_REQUEST, + OTHER_VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 5L)); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("expected UUID"); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + + when(versionStateClient.read(any())) + .thenReturn( + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_RETIRED, + 6L)); + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("must be DRAFT, PUBLISHED, or ACTIVE"); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void reconcilesLostCommitAcknowledgmentFromTheOriginalStoredReceipt() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence current = + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 8L); + WorldAuthoredVersionIdentityReceipt accepted = identityReceipt(intake, current, 102L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty(), Optional.of(accepted)); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())).thenReturn(current); + when(repository.acceptFresh(intake, current)).thenReturn(accepted); + transactionManager.loseCommitAcknowledgment = true; + + WorldAuthoredVersionIdentityReceipt result = + withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID)); + + assertThat(result).isEqualTo(accepted); + assertThat(transactionManager.commitFailureThrown).isTrue(); + verify(repository, times(1)).acceptFresh(intake, current); + } + + @Test + void missingExactFreshIntakeCannotCallGameDesignOrAllocateAnIdentity() { + AuthoredWorldSourceEvidence source = source(); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("exact committed fresh source intake"); + + verifyNoInteractions(repository, versionStateClient); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void substitutedSourceIntakeCannotCallGameDesignOrAllocateAnIdentity() { + AuthoredWorldSourceEvidence requested = source(); + AuthoredWorldSourceEvidence substituted = + source("amber-coast", UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, requested.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt(substituted))); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("exact fresh NEW_GAME_ROW source intake"); + + verifyNoInteractions(repository, versionStateClient); + assertThat(transactionManager.startedWith).isNull(); + } + + private WorldAuthoredVersionIdentityReceipt associate(UUID canonicalVersionId, long versionId) { + AuthoredWorldSourceEvidence source = source(); + return service.associate( + NAMESPACE, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + canonicalVersionId, + versionId, + READ_REQUEST); + } + + private static WorldAuthoredVersionIdentityReceipt identityReceipt( + WorldAuthoredSourceIntakeReceipt intake, + AuthoredWorldVersionStateEvidence evidence, + long localVersionKey) { + return new WorldAuthoredVersionIdentityReceipt( + 1, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + localVersionKey, + intake, + evidence); + } + + private static AuthoredWorldVersionStateEvidence versionState( + AuthoredWorldSourceEvidence source, + UUID readRequestId, + UUID canonicalVersionId, + long gameDesignVersionId, + VersionLifecycleState state, + long epoch) { + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + readRequestId, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + gameDesignVersionId); + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, state, epoch); + } + + private static WorldAuthoredSourceIntakeReceipt sourceReceipt( + AuthoredWorldSourceEvidence source) { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest( + source.targetNamespace(), INTAKE_REQUEST, source); + return new WorldAuthoredSourceIntakeReceipt( + 1, + source.targetNamespace(), + INTAKE_REQUEST, + INTAKE_OPERATION, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + source.targetNamespace(), INTAKE_OPERATION, requestDigest, source, 90_041L), + 90_041L, + source); + } + + private static AuthoredWorldSourceEvidence source() { + return source(WORLD, SOURCE_OPERATION); + } + + private static AuthoredWorldSourceEvidence source(String worldSlug, UUID sourceOperationId) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, SOURCE_REGISTRATION, TENANT, "north-star", worldSlug, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION, + sourceOperationId, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION, + sourceOperationId, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static T withGameDesign(Supplier action) { + return withPeer(peer(NAMESPACE, "game-design-service"), action); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static final class RecordingTransactionManager + implements org.springframework.transaction.PlatformTransactionManager { + private TransactionDefinition startedWith; + private boolean loseCommitAcknowledgment; + private boolean commitFailureThrown; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + if (loseCommitAcknowledgment) { + loseCommitAcknowledgment = false; + commitFailureThrown = true; + throw new IllegalStateException("simulated lost commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java new file mode 100644 index 0000000000..599d93df49 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java @@ -0,0 +1,896 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +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.VersionLifecycleState; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCompleteLaunchBindingServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID INTAKE_OPERATION = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID BINDING_OPERATION = + UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final UUID VERSION = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID OTHER_CANONICAL_VERSION = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID CURRENT_READ_ID = + UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final UUID ADVANCED_READ_ID = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID OTHER_READ_ID = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID OTHER_SOURCE_OPERATION = + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID OTHER_REGISTRATION_REQUEST = + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final String WORLD = "violet-wilds"; + private static final String CONTROL_PLANE_REQUEST = "world-launch-request-41"; + + private final AuthoredWorldLaunchDescriptorClient client = + mock(AuthoredWorldLaunchDescriptorClient.class); + private final AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + private final WorldCompleteLaunchBindingRepository repository = + mock(WorldCompleteLaunchBindingRepository.class); + private final WorldAuthoredSourceIntakeRepository sourceRepository = + mock(WorldAuthoredSourceIntakeRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final WorldCompleteLaunchBindingService service = + new WorldCompleteLaunchBindingService( + client, repository, sourceRepository, transactionManager, NAMESPACE, versionStateClient); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresExactSameNamespaceGameSessionPeerBeforeOwnerOrGameDesignAccess() { + GetRequest request = request(evidence(source())); + + assertThatThrownBy(() -> withoutPeer(() -> service.bind(request))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> withPeer(peer(NAMESPACE, "game-design-service"), () -> service.bind(request))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> withPeer(peer("other", "game-session-service"), () -> service.bind(request))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> withoutPeer(() -> service.readCurrentVersionState(request, CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> service.readCurrentVersionState(request, CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-session-service"), + () -> service.readCurrentVersionState(request, CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + AuthoredWorldLaunchDescriptorEvidence.Request original = request.expectedRequest(); + AuthoredWorldLaunchDescriptorEvidence.Request wrongNamespace = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "other", + original.controlPlaneRequestId(), + original.canonicalTenantId(), + original.worldSlug(), + original.authoredWorldSourceOperationId(), + original.authoredWorldSourceEvidenceDigest(), + original.gameTemplateId(), + original.requestedScriptPatchVersionPresent(), + original.requestedScriptPatchVersion(), + original.sourceVersionIdPresent(), + original.sourceVersionId(), + original.targetVersionIdPresent(), + original.targetVersionId(), + original.requestedRuntimeFlagsJsonPresent(), + original.requestedRuntimeFlagsJson()); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.bind( + new GetRequest(UUID.randomUUID(), wrongNamespace, digest('a'))))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + new GetRequest(UUID.randomUUID(), wrongNamespace, digest('a')), + CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + verifyNoInteractions(client, versionStateClient, repository, sourceRepository); + } + + @Test + void retainsCompletePairThenIndependentlyReadsBackTheSameOwnerReceipt() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + GetRequest request = request(evidence); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(stored)); + when(client.getComplete(any())).thenReturn(evidence); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.acceptFresh(NAMESPACE, sourceReceipt, evidence)).thenReturn(receipt); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + + WorldCompleteLaunchBindingReceipt result = withGameSession(() -> service.bind(request)); + + assertThat(result).isEqualTo(receipt); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + verify(client).getComplete(any()); + verify(repository).acceptFresh(NAMESPACE, sourceReceipt, evidence); + verify(repository).toReceipt(stored, sourceReceipt); + } + + @Test + void exactRetryReadsTheStoredPairBeforeLocalSourceAndDoesNotCallGameDesign() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + GetRequest request = request(evidence); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.of(stored)); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + + WorldCompleteLaunchBindingReceipt result = withGameSession(() -> service.bind(request)); + + assertThat(result).isEqualTo(receipt); + verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + verify(client, never()).getComplete(any()); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedExpectedResultConflictsBeforeSourceLookupOrGameDesign() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.of(stored)); + GetRequest changed = + new GetRequest(UUID.randomUUID(), evidence.descriptor().request(), digest('b')); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(changed))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + verifyNoInteractions(client, sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void missingOrSwappedCompletePairCannotReachWorldPersistence() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence expectedEvidence = evidence(source); + CompleteLaunchBindingEvidence otherEvidence = + evidence(source, "another-world-launch-request", 42L); + assertThatThrownBy( + () -> + new CompleteLaunchBindingEvidence( + expectedEvidence.descriptor(), otherEvidence.releaseAttestation())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new CompleteLaunchBindingEvidence(null, null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> new CompleteLaunchBindingEvidence(expectedEvidence.descriptor(), null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> new CompleteLaunchBindingEvidence(null, expectedEvidence.releaseAttestation())) + .isInstanceOf(NullPointerException.class); + + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.empty()); + when(client.getComplete(any())).thenReturn(null); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(request(expectedEvidence)))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("no complete launch binding"); + verify(repository, never()).acceptFresh(any(), any(), any()); + verifyNoInteractions(sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void refusesAmbientTransactionBeforeReadingOrCallingGameDesign() { + CompleteLaunchBindingEvidence evidence = evidence(source()); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(request(evidence)))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(evidence), CURRENT_READ_ID))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client, versionStateClient, repository, sourceRepository); + } + + @Test + void recoversACommitAcknowledgmentLossByReadingTheSameOwnerOperation() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + GetRequest request = request(evidence); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + AtomicReference committed = + new AtomicReference<>(); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenAnswer( + invocation -> { + WorldCompleteLaunchBindingRepository.StoredBinding value = committed.get(); + return value == null ? Optional.empty() : Optional.of(value); + }); + when(client.getComplete(any())).thenReturn(evidence); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.acceptFresh(NAMESPACE, sourceReceipt, evidence)) + .thenAnswer( + invocation -> { + committed.set(stored); + return receipt; + }); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + transactionManager.loseCommitAcknowledgment = true; + + WorldCompleteLaunchBindingReceipt recovered = withGameSession(() -> service.bind(request)); + + assertThat(recovered.operationId()).isEqualTo(receipt.operationId()); + assertThat(recovered.evidence()).isEqualTo(evidence); + verify(client).getComplete(any()); + verify(repository).acceptFresh(NAMESPACE, sourceReceipt, evidence); + assertThat(transactionManager.commitFailureThrown).isTrue(); + } + + @Test + void readsPublishedCurrentVersionFromTheCommittedPairAndDescriptorVersionId() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + WorldCompleteLaunchBindingReceipt original = stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence current = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(current); + + AuthoredWorldVersionStateEvidence result = + withGameSession(() -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID)); + + assertThat(result).isEqualTo(current); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(AuthoredWorldVersionStateEvidence.Request.class); + InOrder readOrder = inOrder(repository, sourceRepository, versionStateClient); + readOrder.verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + readOrder + .verify(sourceRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + readOrder.verify(repository).toReceipt(any(), any()); + readOrder.verify(versionStateClient).read(requestCaptor.capture()); + AuthoredWorldVersionStateEvidence.Request currentRequest = requestCaptor.getValue(); + assertThat(currentRequest.targetNamespace()).isEqualTo(original.targetNamespace()); + assertThat(currentRequest.canonicalTenantId()).isEqualTo(original.canonicalTenantId()); + assertThat(currentRequest.worldSlug()).isEqualTo(original.worldSlug()); + assertThat(currentRequest.sourceOperationId()).isEqualTo(SOURCE_OPERATION); + assertThat(currentRequest.expectedSourceEvidenceDigest()).isEqualTo(source.evidenceDigest()); + assertThat(currentRequest.versionId()).isEqualTo(binding.descriptor().versionId()); + assertThat(currentRequest.versionId()) + .isNotEqualTo(original.sourceIntakeReceipt().localTenantKey()); + assertThat(currentRequest.readRequestId()).isEqualTo(CURRENT_READ_ID); + assertThat(original.evidence()).isEqualTo(binding); + assertThat(original.operationId()).isEqualTo(BINDING_OPERATION); + assertThat(transactionManager.startedWith).isNull(); + verify(client, never()).getComplete(any()); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void acceptsActiveCurrentVersionAtTheDescriptorEpoch() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence current = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(current); + + AuthoredWorldVersionStateEvidence result = + withGameSession(() -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID)); + + assertThat(result).isEqualTo(current); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void repeatedCurrentReadsObserveVersionAdvanceAndRejectTheStaleDescriptorPair() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + WorldCompleteLaunchBindingReceipt original = stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence first = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence advanced = + currentVersionState( + source, + ADVANCED_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + binding.descriptor().versionStateEpoch() + 1); + when(versionStateClient.read(any())).thenReturn(first, advanced); + + AuthoredWorldVersionStateEvidence firstRead = + withGameSession(() -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID)); + assertThat(firstRead).isEqualTo(first); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), ADVANCED_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("epoch differs"); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(AuthoredWorldVersionStateEvidence.Request.class); + verify(versionStateClient, times(2)).read(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()) + .extracting(AuthoredWorldVersionStateEvidence.Request::readRequestId) + .containsExactly(CURRENT_READ_ID, ADVANCED_READ_ID); + assertThat(original.evidence()).isEqualTo(binding); + assertThat(original.operationId()).isEqualTo(BINDING_OPERATION); + verify(client, never()).getComplete(any()); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsCurrentEvidenceForAnotherAuthoredSource() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + AuthoredWorldSourceEvidence otherSource = + source("other-world", OTHER_REGISTRATION_REQUEST, OTHER_SOURCE_OPERATION); + AuthoredWorldVersionStateEvidence swappedSource = + currentVersionState( + otherSource, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(swappedSource); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsAChangedVersionSelectorInCurrentOwnerEvidence() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence swappedSelector = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId() + 1, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(swappedSelector); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsCurrentEvidenceWithCanonicalVersionUuidDifferentFromReleaseAttestation() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + UUID committedCanonicalVersionId = binding.releaseAttestation().canonicalVersionId(); + AuthoredWorldVersionStateEvidence expected = + currentVersionState( + source, + committedCanonicalVersionId, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence substituted = + currentVersionState( + source, + OTHER_CANONICAL_VERSION, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + assertThat(substituted.request()).isEqualTo(expected.request()); + assertThat(substituted.sourceEvidence()).isEqualTo(expected.sourceEvidence()); + assertThat(substituted.versionState()).isEqualTo(expected.versionState()); + assertThat(substituted.versionStateEpoch()).isEqualTo(expected.versionStateEpoch()); + assertThat(substituted.canonicalVersionId()).isNotEqualTo(committedCanonicalVersionId); + when(versionStateClient.read(any())).thenReturn(substituted); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("canonical version UUID differs"); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void changedBindingRequestIsRejectedBeforeReadingCurrentOwnerEvidence() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + GetRequest substituted = + new GetRequest(UUID.randomUUID(), binding.descriptor().request(), digest('b')); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(substituted, CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + verifyNoInteractions(versionStateClient); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void requiresAnAlreadyCommittedPairWithoutRegisteringOne() { + CompleteLaunchBindingEvidence binding = evidence(source()); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.empty()); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("requires a committed launch binding"); + verifyNoInteractions(client, versionStateClient, sourceRepository); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void deniesDraftRetiredAndUnavailableCurrentVersionEvidenceWithoutChangingThePair() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + WorldCompleteLaunchBindingReceipt original = stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence draft = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(draft); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("not PUBLISHED or ACTIVE"); + + AuthoredWorldVersionStateEvidence retired = + currentVersionState( + source, + OTHER_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_RETIRED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(retired); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), OTHER_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("not PUBLISHED or ACTIVE"); + + when(versionStateClient.read(any())) + .thenThrow(new IllegalStateException("Game Design is unavailable")); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), ADVANCED_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("unavailable or invalid"); + assertThat(original.evidence()).isEqualTo(binding); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsReadCorrelationIdsReusedFromSourceOrRegistration() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), SOURCE_OPERATION))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("separate from source and registration IDs"); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + request(binding), source.registrationRequestId()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("separate from source and registration IDs"); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + request(binding), request(binding).requestId()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("separate from source and registration IDs"); + verifyNoInteractions(versionStateClient); + } + + private WorldCompleteLaunchBindingReceipt stubCommittedBinding( + AuthoredWorldSourceEvidence source, CompleteLaunchBindingEvidence evidence) { + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.of(stored)); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + return receipt; + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID readId, + long versionId, + VersionLifecycleState state, + long epoch) { + return currentVersionState(source, VERSION, readId, versionId, state, epoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + UUID readId, + long versionId, + VersionLifecycleState state, + long epoch) { + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + source.targetNamespace(), + readId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + versionId); + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, state, epoch); + } + + private static WorldCompleteLaunchBindingRepository.StoredBinding stored( + WorldCompleteLaunchBindingReceipt receipt) { + AuthoredWorldLaunchDescriptorEvidence descriptor = receipt.descriptor(); + return new WorldCompleteLaunchBindingRepository.StoredBinding( + receipt.operationId(), + receipt.targetNamespace(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.controlPlaneRequestId(), + receipt.sourceIntakeReceipt().operationId(), + receipt.sourceIntakeReceipt().intakeRequestId(), + receipt.sourceIntakeReceipt().localTenantKey(), + receipt.sourceIntakeReceipt().sourceOperationId(), + receipt.sourceIntakeReceipt().sourceEvidenceDigest(), + receipt.sourceIntakeReceipt().receiptDigest(), + descriptor.requestDigest(), + descriptor.resultDigest(), + receipt.evidence().releaseAttestation().evidenceDigest(), + receipt.evidence()); + } + + private static WorldCompleteLaunchBindingReceipt bindingReceipt( + WorldAuthoredSourceIntakeReceipt sourceReceipt, CompleteLaunchBindingEvidence evidence) { + return new WorldCompleteLaunchBindingReceipt( + 1, + BINDING_OPERATION, + NAMESPACE, + TENANT, + WORLD, + CONTROL_PLANE_REQUEST, + sourceReceipt, + evidence); + } + + private static GetRequest request(CompleteLaunchBindingEvidence evidence) { + return new GetRequest( + UUID.fromString("66666666-6666-4666-8666-666666666666"), + evidence.descriptor().request(), + evidence.descriptor().resultDigest()); + } + + private static CompleteLaunchBindingEvidence evidence(AuthoredWorldSourceEvidence source) { + return evidence(source, CONTROL_PLANE_REQUEST, 41L); + } + + private static CompleteLaunchBindingEvidence evidence( + AuthoredWorldSourceEvidence source, String controlPlaneRequestId, long gameTemplateId) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "launch-descriptor-" + gameTemplateId, + 42L, + false, + null, + "{}", + "generation-config-41", + 7L, + 51L, + "release-bundle-51", + false, + null); + String commitId = "commit-41"; + List participants = + List.of( + participant("WORLD_MANAGEMENT", 2, "a", false), + participant("ENTITY_MANAGEMENT", 2, "b", false), + participant("GAME_LOGIC", 1, "c", true), + participant("AUTOMATION_SCRIPTING", 5, "d", false), + participant("GAME_DESIGN_CONTROL_PLANE", 1, "e", false)); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT, + VERSION, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:owner:launch-41", + commitId, + participants, + digest('f'), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } + + private static AuthoredWorldReleaseAttestationEvidence.Participant participant( + String owner, int schema, String contentHex, boolean hasAbilityDigest) { + return new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "42", + false, + null, + "commit-41", + contentHex.repeat(64), + schema, + hasAbilityDigest, + hasAbilityDigest ? digest('c') : null); + } + + private static WorldAuthoredSourceIntakeReceipt sourceReceipt( + AuthoredWorldSourceEvidence source) { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + return new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + INTAKE_OPERATION, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, INTAKE_OPERATION, requestDigest, source, 90_041L), + 90_041L, + source); + } + + private static AuthoredWorldSourceEvidence source() { + return source(WORLD, UUID.fromString("11111111-1111-4111-8111-111111111111"), SOURCE_OPERATION); + } + + private static AuthoredWorldSourceEvidence source( + String worldSlug, UUID registrationRequest, UUID sourceOperation) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequest, TENANT, "north-star", worldSlug, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequest, + sourceOperation, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequest, + sourceOperation, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static T withGameSession(Supplier action) { + return withPeer(peer(NAMESPACE, "game-session-service"), action); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static final class RecordingTransactionManager + implements org.springframework.transaction.PlatformTransactionManager { + private TransactionDefinition startedWith; + private boolean loseCommitAcknowledgment; + private boolean commitFailureThrown; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + if (loseCommitAcknowledgment) { + loseCommitAcknowledgment = false; + commitFailureThrown = true; + throw new IllegalStateException("simulated lost commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +}