diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7a5a265080..360cdab1b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2125,6 +2125,135 @@ jobs: if-no-files-found: error retention-days: 7 + - name: Capture World guarded UUID topology PostgreSQL XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-guarded-uuid-topology-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldDraftTopologyCommitPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Verify World guarded UUID topology PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#allSixFamiliesAllocateTypedUuidRowsAndPreserveExactInputWithDefaults()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#snakeCaseAndNumericEnumsStoreDefaultsAndRetainOriginalRawBindingAndRetry()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#alteredTrustedProjectionSemanticsRollBackAgainstOriginalParsedPlan()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#lostAckAndIndependentFrozenReadbackReturnOriginalExactEvidence()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#completeReplayRejectsChangedBasePayloadOrderAffectedAndSource()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#lateFailureRollsBackAllFamiliesMappingsEpochsAndHistory()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#exactConcurrentFirstClaimReturnsOneOriginalResult()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#conflictingFirstClaimsCannotRemapPreviouslyAllocatedRows()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#freezeFirstDeniesAndWriterFirstSerializesFreezeUntilAtomicCommit()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#ordinaryWritesMappedMovesEpochTamperAndTruncateStayDenied()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#staleOrWrongInsertManifestCannotAuthorizeOrdinaryFreshRows()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#retainedRowsArePreservedUnmappedAndDenyFreshContent()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#deniedPermissionAndCallerTransactionCannotClaimOrReadOwnerStorage()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#v29ToV30PreservesNumericRowsSourceEpochsAndOriginalRegionHistory()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPostgresIntegrationTest#immutableHistoryAndEveryStoredPayloadAreVerifiedOnIndependentReadback()' \ + world-management-service + + - name: Capture World canonical instance association PostgreSQL XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-canonical-instance-association-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldCanonicalInstanceAssociationPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Verify World canonical instance association PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationPostgresIntegrationTest#retainsFullCanonicalAssociationAndReadsItAfterTheOwnerCommit()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationPostgresIntegrationTest#exactRetryReusesOriginalAssociationAfterReadMetadataChangeWithoutLifecycleMutation()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationPostgresIntegrationTest#rejectsChangedRequestEchoDescriptorAttestationAndPlayableScopeWithoutMutation()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationPostgresIntegrationTest#rejectsMissingPublicProductionAndPrivatePlaytestClassificationBeforeMutation()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationPostgresIntegrationTest#rejectsStructurallyValidPlanFromAnotherFrozenCaptureBeforeAllocation()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationPostgresIntegrationTest#rejectsDifferentBindingTenantVersionAndPrivateWorldRowWithoutMutation()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationPostgresIntegrationTest#deniesLegacyNumericRowAndRejectsUpdatingItToCanonicalIdentity()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationPostgresIntegrationTest#rollsBackCompletePreparationWhenHeldCommitAuthorityIsLostBeforeCommit()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationPostgresIntegrationTest#concurrentExactPreparationsForTheSameCanonicalGameInstanceRetainOneOwnerResult()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationPostgresIntegrationTest#forwardV32MigrationPreservesLegacyRowsWithoutInventingCanonicalMapping()' \ + world-management-service + + - name: Capture World canonical preparation guard PostgreSQL XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-canonical-preparation-guard-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldCanonicalInstancePreparationPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Verify World canonical preparation guard PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationPostgresIntegrationTest#v35PreservesReservedTenantDenialAndDoesNotExposePrepareFunctionToPublic()' \ + world-management-service + + - name: Capture World legacy preparation PostgreSQL XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-legacy-preparation-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldLifecyclePreparationPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Verify World legacy preparation PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.WorldLifecyclePreparationPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldLifecyclePreparationPostgresIntegrationTest#materializesEverySelectedLegacyRowAndExactRetryAddsNoRows()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldLifecyclePreparationPostgresIntegrationTest#rejectsSelectedRoomWhoseZoneBelongsToAnotherVersionBeforeRuntimeWrites()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldLifecyclePreparationPostgresIntegrationTest#rejectsSelectedExitWhoseEndpointBelongsToAnotherVersionBeforeRuntimeWrites()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldLifecyclePreparationPostgresIntegrationTest#lateExitPersistenceFailureRollsBackWorldAndAllEarlierRuntimeRows()' \ + world-management-service + + - name: Capture World canonical frozen topology PostgreSQL XML + if: ${{ always() && matrix.module == 'world-management-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: world-canonical-frozen-topology-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/world-management-service/build/test-results/integrationTest/TEST-*WorldCanonicalFrozenTopologyPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Verify World canonical frozen topology PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'world-management-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#capturesActualSixFamilyGraphAndOriginalFullInputWithExactRetry()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#changedCompleteBindingOrAnyFreezeCheckpointFieldCannotReplayCapture()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#historicalReadAndExactRetryAfterEveryTerminalPhaseUseOnlyOriginalJournal()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#noNewCaptureAfterTerminalAndAbsentJournalRemainsUnknown()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#captureRejectsActualRowTamperingAndMismatchedCurrentFenceBeforeJournalInsert()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#frozenCheckpointWithoutCommittedCompleteStorageCannotCreateCapture()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#v31UpgradePreservesExistingV30SourceRowsMappingsResultsAndFrozenCheckpoint()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#immutableJournalDeniesWritesAndHistoricalReadRejectsEveryTamperedField()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#recomputedGraphChecksumCannotHideTypedEndpointOrCanonicalEntityTampering()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#twoConcurrentCapturesReturnOneOriginalImmutableResult()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#canonicalSpawnSqlMappingIsLosslessAndProducesSchema3DigestWithoutWriteBypass()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#freshSchema2CaptureIsDeniedByApplicationAndDatabase()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#newSchema3CaptureRejectsChangedContentDigestAndEveryReturnedScopeField()' \ + --require-case 'net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyPostgresIntegrationTest#v32PreservesOriginalSchema2FrozenJournalAndExactHistoricalRetries()' \ + world-management-service + - name: Verify Account authored-draft publication PostgreSQL proof if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | @@ -2202,6 +2331,10 @@ jobs: --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#sourceQualifiedStagingRejectsChangedIntakeEvidenceBeforeOwnerCreation()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#sourceQualifiedStagingRejectsFrozenOwnerBeforeReadingAnInvalidPriorGraph()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#sourceQualifiedStagingRejectsCrossVersionParentAndLateInvalidRevisionWithoutAnyApply()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#retainedNumericSpawnSqlMappingAndPrimaryKeyDigestOrderRemainExact()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#newSchema2NumericSnapshotIsRejectedBeforeContentOrRevisionReads()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#mismatchedReturnedPrivateVersionDigestCannotCreateSnapshot()' \ + --require-case 'net.firedevops.firemud.worldmanagement.WorldAuthoredGraphSnapshotPostgresIntegrationTest#v32PreservesOriginalSchema2SnapshotBytesAndExactRetry()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#rollbackAndCommittedExactReadbackRetainOneImmutableAttempt()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#schemaZeroAttemptAtResolvedLocalKeyCannotBePromotedByNumericCoincidence()' \ --require-case 'net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest#sameGameDesignSelectorUsesDistinctWorldLocalVersionRowsAcrossIntakes()' \ @@ -2299,6 +2432,11 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#historicalReadbackPreservesMixedEventsWhileReturningCurrentSourceAndResetRetryStaysSuperseded()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#invalidHistoricalSelectorsFailWithoutChangingAnyAccountSourceEvidence()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#historicalReaderHoldsAccountFenceThroughSelectedAndCurrentSourceReadback()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#revokeOrderWaitsForBothExactAbortsBeforeOneLogoutAdvanceAndNeverAdmitsDelayedCommit()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#commitOrderWaitsForBothExactOutcomesIncludingMixedFailureBeforeLogoutAdvance()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#pendingRetryKeepsOriginalCaptureAndConflictsOnlyOnChangedCallerBindings()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#lateDatabaseFailureAfterReceiptEventAndBothJournalTransitionsRollsBackLogoutOnly()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#v59ToV60PreservesImmutableLogoutResetSourceOutboxAndFenceHistoryWithoutBackfill()' \ account-service - name: Upload Account logout-all source PostgreSQL proof results @@ -2310,6 +2448,30 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Capture Account pending-reset source PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-pending-reset-source-postgresql-proof-${{ github.sha }}-${{ github.run_attempt }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountPasswordResetDraftSourceChangePostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Verify Account pending-reset source PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountPasswordResetDraftSourceChangePostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountPasswordResetDraftSourceChangePostgresIntegrationTest#liveWaitingRetainsExactEnvelopeAndSourceAcrossExactRetryWithoutAccountMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountPasswordResetDraftSourceChangePostgresIntegrationTest#changedRequestAccountTokenBindingAndRemintAreRejectedWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountPasswordResetDraftSourceChangePostgresIntegrationTest#deferredGuardRejectsLiveWaitingWithoutEnvelopeAtTransactionCommit()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountPasswordResetDraftSourceChangePostgresIntegrationTest#commitAndRevokeOrderingRequireTheirExactDefinitiveOwnerOutcomesBeforeSourceAbort()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountPasswordResetDraftSourceChangePostgresIntegrationTest#expiryErasesSecretButDoesNotSettleOrReleaseUnresolvedSourceParticipation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountPasswordResetDraftSourceChangePostgresIntegrationTest#lateRollbackRestoresBothPendingResetJournalAndV57SourceFence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountPasswordResetDraftSourceChangePostgresIntegrationTest#sourceAbortedIsImmutableNoMutationTerminalDistinctFromSourceCommit()' \ + account-service + - name: Verify Account generation projection PostgreSQL and Redis proof cases if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | @@ -2410,7 +2572,7 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#sameRequestUuidAcrossExactIssuersHasDistinctPersistedSourceChangeIdentities()' \ --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#failedIssuerAdvanceRetainsOriginalPendingCaptureForExactRetry()' \ --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#issuerPendingCaptureRetainsIndependentCountersCheckpointAndExactPositiveEventBytes()' \ - --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#v59PreservesV58SourceHistoryAndExactKeysAndSupportsFullMultibyteIssuerParticipation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#v59PreservesV58HistoryAndExactKeysBeforeV61ProducerInteractionsWithFullMultibyteIssuer()' \ account-service - name: Verify Account tenant Draft source ordering PostgreSQL proof cases diff --git a/design/architecture/infrastructure/environment-and-secrets-overview.md b/design/architecture/infrastructure/environment-and-secrets-overview.md index 46df488036..4309cab44f 100644 --- a/design/architecture/infrastructure/environment-and-secrets-overview.md +++ b/design/architecture/infrastructure/environment-and-secrets-overview.md @@ -210,7 +210,7 @@ Each credential record must point to content-addressed output generated by the a The pre-release authority is a dedicated authenticated handoff store/API owned by the environment/secrets provisioning, rotation, or rebinding controller. Its publisher uses an identity scoped to one environment’s compliance path and content-addressed evidence. Before a recovery or release transition, the owner supplies one complete immutable handoff containing the target environment, applicable event kind and identity, exact credential-class keys, evidence references and digests, selected freshness field/value and previous field/value, retained material-lineage identity when applicable, exact target binding when applicable, and canonical parent-record digest. Recovery handoffs use the recovery controller's existing canonical operation identity: `operationId` for the general recovery workflow, or the branch-specific `restoreOperationId` for the ADR 0155 handoff below. That identity binds only the matching recovery event and is absent from ordinary release, promotion, and other transition handoffs. Ordinary release and transition identity uses the existing event-scoped tuple `{deploymentRef, deploymentEventId, trafficOpenEvent}` from the preflight contract. A production promotion additionally retains the existing promotion lineage `{stagingOverlayCommitSha, stagingDeploymentEventId, productionOverlayRef}`; these canonical identifiers are not replaced by a fabricated generic release or promotion operation ID. A rebinding handoff also carries the exact new target binding. The handoff publisher validates and atomically publishes that exact tuple; a retry is allowed only when every field and digest matches, while a partial, conflicting, or ambiguous owner, publisher, or dereferenced-evidence result fails closed. The owner handoff and dereferenced evidence are the sole pre-release authority. A separate authenticated Git exporter projects the finalized record for retention and reporting; Git authorship, branch protection, commit timestamps, file paths, and process exit codes are not publisher authority, and the Git projection is never read back to authorize the same recovery or release. -The Account response-envelope ring uses this same authenticated, content-addressed environment/secrets channel with a distinct `account-response-envelope-ring-materialization-v1` receipt, not a `jwt-signing-keys-jwks` credential record or JWT evidence shape. The typed receipt binds the exact protected source generation and predecessor, source manifest digest, environment and namespace, server-authenticated sole materializer identity, canonical Secret name, and the Secret UID and resourceVersion obtained by post-write readback. It carries only non-secret source and resource metadata; its `immutableArtifactId` is the canonical SHA-256 digest with that field omitted from the preimage. The environment/secrets owner must publish and authenticate the exact typed receipt and reject a missing, conflicting, wrong-writer, wrong-generation, or wrong-Secret result. A local materializer return value, checked-in projection, or digest-shaped string is not that handoff. The separate deployment readback must match the published generation, Secret identity and mounted content binding; live freshness and Account readiness are independently proved before the ring mount or either envelope purpose is activated. Neither a receipt nor the shared channel grants Account permission to replace its own Secret. +The Account response-envelope ring uses this same authenticated, content-addressed environment/secrets channel with a distinct `account-response-envelope-ring-materialization-v1` receipt, not a `jwt-signing-keys-jwks` credential record or JWT evidence shape. The typed receipt binds the exact protected source generation and predecessor, source manifest digest, environment and namespace, server-authenticated sole materializer identity, canonical Secret name, and the Secret UID and resourceVersion obtained by post-write readback. It carries only non-secret source and resource metadata; its `immutableArtifactId` is the canonical SHA-256 digest with that field omitted from the preimage. The environment/secrets owner must publish and authenticate the exact typed receipt and reject a missing, conflicting, wrong-writer, wrong-generation, or wrong-Secret result. A local materializer return value, checked-in projection, or digest-shaped string is not that handoff. The separate deployment readback must match the published generation, Secret identity and mounted content binding; live freshness and Account readiness are independently proved before the ring mount or any applicable Account envelope purpose is activated, including the separate [pending-reset purpose](../microservices/account-service/api-contracts.md#account-owned-password-reset-authority-commit). Neither a receipt nor the shared channel grants Account permission to replace its own Secret. ### Account ring materializer target-cluster binding diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 14ae134d79..3bc93fe82c 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,7 +54,7 @@ Each local transition uses a short owner transaction; no database lock spans a r A disclosed terms effective date is never delayed by unresolved owner work and never grandfathers a later Game Design commit. Recovery may recognize an exact valid pre-deadline commit; otherwise Game Design must provide the durable final no-commit proof before the definitive mixed failure can settle. Staged or partially applied content remains non-authoritative and cannot satisfy publication or admission. -**Implementation boundary:** the internal durable fence and participant readback storage are preparation, not an authenticated authorization producer or enabled writer. Complete source-writer participation, current role/party/terms proof, authenticated participant verification and both commit-versus-revocation interleavings remain required before canonical writes may be enabled. No public route or wire schema is selected by this section. Current proof and remaining gates belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). +**Implementation boundary:** the internal durable fence and participant readback storage are preparation, not an authenticated authorization producer or enabled writer. The unwired logout-all source producer now retains an immutable pending caller binding and original Account capture, waits for both definitive participant outcomes, and commits its source advance, event, receipt and linked journals in one Account transaction. Pending readback grants no authorization. Complete participation by the remaining source writers, current role/party/terms proof, authenticated participant verification and executed commit-versus-revocation proof remain required before canonical writes may be enabled. No public route or wire schema is selected by this section. Current proof and remaining gates belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). ### Account-Owned Playtest Grant Contract @@ -210,6 +210,10 @@ Password reset is an account-wide security cutoff, not only a password-row updat The Account-issued, unpredictable one-use reset token identifies one logical reset attempt. Account uses its SHA-256 token hash as the stable internal request identity; raw token bytes never appear in the source event or retained receipt. The receipt binds the exact verified Account UUID, token hash, original token deadline, and SHA-256 of the salted Argon2 password verifier committed to the Account row. It retains neither an additional password verifier nor a fast plaintext-password digest. A versioned private request digest binds those immutable values in the fixed order `[operationKind, accountId, tokenHash, tokenExpiresAt, passwordVerifierDigest]`, using UTF-8 byte-length framing with domain `account-password-reset-request/v1` and `operationKind=PASSWORD_RESET`. Exact retry first proves that the current Account password verifier matches its recorded digest, then verifies the submitted password against that slow verifier and compares immutable request/event/receipt evidence before returning the same lifecycle-only completion; it does not hash a replacement password, consume another token, advance authority again, or issue a credential. A changed Account password postcondition fails closed as superseded rather than being mislabeled a changed caller request. With the original postcondition proved, reusing the same token identity with a different password is a conflict, not another reset. The original token deadline still limits this retry; this operation does not inherit bare-LOGIN's separately authorized expired-context recovery. +An unresolved source-participating reset retains its original slow Argon2 target verifier only in a separate Account-private encrypted pending envelope, not in the completed receipt or an authority event. Its distinct `pending-reset` AEAD purpose uses independent material from connect-token and bare-`LOGIN` envelopes and binds the exact Account UUID, token hash and original expiry, request identity/digest, target verifier digest and original authority-source capture. An exact pending retry verifies the submitted password against that original slow verifier rather than generating a new salted verifier; a different password conflicts. `WAITING` never installs the verifier, consumes the reset token, advances authority, or issues credentials. Missing encryption material, failed authentication, changed bindings or stale source/participant evidence fail closed. + +Once the [authored-Draft source ordering](#account-owned-authored-draft-authorization-fence) permits completion, Account rechecks the original token deadline and current authority/participant evidence and atomically installs that same target verifier, consumes the one-use token, and commits the existing source, event, checkpoint and digest-only receipt obligations. Pending secret cleanup is automatic and idempotent: erase the envelope on committed completion, definitive abort or original expiry, retaining only necessary non-secret outcome evidence. Secret erasure does not bypass unresolved participant recovery or release an authority fence by expiry. A retained pending record or backup never permits an expired operation to install a password. Neither raw passwords nor fast plaintext-password digests are persisted or logged, and no deadline is extended. + The private digest frame starts with its domain and then each field in the declared order. Each component is its UTF-8 byte sequence preceded by a four-byte big-endian byte count. `accountId` is the canonical non-nil UUID string; both hash fields are exactly 64 lowercase hexadecimal characters. `tokenExpiresAt` is the persisted timezone-less deadline's exact `LocalDateTime.toString()` representation, without inventing an offset or converting retained deadlines to UTC. The immutable internal IDs are `account-password-reset-request-v1:` and `account-password-reset-event-v1:`. The stored receipt and event must be read back exactly before success, including after a lost response. Concurrent retries serialize on the exact Account/source scope and one-use token claim; token consumption, password mutation, authority advance, event append and receipt insertion roll back together on any failure. Receipt cleanup remains Account-owned and must prove its retained recovery/replay horizon, holds and references before deletion; expiry alone is not deletion proof and no fixed retention interval is invented here. The current candidate composes this Account-local producer and immutable receipt; it does not implement downstream event delivery, authenticated recipient readback, projection consumption, or active-binding termination. The capability and execution gates remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index 8a45394394..57c4c719d2 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -24,7 +24,7 @@ The configurable cleanup margin controls issued-token registry retention only. G ### Response-Envelope Key Delivery -The Account-owned response-envelope ring is separate from JWT signing, JWKS, and request-digest material. Account alone reads its versioned key manifest from a read-only mounted Secret at the configured path; no inline key or JWT-key fallback is permitted. The manifest has one active write key ID and distinct AEAD material for connect-token issuance and bare first-party `LOGIN` under each retained ID. Rotation replaces the mounted projection atomically, moves prior IDs to decrypt-only use, and retains them until Account proves that no retained response envelope needing recovery references them. [Account Runtime and Data](./runtime-and-data.md#connect-token-issuance-persistence-and-retention) owns the exact-operation and fail-closed recovery contract. Deployment and producer/consumer proof remain required before either envelope path is enabled. +The Account-owned envelope ring is separate from JWT signing, JWKS, and request-digest material. Account alone reads its versioned key manifest from a read-only mounted Secret at the configured path; no inline key or JWT-key fallback is permitted. The manifest has one active write key ID with independent AEAD material for connect-token issuance, bare first-party `LOGIN` and the separate pending-reset purpose. Retained IDs keep their original response-purpose pair; a pending-reset key is required only where pending-reset envelopes use that ID, and an active ID missing it denies pending-reset writes without falling back to another purpose. Rotation replaces the mounted projection atomically, moves prior IDs to decrypt-only use, and retains required material until Account proves that no retained envelope needing recovery references it. [Account Runtime and Data](./runtime-and-data.md#connect-token-issuance-persistence-and-retention) owns response recovery; the [password-reset owner contract](./api-contracts.md#account-owned-password-reset-authority-commit) owns pending secret and expiry consequences. Protected custody, materializer/readback, deployment and producer/consumer proof remain required before any envelope path is enabled. ## Implementation Status @@ -50,7 +50,7 @@ Additional variables configure outbound email delivery, payment behavior, and Ac | `FIREMUD_AUTH_JWT_SECRET` | Inline JWT signing key material for local/dev or explicitly ephemeral stacks only (legacy compatibility; not for player-facing environments) | *(none)* | | `FIREMUD_AUTH_JWT_SECRET_PATH` | Account-only path to the interim versioned asymmetric signing bundle (fallback while delegated non-exportable signer custody is unavailable; mounted read-only from `jwt-signing-keys`) | *(none)* | | `FIREMUD_AUTH_JWKS_PATH` | Path to the Account-published public `jwks.json` file used by Account and JWT validators (required for player-facing environments; mounted read-only from `jwt-jwks`, normally `/var/run/secrets/firemud/jwks/jwks.json`) | *(none)* | -| `FIREMUD_AUTH_RESPONSE_ENVELOPE_KEY_RING_PATH` | Account-only read-only mounted versioned AEAD ring manifest for connect-token and bare-`LOGIN` response envelopes; no inline or JWT-key fallback | *(none; required before either response-envelope path is enabled)* | +| `FIREMUD_AUTH_RESPONSE_ENVELOPE_KEY_RING_PATH` | Account-only read-only mounted versioned AEAD ring manifest with independent connect-token, bare-`LOGIN` response and pending-reset purposes; no inline or JWT-key fallback | *(none; required before the applicable envelope path is enabled)* | | `FIREMUD_AUTH_JWT_EXPIRATION_MS` | Lifetime of newly issued JWTs for profiles using the global setting (target `control-ui` and receiver-specific private player-delegation profiles); Account-specific player-bootstrap and gameplay-connect lifetimes are configured separately below | `3600000` | | `FIREMUD_ACCOUNT_TOKENS_SESSION_EXPIRATION_MS` | Current default legacy Account authentication-session record TTL when `SessionService.storeSession(tenantId, accountId, token)` is called without an explicit lifetime (currently gameplay text/delegation paths); control-ui and player-bootstrap account rows currently pass their corresponding JWT lifetimes directly, while connect-token rows pass the connect-token lifetime directly. It is not JWT `exp`, gameplay-continuity, or issued-token-registry retention | `3600000` | | `FIREMUD_ACCOUNT_TOKENS_PLAYER_BOOTSTRAP_EXPIRATION_MS` | `player-bootstrap` JWT lifetime; target ceiling is `300000` ms (five minutes). Current runtime consumes this override, but target startup/preflight bound validation remains incomplete | `300000` | diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 77631083e5..edebee4da1 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -62,7 +62,7 @@ The closed `game-design-authored-world-release-attestation/v1` evidence carries, 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. +Participant schemas remain their owner-specific supported versions: World Management `3` under its [Digest Input Manifest](../world-management-service/runtime-and-data.md#digest-input-manifest), 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. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index de83f5a111..d3e9b7a556 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -7,7 +7,7 @@ This API contract is target-state canonical; implementation coverage is partial - The current World Management gameplay bridge serializes runtime room ids as `R-` and rejects scoped decimal `roomInstanceId` values such as `1021`. That storage-derived encoding is not the canonical target identity defined by the [Identifier Glossary](../../system-architecture-identifier-glossary.md). - The bridge, cross-service callers, examples, and focused proof have not migrated together to the scoped decimal `roomInstanceId` contract. The checked-in proof still exercises the legacy encoding. - The typed `ApplyRoomAmbientStatePatch` contract below is target-state: the current service has no complete handler or durable operation/digest-bound guard, so player-significant ambient mutations remain on the fenced Game Session admission/reconciliation path and are not direct table writes. -- `GetDraftDesignDigest` 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 registered `GetDraftDesignDigest` requires the verified same-namespace Game Design workload peer and validates the complete typed publication-read request/workflow/digest binding, then returns `FAILED_PRECONDITION` before owner access because a complete authenticated commit/publication checkpoint is unavailable. Wrong-workload and changed-binding unit denial proof exists. The internal numeric content resolver remains an unverified hashing component, not a successful public read, canonical-source-qualified write authorization, 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 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. @@ -110,6 +110,8 @@ World Management also exposes a read-only design-time synchronization surface so - Revision-level ledgers may exist for replay and diagnostics, but they are not part of the publish-gate response. World Management must not expose `lastAppliedRevisionId` as a substitute convergence token for multi-revision commits. - `contentDigest` must cover only version-scoped template/binding rows and must exclude runtime/instance rows and audit metadata. +The current registered handler returns `FAILED_PRECONDITION` until authenticated complete World commit/publication checkpoint evidence is available; see [World Runtime and Movement implementation status](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). + Digest input manifest rules live in [`runtime-and-data.md`](./runtime-and-data.md#digest-input-manifest), while generation-input ownership lives in [`procedural-generation-control.md`](./procedural-generation-control.md). ## ValidateWorldUpgradeMappings Minimum Contract diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index ed248d2042..9e9cd3eacd 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -7,8 +7,7 @@ - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. - Legacy topology scope/version introduction is also not mapped: `V2__add_tenant_and_expiration.sql` assigns `tenant_id = 0` to existing zone, room, and instance rows, while `V18__version_scoped_world_templates.sql` assigns `version_id = 1` across existing template tables without hierarchy/version-graph backfill evidence. Positive tenant/version reads can orphan or misattribute those rows. A retained-data deployment remains blocked until the owner records a verified no-data boundary or explicit retained-row disposition/mapping and exact readback; this remains migration/proof drift rather than a new identity authority. - The live versioned topology and spawn schemas carry tenant/version columns, but parent references remain scalar-ID foreign keys, so SQL does not enforce child/parent tenant/version equality. Normal typed mutation guards resolve parents with tenant/version predicates, but that is not database integrity and does not protect retained or direct-written rows. Target convergence requires composite parent keys/foreign keys or an equivalent owner-local guard, plus database integration and readback proof. This is separate from the sentinel-default and hierarchy/version-graph backfill drift above. -- The live `ApplyWorldDesignMutation` path performs a remote Game Design Draft-state read before its local transaction, but carries no Game Design `versionStateEpoch` or owner publication fence and has no durable WMS version-freeze row. A concurrent Game Design publish can therefore pass its digest read and transition the version while the pre-checked WMS mutation is still able to commit. This is a current lifecycle-handoff gap, not proof of Published-template immutability; the target freeze/acknowledgement protocol is canonical in [Game Design Version Control](../game-design-service/version-control.md#publication-freeze-and-owner-handoff). -- The target WMS publication owner contract, including `BeginVersionPublicationFreeze` and the outcome-typed `CompleteVersionPublication` terminal handoff, is specified in [World Management API Contracts](./api-contracts.md#publication-freeze-and-terminal-handoff-target-state). The current proto, DTOs, client adapter, persistence schema, handlers, and focused race/retry proof do not implement those surfaces: `ApplyWorldDesignMutation` still has no publication request, Game Design epoch, or WMS `publicationFence` fields. This remains a publication-readiness blocker; no digest, preflight state read, or Temporal completion may be promoted to freeze or terminal owner evidence. +- The registered `ApplyWorldDesignMutation` RPC denies before request decoding or owner access. The V25 publication-fence storage and later immutable graph-capture components remain explicitly unwired; they do not supply authenticated Account commit authorization, complete participant application or the terminal publication handoff. See the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) for current capability and proof, [World API Contracts](./api-contracts.md#publication-freeze-and-terminal-handoff-target-state) for the owner surface, and [Game Design Version Control](../game-design-service/version-control.md#publication-freeze-and-owner-handoff) for the cross-owner sequence. No digest, source receipt or preflight read replaces those gates. - Procedural-generation persistence has a current identity gap: `V21__scoped_generation_rules.sql` creates a unique index over nullable `scope_type`/`scope_id`. Under PostgreSQL, multiple NULLs are distinct, so unscoped rows can duplicate the same `(tenant_id, version_id, name)` and destabilize deterministic generation-rule identity/digests. The current scope-aware repository lookup also compares nullable scope columns with SQL `=`, so it cannot retrieve an unscoped row. The target schema and mutation path must either prohibit unscoped rows or provide an explicit null-safe schema/query uniqueness contract, with focused proof; procedural-generation readiness remains blocked until that contract is enforced. - The synchronous termination command now compares the supplied `terminationRequestId` with retained terminal identity before returning a `TERMINATED` snapshot; an exact retry returns the snapshot and a changed or missing stored identity fails with `IDEMPOTENCY_CONFLICT` without cleanup or mutation. Focused unit proof covers this narrow guard. It does not prove the target frozen all-owner termination snapshot, durable acknowledgements, final fenced CAS, or Temporal lost-response and closed-workflow reconciliation. - The current termination orchestration keeps the Entity Management cleanup RPC outside an open World transaction, preserves `TERMINATING` while remote cleanup or local finalization is incomplete, and commits local runtime-row cleanup with the `TERMINATED` lifecycle state in one local transaction. [WorldLifecycleCommandServiceImplTest](../../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) covers the owner-local control flow and RPC/transaction separation at unit level; it does not provide live PostgreSQL rollback, crash, or concurrency proof. The frozen all-owner cleanup snapshot, durable acknowledgements, final fenced CAS, and Temporal lost-response or closed-workflow reconciliation remain incomplete. @@ -168,7 +167,7 @@ Implementation Notes: - Current concrete `room` digest fields include `id`, `zoneId`, `name`, `description`, `nameLocalizedVariantsJson`, and `descriptionLocalizedVariantsJson`. - Current concrete `room_exit` digest fields include `id`, `fromRoomId`, `toRoomId`, `direction`, and `cost`. - Current concrete `generation_rule` digest fields include `id`, `name`, `scopeType`, `scopeId`, and `value`; generation-rule mutations that carry a subtree scope must validate that declared scope, share the same scope epoch, and participate in `REPLACE_SCOPE` / `SEED_APPEND_ONLY` enforcement. -- Current concrete `world_entity_spawn_binding` digest fields include `id`, `roomId`, `entityTemplateType`, `entityTemplateId`, `spawnCount`, and `respawnDelaySeconds`. +- Current concrete `world_entity_spawn_binding` digest fields include `id`, `roomId`, `entityTemplateType`, `entityReference`, `spawnCount`, and `respawnDelaySeconds`. `entityReference` is exactly one tagged representation: retained numeric-only rows encode `{"kind":"RETAINED_PRIVATE_KEY","templateId":""}`; canonical-only rows encode `{"kind":"CANONICAL_UUID","templateId":"","tenantId":"","versionId":""}`. Numeric keys are decimal JSON strings, preserving the complete positive signed-64-bit value; UUID values are their complete lowercase, hyphenated string representations. Incomplete, nil, mixed numeric/canonical, or nonpositive numeric references fail closed. Retained private keys are representation evidence only and do not prove a mapped canonical or runtime Entity identity; digesting a canonical tuple does not establish Entity existence or authorization. - Included objects: - version-scoped topology tables such as `region_template`, `zone_template`, `room_template`, `terrain_template`, `room_exit_template`, and equivalent normalized topology relations; @@ -184,7 +183,8 @@ Implementation Notes: - stable table ordering; - primary-key ordering within each table; - deterministic encoding for included semantic fields. -- Current implementation note: the concrete first-slice table order is `regions`, `zones`, `rooms`, `roomExits`, `generationRules`, then `worldEntitySpawnBindings`, each ordered by ascending primary key. Null string values are canonicalized as empty strings before hashing. The current World digest schema version is `2` because scoped generation-rule metadata is now hashed. +- Current World digest schema version is `3`. The hash preimage is compact JSON encoded as UTF-8, without a byte-order mark, indentation, trailing newline, or surrounding whitespace; SHA-256 is returned as 64 lowercase hexadecimal digits. The top-level object has exactly this property order: `regions`, `zones`, `rooms`, `roomExits`, `generationRules`, `worldEntitySpawnBindings`. Each value is an array ordered by ascending numeric primary key. Within every row and nested semantic object, field names are lexicographically sorted; the Entity reference field order is therefore `kind`, `templateId`, and, for canonical references, `tenantId`, `versionId`. Strings use standard JSON escaping, non-ASCII characters remain literal UTF-8, integral semantic values remain JSON numbers except the explicitly string-valued Entity reference key, and floating-point values use the fixed JSON encoder's ordinary decimal representation. Existing optional null string normalization to `""` and the other selected semantic fields remain unchanged; JSON-valued text columns remain opaque strings and are not parsed or reordered. Schema serialization uses a dedicated default Jackson encoder and cannot inherit application-wide pretty-printing or map-order settings. +- Existing immutable schema-2 freeze checkpoints, graph/v1 snapshots, and graph/2 frozen journals retain their original digest, request, graph and result bytes and remain readable and exactly retryable. No schema-2 hash is inferred or reinterpreted as schema 3. Fresh snapshot/journal capture requires schema 3 after exact historical-journal lookup; the forward migration admits retained schema 2 while denying new schema-2 or unsupported-schema insertions. The graph/v1 capture remains numeric-reference-only, while the separate canonical graph/2 path can retain a schema-3 checkpoint. Fresh schema-3 capture compares the computed owner digest's private tenant/Version scope, schema and content digest with the exact V25 checkpoint under the shared frozen owner lock before insertion. Both capture paths remain `CAPTURED_UNVERIFIED`; representation and digest evidence do not establish complete Account authorization, participant `APPLIED`, publication, activation, or terminal owner handoff. - `digestSchemaVersion` must increment whenever included tables, field-selection rules, or canonical serialization semantics change. Publish gating fails closed if World Management cannot attest a digest consistent with this manifest. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index b615429655..67d089e0e0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -440,3 +440,13 @@ Entry format: - Context: the Account OTP fixture described on `2026-10-02` failed again in exact-source CI37341390296 after earlier successful executions. Its ultimate-target `doAnswer` setup ran the real advisory-lock query while Mockito stubbing remained unfinished; the later forty-three required source-proof cases did not execute. The exact proxy/instrumentation cause remains unproved, so the older unwrapping recommendation is not sufficient evidence of stable setup. - Outcome: the corrected fixture observes actual advisory-lock SQL through a per-test restored jOOQ listener, asserts the owner transaction and requires a positive observed-execution delta for each tested OTP operation. Exact-source CI37344877274 Account job and its persisted-UUID authentication command/strict case verifier succeeded; no standalone UUID/OTP XML or per-case verifier log was captured. Independently parsed downstream source-proof XML records all 110 captured Account methods cleanly, including the forty-three required selections that had not executed in the failed run. - Expected pattern: transaction observation must not invoke the operation during instrumentation setup or pass vacuously when no observation occurs. Preserve the real lock, mutation and rollback assertions; a prior green run or Docker-skipped local check does not establish recovery. + +- `2026-10-06`: Select substantive CI runs before assigning a proof watcher + - Context: #3007 publication and body/LOC updates created several same-head Validation runs. Selecting the newest run assigned the World proof watcher to a metadata-only required-gate preservation job, while the substantive matrix run had already failed its V31 migration. + - Observation: matching the workflow and exact head alone did not prove that the selected run would execute the required service job. The workflow deliberately skips its build matrix for metadata-only edits; waiting for that matrix would not produce proof. + - Expected pattern: inspect same-head run/job identity once at watcher admission, select the substantive matrix run, and bind subsequent observation to its immutable checkout and scoped job. Do not duplicate parent polling, dispatch replacement CI, or count a metadata-preservation gate as runtime execution. + - Outcome: the sole watcher switched to the exact-head substantive run and preserved raw migration-failure evidence; its metadata-run selection was recorded without granting execution credit. + +- `2026-10-06`: A terminal CI failure may contain no acquired test runner + - Context: exact #3007 source `a6f10921` Validation run 37369680372 ended after about 45 minutes without an Account or World matrix job, raw XML or artifacts. The detector's check annotation explicitly reports that the hosted runner was not acquired despite multiple attempts; its steps are empty. + - Expected pattern: inspect terminal job annotations before attributing an aggregate failure to code. Record zero execution credit and the concrete runner-acquisition failure, retain local skipped-test limits, and continue independent implementation. A failed or cancelled detector is neither a database failure nor successful proof. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 162e8a069d..5a919d02e2 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,24 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +At exact parent `3d801289900a92bdd4384f20b264cf1f60a75f74`, [CI37404171270](https://github.com/benhook1013/FireMUD/actions/runs/37404171270) executes all ten World canonical association and one preparation PostgreSQL cases without skips or failures. Independently verified runner merge `88eb380e9f7b7d2601987ed9280ebad03db62e0e` has the exact base/source parents and the source-identical tree. Account executes issuer22 (one failure), tenant18, logout-all17, password-reset6, issuer acknowledgment8 and reconciliation9; only the issuer retained fixture fails, with no skips in these captured suites. Its V58-to-V59 table-image and exact-binding preservation checks complete, but later current producer interactions still read V61-only `aborted_at`. The corrected definition keeps every preservation assertion at V59, then explicitly advances only its runtime-interaction segment to V61, the first schema supporting that reader. It does not add obsolete production compatibility or weaken source ordering; corrected PostgreSQL execution remains required. TCP Proxy separately fails thirteen of seventeen cross-service tests, Game Session is cancelled and the aggregate is red. These results establish neither authenticated creator/publication delivery nor activation. + +The exact `678ca7c2c18679242c25d708dcbea1ba45894000` [CI37391494393](https://github.com/benhook1013/FireMUD/actions/runs/37391494393) executed all seven pending-reset source-change and seventeen logout-all PostgreSQL methods without skips. All seven reset methods failed because overlong generated schema names were truncated and collided; sixteen logout methods passed, while the V59-to-V60 fixture attempted to read a V61-only column. The correction preserves the full random schema suffix, the exact original source-change binding and every applicable V59/V60 retained-row image, and keeps that migration proof explicitly targeted at V60. Focused compilation, integration SpotBugs and Checkstyle pass locally; corrected PostgreSQL execution remains required. Exact merge parents and a source-identical tree establish attribution. No credential, creator-authority, ring or runtime activation follows from these fixture corrections. + +The prepared V61 preservation component adds an immutable pending-reset request/source journal and a separate encrypted verifier row, linked to V57 ordering. `SOURCE_ABORTED` is a distinct no-mutation terminal result, never a fabricated source commit. An expired verifier may be erased while unresolved owner participation remains `WAITING`; expiry alone cannot settle or release the fence. Seven new PostgreSQL definitions cover retained exact ciphertext, changed-binding/remint denial, deferred live-envelope enforcement, both-owner ordering, expiry, rollback and immutable cancellation. Their upstream owner results are synthetic fixture readbacks, not authenticated producer proof. The Account full check, boot JAR, analyzers, formatting, links and Markdown pass in 30s with 964 clean unit results; all 393 integration cases, including these seven, skip without Docker. The previously failing logout-all assertion now preserves the complete original framed readback, but corrected PostgreSQL execution remains required. Public reset recovery, completion and cleanup integration are not implemented by this preservation checkpoint; further reset expansion is parked while the fresh authored-world application/lifecycle dependency is prioritized. + +At exact published `25848a5d257af0e610b3654c91c38f73e67242d4`, [CI37376053183](https://github.com/benhook1013/FireMUD/actions/runs/37376053183) Account job `111985206038` executes all seventeen logout-all PostgreSQL cases: sixteen pass, one fails and none skip or error. The mixed-terminal ordering case incorrectly expects the raw one-byte owner payload instead of the complete canonical framed owner readback stored by its fixture. Correcting that assertion must retain the exact original owner bytes across both settlement and Account source advancement; production ordering and immutability guards must not be relaxed. Raw suite SHA-256 is `b751dcf3fca03459404621bf00f4586dc67156a09d4b5f2a3445b29ba3c37cdc`; root verifies the source-identical merge `7321b11e47366c345425fc95e24091fd1d5df4b7` and exact parent/source. Corrected execution remains required. This is not pending-reset integration or runtime activation proof. + +The current composed Account/World full-check, boot-JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown gate passes in 1m8s (107 tasks: 24 executed, 83 up-to-date). Matching XML records 964 Account and 332 World unit cases without skips/failures/errors; unchanged Account tests were reused after their successful Account-only gate, and the final World run executes all four new plan cases. All 386 Account and 115 World integration cases compile but skip locally without Docker. The gate discards 36 protobuf configuration-cache serialization problems; this is not cache-support, fresh-image or database proof. Pending reset integration and authenticated publication/lifecycle remain incomplete. + +Nine pending-reset crypto unit cases execute cleanly, including an actual Account Argon2 encoder roundtrip, complete binding substitution, wrong-purpose/key denial, rotation/restart and malformed-verifier rejection. Seventy-nine offline bootstrap/materializer Python cases pass (25 bootstrap and 54 materializer), including exact retained-key preservation and distinct-purpose collision handling. These are local cryptographic and fake-Kubernetes tooling tests, not pending reset transaction/retry/cleanup, authenticated publication, protected custody or live Secret proof. The exact previous-head [CI37369680372](https://github.com/benhook1013/FireMUD/actions/runs/37369680372) failed before either Account or World test job materialized: the detector annotation reports that no hosted runner acquired the job despite repeated attempts. No test XML or artifacts exist for that run; it supplies zero database execution credit. + +The separate Account-private encrypted pending password-reset verifier representation is approved in the [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-password-reset-authority-commit); the completed receipt remains digest-only. The candidate crypto primitive uses a distinct pending-reset purpose and typed original-operation/source-capture binding, preserves the response-purpose encoding, and rejects ordinary plaintext or fast-hash payloads. Protected bootstrap and explicit rotation add three distinct active keys while preserving every retained key exactly, including older response-only IDs. This preparation does not yet retain a pending source journal, verify retries against its original slow verifier, integrate reset completion with participant ordering, or execute automatic pending-secret cleanup. Those owner implementation and proof obligations remain open, as do live custody, delivery, mount and activation gates. + +The current Account/World candidate adds V60 logout-all participation in the existing authored-Draft source ordering. An unresolved attempt retains only its immutable caller request and original Account source capture; counters, event, receipt and both journal completions wait for definitive World and Game Design outcomes and share the eventual Account transaction. Exact pending retries reuse that capture, while changed caller bindings conflict. The producer remains unwired and does not authenticate a caller; other Account-wide writers, creator/role/party/terms authority and authenticated participant readback remain open. Five new PostgreSQL definitions cover both orderings, exact pending retry, late rollback after both journal transitions and V59-to-V60 preservation; the retained lost-response case also verifies unchanged event and journal bytes. Their upstream owner readbacks are explicitly synthetic, and their local Docker skips are not execution proof. Password-reset participation needs the separate pending storage, completion and cleanup proof above; its approved representation does not make the existing verifier-free completed receipt a precommit recovery mechanism. The World publication socket fixture reads the actual base service method allowlist: only Ping and the exact peer-guarded digest read bypass bearer authentication, and the digest handler still denies success until complete authenticated commit/publication evidence exists. No canonical write, lifecycle, credential or admission path is enabled by this batch. + +The combined Account/World full-check, boot-JAR, Account jOOQ generation, formatting, Checkstyle, SpotBugs, coverage and documentation gate passes in 2m27s (108 tasks:40 executed,68 up-to-date). Fresh XML records Account955 and World328 unit methods executed without skips, failures or errors; all six World physical mTLS/configuration cases executed exactly once. Account386 and World115 integration methods compile but skip without Docker, including all seventeen logout-all PostgreSQL cases. Twenty-five CI-scope contracts and workflow lint pass; Flyway sanity passes twelve sets/195 files. The binary token-hash uniqueness index remains enforced in PostgreSQL and uses the existing targeted jOOQ ignore convention because the H2 interpreter cannot index its BLOB representation. Fresh images, PostgreSQL execution, environment/profile overrides, complete authenticated producer/consumer evidence and activation remain independent gates. + At exact published `968fa3bb98efa19f50e659f4769fc3b1537e0787`, [CI37344877274](https://github.com/benhook1013/FireMUD/actions/runs/37344877274) Account Build and Test succeeded. Independently parsed raw XML proves all 110 captured Account PostgreSQL methods passed without skips, failures or errors: authorization fence11, JOIN55, role journal4, issuer22 and tenant18. The duplicate tenant artifact is one execution, not another eighteen cases. All forty-three required authored-Draft selections are present and clean: fence11, retained-role/journal19, issuer7 and tenant6. The persisted-UUID authentication step also succeeded; its committed command runs fourteen UUID/OTP methods and three public-boundary methods, then strictly requires every case without skips. No standalone UUID/OTP XML or per-case verifier log was captured, so that narrower attribution rests on the successful strict step, not raw XML. Verified runner merge `238ac09f75a25a2d742acf6d89a565e85af5d897` has exact Account parent `1a3122769f1251e6773838fe140788d5dcf20f99` and candidate parents, with head-identical tree `2243bed55dbb95c618d7359eb88a00f49026bc50`. This closes the transaction-observer execution gap below. Game Design20 and World29 required database methods also passed; aggregate CI was still active at the scoped handoff, and authenticated actor/creator/terms, complete publication and runtime activation remain unproved. At exact published `add1a85e3374ef0cb93330e96ba76bf5aac526f5`, [CI37341390296](https://github.com/benhook1013/FireMUD/actions/runs/37341390296) Account's preceding UUID/OTP integration selector failed in `emailOtpAuthenticationIssuesPersistedUuidAndConsumesTheChallengeExactlyOnce`: the transaction-observer fixture unwrapped a Mockito/Spring proxy and executed the real advisory-lock method while stubbing remained unfinished. Strict verifiers report all forty-three later required Account source cases missing with zero executions, not passing or skipped. The corrected fixture observes actual advisory-lock SQL through a restored-per-test jOOQ listener, asserts an active owner transaction at execution and requires an increasing observed-lock count for OTP request, verification, rejection, retry and rollback paths. Password-only paths are not required to take an OTP lock. Production authentication, consumption and transaction guards are unchanged. Local compilation without Docker does not prove this instrumentation runs; corrected PostgreSQL/Redis execution remains required. The earlier exact-source Account proof below remains valid at its own source, while Game Design and World passed their separately selected database proof at this newer head. No aggregate-green or activation claim follows. 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 c88f8dccf1..175a951070 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,44 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +At exact published `3d801289900a92bdd4384f20b264cf1f60a75f74`, [CI37404171270](https://github.com/benhook1013/FireMUD/actions/runs/37404171270) executes all ten canonical-instance association and one preparation PostgreSQL cases cleanly, without skips. Raw XML and independently verified source-identical runner merge `88eb380e9f7b7d2601987ed9280ebad03db62e0e` prove the corrected complete-value equality and narrow typed-conflict denial at this source. World Management passes. Account still fails one issuer migration fixture: its V59 preservation checks complete, but later current reader interactions require V61. The bounded fixture correction now separates those two schema boundaries; the [Account tracker](./player-access-and-session.md) records the executed suite counts and remaining re-execution requirement. TCP Proxy separately fails and Game Session is cancelled, so aggregate validation is red. The eleven World storage cases do not establish a protected creator, complete application/release, authenticated preparation/lifecycle transport, fresh image or playable flow. + +Exact parent `3b48b7493766acf80e616eb48dba604081131379` [CI37399537835](https://github.com/benhook1013/FireMUD/actions/runs/37399537835) executes all ten canonical-instance association cases without skips: nine pass and the changed-binding case correctly reaches V35's SQL denial but exposes `DuplicateKeyException` rather than the domain conflict. The one preparation case passes. The bounded correction translates only SQLSTATE `23505` with an exact V35 owner conflict message at the function-call boundary inside the owner transaction; unrelated uniqueness failures remain untouched. SQL guards, original binding and rollback checks are unchanged. Pure cases prove both deliberate conflicts, cause preservation and unrelated/wrong-state denial, including a misleading matching detail line. Account's job is cancelled after the genuine V59 fixture uses a source-change reader expecting V61 columns; its missing raw XML supplies no executed Account proof. That fixture now independently reads and roundtrips the retained exact binding without upgrading its schema or changing production compatibility. + +The corrected Account/World full checks, boot JARs, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass in 1m22s, with 343 World and 964 Account clean unit outcomes. All 126 World and 393 Account PostgreSQL cases compile but skip locally without Docker. Corrected exact-source database execution remains required; this is not authenticated application, release, lifecycle or player-flow proof. + +At exact published `9c9f01be79bc1696bd2ca5a2e707068603916602`, [CI37395254176](https://github.com/benhook1013/FireMUD/actions/runs/37395254176) executes the ten canonical-instance association cases and one reserved-tenant preparation case without skips. Four association cases and the preparation case pass; six association cases fail because the reconstructed frozen request compares a newly reconstructed topology plan by Java object identity, rejecting otherwise identical complete values before materialization. The correction compares the complete canonical Draft binding, owner binding, freeze/affected tuples and ordered typed graph instead; all existing projected entry/family and held-authority checks remain. Pure proof covers separately reconstructed equal values and independent substituted evidence. Corrected PostgreSQL execution remains required. Verified runner merge `3a54423ebe6c956a05691c8eae37e223f7134d38` has exact base/source parents and source-identical tree. Account's pending-reset seven and logout-all seventeen methods pass, but its separate V59 upgrade fixture fails; aggregate CI is red. This does not prove authenticated release, preparation or player-flow activation. + +The corrected candidate passes the combined World/Account full checks, boot JARs, formatting, Checkstyle, SpotBugs, coverage, links and Markdown in 1m15s. Matching XML has 340 World and 964 Account unit methods with no skips/failures/errors; unchanged Account unit outcomes are reused, and the new full-vector regression executes in World. All 126 World and 393 Account integration methods skip locally without Docker. The Account V58-to-V59 fixture now targets V59 explicitly, preserving its exact retained-row assertions. Corrected-state PostgreSQL and authenticated producer/readback proof remain open; discarded protobuf configuration-cache problems are not cache-support proof. + +The exact `678ca7c2c18679242c25d708dcbea1ba45894000` [CI37391494393](https://github.com/benhook1013/FireMUD/actions/runs/37391494393) executed all ten canonical-instance association and the one preparation-denial PostgreSQL cases without skips, but nine association fixtures failed before their assertions because synthetic participant scopes did not match the descriptor Version, and the preparation assertion expected jOOQ's exception instead of Spring's translated denial. The V32 retained-row migration case passed. The correction binds every synthetic participant to the exact descriptor Version and checks the translated PostgreSQL reserved-tenant denial without relaxing the guard or unchanged-row proof. Focused compilation, integration SpotBugs and Checkstyle pass locally; corrected PostgreSQL execution remains required. The runner merge has exactly the published base and source parents and a source-identical tree. This is not authenticated owner application, release, lifecycle or player-flow proof. + +The V34/V35 candidate retains an insert-born, immutable association from the exact Game Session canonical instance and complete launch pair to World-private rows. Its typed request/reply comparison requires explicit owner-recorded `publicProduction=true`; `SHARED` alone is not evidence of that classification. False, absent, private/playtest or conditional lifecycle evidence remains denied. The unregistered, default-denied preparation component materializes a generation-free region/zone/room/exit graph under the exact still-frozen owner lock, using a single-use transaction-specific insert manifest rather than bypassing the V24/V29 reserved-tenant guard. It independently verifies the complete original source, launch pair, Version and frozen six-family projection before allocation; configured generation or spawn intent remains denied. The immutable retry identity excludes fresh Game Session read metadata, while each request/response echo is still checked. Association, runtime topology and exact result commit or roll back together. Results are only `MATERIALIZED_UNVERIFIED`; neither the stored lifecycle enum nor a synthetic test verifier is authenticated `PREPARING`, `ACTIVE` or admission evidence. + +The PostgreSQL definitions now invoke that actual owner writer instead of direct canonical-row fixture insertion, covering graph content and typed maps, exact retry without lifecycle mutation, changed and substituted bindings, rollback when a synthetic held authority is lost, concurrent exact preparation, retained-row preservation and continuing direct-write/function-access denial. The production source/release/application/Account verifier, canonical preparation transport, authenticated lifecycle readback and fresh-image flow remain open. The corrected candidate passes World and Account full checks, boot JARs, formatting, static analysis, coverage, links and Markdown; the matching results contain 339 World and 964 Account unit executions with no failures, errors or skips. All 126 World and 393 Account integration cases compile but skip locally without Docker, including the eleven new World writer/guard cases and seven Account pending-reset cases. Schema generation is successful, not PostgreSQL migration execution. CI captures the raw XML and requires each new case to execute without skips. Actual candidate PostgreSQL execution and authenticated runtime composition remain required; earlier published evidence below does not prove these newer definitions. + +At exact published `25848a5d257af0e610b3654c91c38f73e67242d4`, [CI37376053183](https://github.com/benhook1013/FireMUD/actions/runs/37376053183) World job `111985206298` succeeds: all 66 required PostgreSQL cases execute once with zero skips, failures or errors (topology fifteen, frozen graph fourteen, numeric snapshot twelve, publication fence eight, REGION thirteen and legacy preparation four). The corrected actual-row tamper case passes, closing its previously outstanding execution obligation. Root independently verifies the frozen XML SHA-256 `cd67534b6ec47c787ccdcd1e3e6754eb6ee20d7c825cd7de6bc551a761f3406c` and the remote merge `7321b11e47366c345425fc95e24091fd1d5df4b7`: exact base `a67b503558ec96f8659660abc3cf8333069eb80a`, exact source and source-identical tree `4d2651558a4f85d18371fe221a943b7927055513`. This supplies actual component and migration execution, not complete authenticated release, canonical instance preparation or activation; concurrent unpublished changes are outside that evidence. Older pending-execution statements below describe their historical checkpoints. + +Four pure topology-plan unit cases execute without skips or failures, covering all six families and original source binding/payload/order, missing/duplicate/type-confused or changed frozen rows, and declared-subtree exit rejection. The upstream frozen evidence is synthetic and explicitly unverified; this is not PostgreSQL capture, authenticated release or runtime materialization. Exact previous-head [CI37369680372](https://github.com/benhook1013/FireMUD/actions/runs/37369680372) supplied no World test job or artifacts because its detector could not acquire a hosted runner. The corrected tamper case and all current database obligations remain unproved by that run. + +The complete frozen graph has a pure typed instance-topology projection preserving all six authored families, family-qualified UUID parent links, original input ordering and payload bytes, effective stored defaults, exact Entity reference provenance and the original full source binding. Configured generation rules and spawn bindings remain required intent, not successful execution or optional skipped work. The projection rejects missing, duplicate, type-confused or substituted content and preserves the owning contract's declared subtree closure, including denial of cross-region exit endpoints outside that scope. It allocates no runtime identity, writes no instance rows and remains based on `CAPTURED_UNVERIFIED` evidence. Actual authenticated owner application, released-content verification, generation/spawn execution, atomic Game Session instance association and lifecycle materialization remain open; this component cannot authorize `PREPARING` or admission. + +The registered `GetDraftDesignDigest` handler now preserves exact Game Design peer, typed scope and request-binding validation, then returns `FAILED_PRECONDITION` without exporting success evidence. The internal semantic hashing component's synthetic `version:` marker is not the complete durably applied commit required by the owner contract; an unverified graph or storage capture cannot supply that missing checkpoint. The handler no longer injects that hash-only component. Focused valid-request denial, empty-success-field and existing peer/scope/binding negatives pass within the full World check. The internal digest and `CAPTURED_UNVERIFIED` components remain available for their stated non-authorizing proof only. Implementing the authenticated complete commit/checkpoint producer remains required; no public digest success or publication activation is claimed. + +Four additional PostgreSQL definitions use the actual migrated schema, jOOQ repositories and Spring lifecycle transaction to test complete selected legacy zone/room/exit materialization, exact retry without duplication, cross-Version parent/endpoint rejection with unchanged authored data, and rollback of all runtime rows after a late database error observes earlier writes. Their upstream Game Design release/version answers are synthetic mocks, not authenticated release authority. The consolidated local World check and boot JAR pass with 322 unit executions and no failures/errors/skips; all 115 integration cases compile but skip without Docker, including these four. CI now captures their raw XML and strictly requires all four methods in addition to the existing 62 component cases. Actual PostgreSQL execution, fresh-image boot and complete canonical lifecycle proof remain open for this correction. + +The schema-3 digest candidate reads both retained numeric and fresh canonical UUID Entity references without loss, rejects incomplete, nil, mixed or nonpositive reference representations and serializes selected semantic rows deterministically under the owner's manifest. Common full release evidence and directly affected publish-gate/release fixtures now select World participant schema 3. Forward V32 preserves immutable schema-2 snapshot and canonical-journal evidence and permits only fresh schema-3 capture; historical exact retries remain before new-capture admission. New schema-3 capture checks the actual producer's private tenant/Version scope, schema and content digest under the held V25 lock; negative definitions reject altered returned scope or content without journaling. The legacy graph/v1 capture remains numeric-only, and the canonical graph/2 capture remains explicitly unwired and `CAPTURED_UNVERIFIED`. Focused unit definitions cover exact canonical/retained serialization vectors, each UUID's digest contribution and reference rejection. PostgreSQL definitions cover SQL mapping and row ordering, schema-3 checkpoint/capture/readback, returned private-Version mismatch, preserved V28/V31 schema-2 upgrade history, exact retries, and denied fresh schema-2/unsupported insertions. Local consolidated Common/World/Game Design checks and World/Game Design boot JARs passed: 1,066 unit cases executed without failures, with one separate Game Design unit skip; 111 World and 131 Game Design integration cases compiled but skipped without Docker. Formatting, Checkstyle, SpotBugs, coverage generation, links and Markdown checks passed; integration static analysis still reports a missing annotation class, and protobuf configuration-cache serialization remains unsupported. Exact-source PostgreSQL execution and its outstanding fixture correction are recorded below; fresh-image boot, authenticated release, complete participant application, activation and terminal handoff remain unproved. The synthetic `appliedCommitId` and complete publication-content checkpoint proof remain open. + +At published schema-3 source `0cadc8f117641103b3baf7b880e5b90a245f9406`, [CI37360370191](https://github.com/benhook1013/FireMUD/actions/runs/37360370191) executed all 62 required World PostgreSQL methods: 61 passed, one failed, and none skipped or errored. Independent raw XML and merge-checkout verification bind the exact unchanged parent and source, with a source-identical tree. The V31 reserved-variable parser correction and V32 migration executed successfully; the sole failure was the frozen-journal tamper fixture's replacement of an obsolete placeholder digest, leaving its schema-3 row unchanged. The corrected fixture mutates the actual retained digest and verifies every complete row changed before asserting historical-read rejection; production immutability and readback checks are unchanged. Corrected PostgreSQL execution remains required. This is component execution, not authenticated publication, released content or lifecycle authority. + +The legacy numeric lifecycle preparation adapter now validates one selected zone/room/exit snapshot before its first persistence call, rejecting absent parents/endpoints, duplicate identities and out-of-scope rows instead of silently dropping rooms or exits. Six added no-write unit cases and the existing valid-topology/exact-retry cases pass within the full World check: 322 unit cases executed cleanly; all 111 integration cases compiled but skipped locally without Docker. This contains malformed legacy topology only. It neither supplies complete canonical released-topology materialization nor proves database rollback, immutable published input, authenticated Game Session instance association or `PREPARING` eligibility. + +The canonical graph/2 consumer now validates every scoped typed UUID/private-key mapping and all six families against the exact original complete input, preserving effective storage defaults without altering original payload bytes. Forward V31 and the explicitly unwired frozen-capture component retain that graph, original storage result, complete binding, closed source/Version evidence and exact V25 freeze checkpoint in one immutable journal under the shared owner lock. Exact historical readback verifies the retained evidence without consulting later mutable rows or reentering a writer; terminal retries return the original capture, absent history is unknown and new capture after terminal state is denied. Every result remains `CAPTURED_UNVERIFIED`: original V31 fixtures stipulated the checkpoint, while the schema-3 candidate computes and compares selected semantic content. Account authorization, complete participant application and authenticated publication-convergence evidence are missing. The schema-3 candidate above closes the canonical spawn representation-read gap; authenticated release and complete lifecycle materialization remain explicit gates. The original nine unit definitions and ten required PostgreSQL definitions cover representation, complete binding, changed checkpoints, missing storage, concurrent capture, retained V30-to-V31 upgrade, tamper denial and terminal recovery. Their execution evidence is separate; compilation and Docker-skipped cases are not PostgreSQL proof. + +The fresh canonical topology candidate adds an explicitly unwired six-family component, not an authenticated writer. It parses the complete original Draft input into typed UUID references, derives every aggregate and containing-scope tuple, and accepts only a wholly fresh local Version with zero expected epochs and no retained content or epoch rows. Forward V30 allocates private row keys and immutable fully scoped typed UUID associations, inserts actual region/zone/room/exit/generation/spawn rows in parent order, advances each aggregate and distinct containing fence once, and retains the original full binding, graph and exact result atomically under the shared OPEN/freeze lock. A canonical execution projection comes from the parsed protobuf messages; original payload spelling, other-owner bytes, base and digest remain unchanged. Actual row readback against the original plan rejects altered projection semantics and rolls back the transaction. No numeric coincidence claims retained content. Fresh spawn rows preserve the typed canonical Entity reference with a null private Entity key; retained numeric references remain unchanged and unmapped. + +Independent committed topology readback revalidates source/Version provenance, all UUID associations, actual payload fields, exact epochs and original graph/result bytes without a writer transaction or permission check. An absent result is unknown, not a definitive abort. The default permission verifier denies before storage, and every synthetic success remains `STORED_PERMISSION_UNVERIFIED`; Entity existence, Account authorization and participant commit evidence are not supplied. The old numeric graph/v1 reader intentionally rejects the fresh canonical spawn representation. Strict v2 snapshot/release consumption, normal synchronized reads, retained/replacement writes, authenticated terminal handoff and complete runtime materialization remain required before this becomes publication or lifecycle authority. Fifteen new PostgreSQL definitions and their mandatory CI capture/verifier cover all six families, representation equivalence with unchanged raw retry identity, projection-tamper rollback, races, freeze ordering, ordinary-write denial, exact lost-response readback and V29 retained-history preservation. Execution evidence is reported separately; compilation or Docker-skipped cases do not prove these definitions. + At exact published `968fa3bb98efa19f50e659f4769fc3b1537e0787`, [CI37344877274](https://github.com/benhook1013/FireMUD/actions/runs/37344877274) World Build and Test succeeded. Independently parsed raw XML proves all twenty-nine required PostgreSQL methods executed once without skips, failures or errors: graph8, publication-fence8 and guarded REGION storage13. The new `committedReadbackReturnsOriginalFrozenHistoryWithoutPermissionOrMutation` case passed, closing the independent-readback execution gap below while preserving its unknown-absence and unverified-permission limits. Runner merge `238ac09f75a25a2d742acf6d89a565e85af5d897` has the exact unchanged Account parent and candidate parents and head-identical tree `2243bed55dbb95c618d7359eb88a00f49026bc50`; REGION XML SHA-256 is `1dad91fd526143453b9fccdd64702196094dee7d3b0da844938b0875e03a8136`. Account and Game Design jobs also succeeded; aggregate CI was still active at the scoped handoff. This is no proof of complete fresh topology, authenticated `APPLIED`, synchronized reads, released topology, canonical lifecycle delivery or activation. At exact published `add1a85e3374ef0cb93330e96ba76bf5aac526f5`, [CI37341390296](https://github.com/benhook1013/FireMUD/actions/runs/37341390296) World Build and Test succeeded. Independently parsed raw XML proves all twenty-eight required PostgreSQL cases executed once with zero skips, failures or errors: graph eight, publication-fence eight and guarded REGION storage twelve. This includes the repaired retained V28-to-V29 upgrade case with the normal committed-read transaction composition and unchanged-row/frozen-write assertions. The runner merge has the exact unchanged Account parent and published candidate as parents and a head-identical tree. This closes the upgrade fixture proof gap below, not authenticated `APPLIED`, complete fresh topology, synchronized reads, released topology or the Game Session lifecycle handoff. The independent readback extension described next is later work and still requires its own execution. diff --git a/dev-tools/deploy/README.md b/dev-tools/deploy/README.md index 53e6c64938..ca8fba7e1e 100644 --- a/dev-tools/deploy/README.md +++ b/dev-tools/deploy/README.md @@ -26,7 +26,7 @@ The unactivated Account response-envelope materializer now fails closed before s - This tool is not wired into preview, dev-demo, or player-facing deployment and does not itself establish protected source custody, sole-writer RBAC, deployment readback, a freshness-enforcing workload readiness actor, or live rotation/rollout proof. Do not publish the Account Secret mount or enable either credential-envelope producer until those gates are complete; a missing source or Secret is an activation failure, not a reason to generate fresh keys during deployment. - `bootstrap-account-response-envelope-ring.py` - - Unactivated source-bootstrap candidate for a trusted operator, not a normal deploy or PR job. The initial action requires an absolute output file outside this checkout in a pre-existing operator-owned `0700` custody directory, an exact environment and namespace, and an explicit approved `--source-ttl-seconds`; it creates one `0600` source record with distinct random purpose keys, a random key ID and generation, and an immutable source-created freshness anchor. The explicit `rotate` action additionally requires `--previous-source-record` in protected owner-only custody, retains every prior key for decryption, adds distinct new active purpose keys, and binds the new generation to the prior one. Both actions refuse an existing output rather than regenerating on retry and print no key bytes. The custody operator must separately establish durable protected storage, backup, access control, and audit; this helper alone does not prove them. Actual rotation rollout and proven safe retirement of decrypt-only keys still need separate owner evidence. + - Unactivated source-bootstrap candidate for a trusted operator, not a normal deploy or PR job. The initial action requires an absolute output file outside this checkout in a pre-existing operator-owned `0700` custody directory, an exact environment and namespace, and an explicit approved `--source-ttl-seconds`; it creates one `0600` source record with distinct random connect-token, bare-`LOGIN` and pending-reset keys, a random key ID and generation, and an immutable source-created freshness anchor. The explicit `rotate` action additionally requires `--previous-source-record` in protected owner-only custody, retains every prior key for decryption, adds the three distinct new active purpose keys, and binds the new generation to the prior one. Older retained IDs keep their exact original keys; rotation never invents a pending-reset key for an old ID. The [Account owner contract](../../design/architecture/microservices/account-service/api-contracts.md#account-owned-password-reset-authority-commit) owns pending-reset secret and expiry semantics. Both actions refuse an existing output rather than regenerating on retry and print no key bytes. The custody operator must separately establish durable protected storage, backup, access control, and audit; this helper alone does not prove them. Actual rotation rollout and proven safe retirement of decrypt-only keys still need separate owner evidence. - `write-traffic-open-evidence.py` - Canonical writer for hobby traffic-open projection records. diff --git a/dev-tools/deploy/bootstrap-account-response-envelope-ring.py b/dev-tools/deploy/bootstrap-account-response-envelope-ring.py index 9b2a45c54f..ba84684034 100644 --- a/dev-tools/deploy/bootstrap-account-response-envelope-ring.py +++ b/dev-tools/deploy/bootstrap-account-response-envelope-ring.py @@ -37,9 +37,7 @@ SERVICE_ACCOUNT_NAME_PATTERN = re.compile( r"[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?)*\Z" ) -RFC3339_UTC_PATTERN = re.compile( - r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z\Z" -) +RFC3339_UTC_PATTERN = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z\Z") class BootstrapError(Exception): @@ -115,14 +113,19 @@ def _manifest() -> bytes: key_id = _random_identifier(16) bare_login_key = secrets.token_bytes(KEY_BYTES) connect_token_key = secrets.token_bytes(KEY_BYTES) - while connect_token_key == bare_login_key: + pending_reset_key = secrets.token_bytes(KEY_BYTES) + while connect_token_key == bare_login_key or connect_token_key == pending_reset_key: connect_token_key = secrets.token_bytes(KEY_BYTES) + while pending_reset_key in (bare_login_key, connect_token_key): + pending_reset_key = secrets.token_bytes(KEY_BYTES) bare_login_encoded = base64.urlsafe_b64encode(bare_login_key).rstrip(b"=").decode("ascii") connect_token_encoded = base64.urlsafe_b64encode(connect_token_key).rstrip(b"=").decode("ascii") + pending_reset_encoded = base64.urlsafe_b64encode(pending_reset_key).rstrip(b"=").decode("ascii") return ( f"version=1\nactiveKeyId={key_id}\n" f"key:{key_id}:bare-login={bare_login_encoded}\n" f"key:{key_id}:connect-token={connect_token_encoded}\n" + f"key:{key_id}:pending-reset={pending_reset_encoded}\n" ).encode("ascii") @@ -160,9 +163,7 @@ def _source_record_bytes( "materializerUsername": materializer_username, "previousSourceGeneration": previous_source_generation, } - return (json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode( - "utf-8" - ) + return (json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") def build_source_record( @@ -247,36 +248,33 @@ def _read_previous_source_record(path: Path, repository_root: Path): def _rotation_manifest(materializer, previous_manifest: bytes) -> bytes: previous = materializer.parse_manifest(previous_manifest) - previous_material = { - key_material - for purposes in previous.keys.values() - for key_material in purposes.values() - } + previous_material = {key_material for purposes in previous.keys.values() for key_material in purposes.values()} previous_key_ids = set(previous.keys) while True: active_key_id = _random_identifier(16) if active_key_id not in previous_key_ids: break + used_material = set(previous_material) + def fresh_key() -> bytes: while True: candidate = secrets.token_bytes(KEY_BYTES) - if candidate not in previous_material: + if candidate not in used_material: + used_material.add(candidate) return candidate - bare_login_key = fresh_key() - connect_token_key = fresh_key() - while connect_token_key == bare_login_key: - connect_token_key = fresh_key() + active_keys: dict[str, bytes] = {} + for purpose in ("bare-login", "connect-token", "pending-reset"): + active_keys[purpose] = fresh_key() lines = ["version=1", f"activeKeyId={active_key_id}"] for key_id, purposes in previous.keys.items(): - for purpose in ("bare-login", "connect-token"): + for purpose in ("bare-login", "connect-token", "pending-reset"): + if purpose not in purposes: + continue encoded = base64.urlsafe_b64encode(purposes[purpose]).rstrip(b"=").decode("ascii") lines.append(f"key:{key_id}:{purpose}={encoded}") - for purpose, key_material in ( - ("bare-login", bare_login_key), - ("connect-token", connect_token_key), - ): + for purpose, key_material in active_keys.items(): encoded = base64.urlsafe_b64encode(key_material).rstrip(b"=").decode("ascii") lines.append(f"key:{active_key_id}:{purpose}={encoded}") return ("\n".join(lines) + "\n").encode("ascii") diff --git a/dev-tools/deploy/materialize-account-response-envelope-ring.py b/dev-tools/deploy/materialize-account-response-envelope-ring.py index ec44b48ea9..b22010a57b 100644 --- a/dev-tools/deploy/materialize-account-response-envelope-ring.py +++ b/dev-tools/deploy/materialize-account-response-envelope-ring.py @@ -432,7 +432,8 @@ def parse_manifest(manifest: bytes) -> ParsedManifest: keys: dict[str, dict[str, bytes]] = {} seen_material: set[bytes] = set() - allowed_purposes = {"bare-login", "connect-token"} + required_purposes = {"bare-login", "connect-token"} + allowed_purposes = required_purposes | {"pending-reset"} for line in lines[2:]: if line.count("=") != 1: raise MaterializationError("source manifest contains a malformed key line") @@ -462,8 +463,8 @@ def parse_manifest(manifest: bytes) -> ParsedManifest: if not keys or active_key_id not in keys: raise MaterializationError("source manifest does not contain its active key ID") - if any(set(by_purpose) != allowed_purposes for by_purpose in keys.values()): - raise MaterializationError("every retained key ID must contain both Account purposes") + if any(not required_purposes.issubset(by_purpose) for by_purpose in keys.values()): + raise MaterializationError("every retained key ID must contain both Account response purposes") return ParsedManifest(active_key_id, keys) @@ -568,9 +569,7 @@ def _run_kubectl( def _require_target_cluster_binding() -> None: """Fail closed until the trusted target-cluster binding verifier exists.""" - raise MaterializationError( - "target-cluster binding verification is unavailable; Kubernetes access is disabled" - ) + raise MaterializationError("target-cluster binding verification is unavailable; Kubernetes access is disabled") def _verify_materializer_identity(kubectl: str, expected_username: str) -> str: diff --git a/dev-tools/tests/test_account_response_envelope_bootstrap.py b/dev-tools/tests/test_account_response_envelope_bootstrap.py index f8acc78c9e..4ee8892f8d 100644 --- a/dev-tools/tests/test_account_response_envelope_bootstrap.py +++ b/dev-tools/tests/test_account_response_envelope_bootstrap.py @@ -1,5 +1,6 @@ from __future__ import annotations +import base64 import contextlib import datetime as dt import importlib.util @@ -14,22 +15,14 @@ from types import SimpleNamespace from unittest.mock import patch -SCRIPT_PATH = ( - Path(__file__).resolve().parents[1] - / "deploy" - / "bootstrap-account-response-envelope-ring.py" -) +SCRIPT_PATH = Path(__file__).resolve().parents[1] / "deploy" / "bootstrap-account-response-envelope-ring.py" SPEC = importlib.util.spec_from_file_location("account_response_envelope_bootstrap", SCRIPT_PATH) assert SPEC is not None and SPEC.loader is not None BOOTSTRAP = importlib.util.module_from_spec(SPEC) sys.modules[SPEC.name] = BOOTSTRAP SPEC.loader.exec_module(BOOTSTRAP) -MATERIALIZER_PATH = ( - Path(__file__).resolve().parents[1] - / "deploy" - / "materialize-account-response-envelope-ring.py" -) +MATERIALIZER_PATH = Path(__file__).resolve().parents[1] / "deploy" / "materialize-account-response-envelope-ring.py" MATERIALIZER_SPEC = importlib.util.spec_from_file_location("account_response_envelope_materializer", MATERIALIZER_PATH) assert MATERIALIZER_SPEC is not None and MATERIALIZER_SPEC.loader is not None MATERIALIZER = importlib.util.module_from_spec(MATERIALIZER_SPEC) @@ -40,9 +33,7 @@ NOW = dt.datetime(2026, 9, 27, 12, 0, 0, 123400, tzinfo=dt.timezone.utc) ENVIRONMENT_ID = "player-facing-prod" TARGET_NAMESPACE = "account-prod" -MATERIALIZER_USERNAME = ( - "system:serviceaccount:account-prod:firemud-secret-materializer" -) +MATERIALIZER_USERNAME = "system:serviceaccount:account-prod:firemud-secret-materializer" class FakeKubectl: @@ -59,9 +50,7 @@ def __call__(self, command: list[str], **kwargs: object) -> SimpleNamespace: if operation == "auth": return SimpleNamespace( returncode=0, - stdout=json.dumps( - {"status": {"userInfo": {"username": self.username}}} - ), + stdout=json.dumps({"status": {"userInfo": {"username": self.username}}}), stderr="", ) if operation == "get": @@ -128,7 +117,10 @@ def test_output_is_materializer_compatible_with_valid_timestamps_and_null_predec manifest = MATERIALIZER.parse_manifest(source.manifest_bytes) self.assertEqual(manifest.active_key_id, next(iter(manifest.keys))) - self.assertEqual({"bare-login", "connect-token"}, set(manifest.keys[manifest.active_key_id])) + self.assertEqual( + {"bare-login", "connect-token", "pending-reset"}, + set(manifest.keys[manifest.active_key_id]), + ) def test_purpose_keys_are_distinct_random_32_byte_values(self) -> None: self.create() @@ -138,10 +130,29 @@ def test_purpose_keys_are_distinct_random_32_byte_values(self) -> None: keys = manifest.keys[manifest.active_key_id] self.assertEqual(32, len(keys["bare-login"])) self.assertEqual(32, len(keys["connect-token"])) - self.assertNotEqual(keys["bare-login"], keys["connect-token"]) + self.assertEqual(32, len(keys["pending-reset"])) + self.assertEqual(3, len(set(keys.values()))) self.assertNotEqual("key-id", manifest.active_key_id) self.assertNotEqual("source-generation", source.source_generation) + def test_pending_key_redraw_cannot_collide_with_another_purpose(self) -> None: + first_key, second_key, third_key = (bytes([number]) * 32 for number in (1, 2, 3)) + with ( + patch.object(BOOTSTRAP, "_random_identifier", return_value="k1"), + patch.object( + BOOTSTRAP.secrets, + "token_bytes", + side_effect=[first_key, second_key, first_key, second_key, third_key], + ), + ): + manifest_bytes = BOOTSTRAP._manifest() + + manifest = MATERIALIZER.parse_manifest(manifest_bytes) + self.assertEqual( + {"bare-login": first_key, "connect-token": second_key, "pending-reset": third_key}, + manifest.keys["k1"], + ) + def test_rotation_is_parser_and_materializer_compatible_and_retains_old_keys(self) -> None: self.create() previous = MATERIALIZER.read_source_record(self.output) @@ -169,7 +180,100 @@ def test_rotation_is_parser_and_materializer_compatible_and_retains_old_keys(sel self.assertTrue(previous_manifest.key_ids < rotated_manifest.key_ids) for key_id, purposes in previous_manifest.keys.items(): self.assertEqual(purposes, rotated_manifest.keys[key_id]) - self.assertEqual({"bare-login", "connect-token"}, set(rotated_manifest.keys[rotated_manifest.active_key_id])) + self.assertEqual( + {"bare-login", "connect-token", "pending-reset"}, + set(rotated_manifest.keys[rotated_manifest.active_key_id]), + ) + self.assertEqual( + len({key for purpose_keys in rotated_manifest.keys.values() for key in purpose_keys.values()}), + sum(len(purpose_keys) for purpose_keys in rotated_manifest.keys.values()), + ) + + third_output = self.custody_directory / "third-source-record.json" + BOOTSTRAP.create_rotated_source_record( + output=third_output, + previous_source_record=rotated_output, + environment_id=ENVIRONMENT_ID, + namespace=TARGET_NAMESPACE, + source_ttl_seconds=3600, + now=rotation_time + dt.timedelta(minutes=10), + ) + third = MATERIALIZER.read_source_record(third_output) + third_manifest = MATERIALIZER.parse_manifest(third.manifest_bytes) + self.assertTrue(rotated_manifest.key_ids < third_manifest.key_ids) + for key_id, purposes in rotated_manifest.keys.items(): + self.assertEqual(purposes, third_manifest.keys[key_id]) + self.assertEqual( + {"bare-login", "connect-token", "pending-reset"}, + set(third_manifest.keys[third_manifest.active_key_id]), + ) + + fake_kubectl = FakeKubectl() + # Synthetic Kubernetes transcripts establish only exact offline readback behavior. + with ( + patch.object(MATERIALIZER, "_require_target_cluster_binding", return_value=None), + patch.object(MATERIALIZER.subprocess, "run", side_effect=fake_kubectl), + ): + self.assertTrue( + MATERIALIZER.materialize( + self.output, + ENVIRONMENT_ID, + TARGET_NAMESPACE, + 7200, + now=NOW + dt.timedelta(minutes=1), + ) + ) + self.assertTrue( + MATERIALIZER.materialize( + rotated_output, + ENVIRONMENT_ID, + TARGET_NAMESPACE, + 7200, + now=rotation_time + dt.timedelta(minutes=1), + ) + ) + + def test_rotation_upgrades_a_two_purpose_ring_without_inventing_old_pending_keys(self) -> None: + self.create() + original = MATERIALIZER.read_source_record(self.output) + original_manifest = MATERIALIZER.parse_manifest(original.manifest_bytes) + old_id = original_manifest.active_key_id + old_keys = original_manifest.keys[old_id] + legacy_manifest = ( + f"version=1\nactiveKeyId={old_id}\n" + + "".join( + f"key:{old_id}:{purpose}={base64.urlsafe_b64encode(old_keys[purpose]).rstrip(b'=').decode('ascii')}\n" + for purpose in ("bare-login", "connect-token") + ) + ).encode("ascii") + legacy_record = json.loads(self.output.read_text(encoding="utf-8")) + legacy_record["manifestBase64"] = base64.b64encode(legacy_manifest).decode("ascii") + legacy_output = self.custody_directory / "legacy-source-record.json" + legacy_output.write_text( + json.dumps(legacy_record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n", + encoding="utf-8", + ) + os.chmod(legacy_output, 0o600) + + rotated_output = self.custody_directory / "upgraded-source-record.json" + rotation_time = NOW + dt.timedelta(minutes=10) + BOOTSTRAP.create_rotated_source_record( + output=rotated_output, + previous_source_record=legacy_output, + environment_id=ENVIRONMENT_ID, + namespace=TARGET_NAMESPACE, + source_ttl_seconds=3600, + now=rotation_time, + ) + upgraded = MATERIALIZER.read_source_record(rotated_output) + upgraded_manifest = MATERIALIZER.parse_manifest(upgraded.manifest_bytes) + self.assertEqual({"bare-login", "connect-token"}, set(upgraded_manifest.keys[old_id])) + self.assertEqual(old_keys["bare-login"], upgraded_manifest.keys[old_id]["bare-login"]) + self.assertEqual(old_keys["connect-token"], upgraded_manifest.keys[old_id]["connect-token"]) + self.assertEqual( + {"bare-login", "connect-token", "pending-reset"}, + set(upgraded_manifest.keys[upgraded_manifest.active_key_id]), + ) fake_kubectl = FakeKubectl() # These fake Kubernetes transcripts prove offline behavior only; they @@ -180,7 +284,7 @@ def test_rotation_is_parser_and_materializer_compatible_and_retains_old_keys(sel ): self.assertTrue( MATERIALIZER.materialize( - self.output, + legacy_output, ENVIRONMENT_ID, TARGET_NAMESPACE, 7200, @@ -298,8 +402,9 @@ def test_rotation_rejects_oversized_record_before_writing(self) -> None: MaterializationError=MATERIALIZER.MaterializationError, MAX_SOURCE_RECORD_BYTES=1, ) - with patch.object(BOOTSTRAP, "_load_materializer", return_value=size_limited_materializer), self.assertRaisesRegex( - BOOTSTRAP.BootstrapError, "size limit" + with ( + patch.object(BOOTSTRAP, "_load_materializer", return_value=size_limited_materializer), + self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "size limit"), ): BOOTSTRAP.create_rotated_source_record( output=rotated_output, @@ -314,9 +419,11 @@ def test_rotation_rejects_oversized_record_before_writing(self) -> None: def test_rotation_refuses_same_output_without_overwrite_or_regeneration(self) -> None: self.create() first_bytes = self.output.read_bytes() - with patch.object(BOOTSTRAP.secrets, "token_bytes", side_effect=AssertionError("regenerated")), patch.object( - BOOTSTRAP.secrets, "token_urlsafe", side_effect=AssertionError("regenerated") - ), self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "already exists"): + with ( + patch.object(BOOTSTRAP.secrets, "token_bytes", side_effect=AssertionError("regenerated")), + patch.object(BOOTSTRAP.secrets, "token_urlsafe", side_effect=AssertionError("regenerated")), + self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "already exists"), + ): BOOTSTRAP.create_rotated_source_record( output=self.output, previous_source_record=self.output, @@ -390,9 +497,11 @@ def test_output_is_created_once_and_retry_preserves_bytes_without_regeneration(s self.create() first_bytes = self.output.read_bytes() - with patch.object(BOOTSTRAP.secrets, "token_bytes", side_effect=AssertionError("regenerated")), patch.object( - BOOTSTRAP.secrets, "token_urlsafe", side_effect=AssertionError("regenerated") - ), self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "already exists"): + with ( + patch.object(BOOTSTRAP.secrets, "token_bytes", side_effect=AssertionError("regenerated")), + patch.object(BOOTSTRAP.secrets, "token_urlsafe", side_effect=AssertionError("regenerated")), + self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "already exists"), + ): self.create() self.assertEqual(first_bytes, self.output.read_bytes()) @@ -486,7 +595,9 @@ def test_cli_rejects_missing_output_argument(self) -> None: def test_cli_requires_explicit_credential_class_lifetime(self) -> None: with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as raised: - BOOTSTRAP.main(["--output", str(self.output), "--environment-id", ENVIRONMENT_ID, "--namespace", TARGET_NAMESPACE]) + BOOTSTRAP.main( + ["--output", str(self.output), "--environment-id", ENVIRONMENT_ID, "--namespace", TARGET_NAMESPACE] + ) self.assertEqual(2, raised.exception.code) self.assertFalse(self.output.exists()) @@ -521,9 +632,7 @@ def test_initial_creation_rejects_non_target_or_malformed_service_account(self) ): with self.subTest(username=username): output = self.custody_directory / f"invalid-source-{index}.json" - with self.assertRaisesRegex( - BOOTSTRAP.BootstrapError, "service-account username" - ): + with self.assertRaisesRegex(BOOTSTRAP.BootstrapError, "service-account username"): self.create(output=output, materializer_username=username) self.assertFalse(output.exists()) diff --git a/dev-tools/tests/test_account_response_envelope_materializer.py b/dev-tools/tests/test_account_response_envelope_materializer.py index d03bfa6cca..e3a27f5c99 100644 --- a/dev-tools/tests/test_account_response_envelope_materializer.py +++ b/dev-tools/tests/test_account_response_envelope_materializer.py @@ -34,11 +34,18 @@ UNSET = object() -def manifest_for(*, active: str, ids: tuple[str, ...], first_material_number: int = 1) -> bytes: +def manifest_for( + *, + active: str, + ids: tuple[str, ...], + first_material_number: int = 1, + purposes_by_id: dict[str, tuple[str, ...]] | None = None, +) -> bytes: lines = ["version=1", f"activeKeyId={active}"] material_number = first_material_number for key_id in ids: - for purpose in ("bare-login", "connect-token"): + purposes = (purposes_by_id or {}).get(key_id, ("bare-login", "connect-token")) + for purpose in purposes: material = bytes([material_number]) * 32 material_number += 1 encoded = base64.urlsafe_b64encode(material).rstrip(b"=").decode("ascii") @@ -186,9 +193,7 @@ def setUp(self) -> None: self.addCleanup(self.kubectl_patch.stop) # Permit only this test fixture's fake Kubernetes transcripts. This is # offline behavior proof, not authorization for live materialization. - self.target_binding_patch = patch.object( - MATERIALIZER, "_require_target_cluster_binding", return_value=None - ) + self.target_binding_patch = patch.object(MATERIALIZER, "_require_target_cluster_binding", return_value=None) self.target_binding_patch.start() self.addCleanup(self.target_binding_patch.stop) @@ -250,6 +255,39 @@ def run_materializer( now=now, ) + def test_manifest_parser_accepts_optional_pending_reset_purpose(self) -> None: + manifest = manifest_for( + active="k2", + ids=("k1", "k2"), + purposes_by_id={"k2": ("bare-login", "connect-token", "pending-reset")}, + ) + + parsed = MATERIALIZER.parse_manifest(manifest) + + self.assertEqual({"bare-login", "connect-token"}, set(parsed.keys["k1"])) + self.assertEqual({"bare-login", "connect-token", "pending-reset"}, set(parsed.keys["k2"])) + self.assertEqual(5, len({key for values in parsed.keys.values() for key in values.values()})) + + def test_manifest_parser_rejects_missing_original_purpose(self) -> None: + manifest = manifest_for( + active="k1", + ids=("k1",), + purposes_by_id={"k1": ("bare-login", "pending-reset")}, + ) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "both Account response purposes"): + MATERIALIZER.parse_manifest(manifest) + + def test_manifest_parser_rejects_unknown_purpose(self) -> None: + manifest = manifest_for( + active="k1", + ids=("k1",), + purposes_by_id={"k1": ("bare-login", "connect-token", "unknown-purpose")}, + ) + + with self.assertRaisesRegex(MATERIALIZER.MaterializationError, "invalid key identity"): + MATERIALIZER.parse_manifest(manifest) + def test_rfc3339_utc_accepts_canonical_fractional_precision(self) -> None: timestamp = "2026-09-27T12:00:00.00101Z" parsed = MATERIALIZER.parse_rfc3339_utc(timestamp, "source expiry") diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 58ae2db252..ba50e2416d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -55,6 +55,12 @@ public enum Settlement { FAILED_NONPUBLICATION } + /** Terminal reason for an Account source change that made no source mutation. */ + public enum SourceChangeAbortReason { + EXPIRED, + DEFINITIVE_ABORT + } + public record FenceSnapshot( Ordering ordering, byte[] binding, OffsetDateTime reservedAt, OffsetDateTime orderedAt) { public FenceSnapshot { @@ -83,7 +89,9 @@ public record SourceChangeSnapshot( byte[] binding, String status, OffsetDateTime requestedAt, - OffsetDateTime committedAt) { + OffsetDateTime committedAt, + OffsetDateTime abortedAt, + SourceChangeAbortReason abortReason) { public SourceChangeSnapshot { binding = binding.clone(); } @@ -233,9 +241,16 @@ public boolean requestSourceChange(SourceChange change) { Record prior = readChange(change.changeId()); if (prior != null) { requireChange(prior, change); - if ("SOURCE_COMMITTED".equals(prior.get("status", String.class))) { + String priorStatus = prior.get("status", String.class); + if ("SOURCE_COMMITTED".equals(priorStatus)) { return true; } + if ("SOURCE_ABORTED".equals(priorStatus)) { + throw new IllegalStateException("Aborted source change cannot be requested again"); + } + if (!"WAITING".equals(priorStatus)) { + throw new IllegalStateException("Source change has an unsupported terminal state"); + } } else { if (hasWaitingChange(change.sources())) { throw new IllegalStateException("Another authority source change is already pending"); @@ -275,6 +290,16 @@ public boolean sourceMutationPermitted(SourceChange change) { && allAffectedSettled(change.sources()); } + /** A no-mutation cancellation is safe only after every affected owner operation is settled. */ + public boolean sourceAbortPermitted(SourceChange change) { + requireTransaction(); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + return "WAITING".equals(row.get("status", String.class)) + && allAffectedSettled(change.sources()); + } + /** * Same transaction as actual source mutation/event/readback. No RPC or fake source write here. */ @@ -283,18 +308,69 @@ public void markSourceCommitted(SourceChange change) { lockSources(change.sources()); Record row = readChange(change.changeId()); requireChange(row, change); - if ("SOURCE_COMMITTED".equals(row.get("status", String.class))) { + String status = row.get("status", String.class); + if ("SOURCE_COMMITTED".equals(status)) { return; } + if ("SOURCE_ABORTED".equals(status)) { + throw new IllegalStateException("Aborted source change cannot be committed"); + } + if (!"WAITING".equals(status)) { + throw new IllegalStateException("Source change is not waiting"); + } if (!allAffectedSettled(change.sources())) { throw new IllegalStateException("Owner outcomes unresolved"); } - dsl.execute( - "UPDATE " - + CHANGES - + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP" - + " WHERE change_id = ? AND status = 'WAITING'", - change.changeId()); + int updated = + dsl.execute( + "UPDATE " + + CHANGES + + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP" + + " WHERE change_id = ? AND status = 'WAITING'", + change.changeId()); + if (updated != 1) { + throw new IllegalStateException("Draft source change did not commit exactly once"); + } + } + + /** + * Records a terminal no-mutation result. The same ordering-aware settlement predicate used for + * source commit applies: revoke order requires two definitive aborts; commit order requires two + * exact terminal owner readbacks, including a mixed vector. + */ + public void markSourceAborted(SourceChange change, SourceChangeAbortReason reason) { + requireTransaction(); + Objects.requireNonNull(reason, "source-change abort reason"); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + String status = row.get("status", String.class); + if ("SOURCE_ABORTED".equals(status)) { + if (!reason.name().equals(row.get("abort_reason", String.class))) { + throw new IllegalArgumentException("Source change abort reason differs from readback"); + } + return; + } + if ("SOURCE_COMMITTED".equals(status)) { + throw new IllegalStateException("Committed source change cannot be aborted"); + } + if (!"WAITING".equals(status)) { + throw new IllegalStateException("Source change is not waiting"); + } + if (!allAffectedSettled(change.sources())) { + throw new IllegalStateException("Owner outcomes unresolved"); + } + int updated = + dsl.execute( + "UPDATE " + + CHANGES + + " SET status = 'SOURCE_ABORTED', aborted_at = CURRENT_TIMESTAMP, abort_reason = ?" + + " WHERE change_id = ? AND status = 'WAITING'", + reason.name(), + change.changeId()); + if (updated != 1) { + throw new IllegalStateException("Draft source change did not abort exactly once"); + } } /** Exact durable owner readback, supplied only by the future authenticated owner verifier. */ @@ -372,7 +448,9 @@ public List waitingSourceChanges() { row.get("binding", byte[].class), row.get("status", String.class), row.get("requested_at", OffsetDateTime.class), - row.get("committed_at", OffsetDateTime.class))) + row.get("committed_at", OffsetDateTime.class), + row.get("aborted_at", OffsetDateTime.class), + abortReason(row.get("abort_reason", String.class)))) .toList(); } @@ -380,12 +458,36 @@ public SourceChangeSnapshot readSourceChange(SourceChange change) { requireTransaction(); Record row = readChange(change.changeId()); requireChange(row, change); + return sourceChangeSnapshot(row); + } + + /** + * Non-locking exact inspection for callers that must preserve Account/envelope/V57 lock order. + */ + public SourceChangeSnapshot inspectSourceChange(SourceChange change) { + requireTransaction(); + Record row = + dsl.fetchOne("SELECT * FROM " + CHANGES + " WHERE change_id = ?", change.changeId()); + if (row == null) { + throw new IllegalArgumentException("Absent or changed immutable source mutation intent"); + } + requireChange(row, change); + return sourceChangeSnapshot(row); + } + + private SourceChangeSnapshot sourceChangeSnapshot(Record row) { return new SourceChangeSnapshot( - change.changeId(), + row.get("change_id", UUID.class), row.get("binding", byte[].class), row.get("status", String.class), row.get("requested_at", OffsetDateTime.class), - row.get("committed_at", OffsetDateTime.class)); + row.get("committed_at", OffsetDateTime.class), + row.get("aborted_at", OffsetDateTime.class), + abortReason(row.get("abort_reason", String.class))); + } + + private SourceChangeAbortReason abortReason(String value) { + return value == null ? null : SourceChangeAbortReason.valueOf(value); } private void lockSources(List sources) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCrypto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCrypto.java index 3921381452..d80e93cddd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCrypto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopeCrypto.java @@ -17,16 +17,18 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.crypto.AEADBadTagException; import javax.crypto.Cipher; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; /** - * Account-local AES-256-GCM for bounded credential-bearing response envelopes. The mounted manifest - * is read for every operation so atomic rotation and key removal take effect immediately. Callers - * must provide an Account-only mounted path and must read back the exact durable operation/envelope - * before using {@link #decrypt} for recovery. + * Account-local AES-256-GCM for bounded credential-bearing response and pending-reset envelopes. + * The mounted manifest is read for every operation so atomic rotation and key removal take effect + * immediately. Callers must provide an Account-only mounted path and must read back the exact + * durable operation/envelope before using a decrypt method for recovery. * *

Manifest v1 is strict ASCII (an ASCII subset of UTF-8), terminated by one LF: * @@ -37,10 +39,13 @@ * key:k1:connect-token=<43-character-unpadded-base64url> * key:k2:bare-login=<43-character-unpadded-base64url> * key:k2:connect-token=<43-character-unpadded-base64url> + * key:k2:pending-reset=<43-character-unpadded-base64url> * * - * Every key ID must have one independent 32-byte key for each purpose. The active ID is used for - * new writes; retained older IDs are decrypt-only. No default key or classpath fallback exists. + * Every key ID must have independent 32-byte connect-token and bare-LOGIN keys. A pending-reset key + * is optional for retained IDs and is required only for pending-reset operations. The active ID is + * used for new writes; retained older IDs are decrypt-only. No default key or classpath fallback + * exists. */ public final class AccountEnvelopeCrypto { public static final String KEY_RING_PATH_ENVIRONMENT_VARIABLE = @@ -52,8 +57,14 @@ public final class AccountEnvelopeCrypto { private static final int AES_KEY_LENGTH_BYTES = 32; private static final int GCM_TAG_LENGTH_BITS = 128; private static final int MAX_AAD_FIELD_LENGTH_BYTES = 4096; + private static final Pattern ARGON2_VERIFIER_PATTERN = + Pattern.compile( + "\\$argon2(?:i|id)\\$v=19\\$m=([1-9][0-9]*),t=([1-9][0-9]*),p=([1-9][0-9]*)" + + "\\$([A-Za-z0-9+/]+)\\$([A-Za-z0-9+/]+)"); private static final byte[] AAD_DOMAIN = "firemud-account-response-envelope/v1".getBytes(StandardCharsets.US_ASCII); + private static final byte[] PENDING_RESET_AAD_DOMAIN = + "firemud-account-pending-reset-envelope/v1".getBytes(StandardCharsets.US_ASCII); private static final SecureRandom SECURE_RANDOM = new SecureRandom(); private final Path manifestPath; @@ -90,6 +101,43 @@ public AccountEncryptedEnvelope encrypt( throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); } + return encryptWithAssociatedData( + purpose, + plaintext, + (formatVersion, keyId, envelopePurpose) -> + associatedData(formatVersion, keyId, envelopePurpose, binding)); + } + + /** + * Encrypts the exact encoded slow Argon2 verifier for a pending password-reset operation. The + * binding digest is SHA-256 over this encoded verifier; plaintext passwords and fast password + * digests are not valid plaintext for this purpose. + */ + public AccountEncryptedEnvelope encryptPendingReset( + AccountPendingResetEnvelopeBinding binding, byte[] encodedArgon2Verifier) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(encodedArgon2Verifier, "encodedArgon2Verifier"); + if (encodedArgon2Verifier.length == 0 + || encodedArgon2Verifier.length > AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES) { + throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); + } + if (!isWellFormedArgon2Verifier(encodedArgon2Verifier) + || !matchesTargetVerifierDigest(encodedArgon2Verifier, binding)) { + throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); + } + + return encryptWithAssociatedData( + AccountEnvelopePurpose.PENDING_PASSWORD_RESET, + encodedArgon2Verifier, + (formatVersion, keyId, purpose) -> + pendingResetAssociatedData(formatVersion, keyId, purpose, binding)); + } + + private AccountEncryptedEnvelope encryptWithAssociatedData( + AccountEnvelopePurpose purpose, + byte[] plaintext, + AssociatedDataFactory associatedDataFactory) { + try (LoadedKeyRing keyRing = readKeyRing()) { String keyId = keyRing.activeKeyId; byte[] keyBytes = keyRing.keyBytes(keyId, purpose); @@ -101,7 +149,8 @@ public AccountEncryptedEnvelope encrypt( new SecretKeySpec(keyBytes, "AES"), new GCMParameterSpec(GCM_TAG_LENGTH_BITS, nonce)); cipher.updateAAD( - associatedData(AccountEncryptedEnvelope.CURRENT_FORMAT_VERSION, keyId, purpose, binding)); + associatedDataFactory.create( + AccountEncryptedEnvelope.CURRENT_FORMAT_VERSION, keyId, purpose)); byte[] ciphertext = cipher.doFinal(plaintext); return new AccountEncryptedEnvelope( AccountEncryptedEnvelope.CURRENT_FORMAT_VERSION, keyId, purpose, nonce, ciphertext); @@ -124,6 +173,36 @@ public byte[] decrypt( throw failure(AccountEnvelopeCryptoException.Failure.PURPOSE_MISMATCH); } + return decryptWithAssociatedData( + envelope, + (formatVersion, keyId, purpose) -> associatedData(formatVersion, keyId, purpose, binding)); + } + + /** Decrypts a pending-reset envelope only under its complete original typed binding. */ + public byte[] decryptPendingReset( + AccountEncryptedEnvelope envelope, AccountPendingResetEnvelopeBinding binding) { + Objects.requireNonNull(envelope, "envelope"); + Objects.requireNonNull(binding, "binding"); + if (envelope.purpose() != AccountEnvelopePurpose.PENDING_PASSWORD_RESET) { + throw failure(AccountEnvelopeCryptoException.Failure.PURPOSE_MISMATCH); + } + + byte[] encodedArgon2Verifier = + decryptWithAssociatedData( + envelope, + (formatVersion, keyId, purpose) -> + pendingResetAssociatedData(formatVersion, keyId, purpose, binding)); + if (!isWellFormedArgon2Verifier(encodedArgon2Verifier) + || !matchesTargetVerifierDigest(encodedArgon2Verifier, binding)) { + Arrays.fill(encodedArgon2Verifier, (byte) 0); + throw failure(AccountEnvelopeCryptoException.Failure.AUTHENTICATION_FAILED); + } + return encodedArgon2Verifier; + } + + private byte[] decryptWithAssociatedData( + AccountEncryptedEnvelope envelope, AssociatedDataFactory associatedDataFactory) { + try (LoadedKeyRing keyRing = readKeyRing()) { byte[] keyBytes = keyRing.keyBytes(envelope.keyId(), envelope.purpose()); Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); @@ -132,7 +211,8 @@ public byte[] decrypt( new SecretKeySpec(keyBytes, "AES"), new GCMParameterSpec(GCM_TAG_LENGTH_BITS, envelope.nonce())); cipher.updateAAD( - associatedData(envelope.formatVersion(), envelope.keyId(), envelope.purpose(), binding)); + associatedDataFactory.create( + envelope.formatVersion(), envelope.keyId(), envelope.purpose())); return cipher.doFinal(envelope.ciphertext()); } catch (AEADBadTagException exception) { throw failure(AccountEnvelopeCryptoException.Failure.AUTHENTICATION_FAILED); @@ -230,7 +310,8 @@ private static LoadedKeyRing parseManifest(byte[] manifest) { throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); } for (Map.Entry> entry : keys.entrySet()) { - if (entry.getValue().size() != AccountEnvelopePurpose.values().length) { + if (!entry.getValue().containsKey(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE) + || !entry.getValue().containsKey(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE)) { throw failure(AccountEnvelopeCryptoException.Failure.KEY_RING_MALFORMED); } } @@ -350,6 +431,91 @@ private static byte[] associatedData( } } + private static byte[] pendingResetAssociatedData( + int formatVersion, + String keyId, + AccountEnvelopePurpose purpose, + AccountPendingResetEnvelopeBinding binding) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream output = new DataOutputStream(bytes); + writeFrame(output, PENDING_RESET_AAD_DOMAIN); + output.writeInt(formatVersion); + writeFrame(output, utf8(keyId)); + writeFrame(output, utf8(purpose.manifestName())); + writeFrame(output, utf8(binding.accountId().toString())); + writeFrame(output, utf8(binding.tokenHash())); + writeFrame(output, utf8(binding.tokenExpiresAt().toString())); + writeFrame(output, utf8(binding.requestId())); + writeFrame(output, binding.requestDigest()); + writeFrame(output, binding.sourceCaptureDigest()); + writeFrame(output, binding.targetVerifierDigest()); + output.flush(); + if (bytes.size() > MAX_AAD_FIELD_LENGTH_BYTES * 8) { + throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); + } + return bytes.toByteArray(); + } catch (IOException exception) { + throw failure(AccountEnvelopeCryptoException.Failure.CRYPTO_OPERATION_FAILED); + } + } + + private static boolean matchesTargetVerifierDigest( + byte[] encodedArgon2Verifier, AccountPendingResetEnvelopeBinding binding) { + byte[] calculatedDigest = null; + try { + calculatedDigest = MessageDigest.getInstance("SHA-256").digest(encodedArgon2Verifier); + return MessageDigest.isEqual(calculatedDigest, binding.targetVerifierDigest()); + } catch (GeneralSecurityException exception) { + throw failure(AccountEnvelopeCryptoException.Failure.CRYPTO_OPERATION_FAILED); + } finally { + if (calculatedDigest != null) { + Arrays.fill(calculatedDigest, (byte) 0); + } + } + } + + private static boolean isWellFormedArgon2Verifier(byte[] encodedVerifier) { + for (byte value : encodedVerifier) { + if (value < 0x21 || value > 0x7e) { + return false; + } + } + + Matcher matcher = + ARGON2_VERIFIER_PATTERN.matcher(new String(encodedVerifier, StandardCharsets.US_ASCII)); + if (!matcher.matches() + || !isCanonicalPositiveInt(matcher.group(1)) + || !isCanonicalPositiveInt(matcher.group(2)) + || !isCanonicalPositiveInt(matcher.group(3))) { + return false; + } + return isCanonicalBase64(matcher.group(4)) && isCanonicalBase64(matcher.group(5)); + } + + private static boolean isCanonicalPositiveInt(String value) { + try { + return Integer.parseInt(value) > 0; + } catch (NumberFormatException exception) { + return false; + } + } + + private static boolean isCanonicalBase64(String value) { + byte[] decoded = null; + try { + decoded = Base64.getDecoder().decode(value); + return decoded.length > 0 + && Base64.getEncoder().withoutPadding().encodeToString(decoded).equals(value); + } catch (IllegalArgumentException exception) { + return false; + } finally { + if (decoded != null) { + Arrays.fill(decoded, (byte) 0); + } + } + } + private static void writeFrame(DataOutputStream output, byte[] value) throws IOException { if (value.length > MAX_AAD_FIELD_LENGTH_BYTES) { throw failure(AccountEnvelopeCryptoException.Failure.INVALID_ENVELOPE); @@ -473,4 +639,9 @@ public void close() { wipeKeys(keys); } } + + @FunctionalInterface + private interface AssociatedDataFactory { + byte[] create(int formatVersion, String keyId, AccountEnvelopePurpose purpose); + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopePurpose.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopePurpose.java index d8c11f3bfc..2b00e66c22 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopePurpose.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountEnvelopePurpose.java @@ -1,9 +1,10 @@ package net.firedevops.firemud.accountservice.security; -/** The independently keyed response-envelope purposes owned by Account. */ +/** The independently keyed encrypted-envelope purposes owned by Account. */ public enum AccountEnvelopePurpose { CONNECT_TOKEN_RESPONSE("connect-token"), - BARE_LOGIN_RESPONSE("bare-login"); + BARE_LOGIN_RESPONSE("bare-login"), + PENDING_PASSWORD_RESET("pending-reset"); private final String manifestName; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPendingResetEnvelopeBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPendingResetEnvelopeBinding.java new file mode 100644 index 0000000000..ccf5ee3413 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountPendingResetEnvelopeBinding.java @@ -0,0 +1,127 @@ +package net.firedevops.firemud.accountservice.security; + +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; + +/** Exact immutable source evidence authenticated with a pending password-reset verifier. */ +public record AccountPendingResetEnvelopeBinding( + UUID accountId, + String tokenHash, + LocalDateTime tokenExpiresAt, + String requestId, + byte[] requestDigest, + byte[] sourceCaptureDigest, + byte[] targetVerifierDigest) { + + private static final int DIGEST_LENGTH_BYTES = 32; + private static final int MAX_TEXT_LENGTH_BYTES = 4096; + + public AccountPendingResetEnvelopeBinding { + Objects.requireNonNull(accountId, "accountId"); + if (accountId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Invalid accountId"); + } + tokenHash = requireTokenHash(tokenHash); + Objects.requireNonNull(tokenExpiresAt, "tokenExpiresAt"); + requestId = requireText(requestId, "requestId"); + requestDigest = copyDigest(requestDigest, "requestDigest"); + sourceCaptureDigest = copyDigest(sourceCaptureDigest, "sourceCaptureDigest"); + targetVerifierDigest = copyDigest(targetVerifierDigest, "targetVerifierDigest"); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] sourceCaptureDigest() { + return sourceCaptureDigest.clone(); + } + + @Override + public byte[] targetVerifierDigest() { + return targetVerifierDigest.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AccountPendingResetEnvelopeBinding that)) { + return false; + } + return accountId.equals(that.accountId) + && tokenHash.equals(that.tokenHash) + && tokenExpiresAt.equals(that.tokenExpiresAt) + && requestId.equals(that.requestId) + && Arrays.equals(requestDigest, that.requestDigest) + && Arrays.equals(sourceCaptureDigest, that.sourceCaptureDigest) + && Arrays.equals(targetVerifierDigest, that.targetVerifierDigest); + } + + @Override + public int hashCode() { + int result = Objects.hash(accountId, tokenHash, tokenExpiresAt, requestId); + result = 31 * result + Arrays.hashCode(requestDigest); + result = 31 * result + Arrays.hashCode(sourceCaptureDigest); + result = 31 * result + Arrays.hashCode(targetVerifierDigest); + return result; + } + + @Override + public String toString() { + return "AccountPendingResetEnvelopeBinding{evidence=}"; + } + + private static String requireTokenHash(String value) { + Objects.requireNonNull(value, "tokenHash"); + if (value.length() != 64) { + throw new IllegalArgumentException("Invalid tokenHash"); + } + for (int index = 0; index < value.length(); index++) { + char character = value.charAt(index); + if (!((character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'))) { + throw new IllegalArgumentException("Invalid tokenHash"); + } + } + return value; + } + + private static String requireText(String value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.isBlank() + || hasUnpairedSurrogate(value) + || value.getBytes(StandardCharsets.UTF_8).length > MAX_TEXT_LENGTH_BYTES) { + throw new IllegalArgumentException("Invalid " + fieldName); + } + return value; + } + + private static byte[] copyDigest(byte[] value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.length != DIGEST_LENGTH_BYTES) { + throw new IllegalArgumentException(fieldName + " must be 32 bytes"); + } + return Arrays.copyOf(value, value.length); + } + + private static boolean hasUnpairedSurrogate(String value) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + return true; + } + index++; + } else if (Character.isLowSurrogate(current)) { + return true; + } + } + return false; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java index 3f2aa5ada4..406af7927d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java @@ -7,6 +7,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; @@ -48,6 +49,7 @@ public final class AccountLogoutAllAuthorityEventProducer { private final AccountAuthorityOutboxRepository outboxRepository; private final AccountLogoutAllOperationRepository operationRepository; private final AccountAuthoritySourceEventReadback sourceReadback; + private final AccountLogoutAllDraftSourceChangeRepository draftSourceChanges; private final TransactionTemplate ownerTransaction; public AccountLogoutAllAuthorityEventProducer( @@ -68,6 +70,7 @@ public AccountLogoutAllAuthorityEventProducer( Objects.requireNonNull(operationRepository, "logout-all operation repository is required"); this.sourceReadback = Objects.requireNonNull(sourceReadback, "Account source-event readback is required"); + this.draftSourceChanges = new AccountLogoutAllDraftSourceChangeRepository(dsl); Objects.requireNonNull(dsl, "transaction-aware DSLContext is required"); Objects.requireNonNull(transactionManager, "Account transaction manager is required"); @@ -82,7 +85,9 @@ public AccountLogoutAllAuthorityEventProducer( *

The request digest is recomputed from the exact closed operation tuple and compared with the * supplied lowercase SHA-256 binding. The token profile and digest correlate the receipt; neither * is proof of caller authorization. The supplied Account association and scope state are compared - * against locked persisted state. + * against locked persisted state for a new request. A pending exact retry recovers its original + * server-resolved counters and capture rather than treating a changed retry snapshot as new + * caller identity. */ public LogoutAllResult commit( UUID requestId, @@ -97,7 +102,7 @@ public LogoutAllResult commit( validateExpectedInputs(verifiedAccountAssociation, expectedAccountState); requireNoAmbientTransaction(); - LogoutAllReceipt transactionResult = + CommitAttempt transactionResult = ownerTransaction.execute( status -> commitInOwnerTransaction( @@ -109,7 +114,17 @@ public LogoutAllResult commit( verifiedAccountAssociation, expectedAccountState)); if (transactionResult == null) { - throw new IllegalStateException("Logout-all source transaction returned no receipt"); + throw new IllegalStateException("Logout-all source transaction returned no result"); + } + if (transactionResult.pendingChange() != null) { + ownerTransaction.executeWithoutResult( + status -> + draftSourceChanges.verifyWaiting( + requestId, + transactionResult.requestPayload(), + transactionResult.pendingChange())); + throw new AccountLogoutAllDraftSourceChangeRepository.PendingSourceChangeException( + transactionResult.pendingChange().changeId()); } LogoutAllReceipt committedResult = @@ -120,14 +135,14 @@ public LogoutAllResult commit( tokenProfile, presentedTokenHash, verifiedAccountAssociation); - if (!transactionResult.equals(committedResult)) { + if (!transactionResult.receipt().equals(committedResult)) { throw new IllegalStateException( "Post-commit logout-all receipt differs from the source transaction result"); } return LogoutAllResult.valueOf(committedResult.lifecycleResult()); } - private LogoutAllReceipt commitInOwnerTransaction( + private CommitAttempt commitInOwnerTransaction( UUID requestId, int requestDigestVersion, String requestDigest, @@ -143,6 +158,14 @@ private LogoutAllReceipt commitInOwnerTransaction( Optional priorRequest = operationRepository.findByRequestId(requestId); Optional priorToken = operationRepository.findByPresentedTokenHash(presentedTokenHash); + byte[] requestPayload = + draftSourceChanges.requestBinding( + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + account); if (priorRequest.isPresent()) { LogoutAllReceipt receipt = priorRequest.orElseThrow(); requireExactRetryBinding( @@ -156,13 +179,28 @@ private LogoutAllReceipt commitInOwnerTransaction( if (priorToken.isEmpty() || !receipt.equals(priorToken.orElseThrow())) { throw new IllegalStateException("Logout-all token receipt index readback is inconsistent"); } - return recoverReceipt(account, receipt); + Event historicalEvent = + outboxRepository + .findEvent(receipt.outboxStreamKey(), receipt.outboxSequence()) + .orElseThrow( + () -> new IllegalStateException("Logout-all historical event is missing")); + draftSourceChanges.verifyCommittedIfPresent(requestId, requestPayload, historicalEvent); + return new CommitAttempt(recoverReceipt(account, receipt), null, requestPayload); } if (priorToken.isPresent()) { throw new OperationConflictException( "Presented token identity is already bound to another logout-all request"); } + Optional originalPending = + draftSourceChanges.findPending( + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + account); + if (requestDigestVersion != DIGEST_VERSION) { throw new IllegalArgumentException("Logout-all request digest version must be 1"); } @@ -175,7 +213,7 @@ private LogoutAllReceipt commitInOwnerTransaction( } ScopeState current = generationRepository.read(AuthorityScope.account(account.getAccountUuid())); - if (!current.equals(expectedAccountState)) { + if (originalPending.isEmpty() && !current.equals(expectedAccountState)) { throw new IllegalStateException("Logout-all Account source compare-and-advance is stale"); } AccountAuthoritySourceEventReadback.LatestSourceSnapshot source = @@ -189,6 +227,24 @@ private LogoutAllReceipt commitInOwnerTransaction( String streamKey = streamKey(account.getAccountUuid()); String eventId = EVENT_ID_PREFIX + requestText; + AccountLogoutAllDraftSourceChangeRepository.Participation participation = + draftSourceChanges.participate( + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + account, + current, + source); + SourceChange sourceChange = participation.change(); + if (!participation.settled()) { + return new CommitAttempt(null, sourceChange, requestPayload); + } + if (!draftSourceChanges.permitted(sourceChange)) { + throw new IllegalStateException("Settled logout-all source change is not permitted"); + } + ScopeState advanced = generationRepository.advance(current, current.issuanceFence()); requireAdvancedState(current, advanced, nextGeneration, nextSourceVersion, nextIssuanceFence); @@ -262,6 +318,7 @@ private LogoutAllReceipt commitInOwnerTransaction( || !appended.equals(latest.latestEvent().orElseThrow())) { throw new IllegalStateException("Logout-all current source checkpoint readback differs"); } + draftSourceChanges.complete(requestId, requestPayload, sourceChange, appended); requireReceiptReadback( receipt, requestId, @@ -270,7 +327,7 @@ private LogoutAllReceipt commitInOwnerTransaction( tokenProfile, presentedTokenHash, account); - return receipt; + return new CommitAttempt(receipt, null, requestPayload); } private LogoutAllReceipt recoverReceipt(Account account, LogoutAllReceipt receipt) { @@ -324,6 +381,22 @@ private LogoutAllReceipt readCommittedOperation( tokenProfile, presentedTokenHash, account); + Event event = + outboxRepository + .findEvent(committed.outboxStreamKey(), committed.outboxSequence()) + .orElseThrow( + () -> + new IllegalStateException("Logout-all historical event is missing")); + draftSourceChanges.verifyCommittedIfPresent( + requestId, + draftSourceChanges.requestBinding( + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + account), + event); return recoverReceipt(account, committed); }); if (receipt == null) { @@ -359,6 +432,20 @@ private LogoutAllReceipt requireReceiptReadback( || !expected.equals(byToken.orElseThrow())) { throw new IllegalStateException("Logout-all receipt readback differs from its insert"); } + Event event = + outboxRepository + .findEvent(expected.outboxStreamKey(), expected.outboxSequence()) + .orElseThrow(() -> new IllegalStateException("Logout-all event readback is missing")); + draftSourceChanges.verifyCommittedIfPresent( + requestId, + draftSourceChanges.requestBinding( + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + account), + event); return byRequest; } @@ -388,7 +475,9 @@ private Account lockVerifiedAccount(Account requestedAccount) { accountRepository .findByIdForUpdate(requestedAccount.getId()) .orElseThrow( - () -> new IllegalStateException("Verified Account association is missing")); + () -> + new OperationConflictException( + "Logout-all Account identity binding is absent from persisted Account state")); if (!Objects.equals(requestedAccount.getId(), locked.getId()) || !Objects.equals(requestedAccount.getAccountUuid(), locked.getAccountUuid()) || !Objects.equals( @@ -396,7 +485,8 @@ private Account lockVerifiedAccount(Account requestedAccount) { locked.getAccountUuidSourceNumericId()) || requestedAccount.getAccountUuidProvenance() != locked.getAccountUuidProvenance() || !isVerifiedProvenance(locked.getAccountUuidProvenance())) { - throw new IllegalStateException("Verified Account association changed before logout-all"); + throw new OperationConflictException( + "Logout-all Account identity binding conflicts with persisted Account identity"); } // The source readback enforces that this is an exact persisted UUID association. if (locked.getId() == null @@ -565,6 +655,9 @@ private boolean constantTimeTextEquals(String left, String right) { left.getBytes(StandardCharsets.US_ASCII), right.getBytes(StandardCharsets.US_ASCII)); } + private record CommitAttempt( + LogoutAllReceipt receipt, SourceChange pendingChange, byte[] requestPayload) {} + private long incrementExact(long value, String field) { try { return Math.addExact(value, 1L); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllDraftSourceChangeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllDraftSourceChangeRepository.java new file mode 100644 index 0000000000..c9cbb17680 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllDraftSourceChangeRepository.java @@ -0,0 +1,484 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Exact Account logout-all request journal linked to the V57 Draft authorization fence. */ +public final class AccountLogoutAllDraftSourceChangeRepository { + private static final String TABLE = "account_logout_all_draft_source_changes"; + private static final String REQUEST_SCHEMA = "account-logout-all-draft-source-request/v1"; + private static final String MUTATION_SCHEMA = "account-logout-all-draft-source-mutation/v1"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private final DSLContext dsl; + private final DraftAuthorizationFenceRepository fences; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The transaction-aware DSLContext is an internal persistence collaborator.") + public AccountLogoutAllDraftSourceChangeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + this.fences = new DraftAuthorizationFenceRepository(dsl); + } + + /** Captures one exact logout request and its already verified current Account source. */ + Participation participate( + UUID requestId, + int digestVersion, + String digest, + String tokenProfile, + String tokenHash, + Account account, + ScopeState current, + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest) { + requireTransaction(); + byte[] request = + requestBytes(requestId, digestVersion, digest, tokenProfile, tokenHash, account); + SourceEvidence evidence = capture(account, current, latest); + Record prior = findByRequestId(requestId); + SourceChange change; + if (prior != null) { + change = requireRequest(prior, request, account); + if (!"WAITING".equals(prior.get("status", String.class))) { + throw new IllegalStateException("Completed logout-all source request has no receipt"); + } + if (!Arrays.equals(change.sources().getFirst().canonicalBytes(), evidence.canonicalBytes()) + || !sameState(prior, current)) { + throw new IllegalStateException( + "Pending logout-all source request no longer matches its original capture"); + } + } else { + if (findByTokenHash(tokenHash) != null) { + throw new IllegalStateException( + "Presented token identity is already bound to another pending logout-all request"); + } + byte[] mutation = mutationBytes(request, current, latest, evidence.canonicalBytes()); + change = new SourceChange(UUID.randomUUID(), List.of(evidence), mutation); + } + + boolean settled = fences.requestSourceChange(change); + if (prior == null) { + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, account_id, account_uuid, request_digest_version, request_digest," + + " token_profile, presented_token_hash, expected_generation, expected_source_version," + + " expected_issuance_fence, expected_issuance_fence_source_version, checkpoint_stream," + + " checkpoint_sequence, capture_evidence, request_payload, source_evidence, source_change_id," + + " source_change_request, source_change_binding, status)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'WAITING')", + requestId, + account.getId(), + account.getAccountUuid(), + digestVersion, + decodeHex(digest), + tokenProfile, + decodeHex(tokenHash), + current.generation(), + current.sourceVersion(), + current.issuanceFence().value(), + current.issuanceFence().sourceVersion(), + evidence.checkpointStream(), + latest.outboxSequence(), + captureEvidence(account, current, latest), + request, + evidence.canonicalBytes(), + change.changeId(), + change.mutation(), + change.canonicalBytes()); + } + Record stored = findByRequestId(requestId); + SourceChange readback = requireRequest(stored, request, account); + if (!Arrays.equals(readback.canonicalBytes(), change.canonicalBytes())) { + throw new IllegalStateException( + "Logout-all source request readback differs from its capture"); + } + return new Participation(change, settled); + } + + /** Exact caller-binding lookup used before server-derived counters on retry. */ + Optional findPending( + UUID requestId, + int digestVersion, + String digest, + String tokenProfile, + String tokenHash, + Account account) { + requireTransaction(); + Record row = findByRequestId(requestId); + if (row == null) { + Record token = findByTokenHash(tokenHash); + if (token != null) { + requireRequest( + token, + requestBytes(requestId, digestVersion, digest, tokenProfile, tokenHash, account), + account); + } + return Optional.empty(); + } + SourceChange change = + requireRequest( + row, + requestBytes(requestId, digestVersion, digest, tokenProfile, tokenHash, account), + account); + if (!"WAITING".equals(row.get("status", String.class))) { + throw new IllegalStateException( + "Committed logout-all source intent has no operation receipt"); + } + return Optional.of(change); + } + + byte[] requestBinding( + UUID requestId, + int digestVersion, + String digest, + String tokenProfile, + String tokenHash, + Account account) { + return requestBytes(requestId, digestVersion, digest, tokenProfile, tokenHash, account); + } + + /** Read-only exact journal evidence for owner-local recovery and PostgreSQL proof. */ + public Optional readPendingIntent(UUID requestId) { + requireTransaction(); + Record row = findByRequestId(requestId); + if (row == null) { + return Optional.empty(); + } + requireRequest(row, row.get("request_payload", byte[].class), null); + return Optional.of(snapshot(row)); + } + + boolean permitted(SourceChange change) { + return fences.sourceMutationPermitted(change); + } + + /** Source counters, receipt/outbox and both journal transitions share one owner transaction. */ + void complete(UUID requestId, byte[] request, SourceChange change, Event event) { + requireTransaction(); + fences.markSourceCommitted(change); + int updated = + dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP," + + " event_stream = ?, event_sequence = ?, event_id = ?, event_digest = ?, event_payload = ?" + + " WHERE request_id = ? AND source_change_id = ? AND status = 'WAITING'", + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.payload(), + requestId, + change.changeId()); + if (updated != 1) { + throw new IllegalStateException("Logout-all source request did not complete exactly once"); + } + verifyCommittedIfPresent(requestId, request, event); + } + + void verifyCommittedIfPresent(UUID requestId, byte[] request, Event event) { + requireTransaction(); + Record row = findByRequestId(requestId); + if (row == null) return; + SourceChange change = requireRequest(row, request, null); + if (!"SOURCE_COMMITTED".equals(row.get("status", String.class)) + || !"SOURCE_COMMITTED".equals(fences.readSourceChange(change).status()) + || !event.outboxStreamKey().equals(row.get("event_stream", String.class)) + || !Long.valueOf(event.outboxSequence()).equals(row.get("event_sequence", Long.class)) + || !event.eventId().equals(row.get("event_id", String.class)) + || !event.eventDigest().equals(row.get("event_digest", String.class)) + || !Arrays.equals(event.payload(), row.get("event_payload", byte[].class))) { + throw new IllegalStateException("Logout-all source request and retained event differ"); + } + } + + void verifyWaiting(UUID requestId, byte[] request, SourceChange change) { + requireTransaction(); + Record row = findByRequestId(requestId); + SourceChange stored = requireRequest(row, request, null); + if (!Arrays.equals(stored.canonicalBytes(), change.canonicalBytes()) + || !"WAITING".equals(row.get("status", String.class)) + || !"WAITING".equals(fences.readSourceChange(stored).status())) { + throw new IllegalStateException( + "Logout-all pending intent readback differs from its capture"); + } + } + + private Record findByRequestId(UUID requestId) { + return dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", requestId); + } + + private Record findByTokenHash(String tokenHash) { + return dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE presented_token_hash = ? FOR UPDATE", + decodeHex(tokenHash)); + } + + private SourceChange requireRequest(Record row, byte[] request, Account account) { + if (row == null || !Arrays.equals(request, row.get("request_payload", byte[].class))) { + throw new AccountLogoutAllAuthorityEventProducer.OperationConflictException( + "Logout-all request, token, or Account binding conflicts with its pending intent"); + } + if (account != null + && (!account.getId().equals(row.get("account_id", Long.class)) + || !account.getAccountUuid().equals(row.get("account_uuid", UUID.class)))) { + throw new AccountLogoutAllAuthorityEventProducer.OperationConflictException( + "Logout-all Account binding conflicts with its pending intent"); + } + SourceChange change = SourceChange.fromStored(row.get("source_change_binding", byte[].class)); + byte[] expectedMutation = + mutationBytes( + row.get("request_payload", byte[].class), + row.get("expected_generation", Long.class), + row.get("expected_source_version", Long.class), + row.get("expected_issuance_fence", Long.class), + row.get("expected_issuance_fence_source_version", Long.class), + row.get("checkpoint_sequence", Long.class), + row.get("source_evidence", byte[].class)); + if (!change.changeId().equals(row.get("source_change_id", UUID.class)) + || !Arrays.equals(change.mutation(), row.get("source_change_request", byte[].class)) + || !Arrays.equals(expectedMutation, change.mutation()) + || !Arrays.equals( + change.sources().getFirst().canonicalBytes(), row.get("source_evidence", byte[].class)) + || !change + .sources() + .getFirst() + .key() + .equals("ACCOUNT:" + row.get("account_uuid", UUID.class))) { + throw new IllegalStateException("Logout-all journal differs from its immutable V57 capture"); + } + fences.readSourceChange(change); + return change; + } + + private PendingIntentSnapshot snapshot(Record row) { + return new PendingIntentSnapshot( + row.get("request_id", UUID.class), + row.get("source_change_id", UUID.class), + row.get("request_payload", byte[].class), + row.get("capture_evidence", byte[].class), + row.get("source_evidence", byte[].class), + row.get("source_change_request", byte[].class), + row.get("source_change_binding", byte[].class), + row.get("status", String.class), + row.get("expected_generation", Long.class), + row.get("expected_source_version", Long.class), + row.get("expected_issuance_fence", Long.class), + row.get("expected_issuance_fence_source_version", Long.class), + row.get("checkpoint_sequence", Long.class)); + } + + private boolean sameState(Record row, ScopeState current) { + return current.generation() == row.get("expected_generation", Long.class) + && current.sourceVersion() == row.get("expected_source_version", Long.class) + && current.issuanceFence().value() == row.get("expected_issuance_fence", Long.class) + && current.issuanceFence().sourceVersion() + == row.get("expected_issuance_fence_source_version", Long.class); + } + + private static SourceEvidence capture( + Account account, + ScopeState current, + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest) { + String stream = STREAM_PREFIX + account.getAccountUuid(); + if (latest.outboxSequence() == 0L && latest.latestEvent().isPresent()) { + throw new IllegalStateException("Account source baseline has contradictory event evidence"); + } + if (latest.outboxSequence() > 0L && latest.latestEvent().isEmpty()) { + throw new IllegalStateException("Account source checkpoint has no exact latest event"); + } + byte[] evidence = captureEvidence(account, current, latest); + return new SourceEvidence( + SourceKind.ACCOUNT, + account.getAccountUuid().toString(), + Long.toString(current.generation()), + Long.toString(current.sourceVersion()), + stream, + Long.toString(latest.outboxSequence()), + evidence); + } + + private static byte[] captureEvidence( + Account account, + ScopeState current, + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest) { + String stream = STREAM_PREFIX + account.getAccountUuid(); + return latest + .latestEvent() + .map(Event::payload) + .orElseGet( + () -> + framed( + List.of( + "account-draft-source-baseline/v1", + account.getAccountUuid().toString(), + Long.toString(current.generation()), + Long.toString(current.sourceVersion()), + stream, + "0"))); + } + + private static byte[] requestBytes( + UUID requestId, + int digestVersion, + String digest, + String tokenProfile, + String tokenHash, + Account account) { + return framed( + List.of( + REQUEST_SCHEMA, + requestId.toString(), + Long.toString(account.getId()), + account.getAccountUuid().toString(), + Integer.toString(digestVersion), + decodeHex(digest), + tokenProfile, + decodeHex(tokenHash))); + } + + private static byte[] mutationBytes( + byte[] request, + ScopeState current, + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest, + byte[] sourceEvidence) { + return mutationBytes( + request, + current.generation(), + current.sourceVersion(), + current.issuanceFence().value(), + current.issuanceFence().sourceVersion(), + latest.outboxSequence(), + sourceEvidence); + } + + private static byte[] mutationBytes( + byte[] request, + long generation, + long sourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + long checkpointSequence, + byte[] sourceEvidence) { + return framed( + List.of( + MUTATION_SCHEMA, + request, + Long.toString(generation), + Long.toString(sourceVersion), + Long.toString(issuanceFence), + Long.toString(issuanceFenceSourceVersion), + Long.toString(checkpointSequence), + sourceEvidence)); + } + + private static byte[] framed(List fields) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (Object field : fields) { + byte[] bytes = + field instanceof byte[] binary + ? binary + : field.toString().getBytes(StandardCharsets.UTF_8); + output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + output.writeBytes(bytes); + } + return output.toByteArray(); + } + + private static byte[] decodeHex(String value) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Logout-all digest binding must be lowercase SHA-256 hex"); + } + return java.util.HexFormat.of().parseHex(value); + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Writable Account transaction required for logout-all source fence"); + } + } + + record Participation(SourceChange change, boolean settled) {} + + public record PendingIntentSnapshot( + UUID requestId, + UUID sourceChangeId, + byte[] requestPayload, + byte[] captureEvidence, + byte[] sourceEvidence, + byte[] sourceChangeRequest, + byte[] sourceChangeBinding, + String status, + long expectedGeneration, + long expectedSourceVersion, + long expectedIssuanceFence, + long expectedIssuanceFenceSourceVersion, + long checkpointSequence) { + public PendingIntentSnapshot { + requestPayload = requestPayload.clone(); + captureEvidence = captureEvidence.clone(); + sourceEvidence = sourceEvidence.clone(); + sourceChangeRequest = sourceChangeRequest.clone(); + sourceChangeBinding = sourceChangeBinding.clone(); + } + + @Override + public byte[] requestPayload() { + return requestPayload.clone(); + } + + @Override + public byte[] captureEvidence() { + return captureEvidence.clone(); + } + + @Override + public byte[] sourceEvidence() { + return sourceEvidence.clone(); + } + + @Override + public byte[] sourceChangeRequest() { + return sourceChangeRequest.clone(); + } + + @Override + public byte[] sourceChangeBinding() { + return sourceChangeBinding.clone(); + } + } + + /** Pending source intent is durable and carries no permission to advance Account state. */ + public static final class PendingSourceChangeException extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final UUID sourceChangeId; + + public PendingSourceChangeException(UUID sourceChangeId) { + super("Draft owner outcomes remain pending for logout-all source change " + sourceChangeId); + this.sourceChangeId = Objects.requireNonNull(sourceChangeId); + } + + public UUID sourceChangeId() { + return sourceChangeId; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java new file mode 100644 index 0000000000..3f12b07a87 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java @@ -0,0 +1,1309 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChangeAbortReason; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.accountservice.security.AccountPendingResetEnvelopeBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Exact Account password-reset owner journal linked to the V57 Draft authorization fence. Methods + * require the caller's writable Account transaction and lock Account before journal and envelope + * rows; V57 source participation then acquires its canonical sorted source locks. No source writer, + * authentication producer, cleanup worker, or Spring component is registered here. + */ +public final class AccountPasswordResetDraftSourceChangeRepository { + private static final String JOURNAL = "account_password_reset_draft_source_changes"; + private static final String ENVELOPES = "account_password_reset_pending_envelopes"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final String REQUEST_PREFIX = "account-password-reset-request-v1:"; + private static final String EVENT_PREFIX = "account-password-reset-event-v1:"; + private static final String REQUEST_DIGEST_SCHEMA = "account-password-reset-request/v1"; + private static final String REQUEST_SCHEMA = "account-password-reset-draft-source-request/v1"; + private static final String MUTATION_SCHEMA = "account-password-reset-draft-source-mutation/v1"; + private static final HexFormat HEX = HexFormat.of(); + + private final DSLContext dsl; + private final DraftAuthorizationFenceRepository fences; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The transaction-aware DSLContext is an internal persistence collaborator.") + public AccountPasswordResetDraftSourceChangeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + this.fences = new DraftAuthorizationFenceRepository(dsl); + } + + /** + * Captures the original reset identity and complete current Account event/baseline. The caller + * must already have authenticated and revalidated the source; this helper does neither. + */ + public PendingResetIntent captureIntent( + Account account, + String tokenHash, + LocalDateTime tokenExpiresAt, + byte[] requestDigest, + byte[] targetVerifierDigest, + ScopeState current, + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest, + UUID sourceChangeId) { + requireAccount(account); + Objects.requireNonNull(current, "Account authority state is required"); + Objects.requireNonNull(latest, "Account source checkpoint is required"); + Objects.requireNonNull(sourceChangeId, "source-change identity is required"); + byte[] tokenHashBytes = decodeDigest(tokenHash, "token hash"); + byte[] checkedRequestDigest = checkedDigest(requestDigest, "request digest"); + byte[] checkedTargetDigest = checkedDigest(targetVerifierDigest, "target verifier digest"); + if (tokenExpiresAt == null + || !current + .scope() + .equals( + net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.AuthorityScope.account( + account.getAccountUuid())) + || current.issuanceFence() == null + || !account.getAccountUuid().equals(current.issuanceFence().accountId())) { + throw new IllegalArgumentException("Original Account source binding is incomplete"); + } + String requestId = REQUEST_PREFIX + tokenHash; + byte[] expectedDigest = + requestDigest(account.getAccountUuid(), tokenHash, tokenExpiresAt, checkedTargetDigest); + if (!MessageDigest.isEqual(expectedDigest, checkedRequestDigest)) { + throw new IllegalArgumentException("Password-reset request digest is inconsistent"); + } + byte[] capture = captureEvidence(account, current, latest); + SourceEvidence evidence = + new SourceEvidence( + SourceKind.ACCOUNT, + account.getAccountUuid().toString(), + Long.toString(current.generation()), + Long.toString(current.sourceVersion()), + STREAM_PREFIX + account.getAccountUuid(), + Long.toString(latest.outboxSequence()), + capture); + byte[] request = + requestPayload( + requestId, + account.getId(), + account.getAccountUuid(), + checkedRequestDigest, + tokenHashBytes, + tokenExpiresAt, + checkedTargetDigest); + byte[] captureDigest = sha256(capture); + byte[] mutation = + mutationPayload( + request, + current.generation(), + current.sourceVersion(), + current.issuanceFence().value(), + current.issuanceFence().sourceVersion(), + latest.outboxSequence(), + evidence.canonicalBytes(), + captureDigest); + SourceChange change = new SourceChange(sourceChangeId, List.of(evidence), mutation); + return new PendingResetIntent( + account.getId(), + account.getAccountUuid(), + tokenHash, + tokenExpiresAt, + checkedRequestDigest, + checkedTargetDigest, + current.generation(), + current.sourceVersion(), + current.issuanceFence().value(), + current.issuanceFence().sourceVersion(), + latest.outboxSequence(), + capture, + evidence.canonicalBytes(), + request, + change); + } + + /** + * Locks Account first, then returns exact durable intent and envelope-presence evidence. An + * absent journal is not authority to recreate an envelope or recover a verifier from a backup. + */ + public Optional findForUpdate( + long accountId, UUID accountUuid, String tokenHash) { + requireTransaction(); + requireIdentity(accountId, accountUuid); + byte[] tokenHashBytes = decodeDigest(tokenHash, "token hash"); + lockAccount(accountId, accountUuid); + Record row = + dsl.fetchOne( + "SELECT * FROM " + JOURNAL + " WHERE token_hash = ? FOR UPDATE", tokenHashBytes); + if (row == null) { + return Optional.empty(); + } + boolean hasEnvelope = envelopeExists(row.get("request_id", String.class)); + PendingResetIntent intent = requireStoredIntent(row); + if (intent.accountId() != accountId || !intent.accountUuid().equals(accountUuid)) { + throw new IllegalStateException("Pending reset belongs to a different Account"); + } + return Optional.of(snapshot(row, intent, hasEnvelope)); + } + + /** + * Begins the exact V57 source participation. A fresh settled operation may omit ciphertext only + * because its caller must commit the matching reset in this same transaction. An unresolved + * WAITING operation always needs its separate pending-reset envelope or the transaction fails. + */ + public Participation beginWaiting( + PendingResetIntent intent, Optional pendingEnvelope) { + requireTransaction(); + Objects.requireNonNull(intent, "pending reset intent"); + Objects.requireNonNull(pendingEnvelope, "pending envelope optional"); + pendingEnvelope.ifPresent( + envelope -> { + if (envelope.purpose() != AccountEnvelopePurpose.PENDING_PASSWORD_RESET) { + throw new IllegalArgumentException( + "Pending reset requires its distinct envelope purpose"); + } + }); + lockAccount(intent.accountId(), intent.accountUuid()); + Record prior = findByRequestId(intent.requestId()); + if (prior != null) { + PendingResetIntent stored = requireStoredIntent(prior); + requireSameIntent(intent, stored); + if (!"WAITING".equals(prior.get("status", String.class))) { + throw new IllegalStateException("Terminal password-reset intent cannot be restarted"); + } + if (!stored.tokenExpiresAt().isAfter(LocalDateTime.now())) { + throw new IllegalArgumentException("Pending reset has expired"); + } + if (pendingEnvelope.isPresent()) { + throw new IllegalStateException("An existing reset intent cannot remint its envelope"); + } + boolean hasEnvelope = envelopeExists(stored.requestId()); + if (!hasEnvelope && stored.tokenExpiresAt().isAfter(LocalDateTime.now())) { + throw new IllegalStateException("Live pending reset has no original encrypted verifier"); + } + boolean settled = fences.requestSourceChange(stored.sourceChange()); + return new Participation(snapshot(prior, stored, hasEnvelope), settled, false); + } + Record tokenCollision = findByTokenHash(decodeDigest(intent.tokenHash(), "token hash")); + if (tokenCollision != null) { + throw new IllegalStateException("Reset token identity is already bound to another intent"); + } + if (dsl.fetchOne( + "SELECT token_hash FROM account_password_reset_operation_receipts WHERE token_hash = ?", + decodeDigest(intent.tokenHash(), "token hash")) + != null) { + throw new IllegalStateException("Completed reset receipt cannot be restarted"); + } + if (!intent.tokenExpiresAt().isAfter(LocalDateTime.now())) { + throw new IllegalArgumentException("Password-reset token is expired"); + } + boolean settled = fences.requestSourceChange(intent.sourceChange()); + Optional persistEnvelope = + settled ? Optional.empty() : pendingEnvelope; + if (persistEnvelope.isEmpty() && !settled) { + throw new IllegalStateException( + "Unsettled reset intent requires its separate encrypted verifier"); + } + persistJournal(intent); + persistEnvelope.ifPresent(envelope -> insertEnvelope(intent.requestId(), envelope)); + Record storedRow = findByRequestId(intent.requestId()); + PendingResetIntent readback = requireStoredIntent(storedRow); + requireSameIntent(intent, readback); + boolean envelopeStored = envelopeExists(intent.requestId()); + DraftAuthorizationFenceRepository.SourceChangeSnapshot sourceReadback = + fences.readSourceChange(intent.sourceChange()); + if (!"WAITING".equals(sourceReadback.status())) { + throw new IllegalStateException("New reset intent did not retain its exact V57 WAITING row"); + } + if (envelopeStored != persistEnvelope.isPresent()) { + throw new IllegalStateException("Pending reset envelope insertion readback differs"); + } + return new Participation(snapshot(storedRow, readback, envelopeStored), settled, true); + } + + /** + * Claims existing exact WAITING intent after locking Account/journal; never creates ciphertext. + */ + public Participation claim(PendingResetSnapshot snapshot) { + requireTransaction(); + Objects.requireNonNull(snapshot, "pending reset snapshot"); + PendingResetIntent intent = snapshot.intent(); + lockAccount(intent.accountId(), intent.accountUuid()); + Record row = findByRequestId(intent.requestId()); + Record envelopeRow = + dsl.fetchOne( + "SELECT * FROM " + ENVELOPES + " WHERE request_id = ? FOR UPDATE", intent.requestId()); + PendingResetIntent stored = requireStoredIntent(row); + requireSameIntent(intent, stored); + if (!"WAITING".equals(row.get("status", String.class))) { + throw new IllegalStateException("Only a pending reset can be claimed"); + } + if (!stored.tokenExpiresAt().isAfter(LocalDateTime.now())) { + throw new IllegalArgumentException("Pending reset has expired"); + } + if (envelopeRow == null) { + throw new IllegalStateException("Original pending reset envelope is missing"); + } + boolean settled = fences.requestSourceChange(stored.sourceChange()); + return new Participation(snapshot(row, stored, true), settled, false); + } + + /** Read-only exact envelope lookup. Absence never means re-encryption is permitted. */ + public Optional readPendingEnvelope(PendingResetSnapshot snapshot) { + requireTransaction(); + Objects.requireNonNull(snapshot, "pending reset snapshot"); + PendingResetIntent intent = snapshot.intent(); + lockAccount(intent.accountId(), intent.accountUuid()); + Record journal = findByRequestId(intent.requestId()); + Record row = + dsl.fetchOne( + "SELECT * FROM " + ENVELOPES + " WHERE request_id = ? FOR UPDATE", intent.requestId()); + requireSameIntent(intent, requireStoredIntent(journal)); + return Optional.ofNullable(row == null ? null : envelopeFromRow(row)); + } + + /** Permission is only the exact ordering-aware V57 predicate; no account state is advanced. */ + public boolean sourceMutationPermitted(Participation participation) { + requireTransaction(); + PendingResetIntent intent = requireParticipation(participation).intent(); + lockAccount(intent.accountId(), intent.accountUuid()); + Record row = findByRequestId(intent.requestId()); + boolean hasEnvelope = envelopeExists(intent.requestId()); + requireSameIntent(intent, requireStoredIntent(row)); + if (!hasEnvelope + && !(participation.createdInThisTransaction() && participation.settledAtClaim())) { + return false; + } + return "WAITING".equals(row.get("status", String.class)) + && intent.tokenExpiresAt().isAfter(LocalDateTime.now()) + && fences.sourceMutationPermitted(intent.sourceChange()); + } + + /** + * Links caller-produced account/token/source/event/receipt readbacks, transitions both journals, + * and erases ciphertext in the same transaction. The no-envelope path is available only to the + * fresh settled participation returned by beginWaiting; callers may not commit it as WAITING. + */ + public void complete( + Participation participation, + PasswordResetReceipt receipt, + Event event, + LocalDateTime capturedNow) { + requireTransaction(); + Objects.requireNonNull(receipt, "password-reset receipt"); + Objects.requireNonNull(event, "password-reset event"); + Objects.requireNonNull(capturedNow, "completion time"); + Participation selected = requireParticipation(participation); + PendingResetIntent intent = selected.intent(); + lockAccount(intent.accountId(), intent.accountUuid()); + Record row = findByRequestId(intent.requestId()); + boolean hasEnvelope = envelopeExists(intent.requestId()); + PendingResetIntent stored = requireStoredIntent(row); + requireSameIntent(intent, stored); + String status = row.get("status", String.class); + if ("SOURCE_ABORTED".equals(status)) { + throw new IllegalStateException("Aborted password-reset intent cannot be completed"); + } + requireReceiptAndEvent(intent, receipt, event); + if ("SOURCE_COMMITTED".equals(status)) { + requireCommittedReadback(intent, receipt, event); + if (!"SOURCE_COMMITTED".equals(fences.readSourceChange(intent.sourceChange()).status())) { + throw new IllegalStateException("Committed reset and V57 source outcome differ"); + } + deleteEnvelopeIfPresent(intent.requestId()); + requireJournalCommitted(row, event); + return; + } + if (!"WAITING".equals(status) + || !intent.tokenExpiresAt().isAfter(capturedNow) + || !fences.sourceMutationPermitted(intent.sourceChange())) { + throw new IllegalStateException("Password-reset source is expired, unresolved, or terminal"); + } + if (!hasEnvelope && !(selected.createdInThisTransaction() && selected.settledAtClaim())) { + throw new IllegalStateException( + "Pending reset cannot complete without its original envelope"); + } + requireCommittedReadback(intent, receipt, event); + fences.markSourceCommitted(intent.sourceChange()); + int updated = + dsl.execute( + "UPDATE " + + JOURNAL + + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP," + + " event_stream = ?, event_sequence = ?, event_id = ?, event_digest = ?," + + " event_payload = ? WHERE request_id = ? AND status = 'WAITING'", + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.payload(), + intent.requestId()); + if (updated != 1) { + throw new IllegalStateException("Password-reset journal did not commit exactly once"); + } + deleteEnvelopeIfPresent(intent.requestId()); + Record readback = findByRequestId(intent.requestId()); + if (!"SOURCE_COMMITTED".equals(readback.get("status", String.class)) + || !"SOURCE_COMMITTED".equals(fences.readSourceChange(intent.sourceChange()).status())) { + throw new IllegalStateException("Password-reset journal outcome readback differs"); + } + requireJournalCommitted(readback, event); + requireCommittedReadback(intent, receipt, event); + } + + /** + * Applies a no-mutation terminal result only after the exact V57 settlement predicate. Expiry + * first erases ciphertext even if owners remain unresolved; in that case the journal/fence stay + * WAITING and the method returns false. + */ + public boolean abort( + PendingResetSnapshot snapshot, AbortReason reason, LocalDateTime capturedNow) { + requireTransaction(); + Objects.requireNonNull(snapshot, "pending reset snapshot"); + Objects.requireNonNull(reason, "abort reason"); + Objects.requireNonNull(capturedNow, "abort time"); + PendingResetIntent intent = snapshot.intent(); + lockAccount(intent.accountId(), intent.accountUuid()); + Record row = findByRequestId(intent.requestId()); + boolean hasEnvelope = envelopeExists(intent.requestId()); + PendingResetIntent stored = requireStoredIntent(row); + requireSameIntent(intent, stored); + String status = row.get("status", String.class); + if ("SOURCE_ABORTED".equals(status)) { + requireAbortReason(row, reason); + requireUnchangedSource(intent); + if (hasEnvelope) { + throw new IllegalStateException("Aborted password-reset envelope was not erased"); + } + return true; + } + if ("SOURCE_COMMITTED".equals(status)) { + throw new IllegalStateException("Committed password-reset intent cannot be aborted"); + } + if (!"WAITING".equals(status)) { + throw new IllegalStateException("Password-reset intent is not waiting"); + } + if (reason == AbortReason.EXPIRED) { + if (intent.tokenExpiresAt().isAfter(capturedNow)) { + throw new IllegalArgumentException("Original password-reset deadline has not expired"); + } + deleteEnvelopeIfPresent(intent.requestId()); + } + requireUnchangedSource(intent); + if (!fences.sourceAbortPermitted(intent.sourceChange())) { + return false; + } + SourceChangeAbortReason fenceReason = + reason == AbortReason.EXPIRED + ? SourceChangeAbortReason.EXPIRED + : SourceChangeAbortReason.DEFINITIVE_ABORT; + fences.markSourceAborted(intent.sourceChange(), fenceReason); + int updated = + dsl.execute( + "UPDATE " + + JOURNAL + + " SET status = 'SOURCE_ABORTED', aborted_at = CURRENT_TIMESTAMP, abort_reason = ?" + + " WHERE request_id = ? AND status = 'WAITING'", + reason.name(), + intent.requestId()); + if (updated != 1) { + throw new IllegalStateException("Password-reset no-mutation outcome was not recorded once"); + } + deleteEnvelopeIfPresent(intent.requestId()); + Record readback = findByRequestId(intent.requestId()); + if (!"SOURCE_ABORTED".equals(readback.get("status", String.class)) + || !reason.name().equals(readback.get("abort_reason", String.class))) { + throw new IllegalStateException("Password-reset abort readback differs"); + } + DraftAuthorizationFenceRepository.SourceChangeSnapshot fenceReadback = + fences.readSourceChange(intent.sourceChange()); + if (!"SOURCE_ABORTED".equals(fenceReadback.status()) + || fenceReadback.abortReason() != fenceReason + || envelopeExists(intent.requestId())) { + throw new IllegalStateException("Password-reset abort and V57 fence readback differ"); + } + return true; + } + + /** Expiry-only idempotent ciphertext erasure; does not settle, cancel, or release V57 fences. */ + public boolean eraseEnvelopeAfterExpiry( + PendingResetSnapshot snapshot, LocalDateTime capturedNow) { + requireTransaction(); + Objects.requireNonNull(snapshot, "pending reset snapshot"); + Objects.requireNonNull(capturedNow, "expiry time"); + PendingResetIntent intent = snapshot.intent(); + lockAccount(intent.accountId(), intent.accountUuid()); + Record row = findByRequestId(intent.requestId()); + envelopeExists(intent.requestId()); + requireSameIntent(intent, requireStoredIntent(row)); + if (intent.tokenExpiresAt().isAfter(capturedNow)) { + throw new IllegalArgumentException("Original password-reset deadline has not expired"); + } + return deleteEnvelopeIfPresent(intent.requestId()); + } + + public enum AbortReason { + EXPIRED, + DEFINITIVE_ABORT + } + + /** Immutable original reset request and complete captured Account source evidence. */ + public static final class PendingResetIntent { + private final long accountId; + private final UUID accountUuid; + private final String tokenHash; + private final LocalDateTime tokenExpiresAt; + private final byte[] requestDigest; + private final byte[] targetVerifierDigest; + private final long expectedGeneration; + private final long expectedSourceVersion; + private final long expectedIssuanceFence; + private final long expectedIssuanceFenceSourceVersion; + private final long checkpointSequence; + private final byte[] captureEvidence; + private final byte[] sourceEvidence; + private final byte[] requestPayload; + private final SourceChange sourceChange; + + private PendingResetIntent( + long accountId, + UUID accountUuid, + String tokenHash, + LocalDateTime tokenExpiresAt, + byte[] requestDigest, + byte[] targetVerifierDigest, + long expectedGeneration, + long expectedSourceVersion, + long expectedIssuanceFence, + long expectedIssuanceFenceSourceVersion, + long checkpointSequence, + byte[] captureEvidence, + byte[] sourceEvidence, + byte[] requestPayload, + SourceChange sourceChange) { + requireIdentity(accountId, accountUuid); + decodeDigest(tokenHash, "token hash"); + this.accountId = accountId; + this.accountUuid = accountUuid; + this.tokenHash = tokenHash; + this.tokenExpiresAt = Objects.requireNonNull(tokenExpiresAt); + this.requestDigest = checkedDigest(requestDigest, "request digest"); + this.targetVerifierDigest = checkedDigest(targetVerifierDigest, "target verifier digest"); + if (expectedGeneration <= 0L + || expectedSourceVersion <= 0L + || expectedIssuanceFence <= 0L + || expectedIssuanceFenceSourceVersion <= 0L + || checkpointSequence < 0L) { + throw new IllegalArgumentException("Original Account source counters are invalid"); + } + this.expectedGeneration = expectedGeneration; + this.expectedSourceVersion = expectedSourceVersion; + this.expectedIssuanceFence = expectedIssuanceFence; + this.expectedIssuanceFenceSourceVersion = expectedIssuanceFenceSourceVersion; + this.checkpointSequence = checkpointSequence; + this.captureEvidence = nonEmptyBytes(captureEvidence, "Account capture evidence"); + this.sourceEvidence = nonEmptyBytes(sourceEvidence, "Account source evidence"); + this.requestPayload = nonEmptyBytes(requestPayload, "reset request payload"); + this.sourceChange = Objects.requireNonNull(sourceChange); + if (sourceChange.sources().size() != 1 + || !sourceChange.sources().getFirst().key().equals("ACCOUNT:" + accountUuid)) { + throw new IllegalArgumentException("Password-reset V57 source binding is malformed"); + } + } + + public long accountId() { + return accountId; + } + + public UUID accountUuid() { + return accountUuid; + } + + public String tokenHash() { + return tokenHash; + } + + public String requestId() { + return REQUEST_PREFIX + tokenHash; + } + + public String eventId() { + return EVENT_PREFIX + tokenHash; + } + + public LocalDateTime tokenExpiresAt() { + return tokenExpiresAt; + } + + public byte[] requestDigest() { + return requestDigest.clone(); + } + + public byte[] targetVerifierDigest() { + return targetVerifierDigest.clone(); + } + + public long expectedGeneration() { + return expectedGeneration; + } + + public long expectedSourceVersion() { + return expectedSourceVersion; + } + + public long expectedIssuanceFence() { + return expectedIssuanceFence; + } + + public long expectedIssuanceFenceSourceVersion() { + return expectedIssuanceFenceSourceVersion; + } + + public long checkpointSequence() { + return checkpointSequence; + } + + public byte[] captureEvidence() { + return captureEvidence.clone(); + } + + public byte[] sourceEvidence() { + return sourceEvidence.clone(); + } + + public byte[] requestPayload() { + return requestPayload.clone(); + } + + public SourceChange sourceChange() { + return sourceChange; + } + + public AccountPendingResetEnvelopeBinding envelopeBinding() { + return new AccountPendingResetEnvelopeBinding( + accountUuid, + tokenHash, + tokenExpiresAt, + requestId(), + requestDigest, + sha256(captureEvidence), + targetVerifierDigest); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof PendingResetIntent that)) return false; + return accountId == that.accountId + && expectedGeneration == that.expectedGeneration + && expectedSourceVersion == that.expectedSourceVersion + && expectedIssuanceFence == that.expectedIssuanceFence + && expectedIssuanceFenceSourceVersion == that.expectedIssuanceFenceSourceVersion + && checkpointSequence == that.checkpointSequence + && accountUuid.equals(that.accountUuid) + && tokenHash.equals(that.tokenHash) + && tokenExpiresAt.equals(that.tokenExpiresAt) + && Arrays.equals(requestDigest, that.requestDigest) + && Arrays.equals(targetVerifierDigest, that.targetVerifierDigest) + && Arrays.equals(captureEvidence, that.captureEvidence) + && Arrays.equals(sourceEvidence, that.sourceEvidence) + && Arrays.equals(requestPayload, that.requestPayload) + && Arrays.equals(sourceChange.canonicalBytes(), that.sourceChange.canonicalBytes()); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + accountId, + accountUuid, + tokenHash, + tokenExpiresAt, + expectedGeneration, + expectedSourceVersion, + expectedIssuanceFence, + expectedIssuanceFenceSourceVersion, + checkpointSequence); + result = 31 * result + Arrays.hashCode(requestDigest); + result = 31 * result + Arrays.hashCode(targetVerifierDigest); + result = 31 * result + Arrays.hashCode(captureEvidence); + result = 31 * result + Arrays.hashCode(sourceEvidence); + result = 31 * result + Arrays.hashCode(requestPayload); + return 31 * result + Arrays.hashCode(sourceChange.canonicalBytes()); + } + + @Override + public String toString() { + return "PendingResetIntent{account=, request=, source=}"; + } + } + + /** Exact pending row readback, with immutable bytes and secret-free rendering. */ + public record PendingResetSnapshot( + PendingResetIntent intent, + String status, + OffsetDateTime createdAt, + OffsetDateTime committedAt, + OffsetDateTime abortedAt, + AbortReason abortReason, + String eventStream, + Long eventSequence, + String eventId, + String eventDigest, + byte[] eventPayload, + boolean envelopePresent) { + public PendingResetSnapshot { + Objects.requireNonNull(intent); + Objects.requireNonNull(status); + eventPayload = eventPayload == null ? null : eventPayload.clone(); + } + + @Override + public byte[] eventPayload() { + return eventPayload == null ? null : eventPayload.clone(); + } + + @Override + public String toString() { + return "PendingResetSnapshot{intent=, status=" + status + ", outcome=}"; + } + } + + /** Returned participation is a caller-transaction capability, not a new source proof. */ + public static final class Participation { + private final PendingResetSnapshot snapshot; + private final boolean settledAtClaim; + private final boolean createdInThisTransaction; + + private Participation( + PendingResetSnapshot snapshot, boolean settledAtClaim, boolean createdInThisTransaction) { + this.snapshot = Objects.requireNonNull(snapshot); + this.settledAtClaim = settledAtClaim; + this.createdInThisTransaction = createdInThisTransaction; + } + + public PendingResetSnapshot snapshot() { + return snapshot; + } + + public boolean settledAtClaim() { + return settledAtClaim; + } + + public boolean createdInThisTransaction() { + return createdInThisTransaction; + } + + private PendingResetIntent intent() { + return snapshot.intent(); + } + } + + private Participation requireParticipation(Participation participation) { + return Objects.requireNonNull(participation, "reset participation"); + } + + private void persistJournal(PendingResetIntent intent) { + dsl.execute( + "INSERT INTO " + + JOURNAL + + " (request_id, account_id, account_uuid, token_hash, request_digest_version," + + " request_digest, token_expires_at, token_expires_at_text, target_verifier_digest," + + " expected_generation, expected_source_version, expected_issuance_fence," + + " expected_issuance_fence_source_version, checkpoint_stream, checkpoint_sequence," + + " capture_evidence, capture_evidence_digest, request_payload, source_evidence," + + " source_change_id, source_change_request, source_change_binding, status)" + + " VALUES (?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'WAITING')", + intent.requestId(), + intent.accountId(), + intent.accountUuid(), + decodeDigest(intent.tokenHash(), "token hash"), + intent.requestDigest(), + intent.tokenExpiresAt(), + intent.tokenExpiresAt().toString(), + intent.targetVerifierDigest(), + intent.expectedGeneration(), + intent.expectedSourceVersion(), + intent.expectedIssuanceFence(), + intent.expectedIssuanceFenceSourceVersion(), + STREAM_PREFIX + intent.accountUuid(), + intent.checkpointSequence(), + intent.captureEvidence(), + sha256(intent.captureEvidence()), + intent.requestPayload(), + intent.sourceEvidence(), + intent.sourceChange().changeId(), + intent.sourceChange().mutation(), + intent.sourceChange().canonicalBytes()); + } + + private void insertEnvelope(String requestId, AccountEncryptedEnvelope envelope) { + if (envelope.purpose() != AccountEnvelopePurpose.PENDING_PASSWORD_RESET) { + throw new IllegalArgumentException("Pending reset requires its distinct envelope purpose"); + } + int inserted = + dsl.execute( + "INSERT INTO " + + ENVELOPES + + " (request_id, format_version, key_id, purpose, nonce, ciphertext)" + + " VALUES (?, ?, ?, 'pending-reset', ?, ?)", + requestId, + envelope.formatVersion(), + envelope.keyId(), + envelope.nonce(), + envelope.ciphertext()); + if (inserted != 1) { + throw new IllegalStateException("Pending reset envelope was not inserted exactly once"); + } + } + + private PendingResetIntent requireStoredIntent(Record row) { + if (row == null) { + throw new IllegalArgumentException("Pending reset intent is absent"); + } + long accountId = requiredLong(row, "account_id"); + UUID accountUuid = Objects.requireNonNull(row.get("account_uuid", UUID.class)); + String tokenHash = HEX.formatHex(requiredBytes(row, "token_hash")); + LocalDateTime expiresAt = + Objects.requireNonNull(row.get("token_expires_at", LocalDateTime.class)); + String expiresText = Objects.requireNonNull(row.get("token_expires_at_text", String.class)); + if (!expiresAt.toString().equals(expiresText)) { + throw new IllegalStateException("Stored password-reset deadline is not canonical"); + } + byte[] requestDigest = requiredBytes(row, "request_digest"); + byte[] verifierDigest = requiredBytes(row, "target_verifier_digest"); + long generation = requiredLong(row, "expected_generation"); + long sourceVersion = requiredLong(row, "expected_source_version"); + long fence = requiredLong(row, "expected_issuance_fence"); + long fenceVersion = requiredLong(row, "expected_issuance_fence_source_version"); + long sequence = requiredLong(row, "checkpoint_sequence"); + byte[] capture = requiredBytes(row, "capture_evidence"); + byte[] sourceEvidence = requiredBytes(row, "source_evidence"); + byte[] request = requiredBytes(row, "request_payload"); + byte[] changeBinding = requiredBytes(row, "source_change_binding"); + SourceChange change = SourceChange.fromStored(changeBinding); + PendingResetIntent intent = + new PendingResetIntent( + accountId, + accountUuid, + tokenHash, + expiresAt, + requestDigest, + verifierDigest, + generation, + sourceVersion, + fence, + fenceVersion, + sequence, + capture, + sourceEvidence, + request, + change); + byte[] expectedRequest = + requestPayload( + intent.requestId(), + accountId, + accountUuid, + requestDigest, + decodeDigest(tokenHash, "token hash"), + expiresAt, + verifierDigest); + SourceEvidence evidence = + new SourceEvidence( + SourceKind.ACCOUNT, + accountUuid.toString(), + Long.toString(generation), + Long.toString(sourceVersion), + STREAM_PREFIX + accountUuid, + Long.toString(sequence), + capture); + byte[] expectedMutation = + mutationPayload( + expectedRequest, + generation, + sourceVersion, + fence, + fenceVersion, + sequence, + evidence.canonicalBytes(), + sha256(capture)); + byte[] expectedBinding = + new SourceChange(change.changeId(), List.of(evidence), expectedMutation).canonicalBytes(); + byte[] expectedDigest = requestDigest(accountUuid, tokenHash, expiresAt, verifierDigest); + if (!intent.requestId().equals(row.get("request_id", String.class)) + || row.get("request_digest_version", Integer.class) != 1 + || !Arrays.equals(expectedDigest, requestDigest) + || !Arrays.equals(expectedRequest, request) + || !Arrays.equals(evidence.canonicalBytes(), sourceEvidence) + || !Arrays.equals(expectedMutation, change.mutation()) + || !Arrays.equals(expectedBinding, changeBinding) + || !change.changeId().equals(row.get("source_change_id", UUID.class)) + || !Arrays.equals(change.mutation(), requiredBytes(row, "source_change_request")) + || !Arrays.equals(sha256(capture), requiredBytes(row, "capture_evidence_digest"))) { + throw new IllegalStateException("Pending reset row differs from its exact immutable binding"); + } + DraftAuthorizationFenceRepository.SourceChangeSnapshot fenceReadback = + fences.inspectSourceChange(change); + if (!Objects.equals(row.get("status", String.class), fenceReadback.status()) + || !Arrays.equals(changeBinding, fenceReadback.binding())) { + throw new IllegalStateException( + "Pending reset journal differs from its exact V57 source row"); + } + if ("SOURCE_ABORTED".equals(fenceReadback.status()) + && (!Objects.equals( + row.get("abort_reason", String.class), fenceReadback.abortReason().name()) + || !Objects.equals( + row.get("aborted_at", OffsetDateTime.class), fenceReadback.abortedAt()))) { + throw new IllegalStateException("Pending reset and V57 abort readbacks differ"); + } + return intent; + } + + private PendingResetSnapshot snapshot( + Record row, PendingResetIntent intent, boolean envelopePresent) { + String abortReason = row.get("abort_reason", String.class); + return new PendingResetSnapshot( + intent, + row.get("status", String.class), + row.get("created_at", OffsetDateTime.class), + row.get("committed_at", OffsetDateTime.class), + row.get("aborted_at", OffsetDateTime.class), + abortReason == null ? null : AbortReason.valueOf(abortReason), + row.get("event_stream", String.class), + row.get("event_sequence", Long.class), + row.get("event_id", String.class), + row.get("event_digest", String.class), + row.get("event_payload", byte[].class), + envelopePresent); + } + + private void requireSameIntent(PendingResetIntent expected, PendingResetIntent actual) { + if (!expected.equals(actual)) { + throw new IllegalArgumentException("Pending reset immutable request/source binding changed"); + } + } + + private Record findByRequestId(String requestId) { + return dsl.fetchOne("SELECT * FROM " + JOURNAL + " WHERE request_id = ? FOR UPDATE", requestId); + } + + private Record findByTokenHash(byte[] tokenHash) { + return dsl.fetchOne("SELECT * FROM " + JOURNAL + " WHERE token_hash = ? FOR UPDATE", tokenHash); + } + + private boolean envelopeExists(String requestId) { + return dsl.fetchOne( + "SELECT request_id FROM " + ENVELOPES + " WHERE request_id = ? FOR UPDATE", requestId) + != null; + } + + private AccountEncryptedEnvelope envelopeFromRow(Record row) { + if (!"pending-reset".equals(row.get("purpose", String.class))) { + throw new IllegalStateException("Stored pending reset envelope has the wrong purpose"); + } + return new AccountEncryptedEnvelope( + row.get("format_version", Short.class).intValue(), + row.get("key_id", String.class), + AccountEnvelopePurpose.PENDING_PASSWORD_RESET, + requiredBytes(row, "nonce"), + requiredBytes(row, "ciphertext")); + } + + private void requireReceiptAndEvent( + PendingResetIntent intent, PasswordResetReceipt receipt, Event event) { + if (receipt.accountId() != intent.accountId() + || !receipt.accountUuid().equals(intent.accountUuid()) + || !receipt.tokenHash().equals(intent.tokenHash()) + || !receipt.requestId().equals(intent.requestId()) + || !receipt.requestDigest().equals(HEX.formatHex(intent.requestDigest())) + || receipt.requestDigestVersion() != 1 + || !receipt.tokenExpiresAt().equals(intent.tokenExpiresAt()) + || !receipt.passwordVerifierDigest().equals(HEX.formatHex(intent.targetVerifierDigest())) + || !receipt.operationKind().equals("PASSWORD_RESET") + || !receipt.eventId().equals(intent.eventId()) + || !receipt.outboxStreamKey().equals(STREAM_PREFIX + intent.accountUuid()) + || receipt.outboxSequence() != intent.checkpointSequence() + 1 + || !event.outboxStreamKey().equals(receipt.outboxStreamKey()) + || !event.requestId().equals(intent.requestId()) + || event.outboxSequence() != receipt.outboxSequence() + || !event.eventId().equals(receipt.eventId()) + || !event.eventDigest().equals(receipt.eventDigest())) { + throw new IllegalArgumentException( + "Reset receipt/event do not match the original pending intent"); + } + } + + private void requireJournalCommitted(Record row, Event expectedEvent) { + if (row == null + || !"SOURCE_COMMITTED".equals(row.get("status", String.class)) + || row.get("committed_at", OffsetDateTime.class) == null + || row.get("aborted_at", OffsetDateTime.class) != null + || row.get("abort_reason", String.class) != null + || !expectedEvent.outboxStreamKey().equals(row.get("event_stream", String.class)) + || !Long.valueOf(expectedEvent.outboxSequence()) + .equals(row.get("event_sequence", Long.class)) + || !expectedEvent.eventId().equals(row.get("event_id", String.class)) + || !expectedEvent.eventDigest().equals(row.get("event_digest", String.class)) + || !Arrays.equals(expectedEvent.payload(), row.get("event_payload", byte[].class)) + || envelopeExists(row.get("request_id", String.class))) { + throw new IllegalStateException("Committed password-reset journal readback differs"); + } + } + + private void requireAbortReason(Record row, AbortReason expected) { + if (!expected.name().equals(row.get("abort_reason", String.class)) + || row.get("aborted_at", OffsetDateTime.class) == null + || row.get("committed_at", OffsetDateTime.class) != null) { + throw new IllegalArgumentException("Password-reset abort outcome differs from its readback"); + } + } + + private void requireCommittedReadback( + PendingResetIntent intent, PasswordResetReceipt expectedReceipt, Event expectedEvent) { + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, password_hash FROM accounts WHERE id = ? AND account_uuid = ? FOR UPDATE", + intent.accountId(), + intent.accountUuid()); + if (account == null + || account.get("password_hash", String.class) == null + || !Arrays.equals( + sha256(account.get("password_hash", String.class).getBytes(StandardCharsets.UTF_8)), + intent.targetVerifierDigest())) { + throw new IllegalStateException("Committed reset verifier readback differs from its intent"); + } + Record generation = + dsl.fetchOne( + "SELECT generation, source_version FROM account_authority_generations" + + " WHERE scope_kind = 'ACCOUNT' AND account_uuid = ? FOR UPDATE", + intent.accountUuid()); + Record issuance = + dsl.fetchOne( + "SELECT issuance_fence, source_version FROM account_authority_issuance_fences" + + " WHERE account_uuid = ? FOR UPDATE", + intent.accountUuid()); + if (generation == null + || issuance == null + || requiredLong(generation, "generation") != intent.expectedGeneration() + 1 + || requiredLong(generation, "source_version") != intent.expectedSourceVersion() + 1 + || requiredLong(issuance, "issuance_fence") != intent.expectedIssuanceFence() + 1 + || requiredLong(issuance, "source_version") + != intent.expectedIssuanceFenceSourceVersion() + 1) { + throw new IllegalStateException( + "Committed reset authority counters differ from the original capture"); + } + Record receipt = + dsl.fetchOne( + "SELECT * FROM account_password_reset_operation_receipts WHERE token_hash = ?", + decodeDigest(intent.tokenHash(), "token hash")); + if (receipt == null || !receiptMatches(receipt, expectedReceipt)) { + throw new IllegalStateException("Committed reset receipt durable readback differs"); + } + Record event = + dsl.fetchOne( + "SELECT * FROM account_authority_outbox_events" + + " WHERE outbox_stream_key = ? AND outbox_sequence = ?", + expectedEvent.outboxStreamKey(), + expectedEvent.outboxSequence()); + if (event == null + || !expectedEvent.requestId().equals(event.get("request_id", String.class)) + || !expectedEvent.eventId().equals(event.get("event_id", String.class)) + || !expectedEvent.eventDigest().equals(event.get("event_digest", String.class)) + || !Arrays.equals(expectedEvent.payload(), requiredBytes(event, "payload"))) { + throw new IllegalStateException("Committed reset event durable readback differs"); + } + Record checkpoint = + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams WHERE outbox_stream_key = ?", + expectedEvent.outboxStreamKey()); + if (checkpoint == null + || requiredLong(checkpoint, "last_sequence") != expectedEvent.outboxSequence()) { + throw new IllegalStateException("Committed reset checkpoint durable readback differs"); + } + if (dsl.fetchOne( + "SELECT token_hash FROM password_reset_token WHERE account_id = ?" + + " AND sha256(convert_to(token, 'UTF8')) = ?", + intent.accountId(), + decodeDigest(intent.tokenHash(), "token hash")) + != null) { + throw new IllegalStateException("Committed reset token was not consumed"); + } + } + + private boolean receiptMatches(Record row, PasswordResetReceipt receipt) { + return requiredLong(row, "account_id") == receipt.accountId() + && receipt.accountUuid().equals(row.get("account_uuid", UUID.class)) + && Arrays.equals( + requiredBytes(row, "token_hash"), decodeDigest(receipt.tokenHash(), "token hash")) + && receipt.operationKind().equals(row.get("operation_kind", String.class)) + && receipt.requestId().equals(row.get("request_id", String.class)) + && row.get("request_digest_version", Integer.class) == receipt.requestDigestVersion() + && Arrays.equals( + requiredBytes(row, "request_digest"), + decodeDigest(receipt.requestDigest(), "request digest")) + && receipt.tokenExpiresAt().equals(row.get("token_expires_at", LocalDateTime.class)) + && Arrays.equals( + requiredBytes(row, "password_verifier_digest"), + decodeDigest(receipt.passwordVerifierDigest(), "verifier digest")) + && receipt.outboxStreamKey().equals(row.get("outbox_stream_key", String.class)) + && requiredLong(row, "outbox_sequence") == receipt.outboxSequence() + && receipt.eventId().equals(row.get("event_id", String.class)) + && receipt.eventDigest().equals(row.get("event_digest", String.class)) + && requiredLong(row, "account_authority_generation") == receipt.accountAuthorityGeneration() + && requiredLong(row, "account_source_version") == receipt.accountSourceVersion() + && requiredLong(row, "issuance_fence") == receipt.issuanceFence() + && requiredLong(row, "issuance_fence_source_version") + == receipt.issuanceFenceSourceVersion(); + } + + private void requireUnchangedSource(PendingResetIntent intent) { + Record generation = + dsl.fetchOne( + "SELECT generation, source_version FROM account_authority_generations" + + " WHERE scope_kind = 'ACCOUNT' AND account_uuid = ? FOR UPDATE", + intent.accountUuid()); + Record issuance = + dsl.fetchOne( + "SELECT issuance_fence, source_version FROM account_authority_issuance_fences" + + " WHERE account_uuid = ? FOR UPDATE", + intent.accountUuid()); + Record checkpoint = + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams WHERE outbox_stream_key = ? FOR UPDATE", + STREAM_PREFIX + intent.accountUuid()); + Long sequence = checkpoint == null ? null : requiredLong(checkpoint, "last_sequence"); + if (generation == null + || issuance == null + || requiredLong(generation, "generation") != intent.expectedGeneration() + || requiredLong(generation, "source_version") != intent.expectedSourceVersion() + || requiredLong(issuance, "issuance_fence") != intent.expectedIssuanceFence() + || requiredLong(issuance, "source_version") != intent.expectedIssuanceFenceSourceVersion() + || (intent.checkpointSequence() == 0 + ? (sequence != null && sequence != 0L) + : !Long.valueOf(intent.checkpointSequence()).equals(sequence))) { + throw new IllegalStateException( + "Pending reset Account source changed before no-mutation outcome"); + } + if (intent.checkpointSequence() > 0) { + Record event = + dsl.fetchOne( + "SELECT payload FROM account_authority_outbox_events" + + " WHERE outbox_stream_key = ? AND outbox_sequence = ?", + STREAM_PREFIX + intent.accountUuid(), + intent.checkpointSequence()); + if (event == null + || !Arrays.equals(requiredBytes(event, "payload"), intent.captureEvidence())) { + throw new IllegalStateException("Pending reset lost its original source event capture"); + } + } + if (dsl.fetchOne( + "SELECT token_hash FROM account_password_reset_operation_receipts WHERE token_hash = ?", + decodeDigest(intent.tokenHash(), "token hash")) + != null + || dsl.fetchOne( + "SELECT event_id FROM account_authority_outbox_events" + + " WHERE outbox_stream_key = ? AND request_id = ?", + STREAM_PREFIX + intent.accountUuid(), + intent.requestId()) + != null) { + throw new IllegalStateException("Pending reset already has a source result"); + } + } + + private boolean deleteEnvelopeIfPresent(String requestId) { + return dsl.execute("DELETE FROM " + ENVELOPES + " WHERE request_id = ?", requestId) == 1; + } + + private void lockAccount(long accountId, UUID accountUuid) { + Record row = + dsl.fetchOne( + "SELECT id FROM accounts WHERE id = ? AND account_uuid = ? FOR UPDATE", + accountId, + accountUuid); + if (row == null) { + throw new IllegalStateException("Pending reset Account association is absent or changed"); + } + } + + private static byte[] captureEvidence( + Account account, + ScopeState current, + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest) { + String stream = STREAM_PREFIX + account.getAccountUuid(); + if (latest.outboxSequence() == 0L && latest.latestEvent().isPresent()) { + throw new IllegalStateException("Account source baseline has contradictory event evidence"); + } + if (latest.outboxSequence() > 0L && latest.latestEvent().isEmpty()) { + throw new IllegalStateException("Account source checkpoint has no latest event"); + } + return latest + .latestEvent() + .map(Event::payload) + .orElseGet( + () -> + framed( + List.of( + "account-draft-source-baseline/v1", + account.getAccountUuid().toString(), + Long.toString(current.generation()), + Long.toString(current.sourceVersion()), + stream, + "0"))); + } + + private static byte[] requestPayload( + String requestId, + long accountId, + UUID accountUuid, + byte[] requestDigest, + byte[] tokenHash, + LocalDateTime expiresAt, + byte[] verifierDigest) { + return framed( + List.of( + REQUEST_SCHEMA, + requestId, + Long.toString(accountId), + accountUuid.toString(), + "1", + requestDigest, + tokenHash, + expiresAt.toString(), + verifierDigest)); + } + + private static byte[] mutationPayload( + byte[] request, + long generation, + long sourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + long checkpointSequence, + byte[] sourceEvidence, + byte[] captureDigest) { + return framed( + List.of( + MUTATION_SCHEMA, + request, + Long.toString(generation), + Long.toString(sourceVersion), + Long.toString(issuanceFence), + Long.toString(issuanceFenceSourceVersion), + Long.toString(checkpointSequence), + sourceEvidence, + captureDigest)); + } + + private static byte[] requestDigest( + UUID accountUuid, String tokenHash, LocalDateTime expiresAt, byte[] verifierDigest) { + return sha256( + framed( + List.of( + REQUEST_DIGEST_SCHEMA, + "PASSWORD_RESET", + accountUuid.toString(), + tokenHash, + expiresAt.toString(), + HEX.formatHex(verifierDigest)))); + } + + private static byte[] framed(List fields) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (Object field : fields) { + byte[] encoded = + field instanceof byte[] binary + ? binary + : field.toString().getBytes(StandardCharsets.UTF_8); + output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + output.writeBytes(encoded); + } + return output.toByteArray(); + } + + 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 byte[] checkedDigest(byte[] value, String name) { + if (value == null || value.length != 32) { + throw new IllegalArgumentException(name + " must be 32 bytes"); + } + return value.clone(); + } + + private static byte[] nonEmptyBytes(byte[] value, String name) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException(name + " is required"); + } + return value.clone(); + } + + private static byte[] decodeDigest(String value, String name) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be lowercase SHA-256 hex"); + } + return HEX.parseHex(value); + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) { + throw new IllegalStateException("Pending reset durable " + field + " is absent"); + } + return value; + } + + private static long requiredLong(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) { + throw new IllegalStateException("Pending reset durable " + field + " is absent"); + } + return value; + } + + private static void requireAccount(Account account) { + if (account == null || account.getId() == null || account.getId() <= 0L) { + throw new IllegalArgumentException("Persisted Account identity is required"); + } + requireIdentity(account.getId(), account.getAccountUuid()); + } + + private static void requireIdentity(long accountId, UUID accountUuid) { + if (accountId <= 0L || accountUuid == null || new UUID(0L, 0L).equals(accountUuid)) { + throw new IllegalArgumentException("Canonical persisted Account identity is required"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account owner transaction is required"); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V60__account_logout_all_pending_draft_source_changes.sql b/services/account-service/src/main/resources/db/migration/V60__account_logout_all_pending_draft_source_changes.sql new file mode 100644 index 0000000000..e2c34a085d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V60__account_logout_all_pending_draft_source_changes.sql @@ -0,0 +1,295 @@ +-- Logout-all has a richer immutable caller binding than the issuer/tenant V59 journal. +CREATE TABLE account_logout_all_draft_source_changes ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'), + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + request_digest_version INTEGER NOT NULL CHECK (request_digest_version = 1), + request_digest BYTEA NOT NULL CHECK (octet_length(request_digest) = 32), + token_profile VARCHAR(32) NOT NULL CHECK (token_profile IN ('control-ui', 'player-bootstrap')), + presented_token_hash BYTEA NOT NULL CHECK (octet_length(presented_token_hash) = 32), + expected_generation BIGINT NOT NULL CHECK (expected_generation > 0), + expected_source_version BIGINT NOT NULL CHECK (expected_source_version > 0), + expected_issuance_fence BIGINT NOT NULL CHECK (expected_issuance_fence > 0), + expected_issuance_fence_source_version BIGINT NOT NULL + CHECK (expected_issuance_fence_source_version > 0), + checkpoint_stream VARCHAR(2048) NOT NULL, + checkpoint_sequence BIGINT NOT NULL CHECK (checkpoint_sequence >= 0), + capture_evidence BYTEA NOT NULL CHECK (octet_length(capture_evidence) > 0), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), + source_change_id UUID NOT NULL UNIQUE + REFERENCES account_draft_authorization_source_changes(change_id) + CHECK (source_change_id <> '00000000-0000-0000-0000-000000000000'), + source_change_request BYTEA NOT NULL CHECK (octet_length(source_change_request) > 0), + source_change_binding BYTEA NOT NULL CHECK (octet_length(source_change_binding) > 0), + status VARCHAR(16) NOT NULL CHECK (status IN ('WAITING', 'SOURCE_COMMITTED')), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + event_stream VARCHAR(2048), + event_sequence BIGINT CHECK (event_sequence > 0), + event_id VARCHAR(128), + event_digest VARCHAR(71), + event_payload BYTEA, + CONSTRAINT account_logout_all_draft_scope_check + CHECK (checkpoint_stream = 'account:auth-authority:v1:account/' || account_uuid::TEXT), + CONSTRAINT account_logout_all_draft_status_check + CHECK ((status = 'WAITING' AND committed_at IS NULL AND event_stream IS NULL + AND event_sequence IS NULL AND event_id IS NULL AND event_digest IS NULL + AND event_payload IS NULL) + OR (status = 'SOURCE_COMMITTED' AND committed_at IS NOT NULL + AND event_stream IS NOT NULL AND event_sequence IS NOT NULL + AND event_id IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND event_payload IS NOT NULL AND octet_length(event_payload) > 0)) +); + +-- [jooq ignore start] +-- jOOQ's H2 DDL interpreter maps BYTEA to BLOB, which cannot be indexed there. +-- PostgreSQL still enforces the exact token identity once across pending requests. +CREATE UNIQUE INDEX account_logout_all_draft_source_token_hash_unique + ON account_logout_all_draft_source_changes (presented_token_hash); + +CREATE FUNCTION account_logout_all_draft_frame(value BYTEA) +RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT int4send(octet_length(value)) || value; +$$; + +CREATE FUNCTION account_logout_all_draft_journal_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + expected_request BYTEA; + expected_mutation BYTEA; + expected_evidence BYTEA; + expected_baseline BYTEA; + expected_change BYTEA; + expected_key TEXT; + persisted_uuid UUID; + current_generation BIGINT; + current_source_version BIGINT; + current_fence BIGINT; + current_fence_source_version BIGINT; + current_sequence BIGINT; +BEGIN + IF TG_OP = 'UPDATE' THEN + IF OLD.status <> 'WAITING' OR NEW.status <> 'SOURCE_COMMITTED' + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.token_profile IS DISTINCT FROM OLD.token_profile + OR NEW.presented_token_hash IS DISTINCT FROM OLD.presented_token_hash + OR NEW.expected_generation IS DISTINCT FROM OLD.expected_generation + OR NEW.expected_source_version IS DISTINCT FROM OLD.expected_source_version + OR NEW.expected_issuance_fence IS DISTINCT FROM OLD.expected_issuance_fence + OR NEW.expected_issuance_fence_source_version IS DISTINCT FROM OLD.expected_issuance_fence_source_version + OR NEW.checkpoint_stream IS DISTINCT FROM OLD.checkpoint_stream + OR NEW.checkpoint_sequence IS DISTINCT FROM OLD.checkpoint_sequence + OR NEW.capture_evidence IS DISTINCT FROM OLD.capture_evidence + OR NEW.request_payload IS DISTINCT FROM OLD.request_payload + OR NEW.source_evidence IS DISTINCT FROM OLD.source_evidence + OR NEW.source_change_id IS DISTINCT FROM OLD.source_change_id + OR NEW.source_change_request IS DISTINCT FROM OLD.source_change_request + OR NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Logout-all Draft source intent and original capture are immutable' + USING ERRCODE = '23514'; + END IF; + NEW.committed_at = CURRENT_TIMESTAMP; + ELSE + IF NEW.status <> 'WAITING' THEN + RAISE EXCEPTION 'Logout-all Draft source intent must begin WAITING' + USING ERRCODE = '23514'; + END IF; + SELECT account_uuid INTO persisted_uuid FROM accounts WHERE id = NEW.account_id; + IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN + RAISE EXCEPTION 'Logout-all Draft intent Account association does not match' + USING ERRCODE = '23514'; + END IF; + + expected_request := account_logout_all_draft_frame(convert_to('account-logout-all-draft-source-request/v1', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.request_id::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.account_id::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.request_digest_version::TEXT, 'UTF8')) + || account_logout_all_draft_frame(NEW.request_digest) + || account_logout_all_draft_frame(convert_to(NEW.token_profile, 'UTF8')) + || account_logout_all_draft_frame(NEW.presented_token_hash); + expected_evidence := account_logout_all_draft_frame(convert_to('account-draft-source-evidence/v1', 'UTF8')) + || account_logout_all_draft_frame(convert_to('ACCOUNT', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to('PRESENT', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.expected_generation::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.expected_source_version::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to('PRESENT', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.checkpoint_stream, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.checkpoint_sequence::TEXT, 'UTF8')) + || account_logout_all_draft_frame(NEW.capture_evidence); + expected_mutation := account_logout_all_draft_frame(convert_to('account-logout-all-draft-source-mutation/v1', 'UTF8')) + || account_logout_all_draft_frame(NEW.request_payload) + || account_logout_all_draft_frame(convert_to(NEW.expected_generation::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.expected_source_version::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.expected_issuance_fence::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.expected_issuance_fence_source_version::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.checkpoint_sequence::TEXT, 'UTF8')) + || account_logout_all_draft_frame(NEW.source_evidence); + expected_change := account_logout_all_draft_frame(convert_to('account-draft-source-change/v1', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.source_change_id::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to('1', 'UTF8')) + || account_logout_all_draft_frame(NEW.source_evidence) + || account_logout_all_draft_frame(NEW.source_change_request); + expected_key := 'ACCOUNT:' || NEW.account_uuid::TEXT; + IF NEW.request_payload IS DISTINCT FROM expected_request + OR NEW.source_evidence IS DISTINCT FROM expected_evidence + OR NEW.source_change_request IS DISTINCT FROM expected_mutation + OR NEW.source_change_binding IS DISTINCT FROM expected_change + OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_source_changes + WHERE change_id = NEW.source_change_id AND status = 'WAITING' + AND binding = expected_change) + OR (SELECT count(*) FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.source_change_id) <> 1 + OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.source_change_id AND source_key = expected_key) THEN + RAISE EXCEPTION 'Logout-all request must bind its exact V57 Account source intent' + USING ERRCODE = '23514'; + END IF; + + SELECT generation, source_version INTO current_generation, current_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid; + SELECT issuance_fence, source_version INTO current_fence, current_fence_source_version + FROM account_authority_issuance_fences WHERE account_uuid = NEW.account_uuid; + IF current_generation IS DISTINCT FROM NEW.expected_generation + OR current_source_version IS DISTINCT FROM NEW.expected_source_version + OR current_fence IS DISTINCT FROM NEW.expected_issuance_fence + OR current_fence_source_version IS DISTINCT FROM NEW.expected_issuance_fence_source_version THEN + RAISE EXCEPTION 'Logout-all Draft capture differs from current Account source counters' + USING ERRCODE = '23514'; + END IF; + SELECT last_sequence INTO current_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.checkpoint_stream; + IF NEW.checkpoint_sequence = 0 THEN + expected_baseline := account_logout_all_draft_frame(convert_to('account-draft-source-baseline/v1', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to('1', 'UTF8')) + || account_logout_all_draft_frame(convert_to('1', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.checkpoint_stream, 'UTF8')) + || account_logout_all_draft_frame(convert_to('0', 'UTF8')); + IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1 + OR NEW.capture_evidence IS DISTINCT FROM expected_baseline + OR (current_sequence IS NOT NULL AND current_sequence <> 0) + OR EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.checkpoint_stream) THEN + RAISE EXCEPTION 'Logout-all zero checkpoint lacks exact pristine source evidence' + USING ERRCODE = '23514'; + END IF; + ELSIF current_sequence IS DISTINCT FROM NEW.checkpoint_sequence + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.checkpoint_stream + AND outbox_sequence = NEW.checkpoint_sequence + AND payload = NEW.capture_evidence) THEN + RAISE EXCEPTION 'Logout-all capture does not bind the exact current Account event' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_logout_all_draft_link_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + journal account_logout_all_draft_source_changes%ROWTYPE; + source_status TEXT; + source_binding BYTEA; + selected_change UUID; + persisted_generation BIGINT; + persisted_source_version BIGINT; + persisted_fence BIGINT; + persisted_fence_source_version BIGINT; +BEGIN + IF TG_TABLE_NAME = 'account_logout_all_draft_source_changes' THEN + selected_change := NEW.source_change_id; + ELSE + selected_change := NEW.change_id; + END IF; + SELECT * INTO journal FROM account_logout_all_draft_source_changes + WHERE source_change_id = selected_change; + IF NOT FOUND THEN + RETURN NULL; + END IF; + SELECT status, binding INTO source_status, source_binding + FROM account_draft_authorization_source_changes WHERE change_id = selected_change; + IF source_status IS DISTINCT FROM journal.status + OR source_binding IS DISTINCT FROM journal.source_change_binding THEN + RAISE EXCEPTION 'Logout-all journal and V57 Account source transition must commit together' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'WAITING' AND EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = journal.checkpoint_stream + AND request_id = journal.request_id::TEXT) THEN + RAISE EXCEPTION 'A WAITING logout-all request cannot publish its source event' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'SOURCE_COMMITTED' AND ( + journal.event_stream IS DISTINCT FROM journal.checkpoint_stream + OR journal.event_id IS DISTINCT FROM 'account-logout-all-event-v1:' || journal.request_id::TEXT + OR journal.event_sequence IS DISTINCT FROM journal.checkpoint_sequence + 1 + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = journal.event_stream AND outbox_sequence = journal.event_sequence + AND request_id = journal.request_id::TEXT AND event_id = journal.event_id + AND event_digest = journal.event_digest AND payload = journal.event_payload) + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_streams + WHERE outbox_stream_key = journal.event_stream AND last_sequence = journal.event_sequence) + OR NOT EXISTS (SELECT 1 FROM account_logout_all_operation_receipts + WHERE request_id = journal.request_id AND account_id = journal.account_id + AND account_uuid = journal.account_uuid + AND request_digest_version = journal.request_digest_version + AND request_digest = journal.request_digest AND token_profile = journal.token_profile + AND presented_token_hash = journal.presented_token_hash + AND outbox_stream_key = journal.event_stream + AND outbox_sequence = journal.event_sequence + AND event_id = journal.event_id AND event_digest = journal.event_digest + AND account_authority_generation = journal.expected_generation + 1 + AND account_source_version = journal.expected_source_version + 1 + AND issuance_fence = journal.expected_issuance_fence + 1 + AND issuance_fence_source_version = journal.expected_issuance_fence_source_version + 1)) THEN + RAISE EXCEPTION 'Committed logout-all intent lacks its exact receipt, event, or checkpoint' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'SOURCE_COMMITTED' THEN + SELECT generation, source_version INTO persisted_generation, persisted_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = journal.account_uuid; + SELECT issuance_fence, source_version INTO persisted_fence, persisted_fence_source_version + FROM account_authority_issuance_fences WHERE account_uuid = journal.account_uuid; + IF persisted_generation IS DISTINCT FROM journal.expected_generation + 1 + OR persisted_source_version IS DISTINCT FROM journal.expected_source_version + 1 + OR persisted_fence IS DISTINCT FROM journal.expected_issuance_fence + 1 + OR persisted_fence_source_version + IS DISTINCT FROM journal.expected_issuance_fence_source_version + 1 THEN + RAISE EXCEPTION 'Logout-all Account authority counters did not advance once from capture' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_logout_all_draft_source_request_guard + BEFORE INSERT OR UPDATE ON account_logout_all_draft_source_changes + FOR EACH ROW EXECUTE FUNCTION account_logout_all_draft_journal_guard(); +CREATE TRIGGER account_logout_all_draft_source_delete_guard + BEFORE DELETE ON account_logout_all_draft_source_changes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_logout_all_draft_source_truncate_guard + BEFORE TRUNCATE ON account_logout_all_draft_source_changes + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE CONSTRAINT TRIGGER account_logout_all_draft_source_complete_guard + AFTER INSERT OR UPDATE ON account_logout_all_draft_source_changes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_logout_all_draft_link_guard(); +CREATE CONSTRAINT TRIGGER account_logout_all_draft_source_v57_link_guard + AFTER INSERT OR UPDATE ON account_draft_authorization_source_changes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_logout_all_draft_link_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V61__account_password_reset_pending_draft_source_changes.sql b/services/account-service/src/main/resources/db/migration/V61__account_password_reset_pending_draft_source_changes.sql new file mode 100644 index 0000000000..104e874f59 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V61__account_password_reset_pending_draft_source_changes.sql @@ -0,0 +1,633 @@ +-- Account password reset's pending owner journal and separate encrypted verifier row. +-- Existing V57/V60 histories and completed digest-only reset receipts remain untouched. + +-- H2's jOOQ simulator gives these inline V57 checks different generated names. +-- Keep the exact PostgreSQL removals active and skip only these name-specific operations in simulation. +-- [jooq ignore start] +ALTER TABLE account_draft_authorization_source_changes + DROP CONSTRAINT account_draft_authorization_source_changes_status_check; +ALTER TABLE account_draft_authorization_source_changes + DROP CONSTRAINT account_draft_authorization_source_changes_check; +-- [jooq ignore stop] + +ALTER TABLE account_draft_authorization_source_changes + ADD COLUMN aborted_at TIMESTAMPTZ; +ALTER TABLE account_draft_authorization_source_changes + ADD COLUMN abort_reason VARCHAR(24); +ALTER TABLE account_draft_authorization_source_changes + ADD CONSTRAINT account_draft_authorization_source_changes_status_check + CHECK (status IN ('WAITING', 'SOURCE_COMMITTED', 'SOURCE_ABORTED')); +ALTER TABLE account_draft_authorization_source_changes + ADD CONSTRAINT account_draft_authorization_source_changes_terminal_check + CHECK ((status = 'WAITING' AND committed_at IS NULL AND aborted_at IS NULL + AND abort_reason IS NULL) + OR (status = 'SOURCE_COMMITTED' AND committed_at IS NOT NULL + AND aborted_at IS NULL AND abort_reason IS NULL) + OR (status = 'SOURCE_ABORTED' AND committed_at IS NULL + AND aborted_at IS NOT NULL + AND abort_reason IS NOT NULL + AND abort_reason IN ('EXPIRED', 'DEFINITIVE_ABORT'))); + +CREATE TABLE account_password_reset_draft_source_changes ( + request_id VARCHAR(128) PRIMARY KEY, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + token_hash BYTEA NOT NULL CHECK (octet_length(token_hash) = 32), + request_digest_version INTEGER NOT NULL CHECK (request_digest_version = 1), + request_digest BYTEA NOT NULL CHECK (octet_length(request_digest) = 32), + token_expires_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, + token_expires_at_text VARCHAR(64) NOT NULL, + target_verifier_digest BYTEA NOT NULL CHECK (octet_length(target_verifier_digest) = 32), + expected_generation BIGINT NOT NULL CHECK (expected_generation > 0), + expected_source_version BIGINT NOT NULL CHECK (expected_source_version > 0), + expected_issuance_fence BIGINT NOT NULL CHECK (expected_issuance_fence > 0), + expected_issuance_fence_source_version BIGINT NOT NULL + CHECK (expected_issuance_fence_source_version > 0), + checkpoint_stream VARCHAR(2048) NOT NULL, + checkpoint_sequence BIGINT NOT NULL CHECK (checkpoint_sequence >= 0), + capture_evidence BYTEA NOT NULL CHECK (octet_length(capture_evidence) > 0), + capture_evidence_digest BYTEA NOT NULL CHECK (octet_length(capture_evidence_digest) = 32), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), + source_change_id UUID NOT NULL UNIQUE + REFERENCES account_draft_authorization_source_changes(change_id) ON DELETE RESTRICT, + source_change_request BYTEA NOT NULL CHECK (octet_length(source_change_request) > 0), + source_change_binding BYTEA NOT NULL CHECK (octet_length(source_change_binding) > 0), + status VARCHAR(16) NOT NULL CHECK (status IN ('WAITING', 'SOURCE_COMMITTED', 'SOURCE_ABORTED')), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + aborted_at TIMESTAMPTZ, + abort_reason VARCHAR(24), + event_stream VARCHAR(2048), + event_sequence BIGINT CHECK (event_sequence > 0), + event_id VARCHAR(128), + event_digest VARCHAR(71), + event_payload BYTEA, + CONSTRAINT account_password_reset_draft_request_identity_check CHECK ( + account_id > 0 + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id = 'account-password-reset-request-v1:' || encode(token_hash, 'hex') + AND token_expires_at_text::TIMESTAMP WITHOUT TIME ZONE = token_expires_at + AND checkpoint_stream = 'account:auth-authority:v1:account/' || account_uuid::TEXT + ), + CONSTRAINT account_password_reset_draft_status_check CHECK ( + (status = 'WAITING' AND committed_at IS NULL AND aborted_at IS NULL + AND abort_reason IS NULL AND event_stream IS NULL AND event_sequence IS NULL + AND event_id IS NULL AND event_digest IS NULL AND event_payload IS NULL) + OR (status = 'SOURCE_COMMITTED' AND committed_at IS NOT NULL AND aborted_at IS NULL + AND abort_reason IS NULL AND event_stream IS NOT NULL AND event_sequence IS NOT NULL + AND event_id IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND event_payload IS NOT NULL AND octet_length(event_payload) > 0) + OR (status = 'SOURCE_ABORTED' AND committed_at IS NULL AND aborted_at IS NOT NULL + AND abort_reason IS NOT NULL + AND abort_reason IN ('EXPIRED', 'DEFINITIVE_ABORT') AND event_stream IS NULL + AND event_sequence IS NULL AND event_id IS NULL AND event_digest IS NULL + AND event_payload IS NULL) + ), + CONSTRAINT account_password_reset_draft_event_uq UNIQUE (event_stream, event_id), + CONSTRAINT account_password_reset_draft_event_fk + FOREIGN KEY (event_stream, event_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT +); + +CREATE INDEX account_password_reset_draft_expiry_idx + ON account_password_reset_draft_source_changes (token_expires_at, request_id) + WHERE status = 'WAITING'; + +-- jOOQ's H2 DDL interpreter maps BYTEA to BLOB, which cannot be indexed there. +-- PostgreSQL still enforces each reset-token identity once across the private journal. +-- [jooq ignore start] +CREATE UNIQUE INDEX account_password_reset_draft_token_hash_uq + ON account_password_reset_draft_source_changes (token_hash); +-- [jooq ignore stop] + +CREATE TABLE account_password_reset_pending_envelopes ( + request_id VARCHAR(128) PRIMARY KEY + REFERENCES account_password_reset_draft_source_changes(request_id) ON DELETE RESTRICT, + format_version SMALLINT NOT NULL CHECK (format_version = 1), + key_id VARCHAR(64) NOT NULL CHECK (key_id ~ '^[A-Za-z0-9_-]{1,64}$'), + purpose VARCHAR(32) NOT NULL CHECK (purpose = 'pending-reset'), + nonce BYTEA NOT NULL CHECK (octet_length(nonce) = 12), + ciphertext BYTEA NOT NULL + CHECK (octet_length(ciphertext) BETWEEN 16 AND 65552), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_draft_authorization_source_change_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Draft source change cannot be deleted'; + END IF; + IF OLD.status <> 'WAITING' + OR NEW.status NOT IN ('SOURCE_COMMITTED', 'SOURCE_ABORTED') + OR NEW.change_id IS DISTINCT FROM OLD.change_id + OR NEW.binding IS DISTINCT FROM OLD.binding + OR NEW.requested_at IS DISTINCT FROM OLD.requested_at + OR (NEW.status = 'SOURCE_COMMITTED' + AND (NEW.committed_at IS NULL OR NEW.aborted_at IS NOT NULL + OR NEW.abort_reason IS NOT NULL)) + OR (NEW.status = 'SOURCE_ABORTED' + AND (NEW.committed_at IS NOT NULL OR NEW.aborted_at IS NULL + OR NEW.abort_reason IS NULL + OR NEW.abort_reason NOT IN ('EXPIRED', 'DEFINITIVE_ABORT'))) THEN + RAISE EXCEPTION 'Draft source change result is immutable' + USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_draft_authorization_sources source USING (source_key) + JOIN account_draft_authorization_fences fence USING (operation_id) + WHERE changed.change_id = OLD.change_id + AND NOT ((fence.ordering = 'REVOKE_ORDER' AND ( + SELECT count(*) FROM account_draft_authorization_owner_readbacks readback + WHERE readback.operation_id = fence.operation_id + AND readback.outcome = 'DEFINITIVELY_ABORTED' + ) = 2) OR (fence.ordering = 'COMMIT_ORDER' AND ( + SELECT count(*) FROM account_draft_authorization_owner_readbacks readback + WHERE readback.operation_id = fence.operation_id + ) = 2)) + ) THEN + RAISE EXCEPTION 'Both definitive owner outcomes are required before source transition' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_password_reset_draft_frame_text(value TEXT) +RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT int4send(octet_length(convert_to(value, 'UTF8'))) + || convert_to(value, 'UTF8'); +$$; + +CREATE FUNCTION account_password_reset_draft_frame_bytes(value BYTEA) +RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT int4send(octet_length(value)) || value; +$$; + +CREATE FUNCTION account_password_reset_draft_journal_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + expected_request_payload BYTEA; + expected_source_evidence BYTEA; + expected_source_change_request BYTEA; + expected_source_change_binding BYTEA; + expected_baseline BYTEA; + expected_request_digest BYTEA; + expected_source_key TEXT; + persisted_uuid UUID; + persisted_generation BIGINT; + persisted_source_version BIGINT; + persisted_fence BIGINT; + persisted_fence_source_version BIGINT; + persisted_sequence BIGINT; +BEGIN + IF TG_OP = 'UPDATE' THEN + IF OLD.status <> 'WAITING' + OR NEW.status NOT IN ('SOURCE_COMMITTED', 'SOURCE_ABORTED') + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.token_expires_at IS DISTINCT FROM OLD.token_expires_at + OR NEW.token_expires_at_text IS DISTINCT FROM OLD.token_expires_at_text + OR NEW.target_verifier_digest IS DISTINCT FROM OLD.target_verifier_digest + OR NEW.expected_generation IS DISTINCT FROM OLD.expected_generation + OR NEW.expected_source_version IS DISTINCT FROM OLD.expected_source_version + OR NEW.expected_issuance_fence IS DISTINCT FROM OLD.expected_issuance_fence + OR NEW.expected_issuance_fence_source_version + IS DISTINCT FROM OLD.expected_issuance_fence_source_version + OR NEW.checkpoint_stream IS DISTINCT FROM OLD.checkpoint_stream + OR NEW.checkpoint_sequence IS DISTINCT FROM OLD.checkpoint_sequence + OR NEW.capture_evidence IS DISTINCT FROM OLD.capture_evidence + OR NEW.capture_evidence_digest IS DISTINCT FROM OLD.capture_evidence_digest + OR NEW.request_payload IS DISTINCT FROM OLD.request_payload + OR NEW.source_evidence IS DISTINCT FROM OLD.source_evidence + OR NEW.source_change_id IS DISTINCT FROM OLD.source_change_id + OR NEW.source_change_request IS DISTINCT FROM OLD.source_change_request + OR NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Password-reset pending request and original capture are immutable' + USING ERRCODE = '23514'; + END IF; + IF NEW.status = 'SOURCE_COMMITTED' THEN + IF NEW.committed_at IS NULL OR NEW.aborted_at IS NOT NULL + OR NEW.abort_reason IS NOT NULL + OR NEW.event_stream IS DISTINCT FROM OLD.checkpoint_stream + OR NEW.event_sequence IS DISTINCT FROM OLD.checkpoint_sequence + 1 + OR NEW.event_id IS DISTINCT FROM + 'account-password-reset-event-v1:' || encode(OLD.token_hash, 'hex') + OR NEW.event_digest IS NULL + OR NEW.event_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.event_payload IS NULL OR octet_length(NEW.event_payload) = 0 + OR OLD.token_expires_at <= LOCALTIMESTAMP THEN + RAISE EXCEPTION 'Password-reset commit lacks live bound pending evidence' + USING ERRCODE = '23514'; + END IF; + ELSE + IF NEW.committed_at IS NOT NULL OR NEW.aborted_at IS NULL + OR NEW.abort_reason IS NULL + OR NEW.abort_reason NOT IN ('EXPIRED', 'DEFINITIVE_ABORT') + OR NEW.event_stream IS NOT NULL OR NEW.event_sequence IS NOT NULL + OR NEW.event_id IS NOT NULL OR NEW.event_digest IS NOT NULL + OR NEW.event_payload IS NOT NULL + OR (NEW.abort_reason = 'EXPIRED' + AND OLD.token_expires_at > LOCALTIMESTAMP) THEN + RAISE EXCEPTION 'Password-reset cancellation is not a terminal no-mutation result' + USING ERRCODE = '23514'; + END IF; + END IF; + ELSE + IF NEW.status <> 'WAITING' OR NEW.committed_at IS NOT NULL + OR NEW.aborted_at IS NOT NULL OR NEW.abort_reason IS NOT NULL + OR NEW.event_stream IS NOT NULL OR NEW.event_sequence IS NOT NULL + OR NEW.event_id IS NOT NULL OR NEW.event_digest IS NOT NULL + OR NEW.event_payload IS NOT NULL THEN + RAISE EXCEPTION 'Password-reset source intent must begin WAITING' + USING ERRCODE = '23514'; + END IF; + SELECT account_uuid INTO persisted_uuid FROM accounts WHERE id = NEW.account_id; + IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN + RAISE EXCEPTION 'Password-reset intent Account association does not match' + USING ERRCODE = '23514'; + END IF; + IF NEW.request_id IS DISTINCT FROM + 'account-password-reset-request-v1:' || encode(NEW.token_hash, 'hex') + OR NEW.capture_evidence_digest IS DISTINCT FROM sha256(NEW.capture_evidence) + OR NEW.token_expires_at_text::TIMESTAMP WITHOUT TIME ZONE + IS DISTINCT FROM NEW.token_expires_at THEN + RAISE EXCEPTION 'Password-reset immutable request binding is malformed' + USING ERRCODE = '23514'; + END IF; + expected_request_digest := sha256( + account_password_reset_draft_frame_text('account-password-reset-request/v1') + || account_password_reset_draft_frame_text('PASSWORD_RESET') + || account_password_reset_draft_frame_text(NEW.account_uuid::TEXT) + || account_password_reset_draft_frame_text(encode(NEW.token_hash, 'hex')) + || account_password_reset_draft_frame_text(NEW.token_expires_at_text) + || account_password_reset_draft_frame_text(encode(NEW.target_verifier_digest, 'hex')) + ); + expected_request_payload := + account_password_reset_draft_frame_text('account-password-reset-draft-source-request/v1') + || account_password_reset_draft_frame_text(NEW.request_id) + || account_password_reset_draft_frame_text(NEW.account_id::TEXT) + || account_password_reset_draft_frame_text(NEW.account_uuid::TEXT) + || account_password_reset_draft_frame_text(NEW.request_digest_version::TEXT) + || account_password_reset_draft_frame_bytes(NEW.request_digest) + || account_password_reset_draft_frame_bytes(NEW.token_hash) + || account_password_reset_draft_frame_text(NEW.token_expires_at_text) + || account_password_reset_draft_frame_bytes(NEW.target_verifier_digest); + expected_source_evidence := + account_password_reset_draft_frame_text('account-draft-source-evidence/v1') + || account_password_reset_draft_frame_text('ACCOUNT') + || account_password_reset_draft_frame_text(NEW.account_uuid::TEXT) + || account_password_reset_draft_frame_text('PRESENT') + || account_password_reset_draft_frame_text(NEW.expected_generation::TEXT) + || account_password_reset_draft_frame_text(NEW.expected_source_version::TEXT) + || account_password_reset_draft_frame_text('PRESENT') + || account_password_reset_draft_frame_text(NEW.checkpoint_stream) + || account_password_reset_draft_frame_text(NEW.checkpoint_sequence::TEXT) + || account_password_reset_draft_frame_bytes(NEW.capture_evidence); + expected_source_change_request := + account_password_reset_draft_frame_text('account-password-reset-draft-source-mutation/v1') + || account_password_reset_draft_frame_bytes(NEW.request_payload) + || account_password_reset_draft_frame_text(NEW.expected_generation::TEXT) + || account_password_reset_draft_frame_text(NEW.expected_source_version::TEXT) + || account_password_reset_draft_frame_text(NEW.expected_issuance_fence::TEXT) + || account_password_reset_draft_frame_text(NEW.expected_issuance_fence_source_version::TEXT) + || account_password_reset_draft_frame_text(NEW.checkpoint_sequence::TEXT) + || account_password_reset_draft_frame_bytes(NEW.source_evidence) + || account_password_reset_draft_frame_bytes(NEW.capture_evidence_digest); + expected_source_change_binding := + account_password_reset_draft_frame_text('account-draft-source-change/v1') + || account_password_reset_draft_frame_text(NEW.source_change_id::TEXT) + || account_password_reset_draft_frame_text('1') + || account_password_reset_draft_frame_bytes(NEW.source_evidence) + || account_password_reset_draft_frame_bytes(NEW.source_change_request); + expected_source_key := 'ACCOUNT:' || NEW.account_uuid::TEXT; + IF NEW.request_digest IS DISTINCT FROM expected_request_digest + OR NEW.request_payload IS DISTINCT FROM expected_request_payload + OR NEW.source_evidence IS DISTINCT FROM expected_source_evidence + OR NEW.source_change_request IS DISTINCT FROM expected_source_change_request + OR NEW.source_change_binding IS DISTINCT FROM expected_source_change_binding + OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_source_changes + WHERE change_id = NEW.source_change_id AND status = 'WAITING' + AND binding = expected_source_change_binding) + OR (SELECT count(*) FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.source_change_id) <> 1 + OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.source_change_id AND source_key = expected_source_key) + OR NOT EXISTS (SELECT 1 FROM password_reset_token token + WHERE token.account_id = NEW.account_id + AND token.expires_at = NEW.token_expires_at + AND sha256(convert_to(token.token, 'UTF8')) = NEW.token_hash) THEN + RAISE EXCEPTION 'Password-reset journal does not bind its exact request and V57 Account source intent' + USING ERRCODE = '23514'; + END IF; + + SELECT generation, source_version INTO persisted_generation, persisted_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid; + SELECT issuance_fence, source_version INTO persisted_fence, persisted_fence_source_version + FROM account_authority_issuance_fences WHERE account_uuid = NEW.account_uuid; + IF persisted_generation IS DISTINCT FROM NEW.expected_generation + OR persisted_source_version IS DISTINCT FROM NEW.expected_source_version + OR persisted_fence IS DISTINCT FROM NEW.expected_issuance_fence + OR persisted_fence_source_version + IS DISTINCT FROM NEW.expected_issuance_fence_source_version THEN + RAISE EXCEPTION 'Password-reset source capture differs from current Account counters' + USING ERRCODE = '23514'; + END IF; + SELECT last_sequence INTO persisted_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.checkpoint_stream; + IF NEW.checkpoint_sequence = 0 THEN + expected_baseline := + account_password_reset_draft_frame_text('account-draft-source-baseline/v1') + || account_password_reset_draft_frame_text(NEW.account_uuid::TEXT) + || account_password_reset_draft_frame_text('1') + || account_password_reset_draft_frame_text('1') + || account_password_reset_draft_frame_text(NEW.checkpoint_stream) + || account_password_reset_draft_frame_text('0'); + IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1 + OR NEW.capture_evidence IS DISTINCT FROM expected_baseline + OR (persisted_sequence IS NOT NULL AND persisted_sequence <> 0) + OR EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.checkpoint_stream) THEN + RAISE EXCEPTION 'Password-reset sequence-zero capture is not the pristine 1/1 baseline' + USING ERRCODE = '23514'; + END IF; + ELSIF persisted_sequence IS DISTINCT FROM NEW.checkpoint_sequence + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.checkpoint_stream + AND outbox_sequence = NEW.checkpoint_sequence + AND payload = NEW.capture_evidence) THEN + RAISE EXCEPTION 'Password-reset capture does not bind the latest Account event' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_password_reset_pending_envelope_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + journal account_password_reset_draft_source_changes%ROWTYPE; +BEGIN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Pending password-reset ciphertext is immutable' + USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + SELECT * INTO journal FROM account_password_reset_draft_source_changes + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR journal.status <> 'WAITING' + OR journal.token_expires_at <= LOCALTIMESTAMP THEN + RAISE EXCEPTION 'Pending password-reset ciphertext requires a live WAITING intent' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + ELSE + SELECT * INTO journal FROM account_password_reset_draft_source_changes + WHERE request_id = OLD.request_id FOR UPDATE; + IF NOT FOUND OR NOT (journal.status IN ('SOURCE_COMMITTED', 'SOURCE_ABORTED') + OR journal.token_expires_at <= LOCALTIMESTAMP) THEN + RAISE EXCEPTION 'Pending password-reset ciphertext may be erased only after outcome or original expiry' + USING ERRCODE = '23514'; + END IF; + RETURN OLD; + END IF; +END; +$$; + +CREATE FUNCTION account_password_reset_draft_link_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + journal account_password_reset_draft_source_changes%ROWTYPE; + source_status TEXT; + source_binding BYTEA; + source_aborted_at TIMESTAMPTZ; + source_abort_reason TEXT; + selected_change UUID; + selected_request TEXT; + persisted_generation BIGINT; + persisted_source_version BIGINT; + persisted_fence BIGINT; + persisted_fence_source_version BIGINT; + persisted_sequence BIGINT; +BEGIN + IF TG_TABLE_NAME = 'account_password_reset_draft_source_changes' THEN + selected_change := NEW.source_change_id; + selected_request := NEW.request_id; + ELSIF TG_TABLE_NAME = 'account_draft_authorization_source_changes' THEN + selected_change := NEW.change_id; + ELSE + selected_request := CASE WHEN TG_OP = 'DELETE' THEN OLD.request_id ELSE NEW.request_id END; + END IF; + IF selected_change IS NOT NULL AND selected_request IS NULL THEN + SELECT request_id INTO selected_request + FROM account_password_reset_draft_source_changes + WHERE source_change_id = selected_change; + END IF; + IF selected_request IS NULL THEN + RETURN NULL; + END IF; + SELECT * INTO journal FROM account_password_reset_draft_source_changes + WHERE request_id = selected_request; + IF NOT FOUND THEN + RETURN NULL; + END IF; + SELECT status, binding, aborted_at, abort_reason + INTO source_status, source_binding, source_aborted_at, source_abort_reason + FROM account_draft_authorization_source_changes + WHERE change_id = journal.source_change_id; + IF source_status IS DISTINCT FROM journal.status + OR source_binding IS DISTINCT FROM journal.source_change_binding + OR (journal.status = 'SOURCE_ABORTED' + AND (source_aborted_at IS DISTINCT FROM journal.aborted_at + OR source_abort_reason IS DISTINCT FROM journal.abort_reason)) THEN + RAISE EXCEPTION 'Password-reset journal and V57 source transition must commit together' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'WAITING' THEN + SELECT generation, source_version INTO persisted_generation, persisted_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = journal.account_uuid; + SELECT issuance_fence, source_version INTO persisted_fence, persisted_fence_source_version + FROM account_authority_issuance_fences WHERE account_uuid = journal.account_uuid; + SELECT last_sequence INTO persisted_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = journal.checkpoint_stream; + IF EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = journal.checkpoint_stream + AND request_id = journal.request_id) + OR EXISTS (SELECT 1 FROM account_password_reset_operation_receipts + WHERE token_hash = journal.token_hash) + OR EXISTS (SELECT 1 FROM accounts account + WHERE account.id = journal.account_id + AND account.account_uuid = journal.account_uuid + AND sha256(convert_to(account.password_hash, 'UTF8')) + = journal.target_verifier_digest) + OR (journal.token_expires_at > LOCALTIMESTAMP + AND NOT EXISTS (SELECT 1 FROM account_password_reset_pending_envelopes + WHERE request_id = journal.request_id)) + OR (journal.token_expires_at > LOCALTIMESTAMP + AND NOT EXISTS (SELECT 1 FROM password_reset_token token + WHERE token.account_id = journal.account_id + AND token.expires_at = journal.token_expires_at + AND sha256(convert_to(token.token, 'UTF8')) = journal.token_hash)) + OR persisted_generation IS DISTINCT FROM journal.expected_generation + OR persisted_source_version IS DISTINCT FROM journal.expected_source_version + OR persisted_fence IS DISTINCT FROM journal.expected_issuance_fence + OR persisted_fence_source_version + IS DISTINCT FROM journal.expected_issuance_fence_source_version + OR (journal.checkpoint_sequence = 0 + AND persisted_sequence IS NOT NULL AND persisted_sequence <> 0) + OR (journal.checkpoint_sequence > 0 + AND persisted_sequence IS DISTINCT FROM journal.checkpoint_sequence) + OR (journal.checkpoint_sequence > 0 AND NOT EXISTS ( + SELECT 1 FROM account_authority_outbox_events event + WHERE event.outbox_stream_key = journal.checkpoint_stream + AND event.outbox_sequence = journal.checkpoint_sequence + AND event.payload = journal.capture_evidence)) + OR (journal.checkpoint_sequence = 0 AND EXISTS ( + SELECT 1 FROM account_authority_outbox_events event + WHERE event.outbox_stream_key = journal.checkpoint_stream)) THEN + RAISE EXCEPTION 'WAITING password reset cannot mutate source or lose its live envelope' + USING ERRCODE = '23514'; + END IF; + ELSIF journal.status = 'SOURCE_COMMITTED' THEN + IF journal.event_stream IS DISTINCT FROM journal.checkpoint_stream + OR journal.event_id IS DISTINCT FROM + 'account-password-reset-event-v1:' || encode(journal.token_hash, 'hex') + OR journal.event_sequence IS DISTINCT FROM journal.checkpoint_sequence + 1 + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events event + WHERE event.outbox_stream_key = journal.event_stream + AND event.outbox_sequence = journal.event_sequence + AND event.request_id = journal.request_id + AND event.event_id = journal.event_id + AND event.event_digest = journal.event_digest + AND event.payload = journal.event_payload) + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_streams stream + WHERE stream.outbox_stream_key = journal.event_stream + AND stream.last_sequence = journal.event_sequence) + OR NOT EXISTS (SELECT 1 FROM account_password_reset_operation_receipts receipt + WHERE receipt.token_hash = journal.token_hash + AND receipt.account_id = journal.account_id + AND receipt.account_uuid = journal.account_uuid + AND receipt.operation_kind = 'PASSWORD_RESET' + AND receipt.request_id = journal.request_id + AND receipt.request_digest_version = journal.request_digest_version + AND receipt.request_digest = journal.request_digest + AND receipt.token_expires_at = journal.token_expires_at + AND receipt.password_verifier_digest = journal.target_verifier_digest + AND receipt.outbox_stream_key = journal.event_stream + AND receipt.outbox_sequence = journal.event_sequence + AND receipt.event_id = journal.event_id + AND receipt.event_digest = journal.event_digest + AND receipt.account_authority_generation = journal.expected_generation + 1 + AND receipt.account_source_version = journal.expected_source_version + 1 + AND receipt.issuance_fence = journal.expected_issuance_fence + 1 + AND receipt.issuance_fence_source_version + = journal.expected_issuance_fence_source_version + 1) + OR EXISTS (SELECT 1 FROM account_password_reset_pending_envelopes + WHERE request_id = journal.request_id) + OR EXISTS (SELECT 1 FROM password_reset_token token + WHERE token.account_id = journal.account_id + AND sha256(convert_to(token.token, 'UTF8')) = journal.token_hash) THEN + RAISE EXCEPTION 'Committed password reset lacks exact source receipt/event or secret erasure' + USING ERRCODE = '23514'; + END IF; + SELECT generation, source_version INTO persisted_generation, persisted_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = journal.account_uuid; + SELECT issuance_fence, source_version INTO persisted_fence, persisted_fence_source_version + FROM account_authority_issuance_fences WHERE account_uuid = journal.account_uuid; + IF persisted_generation IS DISTINCT FROM journal.expected_generation + 1 + OR persisted_source_version IS DISTINCT FROM journal.expected_source_version + 1 + OR persisted_fence IS DISTINCT FROM journal.expected_issuance_fence + 1 + OR persisted_fence_source_version + IS DISTINCT FROM journal.expected_issuance_fence_source_version + 1 + OR NOT EXISTS (SELECT 1 FROM accounts account + WHERE account.id = journal.account_id + AND account.account_uuid = journal.account_uuid + AND sha256(convert_to(account.password_hash, 'UTF8')) + = journal.target_verifier_digest) THEN + RAISE EXCEPTION 'Committed password reset did not install its exact verifier and counters' + USING ERRCODE = '23514'; + END IF; + ELSE + IF journal.status <> 'SOURCE_ABORTED' + OR EXISTS (SELECT 1 FROM account_authority_outbox_events event + WHERE event.outbox_stream_key = journal.checkpoint_stream + AND (event.request_id = journal.request_id + OR event.event_id = 'account-password-reset-event-v1:' || encode(journal.token_hash, 'hex'))) + OR EXISTS (SELECT 1 FROM account_password_reset_operation_receipts + WHERE token_hash = journal.token_hash) + OR EXISTS (SELECT 1 FROM account_password_reset_pending_envelopes + WHERE request_id = journal.request_id) THEN + RAISE EXCEPTION 'Aborted password reset must retain no source result or ciphertext' + USING ERRCODE = '23514'; + END IF; + SELECT generation, source_version INTO persisted_generation, persisted_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = journal.account_uuid; + SELECT issuance_fence, source_version INTO persisted_fence, persisted_fence_source_version + FROM account_authority_issuance_fences WHERE account_uuid = journal.account_uuid; + SELECT last_sequence INTO persisted_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = journal.checkpoint_stream; + IF persisted_generation IS DISTINCT FROM journal.expected_generation + OR persisted_source_version IS DISTINCT FROM journal.expected_source_version + OR persisted_fence IS DISTINCT FROM journal.expected_issuance_fence + OR persisted_fence_source_version + IS DISTINCT FROM journal.expected_issuance_fence_source_version + OR (journal.checkpoint_sequence = 0 AND persisted_sequence IS NOT NULL AND persisted_sequence <> 0) + OR (journal.checkpoint_sequence > 0 AND persisted_sequence IS DISTINCT FROM journal.checkpoint_sequence) + OR (journal.checkpoint_sequence > 0 AND NOT EXISTS ( + SELECT 1 FROM account_authority_outbox_events event + WHERE event.outbox_stream_key = journal.checkpoint_stream + AND event.outbox_sequence = journal.checkpoint_sequence + AND event.payload = journal.capture_evidence)) + OR (journal.checkpoint_sequence = 0 AND EXISTS ( + SELECT 1 FROM account_authority_outbox_events event + WHERE event.outbox_stream_key = journal.checkpoint_stream)) THEN + RAISE EXCEPTION 'Aborted password reset changed its captured Account source' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_password_reset_draft_request_guard + BEFORE INSERT OR UPDATE ON account_password_reset_draft_source_changes + FOR EACH ROW EXECUTE FUNCTION account_password_reset_draft_journal_guard(); +CREATE TRIGGER account_password_reset_draft_no_delete_guard + BEFORE DELETE ON account_password_reset_draft_source_changes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_password_reset_draft_no_truncate_guard + BEFORE TRUNCATE ON account_password_reset_draft_source_changes + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_password_reset_pending_envelope_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_password_reset_pending_envelopes + FOR EACH ROW EXECUTE FUNCTION account_password_reset_pending_envelope_guard(); +CREATE TRIGGER account_password_reset_pending_envelope_no_truncate_guard + BEFORE TRUNCATE ON account_password_reset_pending_envelopes + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +CREATE CONSTRAINT TRIGGER account_password_reset_draft_link_guard + AFTER INSERT OR UPDATE ON account_password_reset_draft_source_changes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_password_reset_draft_link_guard(); +CREATE CONSTRAINT TRIGGER account_password_reset_draft_v57_link_guard + AFTER UPDATE ON account_draft_authorization_source_changes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_password_reset_draft_link_guard(); +CREATE CONSTRAINT TRIGGER account_password_reset_draft_envelope_link_guard + AFTER INSERT OR DELETE ON account_password_reset_pending_envelopes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_password_reset_draft_link_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java index 8db75ac035..a7e0146701 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java @@ -20,6 +20,16 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.entity.Account; @@ -38,14 +48,22 @@ import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader; import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer.LogoutAllResult; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllDraftSourceChangeRepository.PendingIntentSnapshot; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -153,6 +171,12 @@ void exactRetryRecoversOriginalResultAfterLaterSourceAdvanceWithoutRewritingCoun LogoutAllResult firstResult = commit(fixture, seed, firstRequest, firstDigest, firstTokenHash, seed.initialState()); LogoutAllReceipt firstReceipt = logoutReceipt(fixture, firstRequest); + AccountAuthorityOutboxRepository.Event firstEvent = event(fixture, seed, 1L); + PendingIntentSnapshot firstSourceIntent = pendingIntent(fixture, firstRequest).orElseThrow(); + var firstFenceChange = sourceChange(firstSourceIntent); + var firstFenceChangeSnapshot = + transaction( + fixture.transaction(), () -> draftFences(fixture).readSourceChange(firstFenceChange)); UUID laterRequest = UUID.randomUUID(); String laterTokenHash = digest("presented-token:" + laterRequest); @@ -171,6 +195,366 @@ void exactRetryRecoversOriginalResultAfterLaterSourceAdvanceWithoutRewritingCoun assertThat(retry).isEqualTo(firstResult); assertThat(logoutReceipt(fixture, firstRequest)).isEqualTo(firstReceipt); assertThat(snapshot(fixture, seed)).isEqualTo(afterLaterAdvance); + assertSameEvent(firstEvent, event(fixture, seed, 1L)); + assertThat(pendingIntent(fixture, firstRequest).orElseThrow()) + .satisfies( + replay -> { + assertThat(replay.requestPayload()) + .containsExactly(firstSourceIntent.requestPayload()); + assertThat(replay.captureEvidence()) + .containsExactly(firstSourceIntent.captureEvidence()); + assertThat(replay.sourceEvidence()) + .containsExactly(firstSourceIntent.sourceEvidence()); + assertThat(replay.sourceChangeBinding()) + .containsExactly(firstSourceIntent.sourceChangeBinding()); + assertThat(replay.status()).isEqualTo("SOURCE_COMMITTED"); + }); + var replayedFenceChange = + transaction( + fixture.transaction(), () -> draftFences(fixture).readSourceChange(firstFenceChange)); + assertThat(replayedFenceChange.changeId()).isEqualTo(firstFenceChangeSnapshot.changeId()); + assertThat(replayedFenceChange.binding()).containsExactly(firstFenceChangeSnapshot.binding()); + assertThat(replayedFenceChange.status()).isEqualTo(firstFenceChangeSnapshot.status()); + assertThat(replayedFenceChange.requestedAt()).isEqualTo(firstFenceChangeSnapshot.requestedAt()); + assertThat(replayedFenceChange.committedAt()).isEqualTo(firstFenceChangeSnapshot.committedAt()); + } + + /** + * These cases connect real PostgreSQL Account source writes to the V57 fence tables. The Draft + * bindings and owner readbacks below are synthetic test evidence; they do not authenticate a real + * Draft operation or prove the absent Game Design/World owner readback producers. + */ + @Test + void revokeOrderWaitsForBothExactAbortsBeforeOneLogoutAdvanceAndNeverAdmitsDelayedCommit() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + DraftAuthorizationFenceBinding binding = + syntheticDraftBinding(seed, seed.initialState(), 0L, null); + transaction( + fixture.transaction(), + () -> { + draftFences(fixture).reserve(binding); + return null; + }); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("revocation-wins-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + StoredState before = snapshot(fixture, seed); + + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + PendingIntentSnapshot waiting = pendingIntent(fixture, requestId).orElseThrow(); + assertThat(waiting.status()).isEqualTo("WAITING"); + assertThat(waiting.expectedGeneration()).isEqualTo(1L); + assertThat(waiting.expectedSourceVersion()).isEqualTo(1L); + assertThat(waiting.expectedIssuanceFence()).isEqualTo(1L); + assertThat(waiting.expectedIssuanceFenceSourceVersion()).isEqualTo(1L); + assertThat(waiting.checkpointSequence()).isZero(); + SourceChange sourceChange = sourceChange(waiting); + assertThat(sourceChange.sources()).hasSize(1); + assertThat(sourceChange.sources().getFirst().kind()).isEqualTo(SourceKind.ACCOUNT); + assertThat(sourceChange.sources().getFirst().scopeId()) + .isEqualTo(seed.accountUuid().toString()); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).read(binding).ordering())) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), () -> draftFences(fixture).claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + + syntheticOwnerReadback( + fixture, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {31}); + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat(pendingIntent(fixture, requestId).orElseThrow().sourceChangeBinding()) + .containsExactly(waiting.sourceChangeBinding()); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + + syntheticOwnerReadback( + fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {32}); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).readSettlement(binding))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat( + transaction( + fixture.transaction(), + () -> draftFences(fixture).sourceMutationPermitted(sourceChange))) + .isTrue(); + + assertThat(commit(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState())) + .isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + assertThat(authority(fixture, seed).generation()).isEqualTo(2L); + assertThat(authority(fixture, seed).sourceVersion()).isEqualTo(2L); + assertThat(authority(fixture, seed).issuanceFence().value()).isEqualTo(2L); + assertThat(authority(fixture, seed).issuanceFence().sourceVersion()).isEqualTo(2L); + assertThat(logoutReceipt(fixture, requestId).outboxSequence()).isEqualTo(1L); + assertThat(event(fixture, seed, 1L).requestId()).isEqualTo(requestId.toString()); + assertThat(pendingIntent(fixture, requestId).orElseThrow().status()) + .isEqualTo("SOURCE_COMMITTED"); + assertThat( + transaction( + fixture.transaction(), + () -> draftFences(fixture).readSourceChange(sourceChange).status())) + .isEqualTo("SOURCE_COMMITTED"); + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), () -> draftFences(fixture).claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + assertThat(snapshot(fixture, seed).generation()).isEqualTo(2L); + assertThat(count(fixture, "account_authority_outbox_events")).isEqualTo(1L); + assertThat(count(fixture, "account_logout_all_operation_receipts")).isEqualTo(1L); + } + + @Test + void commitOrderWaitsForBothExactOutcomesIncludingMixedFailureBeforeLogoutAdvance() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + DraftAuthorizationFenceBinding binding = + syntheticDraftBinding(seed, seed.initialState(), 0L, null); + transaction( + fixture.transaction(), + () -> { + draftFences(fixture).reserve(binding); + draftFences(fixture).claimCommitOrder(binding); + return null; + }); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("commit-order-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + StoredState before = snapshot(fixture, seed); + + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + PendingIntentSnapshot waiting = pendingIntent(fixture, requestId).orElseThrow(); + SourceChange sourceChange = sourceChange(waiting); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).read(binding).ordering())) + .isEqualTo(Ordering.COMMIT_ORDER); + + OwnerReadback expectedWorldReadback = + syntheticOwnerReadback(fixture, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {41}); + byte[] expectedWorldReadbackBytes = expectedWorldReadback.canonicalBytes(); + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + + syntheticOwnerReadback( + fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {42}); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).readSettlement(binding))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + var originalWorldResult = + transaction( + fixture.transaction(), + () -> draftFences(fixture).readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(originalWorldResult.outcome()).isEqualTo(Outcome.COMMITTED); + assertThat(originalWorldResult.readback()).containsExactly(expectedWorldReadbackBytes); + + assertThat(commit(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState())) + .isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + assertThat(authority(fixture, seed).generation()).isEqualTo(2L); + assertThat(logoutReceipt(fixture, requestId).outboxSequence()).isEqualTo(1L); + assertThat(event(fixture, seed, 1L).requestId()).isEqualTo(requestId.toString()); + assertThat(pendingIntent(fixture, requestId).orElseThrow().status()) + .isEqualTo("SOURCE_COMMITTED"); + assertThat( + transaction( + fixture.transaction(), + () -> draftFences(fixture).readSourceChange(sourceChange).status())) + .isEqualTo("SOURCE_COMMITTED"); + var replayedWorldResult = + transaction( + fixture.transaction(), + () -> draftFences(fixture).readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(replayedWorldResult.outcome()).isEqualTo(originalWorldResult.outcome()); + assertThat(replayedWorldResult.readback()).containsExactly(expectedWorldReadbackBytes); + assertThat(replayedWorldResult.recordedAt()).isEqualTo(originalWorldResult.recordedAt()); + assertThat(count(fixture, "account_authority_outbox_events")).isEqualTo(1L); + assertThat(count(fixture, "account_logout_all_operation_receipts")).isEqualTo(1L); + } + + @Test + void pendingRetryKeepsOriginalCaptureAndConflictsOnlyOnChangedCallerBindings() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + Seed otherAccount = seedAccount(fixture); + DraftAuthorizationFenceBinding binding = + syntheticDraftBinding(seed, seed.initialState(), 0L, null); + transaction( + fixture.transaction(), + () -> { + draftFences(fixture).reserve(binding); + return null; + }); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("original-pending-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + PendingIntentSnapshot original = pendingIntent(fixture, requestId).orElseThrow(); + StoredState before = snapshot(fixture, seed); + ScopeState changedServerCounters = + new ScopeState( + seed.initialState().scope(), + 81L, + 82L, + new AccountAuthorityGenerationRepository.IssuanceFence(seed.accountUuid(), 83L, 84L)); + + assertPending(fixture, seed, requestId, requestDigest, tokenHash, changedServerCounters); + assertPendingIntentEquals(pendingIntent(fixture, requestId).orElseThrow(), original); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + + assertThatThrownBy( + () -> + commit( + fixture, + seed, + requestId, + digest("changed-pending-caller-digest:" + requestId), + tokenHash, + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + requestId, + logoutAllDigest(seed.accountUuid(), "player-bootstrap", tokenHash), + "player-bootstrap", + tokenHash, + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + requestId, + requestDigest, + digest("changed-pending-token:" + requestId), + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + producer(fixture) + .commit( + requestId, + 1, + requestDigest, + TOKEN_PROFILE, + tokenHash, + account(fixture, otherAccount), + authority(fixture, otherAccount))) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + UUID.randomUUID(), + logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash), + tokenHash, + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + + assertPendingIntentEquals(pendingIntent(fixture, requestId).orElseThrow(), original); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat(count(fixture, "account_logout_all_operation_receipts")).isZero(); + assertThat(count(fixture, "account_authority_outbox_events")).isZero(); + } + + @Test + void lateDatabaseFailureAfterReceiptEventAndBothJournalTransitionsRollsBackLogoutOnly() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + DraftAuthorizationFenceBinding binding = + syntheticDraftBinding(seed, seed.initialState(), 0L, null); + transaction( + fixture.transaction(), + () -> { + draftFences(fixture).reserve(binding); + draftFences(fixture).claimCommitOrder(binding); + return null; + }); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("late-failure-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + PendingIntentSnapshot waiting = pendingIntent(fixture, requestId).orElseThrow(); + SourceChange sourceChange = sourceChange(waiting); + syntheticOwnerReadback(fixture, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {51}); + syntheticOwnerReadback(fixture, binding, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {52}); + StoredState beforeRetry = snapshot(fixture, seed); + + installLateLogoutFailureTrigger(fixture, requestId); + assertThatThrownBy( + () -> commit(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState())) + .satisfies( + failure -> { + PSQLException postgresFailure = rootPostgresCause(failure); + assertThat(postgresFailure.getSQLState()).isEqualTo("P0001"); + assertThat((Throwable) postgresFailure) + .hasMessageContaining( + "injected late failure after logout receipt, event, V57 and V60 transitions"); + }); + + assertThat(snapshot(fixture, seed)).isEqualTo(beforeRetry); + assertThat(count(fixture, "account_authority_outbox_events")).isZero(); + assertThat(count(fixture, "account_authority_outbox_streams")).isZero(); + assertThat(count(fixture, "account_logout_all_operation_receipts")).isZero(); + PendingIntentSnapshot retained = pendingIntent(fixture, requestId).orElseThrow(); + assertPendingIntentEquals(retained, waiting); + assertThat(retained.status()).isEqualTo("WAITING"); + assertThat( + transaction( + fixture.transaction(), + () -> draftFences(fixture).readSourceChange(sourceChange).status())) + .isEqualTo("WAITING"); + assertThat( + transaction(fixture.transaction(), () -> draftFences(fixture).readSettlement(binding))) + .isEqualTo(Settlement.COMMITTED); + } + + @Test + void v59ToV60PreservesImmutableLogoutResetSourceOutboxAndFenceHistoryWithoutBackfill() { + Fixture fixture = newFixtureAtVersion("59"); + Seed seed = seedAccount(fixture); + reset(fixture, seed, "migration-preservation-password"); + seedLegacyLogoutReceipt(fixture, seed); + seedSyntheticDraftHistory(fixture, seed); + + List preservedTables = + List.of( + "account_password_reset_operation_receipts", + "account_logout_all_operation_receipts", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_outbox_streams", + "account_authority_outbox_events", + "account_draft_authorization_source_locks", + "account_draft_authorization_fences", + "account_draft_authorization_sources", + "account_draft_authorization_owner_readbacks", + "account_draft_authorization_source_changes", + "account_draft_authorization_changed_scopes", + "account_issuer_tenant_draft_source_changes"); + List> before = preservedTables.stream().map(t -> rowImages(fixture, t)).toList(); + + migrateFixtureToV60(fixture); + + for (int index = 0; index < preservedTables.size(); index++) { + assertThat(rowImages(fixture, preservedTables.get(index))) + .as("V60 preserves every existing row in %s byte-for-byte", preservedTables.get(index)) + .isEqualTo(before.get(index)); + } + assertThat(count(fixture, "account_logout_all_draft_source_changes")).isZero(); } @Test @@ -719,21 +1103,312 @@ private LogoutAllResult concurrentCommit( return commit(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); } + private DraftAuthorizationFenceRepository draftFences(Fixture fixture) { + return new DraftAuthorizationFenceRepository(fixture.transactionDsl()); + } + + private Optional pendingIntent(Fixture fixture, UUID requestId) { + return transaction( + fixture.transaction(), + () -> + new AccountLogoutAllDraftSourceChangeRepository(fixture.transactionDsl()) + .readPendingIntent(requestId)); + } + + private SourceChange sourceChange(PendingIntentSnapshot intent) { + return SourceChange.fromStored(intent.sourceChangeBinding()); + } + + private void assertPending( + Fixture fixture, + Seed seed, + UUID requestId, + String requestDigest, + String tokenHash, + ScopeState expectedState) { + assertThatThrownBy( + () -> commit(fixture, seed, requestId, requestDigest, tokenHash, expectedState)) + .isInstanceOf( + AccountLogoutAllDraftSourceChangeRepository.PendingSourceChangeException.class); + } + + private void assertPendingIntentEquals( + PendingIntentSnapshot actual, PendingIntentSnapshot expected) { + assertThat(actual.requestId()).isEqualTo(expected.requestId()); + assertThat(actual.sourceChangeId()).isEqualTo(expected.sourceChangeId()); + assertThat(actual.requestPayload()).containsExactly(expected.requestPayload()); + assertThat(actual.captureEvidence()).containsExactly(expected.captureEvidence()); + assertThat(actual.sourceEvidence()).containsExactly(expected.sourceEvidence()); + assertThat(actual.sourceChangeRequest()).containsExactly(expected.sourceChangeRequest()); + assertThat(actual.sourceChangeBinding()).containsExactly(expected.sourceChangeBinding()); + assertThat(actual.status()).isEqualTo(expected.status()); + assertThat(actual.expectedGeneration()).isEqualTo(expected.expectedGeneration()); + assertThat(actual.expectedSourceVersion()).isEqualTo(expected.expectedSourceVersion()); + assertThat(actual.expectedIssuanceFence()).isEqualTo(expected.expectedIssuanceFence()); + assertThat(actual.expectedIssuanceFenceSourceVersion()) + .isEqualTo(expected.expectedIssuanceFenceSourceVersion()); + assertThat(actual.checkpointSequence()).isEqualTo(expected.checkpointSequence()); + } + + private DraftAuthorizationFenceBinding syntheticDraftBinding( + Seed seed, ScopeState sourceState, long checkpointSequence, byte[] sourceEvidence) { + byte[] evidence = + sourceEvidence == null + ? "synthetic-authenticated-owner-source-readback".getBytes(StandardCharsets.UTF_8) + : sourceEvidence.clone(); + SourceEvidence accountSource = + new SourceEvidence( + SourceKind.ACCOUNT, + seed.accountUuid().toString(), + Long.toString(sourceState.generation()), + Long.toString(sourceState.sourceVersion()), + streamKey(seed.accountUuid()), + Long.toString(checkpointSequence), + evidence); + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof(tenantId, versionId, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + requestId, + commitId, + "logout-all-draft-base:" + UUID.randomUUID(), + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "synthetic complete Draft owner payload")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"))); + byte[] completeBytes = complete.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + seed.accountUuid(), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "1", + completeBytes, + completeBytes, + complete.digest(), + List.of(accountSource)); + } + + private OwnerReadback syntheticOwnerReadback( + Fixture fixture, + DraftAuthorizationFenceBinding binding, + Owner owner, + Outcome outcome, + byte[] result) { + OwnerReadback readback = + new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + result); + transaction( + fixture.transaction(), + () -> { + draftFences(fixture).recordOwnerReadback(binding, readback); + return null; + }); + return readback; + } + + private void installLateLogoutFailureTrigger(Fixture fixture, UUID requestId) { + fixture + .setupDsl() + .execute( + "CREATE FUNCTION account_logout_all_test_late_failure() RETURNS trigger " + + "LANGUAGE plpgsql AS $$ BEGIN " + + "IF NOT EXISTS (SELECT 1 FROM account_logout_all_operation_receipts receipt " + + "JOIN account_authority_outbox_events event ON " + + "event.outbox_stream_key = receipt.outbox_stream_key " + + "AND event.outbox_sequence = receipt.outbox_sequence " + + "JOIN account_logout_all_draft_source_changes journal ON " + + "journal.request_id = receipt.request_id " + + "JOIN account_draft_authorization_source_changes source_change ON " + + "source_change.change_id = journal.source_change_id " + + "WHERE receipt.request_id = NEW.request_id " + + "AND journal.status = 'SOURCE_COMMITTED' " + + "AND source_change.status = 'SOURCE_COMMITTED' " + + "AND event.event_id = receipt.event_id AND event.event_digest = receipt.event_digest) " + + "THEN RAISE EXCEPTION 'late failure ran before receipt, event, and both journal transitions'; " + + "END IF; " + + "RAISE EXCEPTION 'injected late failure after logout receipt, event, V57 and V60 transitions'; " + + "END; $$"); + fixture + .setupDsl() + .execute( + "CREATE CONSTRAINT TRIGGER account_logout_all_test_late_failure " + + "AFTER INSERT ON account_logout_all_operation_receipts " + + "DEFERRABLE INITIALLY DEFERRED FOR EACH ROW " + + "EXECUTE FUNCTION account_logout_all_test_late_failure()"); + } + + private LogoutAllReceipt seedLegacyLogoutReceipt(Fixture fixture, Seed seed) { + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("pre-v60-logout-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + return transaction( + fixture.transaction(), + () -> { + ScopeState current = fixture.authority().read(AuthorityScope.account(seed.accountUuid())); + ScopeState advanced = fixture.authority().advance(current, current.issuanceFence()); + String stream = streamKey(seed.accountUuid()); + String eventId = EVENT_ID_PREFIX + requestId; + long sequence = + fixture + .outbox() + .readCheckpoint(stream) + .map(checkpoint -> checkpoint.outboxSequence() + 1L) + .orElse(1L); + var eventEvidence = + AccountLogoutAllAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", requestId.toString()), + Map.entry("accountId", seed.accountUuid().toString()), + Map.entry("sourceScope", "account/" + seed.accountUuid()), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", Long.toString(advanced.generation())), + Map.entry("sourceVersion", Long.toString(advanced.sourceVersion())), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", Long.toString(advanced.generation()), + "outboxStreamKey", stream, + "outboxSequence", Long.toString(sequence))))); + var appended = + fixture + .outbox() + .append( + stream, + requestId.toString(), + eventEvidence.eventId(), + eventEvidence.eventDigest(), + eventEvidence.canonicalJsonUtf8()); + LogoutAllReceipt receipt = + LogoutAllReceipt.committed( + requestId, + seed.accountId(), + seed.accountUuid(), + requestDigest, + tokenHash, + TOKEN_PROFILE, + stream, + appended.outboxSequence(), + eventEvidence.eventId(), + eventEvidence.eventDigest(), + advanced, + advanced.issuanceFence()); + fixture.logoutOperations().insert(receipt); + return receipt; + }); + } + + private void seedSyntheticDraftHistory(Fixture fixture, Seed seed) { + ScopeState state = authority(fixture, seed); + AccountAuthorityOutboxRepository.Event latest = event(fixture, seed, 2L); + DraftAuthorizationFenceBinding binding = + syntheticDraftBinding(seed, state, latest.outboxSequence(), latest.payload()); + DraftAuthorizationFenceRepository fences = draftFences(fixture); + SourceChange change = + new SourceChange( + UUID.randomUUID(), + binding.sources(), + "synthetic prior source change".getBytes(StandardCharsets.UTF_8)); + transaction( + fixture.transaction(), + () -> { + fences.reserve(binding); + fences.claimCommitOrder(binding); + fences.requestSourceChange(change); + return null; + }); + syntheticOwnerReadback(fixture, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {61}); + syntheticOwnerReadback(fixture, binding, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {62}); + transaction( + fixture.transaction(), + () -> { + fences.markSourceCommitted(change); + return null; + }); + } + + private List rowImages(Fixture fixture, String table) { + return fixture + .setupDsl() + .fetch( + "SELECT row_to_json(row_data)::text AS row_image FROM " + + table + + " row_data ORDER BY row_image") + .getValues("row_image", String.class); + } + + private void migrateFixtureToV60(Fixture fixture) { + Flyway.configure() + .dataSource(fixture.dataSource()) + .schemas(fixture.schema()) + .defaultSchema(fixture.schema()) + .placeholders(Map.of("serviceSchema", fixture.schema())) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("60")) + .load() + .migrate(); + } + + private static PSQLException rootPostgresCause(Throwable failure) { + Throwable cause = failure; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(PSQLException.class); + return (PSQLException) cause; + } + private Fixture newFixture() { + return newFixtureAtVersion(null); + } + + private Fixture newFixtureAtVersion(String targetVersion) { String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); + var flywayConfiguration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (targetVersion != null) { + flywayConfiguration.target(MigrationVersion.fromVersion(targetVersion)); + } + flywayConfiguration.load().migrate(); DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); DSLContext transactionDsl = @@ -750,6 +1425,8 @@ private Fixture newFixture() { new AccountLogoutAllOperationRepository(transactionDsl); PasswordResetTokenRepository tokens = new PasswordResetTokenRepository(transactionDsl); return new Fixture( + schema, + dataSource, setupDsl, transactionDsl, transactionManager, @@ -1137,6 +1814,8 @@ private T transaction(TransactionTemplate transaction, Supplier operation } private record Fixture( + String schema, + DriverManagerDataSource dataSource, DSLContext setupDsl, DSLContext transactionDsl, PlatformTransactionManager transactionManager, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountPasswordResetDraftSourceChangePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountPasswordResetDraftSourceChangePostgresIntegrationTest.java new file mode 100644 index 0000000000..5be8ddd2f3 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountPasswordResetDraftSourceChangePostgresIntegrationTest.java @@ -0,0 +1,917 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.PasswordResetToken; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository.AbortReason; +import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository.Participation; +import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository.PendingResetIntent; +import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository.PendingResetSnapshot; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.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 proof for V61 storage and V57 source-ordering participation only. + * + *

Owner outcomes in these fixtures are synthetic rows supplied directly to the Account fence. + * They model exact durable upstream readback shapes; they do not authenticate an owner producer or + * prove the public password-reset flow, source recovery worker, or cleanup worker. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountPasswordResetDraftSourceChangePostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "pw_reset_draft_source"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final String TARGET_VERIFIER = + "$argon2id$v=19$m=65536,t=3,p=1$AAAAAAAAAAAAAAAAAAAAAA$" + + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + private static final byte[] TARGET_VERIFIER_BYTES = + TARGET_VERIFIER.getBytes(StandardCharsets.UTF_8); + private static final String ORIGINAL_VERIFIER = "unchanged-original-verifier"; + private static final HexFormat HEX = HexFormat.of(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @TempDir Path temporaryDirectory; + + @Test + void liveWaitingRetainsExactEnvelopeAndSourceAcrossExactRetryWithoutAccountMutation() + throws Exception { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, Duration.ofHours(2)); + AccountState accountBefore = accountState(fixture, seed); + + PendingCase pending = beginPending(fixture, seed, FenceOrder.REVOKE); + PendingResetSnapshot snapshot = durableSnapshot(fixture, seed, pending.intent()); + StoredState retained = storedState(fixture, seed, pending); + AccountEncryptedEnvelope storedEnvelope = + transaction( + fixture.transaction(), + () -> fixture.pendingResets().readPendingEnvelope(snapshot).orElseThrow()); + assertThat(storedEnvelope).isEqualTo(pending.originalEnvelope()); + byte[] recoveredVerifier = + fixture.crypto().decryptPendingReset(storedEnvelope, pending.intent().envelopeBinding()); + try { + assertThat(recoveredVerifier).containsExactly(TARGET_VERIFIER_BYTES); + } finally { + Arrays.fill(recoveredVerifier, (byte) 0); + } + + assertThat(snapshot.status()).isEqualTo("WAITING"); + assertThat(snapshot.envelopePresent()).isTrue(); + assertThat(snapshot.intent()).isEqualTo(pending.intent()); + assertThat( + transaction( + fixture.transaction(), + () -> fixture.fences().readSourceChange(pending.intent().sourceChange()).binding())) + .containsExactly(pending.intent().sourceChange().canonicalBytes()); + assertThat(accountState(fixture, seed)).isEqualTo(accountBefore); + + Participation exactRetry = + transaction( + fixture.transaction(), + () -> fixture.pendingResets().beginWaiting(pending.intent(), Optional.empty())); + + assertThat(exactRetry.snapshot().intent()).isEqualTo(snapshot.intent()); + assertThat(exactRetry.snapshot().status()).isEqualTo("WAITING"); + assertThat(exactRetry.snapshot().envelopePresent()).isTrue(); + assertThat(storedState(fixture, seed, pending)).isEqualTo(retained); + assertThat(accountState(fixture, seed)).isEqualTo(accountBefore); + } + + @Test + void changedRequestAccountTokenBindingAndRemintAreRejectedWithoutMutation() throws Exception { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, Duration.ofHours(2)); + PendingCase pending = beginPending(fixture, seed, FenceOrder.REVOKE); + StoredState retained = storedState(fixture, seed, pending); + AccountState accountBefore = accountState(fixture, seed); + + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), + () -> + fixture + .pendingResets() + .findForUpdate( + seed.accountId(), UUID.randomUUID(), pending.intent().tokenHash()))) + .isInstanceOf(IllegalStateException.class); + assertThat( + transaction( + fixture.transaction(), + () -> + fixture + .pendingResets() + .findForUpdate( + seed.accountId(), + seed.accountUuid(), + tokenHash("different-reset-token")) + .isEmpty())) + .isTrue(); + + PendingResetIntent changedRequest = + recapture( + fixture, + seed, + pending.intent().tokenExpiresAt().plusMinutes(1), + TARGET_VERIFIER_BYTES, + UUID.randomUUID()); + assertRejectedBegin(fixture, changedRequest, Optional.empty()); + + PendingResetIntent changedPassword = + recapture( + fixture, + seed, + pending.intent().tokenExpiresAt(), + "$argon2id$v=19$m=65536,t=3,p=1$BBBBBBBBBBBBBBBBBBBBBB$" + .concat("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB") + .getBytes(StandardCharsets.UTF_8), + UUID.randomUUID()); + assertRejectedBegin(fixture, changedPassword, Optional.empty()); + + PendingResetIntent changedSourceBinding = + recapture( + fixture, + seed, + pending.intent().tokenExpiresAt(), + TARGET_VERIFIER_BYTES, + UUID.randomUUID()); + assertRejectedBegin(fixture, changedSourceBinding, Optional.empty()); + assertRejectedBegin(fixture, pending.intent(), Optional.of(encrypt(fixture, pending.intent()))); + + assertThat(storedState(fixture, seed, pending)).isEqualTo(retained); + assertThat(accountState(fixture, seed)).isEqualTo(accountBefore); + } + + @Test + void deferredGuardRejectsLiveWaitingWithoutEnvelopeAtTransactionCommit() throws Exception { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, Duration.ofHours(2)); + PendingResetIntent intent = + recapture(fixture, seed, seed.deadline(), TARGET_VERIFIER_BYTES, UUID.randomUUID()); + AccountState accountBefore = accountState(fixture, seed); + + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> { + Participation settled = + fixture.pendingResets().beginWaiting(intent, Optional.empty()); + assertThat(settled.settledAtClaim()).isTrue(); + return null; + })) + .hasStackTraceContaining( + "WAITING password reset cannot mutate source or lose its live envelope"); + + assertThat(accountState(fixture, seed)).isEqualTo(accountBefore); + assertThat( + rows( + fixture.setupDsl(), + "account_password_reset_draft_source_changes", + "request_id = ?", + intent.requestId())) + .isEmpty(); + assertThat( + rows( + fixture.setupDsl(), + "account_draft_authorization_source_changes", + "change_id = ?", + intent.sourceChange().changeId())) + .isEmpty(); + assertThat( + rows( + fixture.setupDsl(), + "account_password_reset_pending_envelopes", + "request_id = ?", + intent.requestId())) + .isEmpty(); + } + + @Test + void commitAndRevokeOrderingRequireTheirExactDefinitiveOwnerOutcomesBeforeSourceAbort() + throws Exception { + Fixture revokeFixture = newFixture(); + Seed revokeSeed = seedAccountAndToken(revokeFixture, Duration.ofHours(2)); + PendingCase revokePending = beginPending(revokeFixture, revokeSeed, FenceOrder.REVOKE); + PendingResetSnapshot revokeSnapshot = + durableSnapshot(revokeFixture, revokeSeed, revokePending.intent()); + + assertThat(readOrdering(revokeFixture, revokePending.binding())) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThat(abort(revokeFixture, revokeSnapshot, AbortReason.DEFINITIVE_ABORT)).isFalse(); + recordOwner(revokeFixture, revokePending.binding(), Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + assertThat(abort(revokeFixture, revokeSnapshot, AbortReason.DEFINITIVE_ABORT)).isFalse(); + recordOwner( + revokeFixture, revokePending.binding(), Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThat(readSettlement(revokeFixture, revokePending.binding())) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat(abort(revokeFixture, revokeSnapshot, AbortReason.DEFINITIVE_ABORT)).isTrue(); + + Fixture commitFixture = newFixture(); + Seed commitSeed = seedAccountAndToken(commitFixture, Duration.ofHours(2)); + PendingCase commitPending = beginPending(commitFixture, commitSeed, FenceOrder.COMMIT); + PendingResetSnapshot commitSnapshot = + durableSnapshot(commitFixture, commitSeed, commitPending.intent()); + + assertThat(readOrdering(commitFixture, commitPending.binding())) + .isEqualTo(Ordering.COMMIT_ORDER); + recordOwner(commitFixture, commitPending.binding(), Owner.WORLD, Outcome.COMMITTED); + assertThat(abort(commitFixture, commitSnapshot, AbortReason.DEFINITIVE_ABORT)).isFalse(); + recordOwner( + commitFixture, commitPending.binding(), Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThat(readSettlement(commitFixture, commitPending.binding())) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat(abort(commitFixture, commitSnapshot, AbortReason.DEFINITIVE_ABORT)).isTrue(); + } + + @Test + void expiryErasesSecretButDoesNotSettleOrReleaseUnresolvedSourceParticipation() throws Exception { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, Duration.ofSeconds(4)); + PendingCase pending = beginPending(fixture, seed, FenceOrder.REVOKE); + PendingResetSnapshot original = durableSnapshot(fixture, seed, pending.intent()); + + awaitExpiry(pending.intent().tokenExpiresAt()); + assertThat( + transaction( + fixture.transaction(), + () -> + fixture + .pendingResets() + .eraseEnvelopeAfterExpiry(original, LocalDateTime.now()))) + .isTrue(); + + PendingResetSnapshot erased = durableSnapshot(fixture, seed, pending.intent()); + assertThat(erased.status()).isEqualTo("WAITING"); + assertThat(erased.envelopePresent()).isFalse(); + assertThat(readSourceStatus(fixture, pending.intent().sourceChange())).isEqualTo("WAITING"); + assertThat(readOrdering(fixture, pending.binding())).isEqualTo(Ordering.REVOKE_ORDER); + assertThat(abort(fixture, erased, AbortReason.EXPIRED)).isFalse(); + assertThat(readSourceStatus(fixture, pending.intent().sourceChange())).isEqualTo("WAITING"); + + recordOwner(fixture, pending.binding(), Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + recordOwner(fixture, pending.binding(), Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThat(abort(fixture, erased, AbortReason.EXPIRED)).isTrue(); + } + + @Test + void lateRollbackRestoresBothPendingResetJournalAndV57SourceFence() throws Exception { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, Duration.ofHours(2)); + PendingCase pending = beginPending(fixture, seed, FenceOrder.REVOKE); + PendingResetSnapshot waiting = durableSnapshot(fixture, seed, pending.intent()); + recordOwner(fixture, pending.binding(), Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + recordOwner(fixture, pending.binding(), Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + StoredState beforeAbort = storedState(fixture, seed, pending); + + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), + () -> { + assertThat( + fixture + .pendingResets() + .abort( + waiting, AbortReason.DEFINITIVE_ABORT, LocalDateTime.now())) + .isTrue(); + throw new DeliberateRollback(); + })) + .isInstanceOf(DeliberateRollback.class); + + assertThat(storedState(fixture, seed, pending)).isEqualTo(beforeAbort); + assertThat(durableSnapshot(fixture, seed, pending.intent()).status()).isEqualTo("WAITING"); + } + + @Test + void sourceAbortedIsImmutableNoMutationTerminalDistinctFromSourceCommit() throws Exception { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, Duration.ofHours(2)); + AccountState accountBefore = accountState(fixture, seed); + PendingCase pending = beginPending(fixture, seed, FenceOrder.REVOKE); + PendingResetSnapshot waiting = durableSnapshot(fixture, seed, pending.intent()); + recordOwner(fixture, pending.binding(), Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + recordOwner(fixture, pending.binding(), Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + + assertThat(abort(fixture, waiting, AbortReason.DEFINITIVE_ABORT)).isTrue(); + + PendingResetSnapshot aborted = durableSnapshot(fixture, seed, pending.intent()); + StoredState terminal = storedState(fixture, seed, pending); + assertThat(aborted.status()).isEqualTo("SOURCE_ABORTED"); + assertThat(aborted.abortReason()).isEqualTo(AbortReason.DEFINITIVE_ABORT); + assertThat(aborted.committedAt()).isNull(); + assertThat(aborted.eventId()).isNull(); + assertThat(aborted.eventPayload()).isNull(); + assertThat(aborted.envelopePresent()).isFalse(); + assertThat(readSourceStatus(fixture, pending.intent().sourceChange())) + .isEqualTo("SOURCE_ABORTED"); + assertThat(readSourceAbortReason(fixture, pending.intent().sourceChange())) + .isEqualTo(DraftAuthorizationFenceRepository.SourceChangeAbortReason.DEFINITIVE_ABORT); + assertThat(accountState(fixture, seed)).isEqualTo(accountBefore); + assertThat(countReceipts(fixture, seed.accountId())).isZero(); + assertThat(countEvents(fixture, STREAM_PREFIX + seed.accountUuid())).isZero(); + assertThat( + transaction( + fixture.transaction(), + () -> + fixture + .pendingResets() + .abort(aborted, AbortReason.DEFINITIVE_ABORT, LocalDateTime.now()))) + .isTrue(); + + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), + () -> { + fixture.fences().markSourceCommitted(pending.intent().sourceChange()); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), + () -> + fixture + .pendingResets() + .abort(aborted, AbortReason.EXPIRED, LocalDateTime.now()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_password_reset_draft_source_changes" + + " SET abort_reason = 'EXPIRED' WHERE request_id = ?", + pending.intent().requestId())) + .isInstanceOf(DataAccessException.class); + + assertThat(storedState(fixture, seed, pending)).isEqualTo(terminal); + } + + private Fixture newFixture() throws Exception { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + AccountRepository accounts = new AccountRepository(transactionDsl); + AccountAuthorityGenerationRepository authority = + new AccountAuthorityGenerationRepository(transactionDsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl); + AccountPasswordResetOperationRepository operations = + new AccountPasswordResetOperationRepository(transactionDsl); + AccountLogoutAllOperationRepository logoutAll = + new AccountLogoutAllOperationRepository(transactionDsl); + PasswordResetTokenRepository tokens = new PasswordResetTokenRepository(transactionDsl); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(transactionDsl); + AccountPasswordResetDraftSourceChangeRepository pendingResets = + new AccountPasswordResetDraftSourceChangeRepository(transactionDsl); + AccountAuthoritySourceEventReadback sourceReadback = + new AccountAuthoritySourceEventReadback(outbox, operations, logoutAll); + Path manifest = temporaryDirectory.resolve(UUID.randomUUID() + ".manifest.v1"); + writeKeyRing(manifest); + return new Fixture( + setupDsl, + transaction, + accounts, + authority, + outbox, + operations, + logoutAll, + tokens, + fences, + pendingResets, + sourceReadback, + new AccountEnvelopeCrypto(manifest)); + } + + private Seed seedAccountAndToken(Fixture fixture, Duration lifetime) { + return transaction( + fixture.transaction(), + () -> { + Account account = new Account(); + String unique = UUID.randomUUID().toString(); + account.setUsername("pending-reset-" + unique); + account.setEmail("pending-reset-" + unique + "@example.test"); + account.setPasswordHash(ORIGINAL_VERIFIER); + Account saved = fixture.accounts().save(account); + fixture.authority().initialize(AuthorityScope.account(saved.getAccountUuid())); + + String rawToken = "pending-reset-token-" + unique; + PasswordResetToken token = new PasswordResetToken(); + token.setAccount(saved); + token.setToken(rawToken); + token.setExpiresAt(LocalDateTime.now().plus(lifetime)); + fixture.tokens().save(token); + LocalDateTime storedDeadline = + fixture.tokens().findByToken(rawToken).orElseThrow().getExpiresAt(); + return new Seed( + saved.getId(), saved.getAccountUuid(), rawToken, storedDeadline, ORIGINAL_VERIFIER); + }); + } + + private PendingCase beginPending(Fixture fixture, Seed seed, FenceOrder order) { + PendingResetIntent intent = + recapture(fixture, seed, seed.deadline(), TARGET_VERIFIER_BYTES, UUID.randomUUID()); + DraftAuthorizationFenceBinding binding = + order == FenceOrder.NONE ? null : draftBinding(seed.accountUuid(), intent.sourceChange()); + if (binding != null) { + transaction( + fixture.transaction(), + () -> { + fixture.fences().reserve(binding); + if (order == FenceOrder.COMMIT) { + fixture.fences().claimCommitOrder(binding); + } + return null; + }); + } + AccountEncryptedEnvelope envelope = encrypt(fixture, intent); + Participation participation = + transaction( + fixture.transaction(), + () -> fixture.pendingResets().beginWaiting(intent, Optional.of(envelope))); + if (!participation.snapshot().status().equals("WAITING")) { + throw new IllegalStateException("Pending reset fixture did not persist WAITING"); + } + return new PendingCase(intent, binding, envelope); + } + + private PendingResetIntent recapture( + Fixture fixture, + Seed seed, + LocalDateTime deadline, + byte[] verifierBytes, + UUID sourceChangeId) { + return transaction( + fixture.transaction(), + () -> { + Account account = fixture.accounts().findById(seed.accountId()).orElseThrow(); + ScopeState authority = + fixture.authority().read(AuthorityScope.account(seed.accountUuid())); + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest = + fixture.sourceReadback().requireCurrentLatest(account, authority); + byte[] verifierDigest = sha256(verifierBytes); + String tokenHash = tokenHash(seed.rawToken()); + return fixture + .pendingResets() + .captureIntent( + account, + tokenHash, + deadline, + requestDigest(seed.accountUuid(), tokenHash, deadline, verifierDigest), + verifierDigest, + authority, + latest, + sourceChangeId); + }); + } + + private DraftAuthorizationFenceBinding draftBinding(UUID accountUuid, SourceChange sourceChange) { + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "tenant-key", + 2, + "tenant-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "opaque/base:pending-reset-proof", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "source-ordering-fixture")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + accountUuid, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "2", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + sourceChange.sources()); + } + + private AccountEncryptedEnvelope encrypt(Fixture fixture, PendingResetIntent intent) { + return fixture.crypto().encryptPendingReset(intent.envelopeBinding(), TARGET_VERIFIER_BYTES); + } + + private void assertRejectedBegin( + Fixture fixture, + PendingResetIntent changedIntent, + Optional remint) { + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), + () -> fixture.pendingResets().beginWaiting(changedIntent, remint))) + .isInstanceOf(RuntimeException.class); + } + + private PendingResetSnapshot durableSnapshot( + Fixture fixture, Seed seed, PendingResetIntent intent) { + return transaction( + fixture.transaction(), + () -> + fixture + .pendingResets() + .findForUpdate(seed.accountId(), seed.accountUuid(), intent.tokenHash()) + .orElseThrow()); + } + + private AccountState accountState(Fixture fixture, Seed seed) { + return transaction( + fixture.transaction(), + () -> { + Account account = fixture.accounts().findById(seed.accountId()).orElseThrow(); + ScopeState authority = + fixture.authority().read(AuthorityScope.account(seed.accountUuid())); + return new AccountState( + account.getPasswordHash(), + authority.generation(), + authority.sourceVersion(), + authority.issuanceFence().value(), + authority.issuanceFence().sourceVersion(), + rows(fixture.setupDsl(), "password_reset_token", "account_id = ?", seed.accountId()), + rows( + fixture.setupDsl(), + "account_password_reset_operation_receipts", + "account_id = ?", + seed.accountId()), + rows( + fixture.setupDsl(), + "account_authority_outbox_events", + "outbox_stream_key = ?", + STREAM_PREFIX + seed.accountUuid()), + rows( + fixture.setupDsl(), + "account_authority_outbox_streams", + "outbox_stream_key = ?", + STREAM_PREFIX + seed.accountUuid()), + countReceipts(fixture, seed.accountId()), + countEvents(fixture, STREAM_PREFIX + seed.accountUuid())); + }); + } + + private StoredState storedState(Fixture fixture, Seed seed, PendingCase pending) { + DraftAuthorizationFenceBinding binding = pending.binding(); + SourceChange sourceChange = pending.intent().sourceChange(); + String requestId = pending.intent().requestId(); + return new StoredState( + accountState(fixture, seed), + rows( + fixture.setupDsl(), + "account_password_reset_draft_source_changes", + "request_id = ?", + requestId), + rows( + fixture.setupDsl(), + "account_password_reset_pending_envelopes", + "request_id = ?", + requestId), + rows( + fixture.setupDsl(), + "account_draft_authorization_source_changes", + "change_id = ?", + sourceChange.changeId()), + rows( + fixture.setupDsl(), + "account_draft_authorization_changed_scopes", + "change_id = ?", + sourceChange.changeId()), + binding == null + ? List.of() + : rows( + fixture.setupDsl(), + "account_draft_authorization_fences", + "operation_id = ?", + binding.operationId()), + binding == null + ? List.of() + : rows( + fixture.setupDsl(), + "account_draft_authorization_sources", + "operation_id = ?", + binding.operationId()), + binding == null + ? List.of() + : rows( + fixture.setupDsl(), + "account_draft_authorization_owner_readbacks", + "operation_id = ?", + binding.operationId())); + } + + private List rows(DSLContext dsl, String table, String predicate, Object... arguments) { + return dsl + .fetch("SELECT * FROM " + table + " WHERE " + predicate + " ORDER BY 1", arguments) + .stream() + .map( + row -> { + List values = new ArrayList<>(); + for (Field field : row.fields()) { + Object value = row.get(field); + String rendered = + value instanceof byte[] bytes + ? HEX.formatHex(bytes) + : value == null ? "" : value.toString(); + values.add(field.getName() + "=" + rendered); + } + return String.join("|", values); + }) + .toList(); + } + + private long countReceipts(Fixture fixture, long accountId) { + return countRows( + fixture.setupDsl(), + "account_password_reset_operation_receipts", + "account_id = ?", + accountId); + } + + private long countEvents(Fixture fixture, String streamKey) { + return countRows( + fixture.setupDsl(), "account_authority_outbox_events", "outbox_stream_key = ?", streamKey); + } + + private long countRows(DSLContext dsl, String table, String predicate, Object... arguments) { + var result = dsl.fetchOne("SELECT COUNT(*) FROM " + table + " WHERE " + predicate, arguments); + if (result == null) { + throw new AssertionError("Count query returned no row for " + table); + } + return result.get(0, Long.class); + } + + private Ordering readOrdering(Fixture fixture, DraftAuthorizationFenceBinding binding) { + return transaction(fixture.transaction(), () -> fixture.fences().read(binding).ordering()); + } + + private Settlement readSettlement(Fixture fixture, DraftAuthorizationFenceBinding binding) { + return transaction(fixture.transaction(), () -> fixture.fences().readSettlement(binding)); + } + + private String readSourceStatus(Fixture fixture, SourceChange change) { + return transaction( + fixture.transaction(), () -> fixture.fences().readSourceChange(change).status()); + } + + private DraftAuthorizationFenceRepository.SourceChangeAbortReason readSourceAbortReason( + Fixture fixture, SourceChange change) { + return transaction( + fixture.transaction(), () -> fixture.fences().readSourceChange(change).abortReason()); + } + + private boolean abort(Fixture fixture, PendingResetSnapshot snapshot, AbortReason reason) { + return transaction( + fixture.transaction(), + () -> fixture.pendingResets().abort(snapshot, reason, LocalDateTime.now())); + } + + private void recordOwner( + Fixture fixture, DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { + OwnerReadback readback = + new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + ("synthetic durable fixture result for " + owner + " " + outcome) + .getBytes(StandardCharsets.UTF_8)); + transaction( + fixture.transaction(), + () -> { + fixture.fences().recordOwnerReadback(binding, readback); + return null; + }); + } + + private void awaitExpiry(LocalDateTime deadline) throws InterruptedException { + while (!LocalDateTime.now().isAfter(deadline.plusNanos(250_000_000))) { + Thread.sleep(50); + } + } + + private void writeKeyRing(Path manifest) throws Exception { + byte[] connectKey = key(1); + byte[] loginKey = key(2); + byte[] resetKey = key(3); + String contents = + "version=1\n" + + "activeKeyId=k1\n" + + "key:k1:bare-login=" + + Base64.getUrlEncoder().withoutPadding().encodeToString(loginKey) + + "\nkey:k1:connect-token=" + + Base64.getUrlEncoder().withoutPadding().encodeToString(connectKey) + + "\nkey:k1:pending-reset=" + + Base64.getUrlEncoder().withoutPadding().encodeToString(resetKey) + + "\n"; + Files.writeString(manifest, contents, StandardCharsets.US_ASCII); + Arrays.fill(connectKey, (byte) 0); + Arrays.fill(loginKey, (byte) 0); + Arrays.fill(resetKey, (byte) 0); + } + + private static byte[] key(int value) { + byte[] bytes = new byte[32]; + Arrays.fill(bytes, (byte) value); + return bytes; + } + + private String tokenHash(String rawToken) { + return HEX.formatHex(sha256(rawToken.getBytes(StandardCharsets.UTF_8))); + } + + private static byte[] requestDigest( + UUID accountUuid, String tokenHash, LocalDateTime deadline, byte[] verifierDigest) { + return sha256( + framed( + List.of( + "account-password-reset-request/v1", + "PASSWORD_RESET", + accountUuid.toString(), + tokenHash, + deadline.toString(), + HEX.formatHex(verifierDigest)))); + } + + private static byte[] framed(List fields) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String field : fields) { + byte[] bytes = field.getBytes(StandardCharsets.UTF_8); + output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + output.writeBytes(bytes); + } + return output.toByteArray(); + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private T transaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private enum FenceOrder { + NONE, + REVOKE, + COMMIT + } + + private record Fixture( + DSLContext setupDsl, + TransactionTemplate transaction, + AccountRepository accounts, + AccountAuthorityGenerationRepository authority, + AccountAuthorityOutboxRepository outbox, + AccountPasswordResetOperationRepository operations, + AccountLogoutAllOperationRepository logoutAll, + PasswordResetTokenRepository tokens, + DraftAuthorizationFenceRepository fences, + AccountPasswordResetDraftSourceChangeRepository pendingResets, + AccountAuthoritySourceEventReadback sourceReadback, + AccountEnvelopeCrypto crypto) {} + + private record Seed( + long accountId, + UUID accountUuid, + String rawToken, + LocalDateTime deadline, + String originalVerifier) {} + + private record PendingCase( + PendingResetIntent intent, + DraftAuthorizationFenceBinding binding, + AccountEncryptedEnvelope originalEnvelope) {} + + private record AccountState( + String passwordHash, + long generation, + long sourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + List resetTokens, + List receipts, + List events, + List checkpoints, + long receiptCount, + long eventCount) {} + + private record StoredState( + AccountState account, + List passwordResetJournal, + List pendingEnvelope, + List sourceChange, + List changedScope, + List fence, + List source, + List ownerReadbacks) {} + + private static final class DeliberateRollback extends RuntimeException {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java index 3bec1913f9..01f78af1eb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java @@ -359,7 +359,7 @@ void issuerPendingCaptureRetainsIndependentCountersCheckpointAndExactPositiveEve } @Test - void v59PreservesV58SourceHistoryAndExactKeysAndSupportsFullMultibyteIssuerParticipation() { + void v59PreservesV58HistoryAndExactKeysBeforeV61ProducerInteractionsWithFullMultibyteIssuer() { Fixture fixture = newFixture("58"); seedIssuer(fixture); UUID oldRequest = UUID.randomUUID(); @@ -424,6 +424,7 @@ void v59PreservesV58SourceHistoryAndExactKeysAndSupportsFullMultibyteIssuerParti .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") + .target("59") .load() .migrate(); assertThat( @@ -460,9 +461,33 @@ void v59PreservesV58SourceHistoryAndExactKeysAndSupportsFullMultibyteIssuerParti "SELECT * FROM account_draft_authorization_changed_scopes ORDER BY source_key, change_id") .formatJSON()) .isEqualTo(oldChangedScopes); - assertThat( - transaction(fixture.transaction(), () -> fences.readSourceChange(oldChange).binding())) + byte[] retainedBinding = + Objects.requireNonNull( + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT binding FROM account_draft_authorization_source_changes WHERE change_id = ?", + oldChange.changeId()), + "Retained V59 source-change row is missing") + .get("binding", byte[].class), + "Retained V59 source-change binding is missing"); + assertThat(retainedBinding).containsExactly(oldChange.canonicalBytes()); + assertThat(SourceChange.fromStored(retainedBinding).canonicalBytes()) .containsExactly(oldChange.canonicalBytes()); + + // V59's retained-data proof is complete above. Current producer readback uses aborted_at, + // which first exists after V61, so run interactions only after advancing this private schema. + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("61") + .load() + .migrate(); + assertThat(fixture.producer().advance(ISSUER_ID, oldRequest, 1, 1).requestId()) .isEqualTo(oldRequest.toString()); assertThat( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPendingResetEnvelopeCryptoTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPendingResetEnvelopeCryptoTest.java new file mode 100644 index 0000000000..e064293339 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPendingResetEnvelopeCryptoTest.java @@ -0,0 +1,496 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import de.mkammerer.argon2.Argon2; +import de.mkammerer.argon2.Argon2Factory; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException.Failure; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.accountservice.security.AccountPendingResetEnvelopeBinding; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AccountPendingResetEnvelopeCryptoTest { + private static final UUID ACCOUNT_ID = UUID.fromString("b61a90bc-cdb4-42ac-9067-08667de2ac84"); + private static final String TOKEN_HASH = "12".repeat(32); + private static final LocalDateTime TOKEN_EXPIRES_AT = + LocalDateTime.parse("2030-05-06T07:08:09.123"); + private static final String REQUEST_ID = "account-password-reset-request-v1:" + TOKEN_HASH; + private static final String ARGON2_VERIFIER = + "$argon2id$v=19$m=65536,t=3,p=1$AAAAAAAAAAAAAAAAAAAAAA$" + + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + private static final String ARGON2I_VERIFIER = + "$argon2i$v=19$m=65536,t=3,p=1$AAAAAAAAAAAAAAAAAAAAAA$" + + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + + @TempDir private Path temporaryDirectory; + + private Path manifestPath; + + @BeforeEach + void setUp() { + manifestPath = temporaryDirectory.resolve("manifest.v1"); + } + + @Test + void exactPendingVerifierDecryptsAfterCryptoObjectRecreation() throws Exception { + writeManifest("k1", keySet("k1", 1, 2, 3)); + AccountPendingResetEnvelopeBinding binding = binding(); + byte[] encodedVerifier = ARGON2_VERIFIER.getBytes(StandardCharsets.UTF_8); + AccountEnvelopeCrypto writer = new AccountEnvelopeCrypto(manifestPath); + + AccountEncryptedEnvelope envelope = writer.encryptPendingReset(binding, encodedVerifier); + AccountEnvelopeCrypto restartedReader = new AccountEnvelopeCrypto(manifestPath); + + assertEquals("k1", envelope.keyId()); + assertEquals(AccountEnvelopePurpose.PENDING_PASSWORD_RESET, envelope.purpose()); + assertArrayEquals(encodedVerifier, restartedReader.decryptPendingReset(envelope, binding)); + } + + @Test + void argon2iEncodingIsAccepted() throws Exception { + writeManifest("k1", keySet("k1", 1, 2, 3)); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + byte[] encodedVerifier = ARGON2I_VERIFIER.getBytes(StandardCharsets.UTF_8); + AccountPendingResetEnvelopeBinding binding = bindingForVerifier(encodedVerifier); + + AccountEncryptedEnvelope envelope = crypto.encryptPendingReset(binding, encodedVerifier); + + assertArrayEquals(encodedVerifier, crypto.decryptPendingReset(envelope, binding)); + } + + @Test + void currentAccountEncoderOutputRoundTripsWithoutRehashing() throws Exception { + writeManifest("k1", keySet("k1", 1, 2, 3)); + Argon2 argon2 = Argon2Factory.create(); + char[] password = "component-only reset choice".toCharArray(); + byte[] encodedVerifier = null; + byte[] recoveredVerifier = null; + try { + encodedVerifier = argon2.hash(2, 65536, 1, password).getBytes(StandardCharsets.UTF_8); + AccountPendingResetEnvelopeBinding binding = bindingForVerifier(encodedVerifier); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + AccountEncryptedEnvelope envelope = crypto.encryptPendingReset(binding, encodedVerifier); + recoveredVerifier = + new AccountEnvelopeCrypto(manifestPath).decryptPendingReset(envelope, binding); + assertArrayEquals(encodedVerifier, recoveredVerifier); + assertTrue(argon2.verify(new String(recoveredVerifier, StandardCharsets.UTF_8), password)); + } finally { + argon2.wipeArray(password); + if (encodedVerifier != null) Arrays.fill(encodedVerifier, (byte) 0); + if (recoveredVerifier != null) Arrays.fill(recoveredVerifier, (byte) 0); + } + } + + @Test + void plaintextFastHashAndMalformedPhcWithMatchingDigestAreRejected() throws Exception { + writeManifest("k1", keySet("k1", 1, 2, 3)); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + List invalidVerifiers = + List.of( + "a submitted plaintext password".getBytes(StandardCharsets.UTF_8), + "0".repeat(64).getBytes(StandardCharsets.US_ASCII), + ("$argon2id$v=19$m=065536,t=3,p=1$AAAAAAAAAAAAAAAAAAAAAA$" + + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") + .getBytes(StandardCharsets.US_ASCII), + ("$argon2id$v=19$m=0,t=3,p=1$AAAAAAAAAAAAAAAAAAAAAA$" + + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") + .getBytes(StandardCharsets.US_ASCII), + ("$argon2id$v=19$m=65536,t=3,p=1$AAAAAAAAAAAAAAAAAAAA==$" + + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") + .getBytes(StandardCharsets.US_ASCII)); + + for (byte[] invalidVerifier : invalidVerifiers) { + AccountPendingResetEnvelopeBinding binding = bindingForVerifier(invalidVerifier); + assertFailure( + Failure.INVALID_ENVELOPE, () -> crypto.encryptPendingReset(binding, invalidVerifier)); + } + } + + @Test + void everyPendingResetBindingFieldAndCiphertextTamperingFailAuthentication() throws Exception { + writeManifest("k1", keySet("k1", 1, 2, 3)); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + AccountPendingResetEnvelopeBinding binding = binding(); + byte[] verifier = ARGON2_VERIFIER.getBytes(StandardCharsets.UTF_8); + AccountEncryptedEnvelope envelope = crypto.encryptPendingReset(binding, verifier); + + byte[] changedNonce = envelope.nonce(); + changedNonce[0] ^= 1; + assertAuthenticationFailure( + crypto, + new AccountEncryptedEnvelope( + envelope.formatVersion(), + envelope.keyId(), + envelope.purpose(), + changedNonce, + envelope.ciphertext()), + binding); + + byte[] changedCiphertext = envelope.ciphertext(); + changedCiphertext[0] ^= 1; + assertAuthenticationFailure( + crypto, + new AccountEncryptedEnvelope( + envelope.formatVersion(), + envelope.keyId(), + envelope.purpose(), + envelope.nonce(), + changedCiphertext), + binding); + + assertFailure( + Failure.INVALID_ENVELOPE, + () -> + crypto.encryptPendingReset( + binding( + ACCOUNT_ID, + TOKEN_HASH, + TOKEN_EXPIRES_AT, + REQUEST_ID, + digest(1), + digest(2), + digest(13)), + verifier)); + + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + TOKEN_HASH, + TOKEN_EXPIRES_AT.plusSeconds(1), + REQUEST_ID, + digest(1), + digest(2), + digestFor(verifier))); + assertAuthenticationFailure( + crypto, + envelope, + binding( + UUID.fromString("08cd8f48-7040-450a-a3de-ece2bb90dc20"), + TOKEN_HASH, + TOKEN_EXPIRES_AT, + REQUEST_ID, + digest(1), + digest(2), + digestFor(verifier))); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + "34".repeat(32), + TOKEN_EXPIRES_AT, + REQUEST_ID, + digest(1), + digest(2), + digestFor(verifier))); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + TOKEN_HASH, + TOKEN_EXPIRES_AT, + REQUEST_ID + "-changed", + digest(1), + digest(2), + digestFor(verifier))); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + TOKEN_HASH, + TOKEN_EXPIRES_AT, + REQUEST_ID, + digest(11), + digest(2), + digestFor(verifier))); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + TOKEN_HASH, + TOKEN_EXPIRES_AT, + REQUEST_ID, + digest(1), + digest(12), + digestFor(verifier))); + assertAuthenticationFailure( + crypto, + envelope, + binding( + ACCOUNT_ID, + TOKEN_HASH, + TOKEN_EXPIRES_AT, + REQUEST_ID, + digest(1), + digest(2), + digest(13))); + } + + @Test + void missingPendingKeyDeniesAndResponseEnvelopesCannotBeUsedAsPendingReset() throws Exception { + writeManifest("k1", keySet("k1", 1, 2, null)); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + AccountPendingResetEnvelopeBinding pendingBinding = binding(); + AccountEnvelopeBinding responseBinding = responseBinding(); + AccountEncryptedEnvelope responseEnvelope = + crypto.encrypt( + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + responseBinding, + "response credential".getBytes(StandardCharsets.UTF_8)); + + assertFailure( + Failure.KEY_UNAVAILABLE, + () -> + crypto.encryptPendingReset( + pendingBinding, ARGON2_VERIFIER.getBytes(StandardCharsets.UTF_8))); + assertFailure( + Failure.PURPOSE_MISMATCH, + () -> crypto.decryptPendingReset(responseEnvelope, pendingBinding)); + + writeManifest("k1", keySet("k1", 1, 2, 3)); + AccountEnvelopeCrypto fullRingCrypto = new AccountEnvelopeCrypto(manifestPath); + AccountEncryptedEnvelope relabeledResponse = + new AccountEncryptedEnvelope( + responseEnvelope.formatVersion(), + responseEnvelope.keyId(), + AccountEnvelopePurpose.PENDING_PASSWORD_RESET, + responseEnvelope.nonce(), + responseEnvelope.ciphertext()); + assertFailure( + Failure.AUTHENTICATION_FAILED, + () -> fullRingCrypto.decryptPendingReset(relabeledResponse, pendingBinding)); + + AccountEncryptedEnvelope pendingEnvelope = + fullRingCrypto.encryptPendingReset( + pendingBinding, ARGON2_VERIFIER.getBytes(StandardCharsets.UTF_8)); + writeManifest("k1", keySet("k1", 1, 2, null)); + assertFailure( + Failure.KEY_UNAVAILABLE, + () -> + new AccountEnvelopeCrypto(manifestPath) + .decryptPendingReset(pendingEnvelope, pendingBinding)); + } + + @Test + void retainedPendingKeyDecryptsExactVerifierWhileNewWritesUseOnlyActiveKey() throws Exception { + KeySet oldKey = keySet("k1", 1, 2, 3); + KeySet activeKey = keySet("k2", 4, 5, 6); + writeManifest("k1", oldKey); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + AccountPendingResetEnvelopeBinding originalBinding = binding(); + byte[] originalVerifier = ARGON2_VERIFIER.getBytes(StandardCharsets.UTF_8); + AccountEncryptedEnvelope originalEnvelope = + crypto.encryptPendingReset(originalBinding, originalVerifier); + + writeManifest("k2", oldKey, activeKey); + byte[] laterVerifier = ARGON2I_VERIFIER.getBytes(StandardCharsets.UTF_8); + AccountPendingResetEnvelopeBinding laterBinding = + binding( + ACCOUNT_ID, + "56".repeat(32), + TOKEN_EXPIRES_AT.plusDays(1), + "account-password-reset-request-v1:" + "56".repeat(32), + digest(21), + digest(22), + digestFor(laterVerifier)); + AccountEncryptedEnvelope laterEnvelope = + crypto.encryptPendingReset(laterBinding, laterVerifier); + + assertEquals("k2", laterEnvelope.keyId()); + assertArrayEquals( + originalVerifier, crypto.decryptPendingReset(originalEnvelope, originalBinding)); + assertArrayEquals(laterVerifier, crypto.decryptPendingReset(laterEnvelope, laterBinding)); + + writeManifest("k2", activeKey); + assertFailure( + Failure.KEY_UNAVAILABLE, + () -> crypto.decryptPendingReset(originalEnvelope, originalBinding)); + assertArrayEquals(laterVerifier, crypto.decryptPendingReset(laterEnvelope, laterBinding)); + } + + @Test + void retainedResponseOnlyIdsNeedNoPendingResetKey() throws Exception { + KeySet oldResponseOnlyKey = keySet("k1", 1, 2, null); + KeySet activeKey = keySet("k2", 4, 5, 6); + writeManifest("k1", oldResponseOnlyKey); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + AccountEnvelopeBinding responseBinding = responseBinding(); + byte[] exactResponse = "exact response bytes".getBytes(StandardCharsets.UTF_8); + AccountEncryptedEnvelope oldResponse = + crypto.encrypt( + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, responseBinding, exactResponse); + + writeManifest("k2", oldResponseOnlyKey, activeKey); + + assertArrayEquals( + exactResponse, + crypto.decrypt( + oldResponse, AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, responseBinding)); + assertEquals( + "k2", + crypto + .encryptPendingReset(binding(), ARGON2_VERIFIER.getBytes(StandardCharsets.UTF_8)) + .keyId()); + } + + @Test + void pendingBindingAndErrorsDoNotExposeVerifierOrTokenHash() throws Exception { + writeManifest("k1", keySet("k1", 1, 2, 3)); + AccountEnvelopeCrypto crypto = new AccountEnvelopeCrypto(manifestPath); + AccountPendingResetEnvelopeBinding binding = binding(); + byte[] verifier = ARGON2_VERIFIER.getBytes(StandardCharsets.UTF_8); + AccountEncryptedEnvelope envelope = crypto.encryptPendingReset(binding, verifier); + + assertFalse(binding.toString().contains(TOKEN_HASH)); + assertFalse(envelope.toString().contains(ARGON2_VERIFIER)); + assertFalse(envelope.toString().contains(TOKEN_HASH)); + AccountEnvelopeCryptoException exception = + assertThrows( + AccountEnvelopeCryptoException.class, + () -> + crypto.decryptPendingReset( + envelope, + binding( + ACCOUNT_ID, + TOKEN_HASH, + TOKEN_EXPIRES_AT, + REQUEST_ID, + digest(1), + digest(2), + digest(99)))); + assertFalse(exception.getMessage().contains(ARGON2_VERIFIER)); + assertFalse(exception.getMessage().contains(TOKEN_HASH)); + } + + private void writeManifest(String activeKeyId, KeySet... keySets) throws Exception { + List lines = new ArrayList<>(); + lines.add("version=1"); + lines.add("activeKeyId=" + activeKeyId); + for (KeySet keySet : keySets) { + lines.add("key:" + keySet.keyId() + ":bare-login=" + encode(keySet.bareLoginKey())); + lines.add("key:" + keySet.keyId() + ":connect-token=" + encode(keySet.connectTokenKey())); + if (keySet.pendingResetKey() != null) { + lines.add("key:" + keySet.keyId() + ":pending-reset=" + encode(keySet.pendingResetKey())); + } + } + Files.writeString(manifestPath, String.join("\n", lines) + "\n", StandardCharsets.US_ASCII); + } + + private static KeySet keySet( + String keyId, int connectValue, int loginValue, Integer pendingValue) { + return new KeySet( + keyId, key(connectValue), key(loginValue), pendingValue == null ? null : key(pendingValue)); + } + + private static String encode(byte[] key) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(key); + } + + private static byte[] key(int value) { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) value); + return key; + } + + private static AccountPendingResetEnvelopeBinding binding() throws Exception { + return bindingForVerifier(ARGON2_VERIFIER.getBytes(StandardCharsets.UTF_8)); + } + + private static AccountPendingResetEnvelopeBinding bindingForVerifier(byte[] verifier) + throws Exception { + return binding( + ACCOUNT_ID, + TOKEN_HASH, + TOKEN_EXPIRES_AT, + REQUEST_ID, + digest(1), + digest(2), + digestFor(verifier)); + } + + private static AccountPendingResetEnvelopeBinding binding( + UUID accountId, + String tokenHash, + LocalDateTime tokenExpiresAt, + String requestId, + byte[] requestDigest, + byte[] sourceCaptureDigest, + byte[] targetVerifierDigest) { + return new AccountPendingResetEnvelopeBinding( + accountId, + tokenHash, + tokenExpiresAt, + requestId, + requestDigest, + sourceCaptureDigest, + targetVerifierDigest); + } + + private static AccountEnvelopeBinding responseBinding() { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + "connect-op-1", + "request-1", + ACCOUNT_ID.toString(), + "tenant-a", + "connect-scope-a", + null, + digest(1), + digest(2), + digest(3), + digest(4), + digest(5)); + } + + private static byte[] digest(int value) { + byte[] digest = new byte[32]; + Arrays.fill(digest, (byte) value); + return digest; + } + + private static byte[] digestFor(byte[] value) throws Exception { + return MessageDigest.getInstance("SHA-256").digest(value); + } + + private static void assertFailure(Failure expected, Runnable operation) { + AccountEnvelopeCryptoException exception = + assertThrows(AccountEnvelopeCryptoException.class, operation::run); + assertEquals(expected, exception.failure()); + } + + private static void assertAuthenticationFailure( + AccountEnvelopeCrypto crypto, + AccountEncryptedEnvelope envelope, + AccountPendingResetEnvelopeBinding binding) { + assertFailure( + Failure.AUTHENTICATION_FAILED, () -> crypto.decryptPendingReset(envelope, binding)); + } + + private record KeySet( + String keyId, byte[] connectTokenKey, byte[] bareLoginKey, byte[] pendingResetKey) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java index 95f27d4b56..09409b7abf 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java @@ -1,5 +1,6 @@ package unit.net.firedevops.firemud.accountservice.service; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -15,6 +16,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllDraftSourceChangeRepository; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.transaction.PlatformTransactionManager; @@ -27,6 +29,17 @@ class AccountLogoutAllAuthorityEventProducerTest { private static final String REQUEST_DIGEST = AccountLogoutRequestDigest.accountLogoutAll(ACCOUNT_UUID, TOKEN_PROFILE, TOKEN_HASH); + @Test + void pendingSourceChangeExposesOnlyItsStableRecoveryIdentity() { + UUID changeId = UUID.randomUUID(); + + var pending = + new AccountLogoutAllDraftSourceChangeRepository.PendingSourceChangeException(changeId); + + assertThat(pending.sourceChangeId()).isEqualTo(changeId); + assertThat(pending.getMessage()).contains(changeId.toString()).doesNotContain(TOKEN_HASH); + } + @Test void rejectsMalformedRequestEvidenceBeforeDatabaseOrTransactionInteraction() { Collaborators collaborators = new Collaborators(); 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 index d8962c24bd..ea1129826a 100644 --- 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 @@ -57,7 +57,7 @@ public record AuthoredWorldReleaseAttestationEvidence( "GAME_DESIGN_CONTROL_PLANE"); private static final Map SUPPORTED_PARTICIPANT_DIGEST_SCHEMAS = Map.of( - "WORLD_MANAGEMENT", 2, + "WORLD_MANAGEMENT", 3, "ENTITY_MANAGEMENT", 2, "GAME_LOGIC", 1, "AUTOMATION_SCRIPTING", 5, 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 index 20d7d75f37..431c77019a 100644 --- 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 @@ -22,7 +22,7 @@ class AuthoredWorldReleaseAttestationEvidenceTest { private static final String EXPECTED_DESCRIPTOR_RESULT_DIGEST = "sha256:7129db5acb9aa27830598cdcfe4996f2f2259cfbe1f6dc137db5d39ec8ebc80c"; private static final String EXPECTED_EVIDENCE_DIGEST = - "sha256:c1a8d369e3012ced0247b6de05a152fc0434b565db611acc9095447184cbe42f"; + "sha256:156077bf55bfc35bff1dff953beb1b26fe35f6edf6cd4918b7c512977b8db10b"; @Test void fullEvidenceMatchesIndependentUnicodeFramingVectorAndExactDescriptor() { @@ -53,7 +53,7 @@ void fullEvidenceMatchesIndependentUnicodeFramingVectorAndExactDescriptor() { "GAME_DESIGN_CONTROL_PLANE"), AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()); assertEquals( - List.of(2, 2, 1, 5, 1), + List.of(3, 2, 1, 5, 1), AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() .map(AuthoredWorldReleaseAttestationEvidence::supportedParticipantDigestSchema) .toList()); @@ -123,6 +123,28 @@ void changedFieldsAndRetainedArrayOrderChangeTheDigest() { assertThrows(IllegalArgumentException.class, tampered::requireValid); } + @Test + void retainedWorldSchema2IsNotAcceptedAsCurrentReleaseEvidence() { + Fixture fixture = fixture(); + List participants = + new ArrayList<>(fixture.evidence().participantDigests()); + participants.set( + 0, + participant( + "WORLD_MANAGEMENT", "42", false, null, "commit-雪", digest("a"), false, null, 2)); + assertThrows( + IllegalArgumentException.class, + () -> + evidence( + fixture.descriptor(), + MAX_EPOCH, + participants, + keys(), + artifacts(), + commands(), + GENERATION_REVISION)); + } + @Test void fullVersionParticipantSetIsExactOrderedAndBoundToTheDescriptorVersion() { Fixture fixture = fixture(); @@ -960,7 +982,8 @@ private static AuthoredWorldReleaseAttestationEvidence.Participant participant( abilityPresent, abilityDigest, switch (key) { - case "WORLD_MANAGEMENT", "ENTITY_MANAGEMENT" -> 2; + case "WORLD_MANAGEMENT" -> 3; + case "ENTITY_MANAGEMENT" -> 2; case "AUTOMATION_SCRIPTING" -> 5; case "GAME_LOGIC", "GAME_DESIGN_CONTROL_PLANE" -> 1; default -> 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 index 9b153914fd..3afb1d2d54 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -885,7 +885,7 @@ private PublishedReleaseBundleDto validBundle() { private List validParticipants() { return List.of( - participant(PublishParticipantKey.WORLD_MANAGEMENT.name(), 2, null), + participant(PublishParticipantKey.WORLD_MANAGEMENT.name(), 3, null), participant(PublishParticipantKey.ENTITY_MANAGEMENT.name(), 2, null), participant(PublishParticipantKey.GAME_LOGIC.name(), 1, ABILITY_SCHEMA_DIGEST), participant(PublishParticipantKey.AUTOMATION_SCRIPTING.name(), 5, null), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java index b08bca7d41..62159ff5a0 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java @@ -68,7 +68,7 @@ void collectFullVersionParticipantDigestsAcceptsEntitySchemaTwoWhenParticipantsC any(PublicationDigestRequestBinding.class))) .thenReturn( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null)); + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null)); when(entityManagementClient.getDraftDesignDigestForVersion( any(PublicationDigestRequestBinding.class))) .thenReturn( @@ -129,7 +129,7 @@ void fullVersionGateRejectsUnavailableGameLogicManifest() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), new PublishParticipantDigestDto( @@ -200,7 +200,7 @@ void fullVersionGateFailsClosedForUnsupportedSchema() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 4, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), new PublishParticipantDigestDto( @@ -242,7 +242,7 @@ void fullVersionGateChecksEachParticipantAgainstItsOwnDigestSchema() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 5, null, null), new PublishParticipantDigestDto( @@ -314,7 +314,7 @@ void fullVersionGateRejectsObsoleteAutomationDigestSchema() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), new PublishParticipantDigestDto( @@ -436,9 +436,9 @@ void fullVersionGateFailsClosedForDuplicateParticipantKey() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world-2", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world-2", 3, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), new PublishParticipantDigestDto( @@ -481,7 +481,7 @@ void fullVersionGateFailsClosedForNullParticipantObservation() { List digests = java.util.Arrays.asList( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), null, new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 2, null, null), @@ -782,7 +782,7 @@ private List fullVersionDigests( Integer entitySchemaVersion, String entityContentDigest, String entityAppliedCommitId) { return List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java index de672ba3bb..09805f65ac 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.worldmanagement.entity; +import java.util.UUID; import lombok.Data; @Data @@ -10,6 +11,9 @@ public class WorldEntitySpawnBinding { private Room room; private String entityTemplateType; private Long entityTemplateId; + private UUID entityCanonicalTenantId; + private UUID entityCanonicalVersionId; + private UUID entityCanonicalTemplateId; private int spawnCount = 1; private int respawnDelaySeconds; diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java index c62b8cbc3f..fbccb4f069 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java @@ -85,6 +85,15 @@ public WorldEntitySpawnBinding save(WorldEntitySpawnBinding entity) { .set(WORLD_ENTITY_SPAWN_BINDING.ROOM_ID, entity.getRoom().getId()) .set(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_TYPE, entity.getEntityTemplateType()) .set(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_ID, entity.getEntityTemplateId()) + .set( + WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TENANT_ID, + entity.getEntityCanonicalTenantId()) + .set( + WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_VERSION_ID, + entity.getEntityCanonicalVersionId()) + .set( + WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TEMPLATE_ID, + entity.getEntityCanonicalTemplateId()) .set(WORLD_ENTITY_SPAWN_BINDING.SPAWN_COUNT, entity.getSpawnCount()) .set(WORLD_ENTITY_SPAWN_BINDING.RESPAWN_DELAY_SECONDS, entity.getRespawnDelaySeconds()) .set(WORLD_ENTITY_SPAWN_BINDING.VERSION, entity.getVersion() + 1) @@ -124,6 +133,9 @@ private void populate(WorldEntitySpawnBindingRecord record, WorldEntitySpawnBind record.setRoomId(entity.getRoom().getId()); record.setEntityTemplateType(entity.getEntityTemplateType()); record.setEntityTemplateId(entity.getEntityTemplateId()); + record.setEntityCanonicalTenantId(entity.getEntityCanonicalTenantId()); + record.setEntityCanonicalVersionId(entity.getEntityCanonicalVersionId()); + record.setEntityCanonicalTemplateId(entity.getEntityCanonicalTemplateId()); record.setSpawnCount(entity.getSpawnCount()); record.setRespawnDelaySeconds(entity.getRespawnDelaySeconds()); record.setVersion(entity.getVersion()); @@ -139,6 +151,12 @@ private WorldEntitySpawnBinding toEntity(Record record) { record.get(WORLD_ENTITY_SPAWN_BINDING.ROOM_ID))); entity.setEntityTemplateType(record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_TYPE)); entity.setEntityTemplateId(record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_ID)); + entity.setEntityCanonicalTenantId( + record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TENANT_ID)); + entity.setEntityCanonicalVersionId( + record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_VERSION_ID)); + entity.setEntityCanonicalTemplateId( + record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TEMPLATE_ID)); Integer spawnCount = record.get(WORLD_ENTITY_SPAWN_BINDING.SPAWN_COUNT); entity.setSpawnCount(spawnCount == null ? 1 : spawnCount); Integer respawnDelaySeconds = record.get(WORLD_ENTITY_SPAWN_BINDING.RESPAWN_DELAY_SECONDS); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java index 48306bfc76..491f70ea1f 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java @@ -4,8 +4,14 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; +import java.util.UUID; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.worldmanagement.entity.WorldEntitySpawnBinding; import net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository; import net.firedevops.firemud.worldmanagement.repository.RegionRepository; import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; @@ -20,8 +26,8 @@ @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Spring-managed repositories and mapper are stored internally for digesting") -public class WorldDraftDesignDigestServiceImpl implements WorldDraftDesignDigestService { - private static final int DIGEST_SCHEMA_VERSION = 2; +public final class WorldDraftDesignDigestServiceImpl implements WorldDraftDesignDigestService { + private static final int DIGEST_SCHEMA_VERSION = 3; private final RegionRepository regionRepository; private final ZoneRepository zoneRepository; @@ -45,7 +51,9 @@ public WorldDraftDesignDigestServiceImpl( this.roomExitRepository = roomExitRepository; this.generationRuleRepository = generationRuleRepository; this.worldEntitySpawnBindingRepository = worldEntitySpawnBindingRepository; - this.objectMapper = objectMapper; + Objects.requireNonNull(objectMapper, "objectMapper"); + // Schema serialization must not inherit application-wide pretty-printing or map-order options. + this.objectMapper = new ObjectMapper(); } @Override @@ -58,7 +66,7 @@ public WorldDraftDesignDigest getDraftDesignDigest(String tenantId, String versi try { String canonicalJson = objectMapper.writeValueAsString( - Map.of( + tables( "regions", regionRepository .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) @@ -138,7 +146,7 @@ public WorldDraftDesignDigest getDraftDesignDigest(String tenantId, String versi "id", binding.getId(), "roomId", binding.getRoom().getId(), "entityTemplateType", binding.getEntityTemplateType(), - "entityTemplateId", binding.getEntityTemplateId(), + "entityReference", entityReference(binding), "spawnCount", binding.getSpawnCount(), "respawnDelaySeconds", binding.getRespawnDelaySeconds())) .toList())); @@ -157,6 +165,55 @@ private String value(String value) { return value == null ? "" : value; } + // Top-level table order is part of the manifest, while every nested object is field-sorted. + private Map tables(Object... entries) { + Map tables = new LinkedHashMap<>(); + for (int index = 0; index < entries.length; index += 2) { + tables.put((String) entries[index], canonical(entries[index + 1])); + } + return tables; + } + + private Object canonical(Object value) { + if (value instanceof Map fields) { + Map sorted = new TreeMap<>(); + fields.forEach((key, item) -> sorted.put((String) key, canonical(item))); + return sorted; + } + if (value instanceof List rows) { + return rows.stream().map(this::canonical).toList(); + } + return value; + } + + private Map entityReference(WorldEntitySpawnBinding binding) { + UUID tenant = binding.getEntityCanonicalTenantId(); + UUID version = binding.getEntityCanonicalVersionId(); + UUID template = binding.getEntityCanonicalTemplateId(); + Long numeric = binding.getEntityTemplateId(); + if (numeric != null) { + if (numeric <= 0 || tenant != null || version != null || template != null) { + throw new IllegalArgumentException("spawn Entity reference is mixed or nonpositive"); + } + return Map.of("kind", "RETAINED_PRIVATE_KEY", "templateId", numeric.toString()); + } + requireNonNil(tenant); + requireNonNil(version); + requireNonNil(template); + return Map.of( + "kind", "CANONICAL_UUID", + "tenantId", tenant.toString(), + "versionId", version.toString(), + "templateId", template.toString()); + } + + private void requireNonNil(UUID value) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException( + "spawn Entity reference must contain complete non-nil UUIDs"); + } + } + private String sha256(String value) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java index d85a0faa44..7ca8879625 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java @@ -9,6 +9,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; @@ -55,6 +56,8 @@ public class WorldLifecycleCommandServiceImpl implements WorldLifecycleCommandSe static final String STATUS_TERMINATED = "TERMINATED"; private static final String SUPPORTED_RELEASE_ATTESTATION_SCHEMA_VERSION = "v1"; + private record SelectedRoomTopology(List zones, List rooms, List exits) {} + private final WorldInstanceRepository worldInstanceRepository; private final RegionInstanceRepository regionInstanceRepository; private final ZoneRepository zoneRepository; @@ -200,6 +203,8 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( return snapshot(existing); } validateAttestedLaunchInputs(request); + SelectedRoomTopology topology = + loadAndValidateRoomTopology(request.tenantId(), request.versionId()); WorldInstance worldInstance = new WorldInstance(); worldInstance.setTenantId(request.tenantId()); worldInstance.setGameInstanceId(request.gameInstanceId()); @@ -232,8 +237,7 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( region.setGeneratorParams("{}"); region.setSpacingMultiplier(1.0); RegionInstance savedRegion = regionInstanceRepository.save(region); - materializeRoomTopology( - savedRegion, request.tenantId(), request.versionId(), request.gameInstanceId()); + materializeRoomTopology(savedRegion, request.tenantId(), request.gameInstanceId(), topology); logger.info( "Prepared world instance tenant={} gameInstanceId={} launchDescriptorId={} versionId={}", @@ -538,11 +542,105 @@ private WorldInstance requireWorldInstance(long tenantId, long gameInstanceId) { new IllegalArgumentException("WORLD_INSTANCE_NOT_FOUND: world instance not found")); } + private SelectedRoomTopology loadAndValidateRoomTopology(long tenantId, long versionId) { + List zones = zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantId, versionId); + List rooms = roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantId, versionId); + List exits = + roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantId, versionId); + + Map zonesById = new LinkedHashMap<>(); + for (Zone zone : zones) { + if (zone == null) { + throw incompleteTopology("selected zone row is missing"); + } + requireScopedTopologyRow( + "zone", zone.getId(), zone.getTenantId(), zone.getVersionId(), tenantId, versionId); + if (zonesById.putIfAbsent(zone.getId(), zone) != null) { + throw incompleteTopology("selected topology contains duplicate zone identities"); + } + } + + Map roomsById = new LinkedHashMap<>(); + for (Room room : rooms) { + if (room == null) { + throw incompleteTopology("selected room row is missing"); + } + requireScopedTopologyRow( + "room", room.getId(), room.getTenantId(), room.getVersionId(), tenantId, versionId); + if (roomsById.putIfAbsent(room.getId(), room) != null) { + throw incompleteTopology("selected topology contains duplicate room identities"); + } + Zone parentZone = room.getZone(); + if (parentZone == null) { + throw incompleteTopology("room " + room.getId() + " has no selected zone"); + } + requireTopologyReferenceId("room zone reference", parentZone.getId()); + if (!zonesById.containsKey(parentZone.getId())) { + throw incompleteTopology("room " + room.getId() + " references a missing selected zone"); + } + } + + Set exitIds = new HashSet<>(); + for (RoomExit exit : exits) { + if (exit == null) { + throw incompleteTopology("selected exit row is missing"); + } + requireScopedTopologyRow( + "exit", exit.getId(), exit.getTenantId(), exit.getVersionId(), tenantId, versionId); + if (!exitIds.add(exit.getId())) { + throw incompleteTopology("selected topology contains duplicate exit identities"); + } + requireSelectedExitEndpoint("from", exit.getFromRoom(), roomsById); + requireSelectedExitEndpoint("to", exit.getToRoom(), roomsById); + } + return new SelectedRoomTopology(List.copyOf(zones), List.copyOf(rooms), List.copyOf(exits)); + } + + private void requireScopedTopologyRow( + String rowType, + Long rowId, + Long rowTenantId, + Long rowVersionId, + long tenantId, + long versionId) { + if (rowId == null || rowId <= 0L) { + throw incompleteTopology(rowType + " row has no positive identity"); + } + if (!Long.valueOf(tenantId).equals(rowTenantId) + || !Long.valueOf(versionId).equals(rowVersionId)) { + throw incompleteTopology(rowType + " row is outside the selected tenant/version scope"); + } + } + + private void requireSelectedExitEndpoint( + String endpoint, Room endpointRoom, Map roomsById) { + if (endpointRoom == null) { + throw incompleteTopology("exit has no " + endpoint + " room"); + } + requireTopologyReferenceId(endpoint + " exit room reference", endpointRoom.getId()); + if (!roomsById.containsKey(endpointRoom.getId())) { + throw incompleteTopology("exit " + endpoint + " room is not in the selected topology"); + } + } + + private void requireTopologyReferenceId(String referenceType, Long referenceId) { + if (referenceId == null || referenceId <= 0L) { + throw incompleteTopology(referenceType + " has no positive identity"); + } + } + + private IllegalArgumentException incompleteTopology(String detail) { + return new IllegalArgumentException( + "FAILED_PRECONDITION: INCOMPLETE_WORLD_TOPOLOGY: " + detail); + } + private void materializeRoomTopology( - RegionInstance regionInstance, long tenantId, long versionId, long gameInstanceId) { + RegionInstance regionInstance, + long tenantId, + long gameInstanceId, + SelectedRoomTopology topology) { Map zoneInstancesByTemplateId = new LinkedHashMap<>(); - for (Zone templateZone : - zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantId, versionId)) { + for (Zone templateZone : topology.zones()) { ZoneInstance zoneInstance = new ZoneInstance(); zoneInstance.setTenantId(tenantId); zoneInstance.setGameInstanceId(gameInstanceId); @@ -553,14 +651,9 @@ private void materializeRoomTopology( ZoneInstance savedZoneInstance = zoneInstanceRepository.save(zoneInstance); zoneInstancesByTemplateId.put(templateZone.getId(), savedZoneInstance); } - List templateRooms = - roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantId, versionId); Map roomInstancesByTemplateId = new LinkedHashMap<>(); - for (Room templateRoom : templateRooms) { + for (Room templateRoom : topology.rooms()) { ZoneInstance zoneInstance = zoneInstancesByTemplateId.get(templateRoom.getZone().getId()); - if (zoneInstance == null) { - continue; - } RoomInstance roomInstance = new RoomInstance(); roomInstance.setTenantId(tenantId); roomInstance.setGameInstanceId(gameInstanceId); @@ -576,14 +669,10 @@ private void materializeRoomTopology( RoomInstance savedRoomInstance = roomInstanceRepository.save(roomInstance); roomInstancesByTemplateId.put(templateRoom.getId(), savedRoomInstance); } - for (RoomExit templateExit : - roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantId, versionId)) { + for (RoomExit templateExit : topology.exits()) { RoomInstance fromRoomInstance = roomInstancesByTemplateId.get(templateExit.getFromRoom().getId()); RoomInstance toRoomInstance = roomInstancesByTemplateId.get(templateExit.getToRoom().getId()); - if (fromRoomInstance == null || toRoomInstance == null) { - continue; - } RoomInstanceExit roomInstanceExit = new RoomInstanceExit(); roomInstanceExit.setTenantId(tenantId); roomInstanceExit.setGameInstanceId(gameInstanceId); 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 cf4e5eee5e..f39fdd554e 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 @@ -24,7 +24,6 @@ import net.firedevops.firemud.worldmanagement.service.PingService; import net.firedevops.firemud.worldmanagement.service.RoomService; import net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService; -import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; import net.firedevops.firemud.worldmanagement.service.WorldInstanceActivationService; import net.firedevops.firemud.worldmanagement.service.WorldUpgradeValidationService; import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldRequest; @@ -75,7 +74,6 @@ public class WorldManagementGrpcService private final PingService pingService; private final RoomService roomService; private final WorldInstanceActivationService worldInstanceActivationService; - private final WorldDraftDesignDigestService worldDraftDesignDigestService; private final WorldUpgradeValidationService worldUpgradeValidationService; private final GameplaySessionAttestationService gameplaySessionAttestationService; private final MeterRegistry meterRegistry; @@ -89,7 +87,6 @@ private WorldManagementGrpcService( PingService pingService, RoomService roomService, WorldInstanceActivationService worldInstanceActivationService, - WorldDraftDesignDigestService worldDraftDesignDigestService, WorldDesignMutationService worldDesignMutationService, WorldUpgradeValidationService worldUpgradeValidationService, GameplaySessionAttestationService gameplaySessionAttestationService, @@ -98,7 +95,6 @@ private WorldManagementGrpcService( this.pingService = pingService; this.roomService = roomService; this.worldInstanceActivationService = worldInstanceActivationService; - this.worldDraftDesignDigestService = worldDraftDesignDigestService; this.worldUpgradeValidationService = worldUpgradeValidationService; this.gameplaySessionAttestationService = gameplaySessionAttestationService; this.meterRegistry = meterRegistry; @@ -111,7 +107,6 @@ public WorldManagementGrpcService( PingService pingService, RoomService roomService, WorldInstanceActivationService worldInstanceActivationService, - WorldDraftDesignDigestService worldDraftDesignDigestService, WorldDesignMutationService worldDesignMutationService, WorldUpgradeValidationService worldUpgradeValidationService, GameplaySessionAttestationService gameplaySessionAttestationService, @@ -123,7 +118,6 @@ public WorldManagementGrpcService( pingService, roomService, worldInstanceActivationService, - worldDraftDesignDigestService, worldDesignMutationService, worldUpgradeValidationService, gameplaySessionAttestationService, @@ -144,7 +138,6 @@ public WorldManagementGrpcService( PingService pingService, RoomService roomService, WorldInstanceActivationService worldInstanceActivationService, - WorldDraftDesignDigestService worldDraftDesignDigestService, WorldDesignMutationService worldDesignMutationService, WorldUpgradeValidationService worldUpgradeValidationService, GameplaySessionAttestationService gameplaySessionAttestationService, @@ -156,7 +149,6 @@ public WorldManagementGrpcService( pingService, roomService, worldInstanceActivationService, - worldDraftDesignDigestService, worldDesignMutationService, worldUpgradeValidationService, gameplaySessionAttestationService, @@ -405,18 +397,16 @@ public void getDraftDesignDigest( request.getScriptPatchVersion(), request.getPublishRequestId()); binding.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest()); - var digest = - worldDraftDesignDigestService.getDraftDesignDigest( - request.getTenantId(), request.getVersionId()); - binding.requireOwnerScope(digest.tenantId(), digest.scopeValue()); - GetDraftDesignDigestResponse.Builder response = + responseObserver.onNext( GetDraftDesignDigestResponse.newBuilder() - .setTenantId(binding.tenantId()) - .setVersionId(binding.versionId()) - .setAppliedCommitId(digest.appliedCommitId()) - .setContentDigest(digest.contentDigest()) - .setDigestSchemaVersion(digest.digestSchemaVersion()); - responseObserver.onNext(response.build()); + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetDraftDesignDigest", + "FAILED_PRECONDITION", + "An authenticated complete World commit/publication checkpoint is unavailable.")) + .build()); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { responseObserver.onNext( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java index 5d88703b73..a3065249e6 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java @@ -68,8 +68,9 @@ public record WorldAuthoredGraphSnapshot( requireText(publishWorkflowId, "publishWorkflowId"); requireText(appliedCommitId, "appliedCommitId"); requireSha256(contentDigest, "contentDigest"); - if (digestSchemaVersion != 2) { - throw new IllegalArgumentException("World graph snapshot requires digest schema version 2"); + if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + throw new IllegalArgumentException( + "World graph snapshot requires retained schema 2 or current schema 3"); } requireSha256(captureRequestDigest, "captureRequestDigest"); requireText(suppliedOwnedAffectedTuplesJson, "suppliedOwnedAffectedTuplesJson"); @@ -153,8 +154,9 @@ public record CaptureRequest( requireText(publishWorkflowId, "publishWorkflowId"); requireText(appliedCommitId, "appliedCommitId"); requireSha256(contentDigest, "contentDigest"); - if (digestSchemaVersion != 2) { - throw new IllegalArgumentException("World graph snapshot requires digest schema version 2"); + if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + throw new IllegalArgumentException( + "World graph snapshot requires retained schema 2 or current schema 3"); } Objects.requireNonNull(suppliedOwnedAffectedTuples, "suppliedOwnedAffectedTuples"); List ordered = new ArrayList<>(suppliedOwnedAffectedTuples); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java index 2423f91209..c1767c1e1a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java @@ -33,7 +33,7 @@ * publication eligibility or proof that World applied a complete synchronized owner commit. */ public class WorldAuthoredGraphSnapshotCapture { - private static final int WORLD_DIGEST_SCHEMA_VERSION = 2; + private static final int WORLD_DIGEST_SCHEMA_VERSION = 3; private static final Table REVISION_LEDGER = table("world_design_revision_ledger"); @@ -99,6 +99,9 @@ public WorldAuthoredGraphSnapshot capture(CaptureRequest request) { prior, request, provenance, captureRequestDigest, tuplesJson); return prior; } + if (request.digestSchemaVersion() != WORLD_DIGEST_SCHEMA_VERSION) { + throw new SnapshotConflictException("New World graph capture requires digest schema 3"); + } if (!"FROZEN".equals(provenance.ownerFreezePhase())) { throw new SnapshotConflictException( "World graph capture cannot create a new snapshot after its V25 fence leaves FROZEN"); @@ -113,6 +116,7 @@ public WorldAuthoredGraphSnapshot capture(CaptureRequest request) { Long.toString(provenance.localTenantKey()), Long.toString(provenance.localVersionKey())); if (!Long.toString(provenance.localTenantKey()).equals(currentDigest.tenantId()) + || !Long.toString(provenance.localVersionKey()).equals(currentDigest.scopeValue()) || currentDigest.digestSchemaVersion() != WORLD_DIGEST_SCHEMA_VERSION || !request.contentDigest().equals(currentDigest.contentDigest())) { throw new SnapshotConflictException( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java new file mode 100644 index 0000000000..854495eb61 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.EntityTemplateReference; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; + +/** Owner-private, validated graph/2 storage view, never synchronized or released content. */ +public final class WorldCanonicalAuthoredGraph { + public enum Family { + REGION, + ZONE, + ROOM, + ROOM_EXIT, + GENERATION_RULE, + WORLD_ENTITY_SPAWN_BINDING + } + + /** Family is part of identity: equal UUIDs in different families are distinct templates. */ + public record Template(Family family, UUID templateId) { + public Template { + Objects.requireNonNull(family, "family"); + Objects.requireNonNull(templateId, "templateId"); + if (templateId.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Canonical template ID must be non-nil"); + } + } + } + + /** Private World selectors never become Entity selectors or public template identifiers. */ + @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Protobuf messages are immutable.") + public record Row( + Template template, + long mappingKey, + long privateRowKey, + Node authored, + WorldDesignMutationRevision content) { + public Row { + Objects.requireNonNull(template, "template"); + Objects.requireNonNull(authored, "authored"); + Objects.requireNonNull(content, "content"); + if (mappingKey <= 0 || privateRowKey <= 0) { + throw new IllegalArgumentException("World private keys must be positive"); + } + } + + public Template scope() { + boolean region = authored.mutation().getScopeType().name().endsWith("REGION_SUBTREE"); + return new Template(region ? Family.REGION : Family.ZONE, authored.scopeId()); + } + + public EntityTemplateReference entityReference() { + return authored.entityReference(); + } + } + + private final UUID tenantId; + private final UUID versionId; + private final long localTenantKey; + private final long localVersionKey; + private final List rows; + + WorldCanonicalAuthoredGraph( + UUID tenantId, UUID versionId, long localTenantKey, long localVersionKey, List rows) { + this.tenantId = tenantId; + this.versionId = versionId; + this.localTenantKey = localTenantKey; + this.localVersionKey = localVersionKey; + this.rows = List.copyOf(rows); + } + + public UUID tenantId() { + return tenantId; + } + + public UUID versionId() { + return versionId; + } + + public long localTenantKey() { + return localTenantKey; + } + + public long localVersionKey() { + return localVersionKey; + } + + public List rows() { + return rows; + } + + public List family(Family family) { + return rows.stream().filter(row -> row.template().family() == family).toList(); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java new file mode 100644 index 0000000000..4c4ac48632 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Row; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Template; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Closed graph/2 decoder. Retained numeric graph/1 remains a separate explicit reader. */ +public final class WorldCanonicalAuthoredGraphReader { + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Set MAPPING_FIELDS = + Set.of( + "id", + "target_namespace", + "canonical_tenant_id", + "canonical_version_id", + "family", + "template_id", + "private_row_key", + "tenant_id", + "version_id", + "version_identity_operation_id", + "request_id", + "commit_id", + "revision_id", + "revision_order"); + + /** Complete original input supplies typed hierarchy/scope/Entity closure, never authority. */ + public WorldCanonicalAuthoredGraph read(WorldDraftTopologyCommitPlan plan, byte[] bytes) { + JsonNode root = JSON.readTree(bytes); + fields(root, Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows")); + text(root, "schemaVersion", "2"); + text(root, "canonicalTenantId", plan.graph().tenantId().toString()); + text(root, "canonicalVersionId", plan.graph().versionId().toString()); + JsonNode rows = root.get("rows"); + if (!rows.isArray() || rows.size() != plan.graph().nodes().size()) { + throw invalid("Missing or extra canonical graph rows"); + } + Map keys = new HashMap<>(); + Set privateKeys = new HashSet<>(); + Set mappingKeys = new HashSet<>(); + List decoded = new ArrayList<>(); + long tenant = 0; + long version = 0; + for (int i = 0; i < rows.size(); i++) { + JsonNode item = rows.get(i); + fields(item, Set.of("mapping", "content")); + JsonNode mapping = item.get("mapping"); + fields(mapping, MAPPING_FIELDS); + var node = plan.graph().nodes().get(i); + String family = WorldDraftTopologyCommitRepository.family(node); + var owner = plan.ownerBinding(); + text(mapping, "target_namespace", owner.targetNamespace()); + text(mapping, "canonical_tenant_id", plan.graph().tenantId().toString()); + text(mapping, "canonical_version_id", plan.graph().versionId().toString()); + text(mapping, "family", family); + text(mapping, "template_id", node.templateId().toString()); + text(mapping, "version_identity_operation_id", owner.versionIdentityOperationId().toString()); + text(mapping, "request_id", plan.binding().requestId().toString()); + text(mapping, "commit_id", plan.binding().commitId().toString()); + text(mapping, "revision_id", node.revisionId().toString()); + text(mapping, "revision_order", node.revisionOrder()); + long localTenant = positive(mapping, "tenant_id"); + long localVersion = positive(mapping, "version_id"); + if (i == 0) { + tenant = localTenant; + version = localVersion; + } + if (tenant != localTenant || version != localVersion) { + throw invalid("Canonical graph crosses private tenant or Version scope"); + } + long key = positive(mapping, "private_row_key"); + long mappingKey = positive(mapping, "id"); + if (keys.put(family + ":" + node.templateId(), key) != null + || !privateKeys.add(family + ":" + key) + || !mappingKeys.add(mappingKey)) { + throw invalid("Canonical graph mapping is not one-to-one within its typed family"); + } + decoded.add( + new Row( + new Template(Family.valueOf(family), node.templateId()), + mappingKey, + key, + node, + node.mutation())); + } + for (int i = 0; i < rows.size(); i++) { + JsonNode actual = rows.get(i).get("content"); + JsonNode expected = + JSON.valueToTree( + WorldDraftTopologyCommitRepository.expectedContent( + plan.graph().nodes().get(i), keys, tenant, version)); + if (!actual.isObject() || !WorldDraftTopologyCommitRepository.sameContent(actual, expected)) { + throw invalid("Canonical graph content differs from exact typed original payload"); + } + if (expected.properties().stream() + .anyMatch( + entry -> + entry.getValue().isIntegralNumber() + && !actual.get(entry.getKey()).isIntegralNumber())) { + throw invalid( + "Canonical graph private selectors and integer content require integer representation"); + } + Row original = decoded.get(i); + var content = original.authored().mutation().toBuilder(); + if (content.hasRegion()) { + content.setRegion( + content.getRegion().toBuilder() + .setSpacingMultiplier(actual.get("spacing_multiplier").doubleValue())); + } else if (content.hasRoomExit()) { + content.setRoomExit( + content.getRoomExit().toBuilder().setCost(actual.get("cost").intValue())); + } else if (content.hasWorldEntitySpawnBinding()) { + content.setWorldEntitySpawnBinding( + content.getWorldEntitySpawnBinding().toBuilder() + .setSpawnCount(actual.get("spawn_count").intValue())); + } + decoded.set( + i, + new Row( + original.template(), + original.mappingKey(), + original.privateRowKey(), + original.authored(), + content.build())); + } + return new WorldCanonicalAuthoredGraph( + plan.graph().tenantId(), plan.graph().versionId(), tenant, version, decoded); + } + + private static void fields(JsonNode node, Set expected) { + if (node == null + || !node.isObject() + || node.size() != expected.size() + || node.properties().stream().anyMatch(entry -> !expected.contains(entry.getKey()))) { + throw invalid("Canonical graph has unsupported or missing fields"); + } + } + + private static void text(JsonNode node, String field, String expected) { + JsonNode actual = node.get(field); + if (actual == null || !actual.isString() || !actual.asText().equals(expected)) { + throw invalid("Canonical graph differs at " + field); + } + } + + private static long positive(JsonNode node, String field) { + JsonNode actual = node.get(field); + if (actual == null + || !actual.isIntegralNumber() + || !actual.canConvertToLong() + || actual.longValue() <= 0) { + throw invalid("Canonical graph requires a positive private integer at " + field); + } + return actual.longValue(); + } + + private static ConflictException invalid(String message) { + return new ConflictException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java new file mode 100644 index 0000000000..20ee3b41a1 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; + +/** + * Immutable component capture, never Account authorization or complete participant/release proof. + */ +public final class WorldCanonicalFrozenTopology { + public static final String STATUS = "CAPTURED_UNVERIFIED"; + + public record Request(WorldDraftTopologyCommitPlan plan, CaptureRequest freeze) { + public Request { + Objects.requireNonNull(plan, "plan"); + Objects.requireNonNull(freeze, "freeze"); + var owner = plan.ownerBinding(); + if (!freeze.targetNamespace().equals(owner.targetNamespace()) + || !freeze.canonicalTenantId().equals(owner.canonicalTenantId()) + || !freeze.canonicalVersionId().equals(owner.canonicalVersionId()) + || !freeze.intakeRequestId().equals(owner.intakeRequestId()) + || !freeze.appliedCommitId().equals(plan.binding().commitId().toString())) { + throw new IllegalArgumentException( + "Frozen topology must bind the exact selected complete commit and source"); + } + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId()); + var expected = + plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + if (expected.size() != freeze.suppliedOwnedAffectedTuples().size() + || !new java.util.HashSet<>(expected) + .equals(new java.util.HashSet<>(freeze.suppliedOwnedAffectedTuples()))) { + throw new IllegalArgumentException( + "Frozen topology must retain every exact original World affected tuple"); + } + } + } + + private final UUID captureId; + private final Request request; + private final WorldAuthoredVersionIdentityReceipt sourceIdentity; + private final WorldCanonicalAuthoredGraph graph; + private final byte[] graphBytes; + private final byte[] storageResultBytes; + private final byte[] resultBytes; + + WorldCanonicalFrozenTopology( + UUID captureId, + Request request, + WorldAuthoredVersionIdentityReceipt sourceIdentity, + WorldCanonicalAuthoredGraph graph, + byte[] graphBytes, + byte[] storageResultBytes, + byte[] resultBytes) { + this.captureId = Objects.requireNonNull(captureId, "captureId"); + if (captureId.equals(new UUID(0, 0))) + throw new IllegalArgumentException("Capture ID must be non-nil"); + this.request = Objects.requireNonNull(request, "request"); + this.sourceIdentity = Objects.requireNonNull(sourceIdentity, "sourceIdentity"); + this.graph = Objects.requireNonNull(graph, "graph"); + this.graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + this.storageResultBytes = + Objects.requireNonNull(storageResultBytes, "storageResultBytes").clone(); + this.resultBytes = Objects.requireNonNull(resultBytes, "resultBytes").clone(); + } + + public UUID captureId() { + return captureId; + } + + public Request request() { + return request; + } + + public WorldAuthoredVersionIdentityReceipt sourceIdentity() { + return sourceIdentity; + } + + public WorldCanonicalAuthoredGraph graph() { + return graph; + } + + public byte[] graphBytes() { + return graphBytes.clone(); + } + + public byte[] storageResultBytes() { + return storageResultBytes.clone(); + } + + public byte[] resultBytes() { + return resultBytes.clone(); + } + + public String status() { + return STATUS; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java new file mode 100644 index 0000000000..5174f1c952 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java @@ -0,0 +1,241 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Explicitly unwired immutable graph/2 journal; historical reads never reenter an owner writer. */ +public class WorldCanonicalFrozenTopologyRepository { + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + private final DSLContext dsl; + private final WorldAuthoredGraphSnapshotRepository owner; + private final WorldDraftTopologyCommitRepository topology; + private final WorldDraftDesignDigestService digestService; + + @SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW", justification = "No resources or finalizer.") + public WorldCanonicalFrozenTopologyRepository( + DSLContext dsl, + WorldAuthoredGraphSnapshotRepository owner, + WorldDraftTopologyCommitRepository topology, + WorldDraftDesignDigestService digestService) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.owner = Objects.requireNonNull(owner, "owner"); + this.topology = Objects.requireNonNull(topology, "topology"); + this.digestService = Objects.requireNonNull(digestService, "digestService"); + } + + /** Absence is UNKNOWN, not abort or permission to reopen an owner operation. */ + public Optional readCommitted(Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("Frozen topology readback requires no caller transaction"); + } + return Optional.ofNullable(find(Objects.requireNonNull(request, "request"))); + } + + WorldCanonicalFrozenTopology capture(Request request) { + // This seam validates actual PostgreSQL isolation and serializes through the existing V25 row. + var provenance = owner.lockAndResolve(request.freeze()); + WorldCanonicalFrozenTopology prior = find(request); + if (prior != null) return prior; + if (request.freeze().digestSchemaVersion() != 3) { + throw new ConflictException("New canonical graph capture requires digest schema 3"); + } + if (!"FROZEN".equals(provenance.ownerFreezePhase())) { + throw new ConflictException( + "New canonical graph capture requires the exact current FROZEN attempt"); + } + var stored = topology.readUnderFrozenLock(request.plan()); + Record original = + dsl.resultQuery( + "SELECT to_jsonb(v)::text AS identity_json, to_jsonb(i)::text AS intake_json " + + "FROM world_authored_version_identity v JOIN world_authored_source_intake i " + + "ON i.operation_id=v.intake_operation_id WHERE v.operation_id=?", + request.plan().ownerBinding().versionIdentityOperationId()) + .fetchOne(); + if (original == null) + throw new ConflictException("Frozen topology has no exact original source identity"); + String identityJson = required(original, "identity_json", String.class); + String intakeJson = required(original, "intake_json", String.class); + var identity = topology.verifyOriginalSource(request.plan(), identityJson, intakeJson); + var graph = + topology.verifyImmutableBytes(request.plan(), stored.graphBytes(), stored.resultBytes()); + requirePrivateKeys(graph, identity); + var digest = + digestService.getDraftDesignDigest( + Long.toString(provenance.localTenantKey()), + Long.toString(provenance.localVersionKey())); + if (!Long.toString(provenance.localTenantKey()).equals(digest.tenantId()) + || !Long.toString(provenance.localVersionKey()).equals(digest.scopeValue()) + || digest.digestSchemaVersion() != 3 + || !request.freeze().contentDigest().equals(digest.contentDigest())) { + throw new ConflictException( + "Canonical graph capture differs from exact schema-3 frozen content checkpoint"); + } + UUID captureId = UUID.randomUUID(); + String freezeJson = JSON.writeValueAsString(request.freeze()); + String ownerJson = JSON.writeValueAsString(request.plan().ownerBinding()); + byte[] result = + result( + captureId, + request, + identityJson, + intakeJson, + stored.graphBytes(), + stored.resultBytes()); + dsl.execute( + "INSERT INTO world_canonical_frozen_topology (capture_id,publication_fence," + + "request_id,commit_id,version_identity_operation_id,freeze_request_json,owner_binding_json," + + "binding_json,binding_digest,identity_json,intake_json,graph_bytes,graph_sha256," + + "storage_result_bytes,result_bytes,capture_status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + captureId, + request.freeze().publicationFence(), + request.plan().binding().requestId(), + request.plan().binding().commitId(), + request.plan().ownerBinding().versionIdentityOperationId(), + freezeJson, + ownerJson, + request.plan().binding().canonicalJson(), + request.plan().binding().digest(), + identityJson, + intakeJson, + stored.graphBytes(), + WorldAuthoredGraphSnapshotCapture.sha256(stored.graphBytes()), + stored.resultBytes(), + result, + WorldCanonicalFrozenTopology.STATUS); + WorldCanonicalFrozenTopology readback = find(request); + if (readback == null + || !captureId.equals(readback.captureId()) + || !Arrays.equals(result, readback.resultBytes())) { + throw new ConflictException( + "Frozen topology differs from exact immutable insertion readback"); + } + return readback; + } + + private WorldCanonicalFrozenTopology find(Request supplied) { + Record row = + dsl.resultQuery( + "SELECT * FROM world_canonical_frozen_topology WHERE publication_fence=?", + supplied.freeze().publicationFence()) + .fetchOne(); + if (row == null) return null; + String bindingJson = required(row, "binding_json", String.class); + var binding = + DraftCommitBinding.fromStored(bindingJson, required(row, "binding_digest", String.class)); + String ownerJson = required(row, "owner_binding_json", String.class); + var ownerBinding = JSON.readValue(ownerJson, OwnerBinding.class); + String freezeJson = required(row, "freeze_request_json", String.class); + var freeze = JSON.readValue(freezeJson, CaptureRequest.class); + Request retained = + new Request(WorldDraftTopologyCommitPlan.create(binding, ownerBinding), freeze); + if (!binding.equals(supplied.plan().binding()) + || !ownerBinding.equals(supplied.plan().ownerBinding()) + || !freeze.equals(supplied.freeze()) + || !bindingJson.equals(binding.canonicalJson()) + || !ownerJson.equals(JSON.writeValueAsString(ownerBinding)) + || !freezeJson.equals(JSON.writeValueAsString(freeze))) { + throw new ConflictException( + "Frozen topology request was reused with changed complete input or checkpoint"); + } + UUID captureId = required(row, "capture_id", UUID.class); + if (!freeze.publicationFence().equals(required(row, "publication_fence", UUID.class)) + || !binding.requestId().equals(required(row, "request_id", UUID.class)) + || !binding.commitId().equals(required(row, "commit_id", UUID.class)) + || !ownerBinding + .versionIdentityOperationId() + .equals(required(row, "version_identity_operation_id", UUID.class)) + || !WorldCanonicalFrozenTopology.STATUS.equals( + required(row, "capture_status", String.class))) { + throw new ConflictException("Frozen topology journal identity or proof state differs"); + } + String identityJson = required(row, "identity_json", String.class); + String intakeJson = required(row, "intake_json", String.class); + JSON.readTree(identityJson); + JSON.readTree(intakeJson); + var identity = topology.verifyOriginalSource(retained.plan(), identityJson, intakeJson); + byte[] graphBytes = required(row, "graph_bytes", byte[].class); + byte[] storageResult = required(row, "storage_result_bytes", byte[].class); + if (!WorldAuthoredGraphSnapshotCapture.sha256(graphBytes) + .equals(required(row, "graph_sha256", String.class))) { + throw new ConflictException( + "Frozen canonical graph bytes failed immutable integrity readback"); + } + var graph = topology.verifyImmutableBytes(retained.plan(), graphBytes, storageResult); + requirePrivateKeys(graph, identity); + byte[] resultBytes = required(row, "result_bytes", byte[].class); + if (!Arrays.equals( + resultBytes, + result(captureId, retained, identityJson, intakeJson, graphBytes, storageResult))) { + throw new ConflictException( + "Frozen topology result differs from every original retained field"); + } + return new WorldCanonicalFrozenTopology( + captureId, retained, identity, graph, graphBytes, storageResult, resultBytes); + } + + private static void requirePrivateKeys( + WorldCanonicalAuthoredGraph graph, WorldAuthoredVersionIdentityReceipt identity) { + if (graph.localTenantKey() != identity.sourceIntakeReceipt().localTenantKey() + || graph.localVersionKey() != identity.localVersionKey()) { + throw new ConflictException( + "Canonical graph private keys differ from original source identity"); + } + } + + private byte[] result( + UUID id, + Request request, + String identityJson, + String intakeJson, + byte[] graph, + byte[] storageResult) { + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", "1"); + result.put("status", WorldCanonicalFrozenTopology.STATUS); + result.put( + "missingProof", + java.util.List.of( + "ACCOUNT_AUTHORIZATION", + "COMPLETE_PARTICIPANT_COMMIT", + "PUBLICATION_CHECKPOINT_DIGEST")); + result.put("captureId", id.toString()); + result.put("freeze", request.freeze()); + result.put("ownerBinding", request.plan().ownerBinding()); + result.put("bindingJson", request.plan().binding().canonicalJson()); + result.put("bindingDigest", request.plan().binding().digest()); + result.put("identityJson", identityJson); + result.put("intakeJson", intakeJson); + result.put("graphBytes", graph); + result.put("storageResultBytes", storageResult); + return JSON.writeValueAsBytes(result); + } + + private static T required(Record row, String name, Class type) { + T value = row.get(name, type); + if (value == null) throw new ConflictException("Frozen topology is missing " + name); + return value; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyService.java new file mode 100644 index 0000000000..3e8dceb9f2 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyService.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Owner-private, explicitly unwired capture; this adds no publication or runtime entry point. */ +public final class WorldCanonicalFrozenTopologyService { + private final WorldCanonicalFrozenTopologyRepository repository; + private final TransactionTemplate transaction; + + public WorldCanonicalFrozenTopologyService( + WorldCanonicalFrozenTopologyRepository repository, PlatformTransactionManager manager) { + this.repository = Objects.requireNonNull(repository, "repository"); + transaction = new TransactionTemplate(Objects.requireNonNull(manager, "manager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** Exact retry reads the journal first, including after terminal state, without a writer. */ + public WorldCanonicalFrozenTopology capture(Request request) { + requireNoCallerTransaction(); + var prior = repository.readCommitted(request); + if (prior.isPresent()) return prior.orElseThrow(); + return Objects.requireNonNull(transaction.execute(status -> repository.capture(request))); + } + + public Optional readCommitted(Request request) { + requireNoCallerTransaction(); + return repository.readCommitted(request); + } + + private static void requireNoCallerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("Frozen topology requires an independent owner operation"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java new file mode 100644 index 0000000000..26a18707dd --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java @@ -0,0 +1,455 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +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 net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** + * Owner-local immutable correlation between a claimed canonical Game Session instance and one + * insert-born World instance row. + * + *

This association is not Game Session producer authentication, released-content authority, + * lifecycle state, activation, JOIN, or admission proof. A caller must establish the authenticated + * same-namespace producer and complete canonical prepare/materialization proof independently. + */ +public record WorldCanonicalInstanceAssociation( + CanonicalIdentity identity, + long worldInstanceId, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldPrepareFields worldPrepareFields) { + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + public WorldCanonicalInstanceAssociation { + Objects.requireNonNull(identity, "identity"); + requirePositive(worldInstanceId, "worldInstanceId"); + Objects.requireNonNull(completeLaunchBinding, "completeLaunchBinding"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + Objects.requireNonNull(worldPrepareFields, "worldPrepareFields"); + if (worldInstanceId != worldPrepareFields.worldInstanceId()) { + throw new IllegalArgumentException( + "World association row id differs from its prepare fields"); + } + requireExactLaunchEvidence(identity, completeLaunchBinding, versionIdentity); + worldPrepareFields.requireMatches(identity, completeLaunchBinding, versionIdentity); + } + + public UUID canonicalVersionId() { + return completeLaunchBinding.evidence().releaseAttestation().canonicalVersionId(); + } + + public UUID launchBindingOperationId() { + return completeLaunchBinding.operationId(); + } + + public UUID versionIdentityOperationId() { + return versionIdentity.operationId(); + } + + /** + * Immutable canonical Game Session identity and owner scope, excluding transient read metadata. + */ + public record CanonicalIdentity( + UUID canonicalGameInstanceId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID playableStateNamespaceId, + String playableStateScope, + boolean publicProduction, + String controlPlaneRequestId) { + public CanonicalIdentity { + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "This association slice accepts SHARED only; ISOLATED/playtest identity requires the missing lifecycle/generation carrier"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "This association slice requires explicit public-production evidence; false or absent evidence is denied"); + } + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + } + } + + /** + * Exact caller-owned selector and expected digests for Gameplay's owner-read RPC. + * + *

The read request UUID and expected digests are transient request metadata; the repository + * validates the separate response echo and does not persist this request identity. + */ + public record GameSessionReadRequest( + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + String controlPlaneRequestId, + String launchDescriptorId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationEvidenceDigest) { + public GameSessionReadRequest { + requireNonNil(readRequestId, "readRequestId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 64); + requireDigest(expectedDescriptorRequestDigest, "expectedDescriptorRequestDigest"); + requireDigest(expectedDescriptorResultDigest, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationEvidenceDigest, "expectedReleaseAttestationEvidenceDigest"); + } + } + + /** + * Typed copy of Gameplay's owner-read response, kept separate from its request selector. + * + *

The echoed fields are checked against {@link GameSessionReadRequest}. Current status and row + * version are transient Game Session projection only; neither is frozen into the association or + * treated as World lifecycle authority. + */ + public record GameSessionReadEvidence( + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + String controlPlaneRequestId, + String launchDescriptorId, + String descriptorRequestDigest, + String descriptorResultDigest, + String releaseAttestationEvidenceDigest, + UUID playableStateNamespaceId, + String playableStateScope, + boolean publicProduction, + String currentGameSessionStatus, + long currentGameSessionRowVersion, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation) { + public GameSessionReadEvidence { + requireNonNil(readRequestId, "readRequestId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 64); + requireDigest(descriptorRequestDigest, "descriptorRequestDigest"); + requireDigest(descriptorResultDigest, "descriptorResultDigest"); + requireDigest(releaseAttestationEvidenceDigest, "releaseAttestationEvidenceDigest"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "This association slice accepts SHARED only; ISOLATED/playtest identity requires the missing lifecycle/generation carrier"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "This association slice requires explicit public-production evidence; false or absent evidence is denied"); + } + requireText(currentGameSessionStatus, "currentGameSessionStatus", 32); + requireNonNegative(currentGameSessionRowVersion, "currentGameSessionRowVersion"); + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(releaseAttestation, "releaseAttestation"); + descriptor.requireValid(); + new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId()) + || !descriptorRequestDigest.equals(descriptor.requestDigest()) + || !descriptorResultDigest.equals(descriptor.resultDigest()) + || !releaseAttestationEvidenceDigest.equals(releaseAttestation.evidenceDigest())) { + throw new IllegalArgumentException( + "Game Session launch-association response differs from its typed complete launch evidence"); + } + } + + public CanonicalIdentity canonicalIdentity() { + return new CanonicalIdentity( + canonicalGameInstanceId, + targetNamespace, + canonicalTenantId, + worldSlug, + playableStateNamespaceId, + playableStateScope, + publicProduction, + controlPlaneRequestId); + } + } + + /** + * Non-authorizing persistence input. The transient Game Session read correlation/status fields + * are not association identity; the exact complete binding and source/version receipts are. + */ + public record Claim( + GameSessionReadRequest gameSessionRequest, + GameSessionReadEvidence gameSessionRead, + long worldInstanceId, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + public Claim { + Objects.requireNonNull(gameSessionRequest, "gameSessionRequest"); + Objects.requireNonNull(gameSessionRead, "gameSessionRead"); + requirePositive(worldInstanceId, "worldInstanceId"); + Objects.requireNonNull(completeLaunchBinding, "completeLaunchBinding"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + requireExactReadEcho(gameSessionRequest, gameSessionRead); + CanonicalIdentity identity = gameSessionRead.canonicalIdentity(); + requireExactLaunchEvidence(identity, completeLaunchBinding, versionIdentity); + if (!gameSessionRead.descriptor().equals(completeLaunchBinding.evidence().descriptor()) + || !gameSessionRead + .releaseAttestation() + .equals(completeLaunchBinding.evidence().releaseAttestation()) + || !gameSessionRead + .launchDescriptorId() + .equals(completeLaunchBinding.descriptor().launchDescriptorId()) + || !gameSessionRead + .descriptorRequestDigest() + .equals(completeLaunchBinding.descriptor().requestDigest()) + || !gameSessionRead + .descriptorResultDigest() + .equals(completeLaunchBinding.descriptor().resultDigest()) + || !gameSessionRead + .releaseAttestationEvidenceDigest() + .equals(completeLaunchBinding.evidence().releaseAttestation().evidenceDigest())) { + throw new IllegalArgumentException( + "Game Session read projection differs from the original World V26 complete binding"); + } + } + + public UUID canonicalGameInstanceId() { + return gameSessionRead.canonicalGameInstanceId(); + } + + public CanonicalIdentity identity() { + return gameSessionRead.canonicalIdentity(); + } + + public String targetNamespace() { + return gameSessionRead.targetNamespace(); + } + + public UUID canonicalTenantId() { + return gameSessionRead.canonicalTenantId(); + } + + public String worldSlug() { + return gameSessionRead.worldSlug(); + } + + public UUID playableStateNamespaceId() { + return gameSessionRead.playableStateNamespaceId(); + } + + public String playableStateScope() { + return gameSessionRead.playableStateScope(); + } + + public String controlPlaneRequestId() { + return gameSessionRead.controlPlaneRequestId(); + } + + public String launchDescriptorId() { + return gameSessionRead.launchDescriptorId(); + } + + public String descriptorRequestDigest() { + return gameSessionRead.descriptorRequestDigest(); + } + + public String descriptorResultDigest() { + return gameSessionRead.descriptorResultDigest(); + } + + public String releaseAttestationDigest() { + return gameSessionRead.releaseAttestationEvidenceDigest(); + } + + public UUID canonicalVersionId() { + return completeLaunchBinding.evidence().releaseAttestation().canonicalVersionId(); + } + + public long localTenantKey() { + return completeLaunchBinding.sourceIntakeReceipt().localTenantKey(); + } + + public long localVersionKey() { + return versionIdentity.localVersionKey(); + } + + public UUID launchBindingOperationId() { + return completeLaunchBinding.operationId(); + } + + public UUID versionIdentityOperationId() { + return versionIdentity.operationId(); + } + } + + /** Exact immutable subset of the legacy row created by World's existing prepare owner. */ + public record WorldPrepareFields( + long worldInstanceId, + long privateTenantKey, + long privateGameInstanceKey, + long gameTemplateId, + String controlPlaneRequestId, + String launchDescriptorId, + long localVersionKey, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long releaseBundleId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String remapSetId) { + public WorldPrepareFields { + requirePositive(worldInstanceId, "worldInstanceId"); + requirePositive(privateTenantKey, "privateTenantKey"); + requirePositive(privateGameInstanceKey, "privateGameInstanceKey"); + requirePositive(gameTemplateId, "gameTemplateId"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 64); + requirePositive(localVersionKey, "localVersionKey"); + requireText(runtimeFlagsJson, "runtimeFlagsJson", Integer.MAX_VALUE); + requireText(generationConfigRevision, "generationConfigRevision", 128); + requirePositive(releaseBundleId, "releaseBundleId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef", 128); + requirePositive(versionStateEpoch, "versionStateEpoch"); + requireOptionalText(scriptPatchVersion, "scriptPatchVersion", 100); + requireOptionalText(remapSetId, "remapSetId", 64); + } + + /** + * Compares immutable prepare and release inputs only; lifecycle state, epoch, termination, and + * timestamps are intentionally not part of this association. + */ + public void requireMatches( + CanonicalIdentity identity, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + Objects.requireNonNull(identity, "identity"); + Objects.requireNonNull(completeLaunchBinding, "completeLaunchBinding"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + var descriptor = completeLaunchBinding.descriptor(); + String expectedScriptPatch = + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null; + String expectedRemapSet = descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null; + if (privateTenantKey != completeLaunchBinding.sourceIntakeReceipt().localTenantKey() + || gameTemplateId != descriptor.gameTemplateId() + || !controlPlaneRequestId.equals(identity.controlPlaneRequestId()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId()) + || localVersionKey != versionIdentity.localVersionKey() + || !Objects.equals(scriptPatchVersion, expectedScriptPatch) + || !runtimeFlagsJson.equals(descriptor.runtimeFlagsJson()) + || !generationConfigRevision.equals(descriptor.generationConfigRevision()) + || releaseBundleId != descriptor.releaseBundleId() + || !publishedReleaseBundleRef.equals(descriptor.publishedReleaseBundleRef()) + || versionStateEpoch != descriptor.versionStateEpoch() + || !Objects.equals(remapSetId, expectedRemapSet)) { + throw new IllegalArgumentException( + "World instance row differs from the exact canonical launch prepare inputs"); + } + } + } + + private static void requireExactLaunchEvidence( + CanonicalIdentity identity, + WorldCompleteLaunchBindingReceipt binding, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + var descriptor = binding.evidence().descriptor(); + var release = binding.evidence().releaseAttestation(); + var source = binding.sourceIntakeReceipt(); + if (!identity.targetNamespace().equals(binding.targetNamespace()) + || !identity.canonicalTenantId().equals(binding.canonicalTenantId()) + || !identity.worldSlug().equals(binding.worldSlug()) + || !identity.controlPlaneRequestId().equals(binding.controlPlaneRequestId()) + || !identity.targetNamespace().equals(descriptor.targetNamespace()) + || !identity.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !identity.worldSlug().equals(descriptor.worldSlug()) + || !identity.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !identity.targetNamespace().equals(release.targetNamespace()) + || !identity.canonicalTenantId().equals(release.canonicalTenantId()) + || !identity.worldSlug().equals(release.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(source.sourceOperationId()) + || !descriptor.authoredWorldSourceEvidenceDigest().equals(source.sourceEvidenceDigest()) + || !source.equals(versionIdentity.sourceIntakeReceipt()) + || !identity.targetNamespace().equals(versionIdentity.targetNamespace()) + || !identity.canonicalTenantId().equals(versionIdentity.canonicalTenantId()) + || !identity.worldSlug().equals(versionIdentity.worldSlug()) + || !release.canonicalVersionId().equals(versionIdentity.canonicalVersionId()) + || descriptor.versionId() != versionIdentity.gameDesignVersionId() + || versionIdentity.sourceIntakeReceipt().localTenantKey() != source.localTenantKey()) { + throw new IllegalArgumentException( + "Canonical instance claim differs from its exact World launch/source/version evidence"); + } + } + + private static void requireExactReadEcho( + GameSessionReadRequest request, GameSessionReadEvidence response) { + if (!request.readRequestId().equals(response.readRequestId()) + || !request.targetNamespace().equals(response.targetNamespace()) + || !request.canonicalTenantId().equals(response.canonicalTenantId()) + || !request.worldSlug().equals(response.worldSlug()) + || !request.canonicalGameInstanceId().equals(response.canonicalGameInstanceId()) + || !request.controlPlaneRequestId().equals(response.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(response.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(response.descriptorRequestDigest()) + || !request.expectedDescriptorResultDigest().equals(response.descriptorResultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(response.releaseAttestationEvidenceDigest())) { + throw new IllegalArgumentException( + "Game Session launch-association response does not echo the exact read request tuple and expected digests"); + } + } + + 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 <= 0L) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static void requireNonNegative(long value, String label) { + if (value < 0L) { + throw new IllegalArgumentException(label + " must not be negative"); + } + } + + private static void requireText(String value, String label, int maxLength) { + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(label + " must be nonblank and within its storage bound"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireOptionalText(String value, String label, int maxLength) { + if (value != null && (value.isBlank() || value.length() > maxLength)) { + throw new IllegalArgumentException( + label + " must be absent or nonblank within its storage bound"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java new file mode 100644 index 0000000000..826fce30ef --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java @@ -0,0 +1,854 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +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.AuthoredWorldSourceEvidence; +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; + +/** + * World-local storage and exact readback for a claimed canonical instance association. + * + *

This component has no public transport and does not authenticate Game Session. A positive + * owner readback only returns retained correlation; JOIN, ACTIVE, and admission remain unavailable + * until an authenticated same-namespace producer and complete prepare/materialization proof are + * integrated by the lifecycle owner. + */ +public final class WorldCanonicalInstanceAssociationRepository { + private static final Table ASSOCIATION = + DSL.table(DSL.name("world_canonical_instance_association")); + private static final Table WORLD_INSTANCE = DSL.table(DSL.name("world_instance")); + private static final Table COMPLETE_BINDING = + DSL.table(DSL.name("world_complete_launch_binding")); + private static final Table SOURCE_INTAKE = DSL.table(DSL.name("world_authored_source_intake")); + 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 SCHEMA_VERSION = field("schema_version", Short.class); + private static final Field CANONICAL_GAME_INSTANCE_ID = + field("canonical_game_instance_id", UUID.class); + private static final Field CANONICAL_TARGET_NAMESPACE = + field("canonical_target_namespace", String.class); + private static final Field CANONICAL_TENANT_ID = field("canonical_tenant_id", UUID.class); + private static final Field CANONICAL_WORLD_SLUG = + field("canonical_world_slug", String.class); + private static final Field PLAYABLE_STATE_NAMESPACE_ID = + field("playable_state_namespace_id", UUID.class); + private static final Field PLAYABLE_STATE_SCOPE = + field("playable_state_scope", String.class); + private static final Field PUBLIC_PRODUCTION = field("public_production", Boolean.class); + private static final Field PLAYTEST_LIFECYCLE_ID = + field("playtest_lifecycle_id", UUID.class); + private static final Field PLAYTEST_STATE_GENERATION = + field("playtest_state_generation", Long.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + field("control_plane_request_id", String.class); + private static final Field WORLD_INSTANCE_ID = field("world_instance_id", Long.class); + private static final Field LAUNCH_BINDING_OPERATION_ID = + field("canonical_launch_binding_operation_id", UUID.class); + private static final Field VERSION_IDENTITY_OPERATION_ID = + field("version_identity_operation_id", UUID.class); + private static final Field CANONICAL_VERSION_ID = field("canonical_version_id", UUID.class); + private static final Field LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field PRIVATE_GAME_INSTANCE_KEY = + field("private_game_instance_key", Long.class); + private static final Field GAME_TEMPLATE_ID = field("game_template_id", Long.class); + private static final Field LAUNCH_DESCRIPTOR_ID = + field("launch_descriptor_id", String.class); + private static final Field LOCAL_VERSION_KEY = field("local_version_key", Long.class); + private static final Field SCRIPT_PATCH_VERSION = + field("script_patch_version", String.class); + private static final Field RUNTIME_FLAGS_JSON = field("runtime_flags_json", String.class); + private static final Field GENERATION_CONFIG_REVISION = + field("generation_config_revision", String.class); + private static final Field RELEASE_BUNDLE_ID = field("release_bundle_id", Long.class); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + field("published_release_bundle_ref", String.class); + private static final Field VERSION_STATE_EPOCH = field("version_state_epoch", Long.class); + private static final Field REMAP_SET_ID = field("remap_set_id", String.class); + private static final Field INTAKE_OPERATION_ID = field("intake_operation_id", UUID.class); + private static final Field INTAKE_REQUEST_ID = field("intake_request_id", UUID.class); + private static final Field SOURCE_OPERATION_ID = field("source_operation_id", UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field DESCRIPTOR_REQUEST_DIGEST = + field("descriptor_request_digest", String.class); + private static final Field DESCRIPTOR_RESULT_DIGEST = + field("descriptor_result_digest", String.class); + private static final Field RELEASE_ATTESTATION_DIGEST = + field("release_attestation_digest", String.class); + + private static final Field INSTANCE_ID = field("id", Long.class); + private static final Field INSTANCE_TENANT_ID = field("tenant_id", Long.class); + private static final Field INSTANCE_GAME_INSTANCE_ID = + field("game_instance_id", Long.class); + private static final Field INSTANCE_GAME_TEMPLATE_ID = + field("game_template_id", Long.class); + private static final Field INSTANCE_CONTROL_PLANE_REQUEST_ID = + field("control_plane_request_id", String.class); + private static final Field INSTANCE_LAUNCH_DESCRIPTOR_ID = + field("launch_descriptor_id", String.class); + private static final Field INSTANCE_VERSION_ID = field("version_id", Long.class); + private static final Field INSTANCE_SCRIPT_PATCH_VERSION = + field("script_patch_version", String.class); + private static final Field INSTANCE_RUNTIME_FLAGS_JSON = + field("runtime_flags_json", String.class); + private static final Field INSTANCE_GENERATION_CONFIG_REVISION = + field("generation_config_revision", String.class); + private static final Field INSTANCE_RELEASE_BUNDLE_ID = + field("release_bundle_id", Long.class); + private static final Field INSTANCE_PUBLISHED_RELEASE_BUNDLE_REF = + field("published_release_bundle_ref", String.class); + private static final Field INSTANCE_VERSION_STATE_EPOCH = + field("version_state_epoch", Long.class); + private static final Field INSTANCE_REMAP_SET_ID = field("remap_set_id", String.class); + private static final Field INSTANCE_CANONICAL_GAME_INSTANCE_ID = + field("canonical_game_instance_id", UUID.class); + private static final Field INSTANCE_CANONICAL_TARGET_NAMESPACE = + field("canonical_target_namespace", String.class); + private static final Field INSTANCE_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field INSTANCE_CANONICAL_WORLD_SLUG = + field("canonical_world_slug", String.class); + private static final Field INSTANCE_PLAYABLE_STATE_NAMESPACE_ID = + field("playable_state_namespace_id", UUID.class); + private static final Field INSTANCE_PLAYABLE_STATE_SCOPE = + field("playable_state_scope", String.class); + private static final Field INSTANCE_PUBLIC_PRODUCTION = + field("public_production", Boolean.class); + private static final Field INSTANCE_PLAYTEST_LIFECYCLE_ID = + field("playtest_lifecycle_id", UUID.class); + private static final Field INSTANCE_PLAYTEST_STATE_GENERATION = + field("playtest_state_generation", Long.class); + private static final Field INSTANCE_LAUNCH_BINDING_OPERATION_ID = + field("canonical_launch_binding_operation_id", UUID.class); + + private static final Field BINDING_OPERATION_ID = + DSL.field(DSL.name("binding_operation_id"), UUID.class); + private static final Field BINDING_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field BINDING_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field BINDING_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field BINDING_WORLD_SLUG = field("world_slug", String.class); + private static final Field BINDING_CONTROL_PLANE_REQUEST_ID = + field("control_plane_request_id", String.class); + private static final Field BINDING_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field BINDING_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field BINDING_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field BINDING_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field BINDING_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field BINDING_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field BINDING_DESCRIPTOR_REQUEST_DIGEST = + field("descriptor_request_digest", String.class); + private static final Field BINDING_DESCRIPTOR_RESULT_DIGEST = + field("descriptor_result_digest", String.class); + private static final Field BINDING_RELEASE_ATTESTATION_DIGEST = + field("release_attestation_digest", String.class); + private static final Field BINDING_DESCRIPTOR_JSON = + field("descriptor_json", String.class); + private static final Field BINDING_RELEASE_ATTESTATION_JSON = + field("release_attestation_json", String.class); + + private static final Field SOURCE_OPERATION_ID_KEY = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field SOURCE_SCHEMA_VERSION = field("schema_version", Short.class); + private static final Field SOURCE_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field SOURCE_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = field("request_digest", String.class); + private static final Field SOURCE_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field SOURCE_EVIDENCE_SCHEMA_VERSION = + field("source_schema_version", Short.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + field("source_registration_request_id", UUID.class); + private static final Field SOURCE_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field SOURCE_SOURCE_REQUEST_DIGEST = + field("source_request_digest", String.class); + private static final Field SOURCE_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field SOURCE_TENANT_SLUG = field("tenant_slug", String.class); + private static final Field SOURCE_WORLD_SLUG = field("world_slug", String.class); + private static final Field SOURCE_WORLD_DISPLAY_NAME = + field("world_display_name", String.class); + private static final Field SOURCE_GAME_ROW_ID = field("source_game_row_id", Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + field("source_game_tenant_key", String.class); + private static final Field SOURCE_PROVENANCE_KIND = + field("source_provenance_kind", String.class); + private static final Field SOURCE_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field SOURCE_RECEIPT_DIGEST = field("receipt_digest", String.class); + + private static final Field VERSION_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field VERSION_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field VERSION_WORLD_SLUG = field("world_slug", String.class); + private static final Field VERSION_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field VERSION_GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field VERSION_LOCAL_VERSION_KEY = + field("local_version_key", Long.class); + private static final Field VERSION_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field VERSION_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field VERSION_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field VERSION_INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field VERSION_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field VERSION_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field VERSION_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field VERSION_STATE_SCHEMA_VERSION = + field("version_state_schema_version", Short.class); + private static final Field VERSION_STATE_READ_REQUEST_ID = + field("version_state_read_request_id", UUID.class); + private static final Field VERSION_STATE_STATE = + field("version_state_state", String.class); + private static final Field VERSION_STATE_EVIDENCE_EPOCH = + field("version_state_epoch", Long.class); + private static final Field VERSION_STATE_EVIDENCE_DIGEST = + field("version_state_evidence_digest", String.class); + private static final Field VERSION_STATE_EVIDENCE_JSON = + field("version_state_evidence_json", String.class); + + private final DSLContext dsl; + private final WorldCompleteLaunchBindingRepository launchBindingRepository; + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; + private final WorldAuthoredVersionIdentityRepository versionIdentityRepository; + + public WorldCanonicalInstanceAssociationRepository( + DSLContext dsl, + WorldCompleteLaunchBindingRepository launchBindingRepository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + WorldAuthoredVersionIdentityRepository versionIdentityRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.launchBindingRepository = + Objects.requireNonNull(launchBindingRepository, "launchBindingRepository"); + this.sourceIntakeRepository = + Objects.requireNonNull(sourceIntakeRepository, "sourceIntakeRepository"); + this.versionIdentityRepository = + Objects.requireNonNull(versionIdentityRepository, "versionIdentityRepository"); + } + + /** + * Retains an exact non-authorizing claim in the caller's short writable READ COMMITTED World + * transaction, after the same transaction created or selected its exact canonical World row. + * + *

This method does not commit the caller's transaction. The caller must commit, then use + * {@link #readOwnerAssociation(UUID)} as a separate committed read before reporting storage + * success. An exact retry compares the immutable V26 descriptor/release bytes and V23/V27 source + * and Version provenance already supplied in {@code claim}; it never re-resolves Game Design. + */ + public void retainClaimInOwnerTransaction(WorldCanonicalInstanceAssociation.Claim claim) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(claim, "claim"); + + Record worldRow = lockWorldInstance(claim.worldInstanceId()); + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields = + toWorldPrepareFields(worldRow); + requireInsertBornIdentity(worldRow, claim); + prepareFields.requireMatches( + claim.identity(), claim.completeLaunchBinding(), claim.versionIdentity()); + requireExactImmutableOwnerEvidence(claim); + + Record existing = findConflict(claim); + if (existing != null) { + requireSameStoredClaim(existing, claim, prepareFields); + return; + } + + int inserted = + dsl.insertInto(ASSOCIATION) + .set(SCHEMA_VERSION, (short) 1) + .set(CANONICAL_GAME_INSTANCE_ID, claim.canonicalGameInstanceId()) + .set(CANONICAL_TARGET_NAMESPACE, claim.targetNamespace()) + .set(CANONICAL_TENANT_ID, claim.canonicalTenantId()) + .set(CANONICAL_WORLD_SLUG, claim.worldSlug()) + .set(PLAYABLE_STATE_NAMESPACE_ID, claim.playableStateNamespaceId()) + .set(PLAYABLE_STATE_SCOPE, claim.playableStateScope()) + .set(PUBLIC_PRODUCTION, claim.identity().publicProduction()) + .set(PLAYTEST_LIFECYCLE_ID, (UUID) null) + .set(PLAYTEST_STATE_GENERATION, (Long) null) + .set(CONTROL_PLANE_REQUEST_ID, claim.controlPlaneRequestId()) + .set(WORLD_INSTANCE_ID, prepareFields.worldInstanceId()) + .set(LAUNCH_BINDING_OPERATION_ID, claim.launchBindingOperationId()) + .set(VERSION_IDENTITY_OPERATION_ID, claim.versionIdentityOperationId()) + .set(CANONICAL_VERSION_ID, claim.canonicalVersionId()) + .set(LOCAL_TENANT_KEY, prepareFields.privateTenantKey()) + .set(PRIVATE_GAME_INSTANCE_KEY, prepareFields.privateGameInstanceKey()) + .set(GAME_TEMPLATE_ID, prepareFields.gameTemplateId()) + .set(LAUNCH_DESCRIPTOR_ID, prepareFields.launchDescriptorId()) + .set(LOCAL_VERSION_KEY, prepareFields.localVersionKey()) + .set(SCRIPT_PATCH_VERSION, prepareFields.scriptPatchVersion()) + .set(RUNTIME_FLAGS_JSON, prepareFields.runtimeFlagsJson()) + .set(GENERATION_CONFIG_REVISION, prepareFields.generationConfigRevision()) + .set(RELEASE_BUNDLE_ID, prepareFields.releaseBundleId()) + .set(PUBLISHED_RELEASE_BUNDLE_REF, prepareFields.publishedReleaseBundleRef()) + .set(VERSION_STATE_EPOCH, prepareFields.versionStateEpoch()) + .set(REMAP_SET_ID, prepareFields.remapSetId()) + .set( + INTAKE_OPERATION_ID, + claim.completeLaunchBinding().sourceIntakeReceipt().operationId()) + .set( + INTAKE_REQUEST_ID, + claim.completeLaunchBinding().sourceIntakeReceipt().intakeRequestId()) + .set( + SOURCE_OPERATION_ID, + claim.completeLaunchBinding().sourceIntakeReceipt().sourceOperationId()) + .set( + SOURCE_EVIDENCE_DIGEST, + claim.completeLaunchBinding().sourceIntakeReceipt().sourceEvidenceDigest()) + .set( + INTAKE_REQUEST_DIGEST, + claim.completeLaunchBinding().sourceIntakeReceipt().requestDigest()) + .set( + INTAKE_RECEIPT_DIGEST, + claim.completeLaunchBinding().sourceIntakeReceipt().receiptDigest()) + .set( + DESCRIPTOR_REQUEST_DIGEST, + claim.completeLaunchBinding().descriptor().requestDigest()) + .set( + DESCRIPTOR_RESULT_DIGEST, claim.completeLaunchBinding().descriptor().resultDigest()) + .set( + RELEASE_ATTESTATION_DIGEST, + claim.completeLaunchBinding().evidence().releaseAttestation().evidenceDigest()) + .onConflictDoNothing() + .execute(); + + Record stored = findConflict(claim); + if (stored == null) { + throw new InvalidAssociationEvidenceException( + "World canonical instance association is missing after its owner claim"); + } + requireSameStoredClaim(stored, claim, prepareFields); + if (inserted == 0) { + // The complete exact compare above is the only idempotent conflict outcome. + return; + } + } + + /** + * Independently reads and reconstructs one immutable owner association after the write + * transaction commits. A present result is non-authorizing and carries no lifecycle status. + */ + public Optional readOwnerAssociation( + UUID canonicalGameInstanceId) { + requireNoActiveTransaction("World canonical instance association read"); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + Record row = findByCanonicalGameInstance(canonicalGameInstanceId); + if (row == null) { + return Optional.empty(); + } + return Optional.of(toAssociation(row)); + } + + private WorldCanonicalInstanceAssociation toAssociation(Record row) { + try { + short schemaVersion = required(row, SCHEMA_VERSION); + if (schemaVersion != 1) { + throw new IllegalArgumentException( + "Unsupported World canonical instance association schema"); + } + String namespace = required(row, CANONICAL_TARGET_NAMESPACE); + UUID tenantId = required(row, CANONICAL_TENANT_ID); + String worldSlug = required(row, CANONICAL_WORLD_SLUG); + String controlRequestId = required(row, CONTROL_PLANE_REQUEST_ID); + UUID bindingOperationId = required(row, LAUNCH_BINDING_OPERATION_ID); + UUID intakeRequestId = required(row, INTAKE_REQUEST_ID); + WorldCompleteLaunchBindingRepository.StoredBinding storedBinding = + launchBindingRepository + .read(namespace, tenantId, controlRequestId) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "World canonical association lost its immutable launch binding")); + if (!storedBinding.operationId().equals(bindingOperationId)) { + throw new InvalidAssociationEvidenceException( + "World canonical association substituted its complete launch binding"); + } + WorldAuthoredSourceIntakeReceipt sourceReceipt = + sourceIntakeRepository + .read(namespace, intakeRequestId) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "World canonical association lost its original source intake")); + WorldCompleteLaunchBindingReceipt completeBinding = + launchBindingRepository.toReceipt(storedBinding, sourceReceipt); + UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); + WorldAuthoredVersionIdentityReceipt versionIdentity = + versionIdentityRepository + .readByCanonicalVersion(namespace, tenantId, worldSlug, canonicalVersionId) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "World canonical association lost its UUID-to-private-Version receipt")); + WorldCanonicalInstanceAssociation.CanonicalIdentity identity = + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + required(row, CANONICAL_GAME_INSTANCE_ID), + namespace, + tenantId, + worldSlug, + required(row, PLAYABLE_STATE_NAMESPACE_ID), + required(row, PLAYABLE_STATE_SCOPE), + required(row, PUBLIC_PRODUCTION), + controlRequestId); + if (row.get(PLAYTEST_LIFECYCLE_ID) != null || row.get(PLAYTEST_STATE_GENERATION) != null) { + throw new InvalidAssociationEvidenceException( + "Persisted playtest association lacks the current producer's conditional lifecycle/generation proof"); + } + long worldInstanceId = required(row, WORLD_INSTANCE_ID); + Record worldRow = readWorldInstance(worldInstanceId); + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields = + toWorldPrepareFields(worldRow); + requireInsertBornIdentity(worldRow, identity, completeBinding.operationId()); + prepareFields.requireMatches(identity, completeBinding, versionIdentity); + requireStoredAssociationColumns( + row, identity, worldInstanceId, completeBinding, versionIdentity, prepareFields); + return new WorldCanonicalInstanceAssociation( + identity, worldInstanceId, completeBinding, versionIdentity, prepareFields); + } catch (RuntimeException exception) { + if (exception instanceof InvalidAssociationEvidenceException) { + throw exception; + } + throw new InvalidAssociationEvidenceException( + "Persisted World canonical instance association is invalid", exception); + } + } + + private void requireExactImmutableOwnerEvidence(WorldCanonicalInstanceAssociation.Claim claim) { + var sourceReceipt = claim.completeLaunchBinding().sourceIntakeReceipt(); + var evidence = claim.completeLaunchBinding().evidence(); + var descriptor = evidence.descriptor(); + var release = evidence.releaseAttestation(); + + Record binding = + dsl.selectFrom(COMPLETE_BINDING) + .where(BINDING_OPERATION_ID.eq(claim.launchBindingOperationId())) + .fetchOne(); + if (binding == null + || !Objects.equals( + binding.get(BINDING_TARGET_NAMESPACE, String.class), claim.targetNamespace()) + || !Objects.equals( + binding.get(BINDING_CANONICAL_TENANT_ID, UUID.class), claim.canonicalTenantId()) + || !Objects.equals( + binding.get(BINDING_CANONICAL_VERSION_ID, UUID.class), claim.canonicalVersionId()) + || !Objects.equals(binding.get(BINDING_WORLD_SLUG, String.class), claim.worldSlug()) + || !Objects.equals( + binding.get(BINDING_CONTROL_PLANE_REQUEST_ID, String.class), + claim.controlPlaneRequestId()) + || !Objects.equals( + binding.get(BINDING_INTAKE_OPERATION_ID, UUID.class), sourceReceipt.operationId()) + || !Objects.equals( + binding.get(BINDING_INTAKE_REQUEST_ID, UUID.class), sourceReceipt.intakeRequestId()) + || !Objects.equals( + binding.get(BINDING_LOCAL_TENANT_KEY, Long.class), sourceReceipt.localTenantKey()) + || !Objects.equals( + binding.get(BINDING_SOURCE_OPERATION_ID, UUID.class), sourceReceipt.sourceOperationId()) + || !Objects.equals( + binding.get(BINDING_SOURCE_EVIDENCE_DIGEST, String.class), + sourceReceipt.sourceEvidenceDigest()) + || !Objects.equals( + binding.get(BINDING_INTAKE_RECEIPT_DIGEST, String.class), sourceReceipt.receiptDigest()) + || !Objects.equals( + binding.get(BINDING_DESCRIPTOR_REQUEST_DIGEST, String.class), + descriptor.requestDigest()) + || !Objects.equals( + binding.get(BINDING_DESCRIPTOR_RESULT_DIGEST, String.class), descriptor.resultDigest()) + || !Objects.equals( + binding.get(BINDING_RELEASE_ATTESTATION_DIGEST, String.class), release.evidenceDigest()) + || !Objects.equals( + binding.get(BINDING_DESCRIPTOR_JSON, String.class), writeJson(descriptor)) + || !Objects.equals( + binding.get(BINDING_RELEASE_ATTESTATION_JSON, String.class), writeJson(release))) { + throw new RegistrationConflictException( + "Canonical instance claim differs from exact immutable V26 descriptor/release bytes"); + } + + Record source = + dsl.selectFrom(SOURCE_INTAKE) + .where(SOURCE_OPERATION_ID_KEY.eq(sourceReceipt.operationId())) + .fetchOne(); + requireExactSourceColumns(source, sourceReceipt); + + WorldAuthoredVersionIdentityReceipt identity = claim.versionIdentity(); + AuthoredWorldVersionStateEvidence versionEvidence = identity.versionStateEvidence(); + Record version = + dsl.selectFrom(VERSION_IDENTITY) + .where(VERSION_OPERATION_ID.eq(identity.operationId())) + .fetchOne(); + if (version == null + || !Objects.equals( + version.get(VERSION_TARGET_NAMESPACE, String.class), identity.targetNamespace()) + || !Objects.equals( + version.get(VERSION_CANONICAL_TENANT_ID, UUID.class), identity.canonicalTenantId()) + || !Objects.equals(version.get(VERSION_WORLD_SLUG, String.class), identity.worldSlug()) + || !Objects.equals( + version.get(VERSION_CANONICAL_VERSION_ID, UUID.class), identity.canonicalVersionId()) + || !Objects.equals( + version.get(VERSION_GAME_DESIGN_VERSION_ID, Long.class), identity.gameDesignVersionId()) + || !Objects.equals( + version.get(VERSION_LOCAL_VERSION_KEY, Long.class), identity.localVersionKey()) + || !Objects.equals( + version.get(VERSION_INTAKE_OPERATION_ID, UUID.class), sourceReceipt.operationId()) + || !Objects.equals( + version.get(VERSION_INTAKE_REQUEST_ID, UUID.class), sourceReceipt.intakeRequestId()) + || !Objects.equals( + version.get(VERSION_LOCAL_TENANT_KEY, Long.class), sourceReceipt.localTenantKey()) + || !Objects.equals( + version.get(VERSION_INTAKE_REQUEST_DIGEST, String.class), sourceReceipt.requestDigest()) + || !Objects.equals( + version.get(VERSION_SOURCE_OPERATION_ID, UUID.class), sourceReceipt.sourceOperationId()) + || !Objects.equals( + version.get(VERSION_SOURCE_EVIDENCE_DIGEST, String.class), + sourceReceipt.sourceEvidenceDigest()) + || !Objects.equals( + version.get(VERSION_INTAKE_RECEIPT_DIGEST, String.class), sourceReceipt.receiptDigest()) + || !Objects.equals( + version.get(VERSION_STATE_SCHEMA_VERSION, Short.class), + (short) versionEvidence.request().schemaVersion()) + || !Objects.equals( + version.get(VERSION_STATE_READ_REQUEST_ID, UUID.class), + versionEvidence.request().readRequestId()) + || !Objects.equals( + version.get(VERSION_STATE_STATE, String.class), + versionEvidence.versionState().name().replace("VERSION_LIFECYCLE_STATE_", "")) + || !Objects.equals( + version.get(VERSION_STATE_EVIDENCE_EPOCH, Long.class), + versionEvidence.versionStateEpoch()) + || !Objects.equals( + version.get(VERSION_STATE_EVIDENCE_DIGEST, String.class), + versionEvidence.evidenceDigest()) + || !Objects.equals( + version.get(VERSION_STATE_EVIDENCE_JSON, String.class), writeJson(versionEvidence))) { + throw new RegistrationConflictException( + "Canonical instance claim differs from exact immutable V27 Version/source bytes"); + } + } + + private static void requireExactSourceColumns( + Record row, WorldAuthoredSourceIntakeReceipt receipt) { + if (row == null) { + throw new RegistrationConflictException( + "Canonical instance claim lost its original source intake"); + } + AuthoredWorldSourceEvidence source = receipt.source(); + if (!Objects.equals( + row.get(SOURCE_SCHEMA_VERSION, Short.class), (short) receipt.schemaVersion()) + || !Objects.equals( + row.get(SOURCE_TARGET_NAMESPACE, String.class), receipt.targetNamespace()) + || !Objects.equals(row.get(SOURCE_INTAKE_REQUEST_ID, UUID.class), receipt.intakeRequestId()) + || !Objects.equals(row.get(SOURCE_REQUEST_DIGEST, String.class), receipt.requestDigest()) + || !Objects.equals(row.get(SOURCE_LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey()) + || !Objects.equals( + row.get(SOURCE_EVIDENCE_SCHEMA_VERSION, Short.class), (short) source.schemaVersion()) + || !Objects.equals( + row.get(SOURCE_REGISTRATION_REQUEST_ID, UUID.class), source.registrationRequestId()) + || !Objects.equals(row.get(SOURCE_SOURCE_OPERATION_ID, UUID.class), source.operationId()) + || !Objects.equals( + row.get(SOURCE_SOURCE_REQUEST_DIGEST, String.class), source.requestDigest()) + || !Objects.equals( + row.get(SOURCE_CANONICAL_TENANT_ID, UUID.class), source.canonicalTenantId()) + || !Objects.equals(row.get(SOURCE_TENANT_SLUG, String.class), source.tenantSlug()) + || !Objects.equals(row.get(SOURCE_WORLD_SLUG, String.class), source.worldSlug()) + || !Objects.equals( + row.get(SOURCE_WORLD_DISPLAY_NAME, String.class), source.worldDisplayName()) + || !Objects.equals(row.get(SOURCE_GAME_ROW_ID, Long.class), source.sourceGameRowId()) + || !Objects.equals( + row.get(SOURCE_GAME_TENANT_KEY, String.class), source.sourceGameTenantKey()) + || !Objects.equals(row.get(SOURCE_PROVENANCE_KIND, String.class), source.provenanceKind()) + || !Objects.equals( + row.get(SOURCE_SOURCE_EVIDENCE_DIGEST, String.class), source.evidenceDigest()) + || !Objects.equals(row.get(SOURCE_RECEIPT_DIGEST, String.class), receipt.receiptDigest())) { + throw new RegistrationConflictException( + "Canonical instance claim differs from exact immutable World source intake fields"); + } + } + + private void requireSameStoredClaim( + Record stored, + WorldCanonicalInstanceAssociation.Claim claim, + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields) { + requireStoredAssociationColumns( + stored, + claim.identity(), + claim.worldInstanceId(), + claim.completeLaunchBinding(), + claim.versionIdentity(), + prepareFields); + WorldCanonicalInstanceAssociation.WorldPrepareFields actual = + toWorldPrepareFields(readWorldInstance(claim.worldInstanceId())); + if (!actual.equals(prepareFields)) { + throw new InvalidAssociationEvidenceException( + "World canonical association row changed during exact owner retry"); + } + } + + private static void requireStoredAssociationColumns( + Record row, + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + long worldInstanceId, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields) { + var source = completeLaunchBinding.sourceIntakeReceipt(); + var descriptor = completeLaunchBinding.descriptor(); + var release = completeLaunchBinding.evidence().releaseAttestation(); + if (required(row, SCHEMA_VERSION) != 1 + || !Objects.equals( + required(row, CANONICAL_GAME_INSTANCE_ID), identity.canonicalGameInstanceId()) + || !Objects.equals(required(row, CANONICAL_TARGET_NAMESPACE), identity.targetNamespace()) + || !Objects.equals(required(row, CANONICAL_TENANT_ID), identity.canonicalTenantId()) + || !Objects.equals(required(row, CANONICAL_WORLD_SLUG), identity.worldSlug()) + || !Objects.equals( + required(row, PLAYABLE_STATE_NAMESPACE_ID), identity.playableStateNamespaceId()) + || !Objects.equals(required(row, PLAYABLE_STATE_SCOPE), identity.playableStateScope()) + || !Objects.equals(required(row, PUBLIC_PRODUCTION), identity.publicProduction()) + || row.get(PLAYTEST_LIFECYCLE_ID) != null + || row.get(PLAYTEST_STATE_GENERATION) != null + || !Objects.equals( + required(row, CONTROL_PLANE_REQUEST_ID), identity.controlPlaneRequestId()) + || !Objects.equals(required(row, WORLD_INSTANCE_ID), worldInstanceId) + || !Objects.equals( + required(row, LAUNCH_BINDING_OPERATION_ID), completeLaunchBinding.operationId()) + || !Objects.equals( + required(row, VERSION_IDENTITY_OPERATION_ID), versionIdentity.operationId()) + || !Objects.equals(required(row, CANONICAL_VERSION_ID), release.canonicalVersionId()) + || !Objects.equals(required(row, LOCAL_TENANT_KEY), prepareFields.privateTenantKey()) + || !Objects.equals( + required(row, PRIVATE_GAME_INSTANCE_KEY), prepareFields.privateGameInstanceKey()) + || !Objects.equals(required(row, GAME_TEMPLATE_ID), prepareFields.gameTemplateId()) + || !Objects.equals(required(row, LAUNCH_DESCRIPTOR_ID), prepareFields.launchDescriptorId()) + || !Objects.equals(required(row, LOCAL_VERSION_KEY), prepareFields.localVersionKey()) + || !Objects.equals(row.get(SCRIPT_PATCH_VERSION), prepareFields.scriptPatchVersion()) + || !Objects.equals(required(row, RUNTIME_FLAGS_JSON), prepareFields.runtimeFlagsJson()) + || !Objects.equals( + required(row, GENERATION_CONFIG_REVISION), prepareFields.generationConfigRevision()) + || !Objects.equals(required(row, RELEASE_BUNDLE_ID), prepareFields.releaseBundleId()) + || !Objects.equals( + required(row, PUBLISHED_RELEASE_BUNDLE_REF), prepareFields.publishedReleaseBundleRef()) + || !Objects.equals(required(row, VERSION_STATE_EPOCH), prepareFields.versionStateEpoch()) + || !Objects.equals(row.get(REMAP_SET_ID), prepareFields.remapSetId()) + || !Objects.equals(required(row, INTAKE_OPERATION_ID), source.operationId()) + || !Objects.equals(required(row, INTAKE_REQUEST_ID), source.intakeRequestId()) + || !Objects.equals(required(row, SOURCE_OPERATION_ID), source.sourceOperationId()) + || !Objects.equals(required(row, SOURCE_EVIDENCE_DIGEST), source.sourceEvidenceDigest()) + || !Objects.equals(required(row, INTAKE_REQUEST_DIGEST), source.requestDigest()) + || !Objects.equals(required(row, INTAKE_RECEIPT_DIGEST), source.receiptDigest()) + || !Objects.equals(required(row, DESCRIPTOR_REQUEST_DIGEST), descriptor.requestDigest()) + || !Objects.equals(required(row, DESCRIPTOR_RESULT_DIGEST), descriptor.resultDigest()) + || !Objects.equals(required(row, RELEASE_ATTESTATION_DIGEST), release.evidenceDigest())) { + throw new RegistrationConflictException( + "Canonical Game Instance, World row, request, source, Version, descriptor, or release binding conflicts"); + } + } + + private void requireInsertBornIdentity( + Record row, WorldCanonicalInstanceAssociation.Claim claim) { + requireInsertBornIdentity(row, claim.identity(), claim.launchBindingOperationId()); + } + + private void requireInsertBornIdentity( + Record row, + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + UUID launchBindingOperationId) { + if (row == null + || !Objects.equals( + row.get(INSTANCE_CANONICAL_GAME_INSTANCE_ID), identity.canonicalGameInstanceId()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_TARGET_NAMESPACE), identity.targetNamespace()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_TENANT_ID), identity.canonicalTenantId()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_WORLD_SLUG), identity.worldSlug()) + || !Objects.equals( + row.get(INSTANCE_PLAYABLE_STATE_NAMESPACE_ID), identity.playableStateNamespaceId()) + || !Objects.equals(row.get(INSTANCE_PLAYABLE_STATE_SCOPE), identity.playableStateScope()) + || !Objects.equals(row.get(INSTANCE_PUBLIC_PRODUCTION), identity.publicProduction()) + || row.get(INSTANCE_PLAYTEST_LIFECYCLE_ID) != null + || row.get(INSTANCE_PLAYTEST_STATE_GENERATION) != null + || !Objects.equals( + row.get(INSTANCE_LAUNCH_BINDING_OPERATION_ID), launchBindingOperationId)) { + throw new InvalidAssociationEvidenceException( + "World row has no matching insert-born canonical prepare identity; retained numeric rows cannot be associated"); + } + } + + private Record lockWorldInstance(long worldInstanceId) { + Record row = + dsl.selectFrom(WORLD_INSTANCE) + .where(INSTANCE_ID.eq(worldInstanceId)) + .forUpdate() + .fetchOne(); + if (row == null) { + throw new InvalidAssociationEvidenceException( + "Canonical instance association requires an already-created World instance row"); + } + return row; + } + + private Record readWorldInstance(long worldInstanceId) { + Record row = dsl.selectFrom(WORLD_INSTANCE).where(INSTANCE_ID.eq(worldInstanceId)).fetchOne(); + if (row == null) { + throw new InvalidAssociationEvidenceException( + "Canonical instance association lost its exact World instance row"); + } + return row; + } + + private WorldCanonicalInstanceAssociation.WorldPrepareFields toWorldPrepareFields(Record row) { + if (row == null) { + throw new InvalidAssociationEvidenceException("World instance row is missing"); + } + try { + return new WorldCanonicalInstanceAssociation.WorldPrepareFields( + required(row, INSTANCE_ID), + required(row, INSTANCE_TENANT_ID), + required(row, INSTANCE_GAME_INSTANCE_ID), + required(row, INSTANCE_GAME_TEMPLATE_ID), + required(row, INSTANCE_CONTROL_PLANE_REQUEST_ID), + required(row, INSTANCE_LAUNCH_DESCRIPTOR_ID), + required(row, INSTANCE_VERSION_ID), + row.get(INSTANCE_SCRIPT_PATCH_VERSION), + required(row, INSTANCE_RUNTIME_FLAGS_JSON), + required(row, INSTANCE_GENERATION_CONFIG_REVISION), + required(row, INSTANCE_RELEASE_BUNDLE_ID), + required(row, INSTANCE_PUBLISHED_RELEASE_BUNDLE_REF), + required(row, INSTANCE_VERSION_STATE_EPOCH), + row.get(INSTANCE_REMAP_SET_ID)); + } catch (RuntimeException exception) { + if (exception instanceof InvalidAssociationEvidenceException) { + throw exception; + } + throw new InvalidAssociationEvidenceException( + "World instance prepare fields are incomplete or invalid", exception); + } + } + + private Record findConflict(WorldCanonicalInstanceAssociation.Claim claim) { + Record row = findByCanonicalGameInstance(claim.canonicalGameInstanceId()); + if (row == null) { + row = + dsl.selectFrom(ASSOCIATION) + .where( + CANONICAL_TARGET_NAMESPACE + .eq(claim.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(claim.canonicalTenantId())) + .and(CONTROL_PLANE_REQUEST_ID.eq(claim.controlPlaneRequestId()))) + .fetchOne(); + } + if (row == null) { + row = + dsl.selectFrom(ASSOCIATION) + .where(WORLD_INSTANCE_ID.eq(claim.worldInstanceId())) + .fetchOne(); + } + if (row == null) { + row = + dsl.selectFrom(ASSOCIATION) + .where(LAUNCH_BINDING_OPERATION_ID.eq(claim.launchBindingOperationId())) + .fetchOne(); + } + return row; + } + + private Record findByCanonicalGameInstance(UUID canonicalGameInstanceId) { + return dsl.selectFrom(ASSOCIATION) + .where(CANONICAL_GAME_INSTANCE_ID.eq(canonicalGameInstanceId)) + .fetchOne(); + } + + private static String writeJson(Object value) { + try { + return CLOSED_JSON.writeValueAsString(value); + } catch (Exception exception) { + throw new InvalidAssociationEvidenceException( + "Immutable World owner evidence could not be encoded for exact comparison", exception); + } + } + + private static T required(Record row, Field field) { + return Objects.requireNonNull(row.get(field), "Persisted " + field.getName() + " is null"); + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } + + 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 canonical instance association requires an active World owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World canonical instance association requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation == null || declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World canonical instance association requires READ COMMITTED isolation"); + } + } + + 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"); + } + } + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidAssociationEvidenceException extends IllegalStateException { + public InvalidAssociationEvidenceException(String message) { + super(message); + } + + public InvalidAssociationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java new file mode 100644 index 0000000000..a5ceed873a --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java @@ -0,0 +1,135 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; + +/** + * Typed input and storage result for the owner-private canonical instance materialization cut. + * + *

The input preserves the caller's exact Game Session read tuple, World V26/V27 receipts, and + * the original immutable frozen topology source. It is component input only: construction does not + * authenticate a producer, authorize a release, prove publication delivery, or enable lifecycle + * activation or gameplay admission. + */ +public final class WorldCanonicalInstancePreparation { + private WorldCanonicalInstancePreparation() {} + + /** Complete immutable request to materialize one generation-free selected canonical graph. */ + public record Input( + WorldCanonicalInstanceAssociation.GameSessionReadRequest gameSessionReadRequest, + WorldCanonicalInstanceAssociation.GameSessionReadEvidence gameSessionReadEvidence, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldCanonicalInstanceTopologyPlan topologyPlan) { + public Input { + Objects.requireNonNull(gameSessionReadRequest, "gameSessionReadRequest"); + Objects.requireNonNull(gameSessionReadEvidence, "gameSessionReadEvidence"); + Objects.requireNonNull(completeLaunchBinding, "completeLaunchBinding"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + Objects.requireNonNull(topologyPlan, "topologyPlan"); + + // Claim performs the repository's full request-echo and exact V26/V27 source checks without + // allocating or writing anything. The placeholder row id is deliberately not retained. + new WorldCanonicalInstanceAssociation.Claim( + gameSessionReadRequest, + gameSessionReadEvidence, + 1L, + completeLaunchBinding, + versionIdentity); + + var owner = topologyPlan.sourceBinding().plan().ownerBinding(); + if (!topologyPlan.tenantId().equals(versionIdentity.canonicalTenantId()) + || !topologyPlan.versionId().equals(versionIdentity.canonicalVersionId()) + || !owner.targetNamespace().equals(versionIdentity.targetNamespace()) + || !owner.canonicalTenantId().equals(versionIdentity.canonicalTenantId()) + || !owner.canonicalVersionId().equals(versionIdentity.canonicalVersionId()) + || !owner.versionIdentityOperationId().equals(versionIdentity.operationId()) + || !topologyPlan + .sourceBinding() + .plan() + .binding() + .commitId() + .toString() + .equals(topologyPlan.sourceBinding().freeze().appliedCommitId())) { + throw new IllegalArgumentException( + "Canonical preparation topology differs from its exact V27 identity and frozen commit"); + } + requireGenerationFree(topologyPlan); + if (topologyPlan.regions().isEmpty()) { + throw new IllegalArgumentException("Canonical preparation requires at least one region"); + } + } + + public UUID canonicalGameInstanceId() { + return gameSessionReadEvidence.canonicalGameInstanceId(); + } + + public UUID captureId() { + return topologyPlan.captureId(); + } + } + + /** Durable result reconstructed only after the owner transaction has committed. */ + public record Result( + WorldCanonicalInstanceAssociation association, + UUID captureId, + String graphSha256, + String inputDigest, + int regionCount, + int zoneCount, + int roomCount, + int exitCount, + String storageStatus) { + public Result { + Objects.requireNonNull(association, "association"); + Objects.requireNonNull(captureId, "captureId"); + Objects.requireNonNull(graphSha256, "graphSha256"); + Objects.requireNonNull(inputDigest, "inputDigest"); + Objects.requireNonNull(storageStatus, "storageStatus"); + if (regionCount <= 0 || zoneCount < 0 || roomCount < 0 || exitCount < 0) { + throw new IllegalArgumentException("Canonical materialization counts are invalid"); + } + if (!"MATERIALIZED_UNVERIFIED".equals(storageStatus)) { + throw new IllegalArgumentException("Unsupported canonical preparation result status"); + } + } + } + + /** Required intent is rejected before an owner transaction or identifier allocation begins. */ + public static final class GenerationIntentNotSupportedException extends IllegalArgumentException { + public GenerationIntentNotSupportedException(String message) { + super(message); + } + } + + static void requireGenerationFree(WorldCanonicalInstanceTopologyPlan topologyPlan) { + Objects.requireNonNull(topologyPlan, "topologyPlan"); + if (!topologyPlan.generationRules().isEmpty() || !topologyPlan.spawnBindings().isEmpty()) { + throw new GenerationIntentNotSupportedException( + "Canonical preparation cannot allocate or materialize a graph with configured generation or spawn intent"); + } + } + + static int entryCount(Input input, EntryType family) { + Objects.requireNonNull(input, "input"); + Objects.requireNonNull(family, "family"); + return (int) + input.topologyPlan().entries().stream().filter(entry -> matches(entry, family)).count(); + } + + private static boolean matches(WorldCanonicalInstanceTopologyPlan.Entry entry, EntryType family) { + return switch (family) { + case REGION -> entry instanceof WorldCanonicalInstanceTopologyPlan.Region; + case ZONE -> entry instanceof WorldCanonicalInstanceTopologyPlan.Zone; + case ROOM -> entry instanceof WorldCanonicalInstanceTopologyPlan.Room; + case ROOM_EXIT -> entry instanceof WorldCanonicalInstanceTopologyPlan.RoomExit; + }; + } + + enum EntryType { + REGION, + ZONE, + ROOM, + ROOM_EXIT + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java new file mode 100644 index 0000000000..9d99a0ae57 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -0,0 +1,584 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Result; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.Entry; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * World-owned storage for generation-free canonical instance materialization. + * + *

This repository is deliberately not registered as a Spring component. The only write path is + * the exact V35 database function, followed in the same transaction by V34 association retention. + * It reads the immutable V31 capture independently before writing and reconstructs the exact result + * only after commit. + */ +public final class WorldCanonicalInstancePreparationRepository { + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final WorldCanonicalInstanceAssociationRepository associationRepository; + private final WorldCanonicalFrozenTopologyRepository frozenTopologyRepository; + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; + private final WorldCompleteLaunchBindingRepository launchBindingRepository; + private final WorldAuthoredVersionIdentityRepository versionIdentityRepository; + + public WorldCanonicalInstancePreparationRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceAssociationRepository associationRepository, + WorldCanonicalFrozenTopologyRepository frozenTopologyRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository"); + this.frozenTopologyRepository = + Objects.requireNonNull(frozenTopologyRepository, "frozenTopologyRepository"); + sourceIntakeRepository = new WorldAuthoredSourceIntakeRepository(dsl); + launchBindingRepository = new WorldCompleteLaunchBindingRepository(dsl); + versionIdentityRepository = new WorldAuthoredVersionIdentityRepository(dsl); + transaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Runs the one owner transaction, then independently reads its committed immutable result. The + * supplied continuously held authority handle remains valid through the transaction manager's + * commit path. + */ + public Result materialize( + Input input, WorldCanonicalInstancePreparationService.HeldCommitAuthority authority) { + Objects.requireNonNull(input, "input"); + Objects.requireNonNull(authority, "authority"); + requireNoActiveTransaction("Canonical World preparation"); + requireExactOriginalBindings(input); + requireExactFrozenSource(input); + String inputJson = inputJson(input); + String inputDigest = digest(inputJson.getBytes(StandardCharsets.UTF_8)); + + MaterializedInstance committed = + Objects.requireNonNull( + transaction.execute( + status -> { + requireWritableReadCommittedTransaction(); + authority.requireHeld(); + Record row = + Objects.requireNonNull( + fetchCanonicalPreparation(inputJson, inputDigest), + "V35 canonical preparation function returned no row"); + MaterializedInstance materialized = + new MaterializedInstance( + required(row, "world_instance_id", Long.class), + required(row, "private_game_instance_key", Long.class)); + WorldCanonicalInstanceAssociation.Claim claim = + new WorldCanonicalInstanceAssociation.Claim( + input.gameSessionReadRequest(), + input.gameSessionReadEvidence(), + materialized.worldInstanceId(), + input.completeLaunchBinding(), + input.versionIdentity()); + associationRepository.retainClaimInOwnerTransaction(claim); + authority.requireHeld(); + return materialized; + }), + "Canonical World preparation transaction did not commit"); + + // The authority handle is still open here: TransactionTemplate returned only after commit. + authority.requireHeld(); + Result result = + readOwnerPreparation(input) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Committed canonical World preparation has no independent result readback")); + if (result.association().worldInstanceId() != committed.worldInstanceId()) { + throw new InvalidPreparationEvidenceException( + "Canonical World preparation readback differs from its committed owner row"); + } + return result; + } + + /** + * Calls the V35 writer inside its owner transaction and translates only its explicit + * canonical-identity conflict signals. Throwing the domain exception here keeps the transaction + * rollback behavior while leaving unrelated database uniqueness failures visible as such. + */ + private Record fetchCanonicalPreparation(String inputJson, String inputDigest) { + try { + return dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?, ?)", inputJson, inputDigest); + } catch (DuplicateKeyException exception) { + throw translateCanonicalPreparationConflict(exception); + } + } + + static RuntimeException translateCanonicalPreparationConflict(DuplicateKeyException exception) { + for (Throwable cause = exception; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException + && "23505".equals(sqlException.getSQLState()) + && isCanonicalPreparationConflictMessage(sqlException.getMessage())) { + return new ConflictingPreparationException( + "Canonical gameInstanceId is already bound to a different preparation", exception); + } + } + return exception; + } + + private static boolean isCanonicalPreparationConflictMessage(String message) { + if (message == null) return false; + String ownerMessage = message.lines().findFirst().orElse(""); + if (ownerMessage.startsWith("ERROR: ")) ownerMessage = ownerMessage.substring(7); + return ownerMessage.equals( + "Canonical gameInstanceId is already bound to a different preparation") + || ownerMessage.equals("Canonical game instance or request identity is already reserved"); + } + + /** Independent exact read; lifecycle state is intentionally absent from the retained result. */ + public Optional readOwnerPreparation(Input input) { + Objects.requireNonNull(input, "input"); + requireNoActiveTransaction("Canonical World preparation readback"); + String inputJson = inputJson(input); + String inputDigest = digest(inputJson.getBytes(StandardCharsets.UTF_8)); + Record row = + dsl.fetchOne( + "SELECT canonical_game_instance_id, capture_id, graph_sha256, input_digest, input_json, " + + "graph_bytes, world_instance_id, private_game_instance_key, region_count, zone_count, " + + "room_count, exit_count, storage_status " + + "FROM world_canonical_instance_preparation WHERE canonical_game_instance_id = ?", + input.canonicalGameInstanceId()); + if (row == null) return Optional.empty(); + + if (!inputDigest.equals(required(row, "input_digest", String.class)) + || !inputJson.equals(required(row, "input_json", String.class)) + || !input.captureId().equals(required(row, "capture_id", java.util.UUID.class))) { + throw new ConflictingPreparationException( + "Canonical gameInstanceId is already bound to a different complete preparation input"); + } + byte[] graphBytes = required(row, "graph_bytes", byte[].class); + String graphSha256 = required(row, "graph_sha256", String.class); + if (!HexFormat.of().formatHex(sha256(graphBytes)).equals(graphSha256)) { + throw new InvalidPreparationEvidenceException( + "Retained canonical preparation graph bytes differ from their immutable digest"); + } + + WorldCanonicalInstanceAssociation association = + associationRepository + .readOwnerAssociation(input.canonicalGameInstanceId()) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Canonical World preparation result lost its exact V34 association")); + if (!association.identity().equals(input.gameSessionReadEvidence().canonicalIdentity()) + || !association.completeLaunchBinding().equals(input.completeLaunchBinding()) + || !association.versionIdentity().equals(input.versionIdentity()) + || association.worldInstanceId() != required(row, "world_instance_id", Long.class)) { + throw new InvalidPreparationEvidenceException( + "Canonical World preparation association differs from its complete immutable input"); + } + + int regions = required(row, "region_count", Integer.class); + int zones = required(row, "zone_count", Integer.class); + int rooms = required(row, "room_count", Integer.class); + int exits = required(row, "exit_count", Integer.class); + if (regions != input.topologyPlan().regions().size() + || zones != input.topologyPlan().zones().size() + || rooms != input.topologyPlan().rooms().size() + || exits != input.topologyPlan().roomExits().size()) { + throw new InvalidPreparationEvidenceException( + "Canonical World preparation readback omitted or added a selected topology family row"); + } + return Optional.of( + new Result( + association, + input.captureId(), + graphSha256, + inputDigest, + regions, + zones, + rooms, + exits, + required(row, "storage_status", String.class))); + } + + private void requireExactFrozenSource(Input input) { + WorldCanonicalFrozenTopology frozen = + frozenTopologyRepository + .readCommitted(input.topologyPlan().sourceBinding()) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Canonical preparation input has no exact committed frozen topology")); + WorldCanonicalInstanceTopologyPlan reconstructed = + WorldCanonicalInstanceTopologyPlan.create(frozen); + if (!frozen.captureId().equals(input.captureId()) + || !matchesCompleteFrozenSource(frozen.request(), input.topologyPlan().sourceBinding()) + || !reconstructed.entries().equals(input.topologyPlan().entries()) + || !reconstructed.regions().equals(input.topologyPlan().regions()) + || !reconstructed.zones().equals(input.topologyPlan().zones()) + || !reconstructed.rooms().equals(input.topologyPlan().rooms()) + || !reconstructed.roomExits().equals(input.topologyPlan().roomExits()) + || !reconstructed.generationRules().equals(input.topologyPlan().generationRules()) + || !reconstructed.spawnBindings().equals(input.topologyPlan().spawnBindings())) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation plan differs from the full immutable capture row/payload/revision/source vector"); + } + WorldCanonicalInstancePreparation.requireGenerationFree(reconstructed); + } + + /** + * Compares every immutable value in a frozen request without relying on the enclosing plan's + * object identity. The plan intentionally has no value equality of its own. + */ + static boolean matchesCompleteFrozenSource(Request retained, Request supplied) { + Objects.requireNonNull(retained, "retained"); + Objects.requireNonNull(supplied, "supplied"); + var retainedPlan = retained.plan(); + var suppliedPlan = supplied.plan(); + var retainedGraph = retainedPlan.graph(); + var suppliedGraph = suppliedPlan.graph(); + return retained.freeze().equals(supplied.freeze()) + && retainedPlan.binding().equals(suppliedPlan.binding()) + && retainedPlan.ownerBinding().equals(suppliedPlan.ownerBinding()) + && retainedGraph.tenantId().equals(suppliedGraph.tenantId()) + && retainedGraph.versionId().equals(suppliedGraph.versionId()) + && retainedGraph.nodes().equals(suppliedGraph.nodes()); + } + + /** Reloads original World-owned source, launch-pair, and Version rows before allocation. */ + private void requireExactOriginalBindings(Input input) { + var launch = input.completeLaunchBinding(); + var source = launch.sourceIntakeReceipt(); + var retainedSource = + sourceIntakeRepository + .read(source.targetNamespace(), source.intakeRequestId()) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Canonical preparation has no exact committed World source intake")); + if (!retainedSource.equals(source)) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation source differs from its complete original immutable intake row"); + } + + var retainedBinding = + launchBindingRepository + .read( + launch.targetNamespace(), + launch.canonicalTenantId(), + launch.controlPlaneRequestId()) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Canonical preparation has no exact committed V26 launch binding")); + if (!retainedBinding.operationId().equals(launch.operationId()) + || !retainedBinding.targetNamespace().equals(launch.targetNamespace()) + || !retainedBinding.canonicalTenantId().equals(launch.canonicalTenantId()) + || !retainedBinding.worldSlug().equals(launch.worldSlug()) + || !retainedBinding.controlPlaneRequestId().equals(launch.controlPlaneRequestId()) + || !retainedBinding.intakeOperationId().equals(source.operationId()) + || !retainedBinding.intakeRequestId().equals(source.intakeRequestId()) + || retainedBinding.localTenantKey() != source.localTenantKey() + || !retainedBinding.sourceOperationId().equals(source.sourceOperationId()) + || !retainedBinding.sourceEvidenceDigest().equals(source.sourceEvidenceDigest()) + || !retainedBinding.intakeReceiptDigest().equals(source.receiptDigest()) + || !retainedBinding.descriptorRequestDigest().equals(launch.descriptor().requestDigest()) + || !retainedBinding.descriptorResultDigest().equals(launch.descriptor().resultDigest()) + || !retainedBinding + .releaseAttestationDigest() + .equals(launch.evidence().releaseAttestation().evidenceDigest()) + || !retainedBinding.evidence().equals(launch.evidence())) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation V26 launch/source bytes differ from the original committed binding"); + } + + var version = input.versionIdentity(); + var retainedVersion = + versionIdentityRepository + .readByCanonicalVersion( + version.targetNamespace(), + version.canonicalTenantId(), + version.worldSlug(), + version.canonicalVersionId()) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Canonical preparation has no exact committed V27 Version identity")); + if (!retainedVersion.equals(version) || !retainedVersion.sourceIntakeReceipt().equals(source)) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation V27 Version/source evidence differs from its original immutable row"); + } + } + + private static String inputJson(Input input) { + var request = input.gameSessionReadRequest(); + var evidence = input.gameSessionReadEvidence(); + var launch = input.completeLaunchBinding(); + var source = launch.sourceIntakeReceipt(); + var version = input.versionIdentity(); + var versionState = version.versionStateEvidence(); + var topology = input.topologyPlan(); + var topologySource = topology.sourceBinding(); + var owner = topologySource.plan().ownerBinding(); + var freeze = topologySource.freeze(); + + Map root = + object( + "schemaVersion", 1, + "identity", + object( + "canonicalGameInstanceId", evidence.canonicalGameInstanceId().toString(), + "targetNamespace", evidence.targetNamespace(), + "canonicalTenantId", evidence.canonicalTenantId().toString(), + "worldSlug", evidence.worldSlug(), + "playableStateNamespaceId", evidence.playableStateNamespaceId().toString(), + "playableStateScope", evidence.playableStateScope(), + "publicProduction", evidence.publicProduction(), + "controlPlaneRequestId", evidence.controlPlaneRequestId()), + "gameSessionReadRequest", + object( + "targetNamespace", request.targetNamespace(), + "canonicalTenantId", request.canonicalTenantId().toString(), + "worldSlug", request.worldSlug(), + "canonicalGameInstanceId", request.canonicalGameInstanceId().toString(), + "controlPlaneRequestId", request.controlPlaneRequestId(), + "launchDescriptorId", request.launchDescriptorId(), + "expectedDescriptorRequestDigest", request.expectedDescriptorRequestDigest(), + "expectedDescriptorResultDigest", request.expectedDescriptorResultDigest(), + "expectedReleaseAttestationEvidenceDigest", + request.expectedReleaseAttestationEvidenceDigest()), + "gameSessionReadEvidence", + object( + "targetNamespace", evidence.targetNamespace(), + "canonicalTenantId", evidence.canonicalTenantId().toString(), + "worldSlug", evidence.worldSlug(), + "canonicalGameInstanceId", evidence.canonicalGameInstanceId().toString(), + "controlPlaneRequestId", evidence.controlPlaneRequestId(), + "launchDescriptorId", evidence.launchDescriptorId(), + "descriptorRequestDigest", evidence.descriptorRequestDigest(), + "descriptorResultDigest", evidence.descriptorResultDigest(), + "releaseAttestationEvidenceDigest", evidence.releaseAttestationEvidenceDigest(), + "playableStateNamespaceId", evidence.playableStateNamespaceId().toString(), + "playableStateScope", evidence.playableStateScope(), + "publicProduction", evidence.publicProduction(), + "descriptorJson", evidenceJson(evidence.descriptor()), + "releaseAttestationJson", evidenceJson(evidence.releaseAttestation())), + "launchBinding", + object( + "schemaVersion", launch.schemaVersion(), + "operationId", launch.operationId().toString(), + "targetNamespace", launch.targetNamespace(), + "canonicalTenantId", launch.canonicalTenantId().toString(), + "worldSlug", launch.worldSlug(), + "controlPlaneRequestId", launch.controlPlaneRequestId(), + "descriptorRequestDigest", launch.descriptor().requestDigest(), + "descriptorResultDigest", launch.descriptor().resultDigest(), + "releaseAttestationDigest", + launch.evidence().releaseAttestation().evidenceDigest(), + "canonicalVersionId", + launch.evidence().releaseAttestation().canonicalVersionId().toString(), + "localTenantKey", source.localTenantKey(), + "intakeOperationId", source.operationId().toString(), + "intakeRequestId", source.intakeRequestId().toString(), + "sourceOperationId", source.sourceOperationId().toString(), + "sourceEvidenceDigest", source.sourceEvidenceDigest(), + "intakeRequestDigest", source.requestDigest(), + "intakeReceiptDigest", source.receiptDigest()), + "versionIdentity", + object( + "schemaVersion", version.schemaVersion(), + "operationId", version.operationId().toString(), + "canonicalVersionId", version.canonicalVersionId().toString(), + "localVersionKey", version.localVersionKey(), + "gameDesignVersionId", version.gameDesignVersionId(), + "versionState", versionState.versionState().name(), + "versionStateEpoch", versionState.versionStateEpoch(), + "evidenceDigest", versionState.evidenceDigest()), + "sourceIntake", + object( + "schemaVersion", source.schemaVersion(), + "targetNamespace", source.targetNamespace(), + "intakeRequestId", source.intakeRequestId().toString(), + "operationId", source.operationId().toString(), + "canonicalTenantId", source.canonicalTenantId().toString(), + "worldSlug", source.worldSlug(), + "sourceOperationId", source.sourceOperationId().toString(), + "sourceEvidenceDigest", source.sourceEvidenceDigest(), + "requestDigest", source.requestDigest(), + "receiptDigest", source.receiptDigest(), + "localTenantKey", source.localTenantKey(), + "sourceEvidence", + object( + "schemaVersion", source.source().schemaVersion(), + "registrationRequestId", + source.source().registrationRequestId().toString(), + "sourceOperationId", source.source().operationId().toString(), + "requestDigest", source.source().requestDigest(), + "canonicalTenantId", source.source().canonicalTenantId().toString(), + "tenantSlug", source.source().tenantSlug(), + "worldSlug", source.source().worldSlug(), + "worldDisplayName", source.source().worldDisplayName(), + "sourceGameRowId", source.source().sourceGameRowId(), + "sourceGameTenantKey", source.source().sourceGameTenantKey(), + "provenanceKind", source.source().provenanceKind(), + "evidenceDigest", source.source().evidenceDigest())), + "topology", + object( + "captureId", topology.captureId().toString(), + "targetNamespace", owner.targetNamespace(), + "canonicalTenantId", owner.canonicalTenantId().toString(), + "canonicalVersionId", owner.canonicalVersionId().toString(), + "versionIdentityOperationId", owner.versionIdentityOperationId().toString(), + "requestId", topologySource.plan().binding().requestId().toString(), + "commitId", topologySource.plan().binding().commitId().toString(), + "freezeRequestId", freeze.publicationRequestId(), + "publicationFence", freeze.publicationFence().toString(), + "publicationRequestDigest", freeze.requestDigest(), + "appliedCommitId", freeze.appliedCommitId(), + "planDigest", planDigest(topology.entries()), + "regionCount", topology.regions().size(), + "zoneCount", topology.zones().size(), + "roomCount", topology.rooms().size(), + "exitCount", topology.roomExits().size(), + "generationRuleCount", topology.generationRules().size(), + "spawnBindingCount", topology.spawnBindings().size())); + try { + return JSON.writeValueAsString(root); + } catch (JacksonException exception) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation input cannot be serialized exactly", exception); + } + } + + private static String planDigest(List entries) { + List> rows = new ArrayList<>(entries.size()); + for (Entry entry : entries) { + rows.add( + object( + "family", entry.identity().family().name(), + "templateId", entry.identity().templateId().toString(), + "inputPayload", entry.source().inputPayload(), + "authoredRevisionBase64", + Base64.getEncoder() + .encodeToString(entry.source().authoredRevision().toByteArray()), + "effectiveContentBase64", + Base64.getEncoder().encodeToString(entry.source().content().toByteArray()))); + } + try { + return digest(JSON.writeValueAsBytes(rows)); + } catch (JacksonException exception) { + throw new InvalidPreparationEvidenceException( + "Canonical topology source rows cannot be serialized exactly", exception); + } + } + + private static Map object(Object... values) { + if (values.length % 2 != 0) throw new IllegalArgumentException("Map requires key/value pairs"); + Map result = new LinkedHashMap<>(); + for (int index = 0; index < values.length; index += 2) { + result.put((String) values[index], values[index + 1]); + } + return result; + } + + /** Full typed evidence serialization, matching the closed World V26 persistence codec. */ + private static String evidenceJson(Object evidence) { + try { + return JSON.writeValueAsString(Objects.requireNonNull(evidence, "evidence")); + } catch (JacksonException exception) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation launch evidence cannot be serialized exactly", exception); + } + } + + private static String digest(byte[] bytes) { + return "sha256:" + HexFormat.of().formatHex(sha256(bytes)); + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Canonical World preparation requires its owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "Canonical World preparation requires writable READ COMMITTED isolation"); + } + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " must not join an ambient transaction"); + } + } + + private static T required(Record row, String name, Class type) { + T value = row.get(name, type); + if (value == null) throw new InvalidPreparationEvidenceException("Missing " + name); + return value; + } + + private record MaterializedInstance(long worldInstanceId, long privateGameInstanceKey) {} + + public static class ConflictingPreparationException extends IllegalStateException { + public ConflictingPreparationException(String message) { + super(message); + } + + public ConflictingPreparationException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class InvalidPreparationEvidenceException extends IllegalStateException { + public InvalidPreparationEvidenceException(String message) { + super(message); + } + + public InvalidPreparationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java new file mode 100644 index 0000000000..a5a50bb112 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Result; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, default-denied owner operation for a canonical generation-free world instance. + * + *

No production verifier is supplied in this slice. A future authenticated integration must + * verify the same-namespace Game Session producer, current Game Design release and source, applied + * participant state, and Account commit authority before the World transaction begins. Its held + * authority must stay valid until the transaction manager has committed. This class is deliberately + * not a Spring component and adds no RPC or public activation path. + */ +public final class WorldCanonicalInstancePreparationService { + private final WorldCanonicalInstancePreparationRepository repository; + private final CommitAuthorityVerifier verifier; + + /** Constructs the production-safe default: all attempts fail closed. */ + public WorldCanonicalInstancePreparationService( + WorldCanonicalInstancePreparationRepository repository) { + this(repository, WorldCanonicalInstancePreparationService::denyByDefault); + } + + /** Constructor for an explicitly supplied owner verifier, including labeled synthetic tests. */ + public WorldCanonicalInstancePreparationService( + WorldCanonicalInstancePreparationRepository repository, CommitAuthorityVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + } + + /** + * Verifies before opening the owner transaction and returns only committed exact readback. + * Current lifecycle state is never rewritten by a historical preparation retry. + */ + public Result prepare(Input input) { + Objects.requireNonNull(input, "input"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical World preparation must verify outside an ambient transaction"); + } + WorldCanonicalInstancePreparation.requireGenerationFree(input.topologyPlan()); + + HeldCommitAuthority held = + Objects.requireNonNull( + verifier.verifyAndHold(input), + "Canonical preparation verifier returned no held commit authority"); + try (held) { + held.requireHeld(); + return repository.materialize(input, held); + } + } + + private static HeldCommitAuthority denyByDefault(Input input) { + throw new PreparationDeniedException( + "Canonical World preparation has no authenticated source/release and Account commit verifier"); + } + + /** Performs remote/current-state checks before returning a continuously held local fence. */ + @FunctionalInterface + public interface CommitAuthorityVerifier { + HeldCommitAuthority verifyAndHold(Input input); + } + + /** + * A verifier-owned, continuously held authority/fence handle. It stays open throughout the World + * transaction and its commit; implementations must fail closed from {@link #requireHeld()} if + * current authority has been lost or is no longer effective. Remote/current-state checks happen + * before the World transaction; {@code requireHeld()} is a local fence/effective-state assertion + * and must never perform RPC while World holds database locks. It is not a time lease and cannot + * extend authority beyond its effective period. + */ + public interface HeldCommitAuthority extends AutoCloseable { + void requireHeld(); + + @Override + void close(); + } + + public static final class PreparationDeniedException extends IllegalStateException { + public PreparationDeniedException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlan.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlan.java new file mode 100644 index 0000000000..27ce430442 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlan.java @@ -0,0 +1,575 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Row; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Template; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.EntityTemplateReference; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +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.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; + +/** + * Pure typed projection of a frozen World topology for a possible instance materialization. + * + *

The source remains {@link WorldCanonicalFrozenTopology#STATUS}; this plan is not release, + * Account authorization, execution, lifecycle, or admission proof. It allocates no runtime IDs, + * persists nothing, and preserves the complete source binding and authored payloads. + */ +public final class WorldCanonicalInstanceTopologyPlan { + /** One source-bound row with both exact input and the frozen storage projection. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record SourceRow( + Template identity, + WorldDesignMutationRevision authoredRevision, + WorldDesignMutationRevision content, + String inputPayload) { + public SourceRow { + Objects.requireNonNull(identity, "identity"); + Objects.requireNonNull(authoredRevision, "authoredRevision"); + Objects.requireNonNull(content, "content"); + Objects.requireNonNull(inputPayload, "inputPayload"); + } + + /** Exact UTF-8 encoding of the immutable input payload retained by the source binding. */ + public byte[] inputPayloadBytes() { + return inputPayload.getBytes(StandardCharsets.UTF_8); + } + } + + public sealed interface Entry + permits Region, Zone, Room, RoomExit, GenerationRuleIntent, SpawnBindingIntent { + SourceRow source(); + + default Template identity() { + return source().identity(); + } + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record Region(SourceRow source, RegionDesignMutation content) implements Entry { + public Region { + requireFamily(source, Family.REGION); + Objects.requireNonNull(content, "content"); + if (!source.content().hasRegion() || !source.content().getRegion().equals(content)) { + throw invalid("REGION content differs from its frozen source row"); + } + } + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record Zone(SourceRow source, Template region, ZoneDesignMutation content) + implements Entry { + public Zone { + requireFamily(source, Family.ZONE); + requireFamily(region, Family.REGION); + Objects.requireNonNull(content, "content"); + if (!source.content().hasZone() || !source.content().getZone().equals(content)) { + throw invalid("ZONE content differs from its frozen source row"); + } + } + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record Room(SourceRow source, Template zone, RoomDesignMutation content) implements Entry { + public Room { + requireFamily(source, Family.ROOM); + requireFamily(zone, Family.ZONE); + Objects.requireNonNull(content, "content"); + if (!source.content().hasRoom() || !source.content().getRoom().equals(content)) { + throw invalid("ROOM content differs from its frozen source row"); + } + } + } + + public record RoomExit( + SourceRow source, Template fromRoom, Template toRoom, RoomExitDesignMutation content) + implements Entry { + public RoomExit { + requireFamily(source, Family.ROOM_EXIT); + requireFamily(fromRoom, Family.ROOM); + requireFamily(toRoom, Family.ROOM); + Objects.requireNonNull(content, "content"); + if (!source.content().hasRoomExit() || !source.content().getRoomExit().equals(content)) { + throw invalid("ROOM_EXIT content differs from its frozen source row"); + } + } + } + + /** A configured rule is required intent; this entry carries no execution or skip outcome. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record GenerationRuleIntent( + SourceRow source, Template scope, GenerationRuleDesignMutation requiredIntent) + implements Entry { + public GenerationRuleIntent { + requireFamily(source, Family.GENERATION_RULE); + requireScopeFamily(scope); + Objects.requireNonNull(requiredIntent, "requiredIntent"); + if (!source.authoredRevision().hasGenerationRule() + || !source.authoredRevision().getGenerationRule().equals(requiredIntent)) { + throw invalid("GENERATION_RULE intent differs from its exact authored input"); + } + } + } + + /** A configured spawn is required intent and retains its canonical Entity UUID reference. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record SpawnBindingIntent( + SourceRow source, + Template room, + EntityTemplateReference entityReference, + WorldEntitySpawnBindingDesignMutation requiredIntent) + implements Entry { + public SpawnBindingIntent { + requireFamily(source, Family.WORLD_ENTITY_SPAWN_BINDING); + requireFamily(room, Family.ROOM); + Objects.requireNonNull(entityReference, "entityReference"); + Objects.requireNonNull(requiredIntent, "requiredIntent"); + if (!source.authoredRevision().hasWorldEntitySpawnBinding() + || !source.authoredRevision().getWorldEntitySpawnBinding().equals(requiredIntent)) { + throw invalid("Spawn-binding intent differs from its exact authored input"); + } + } + } + + private final WorldCanonicalFrozenTopology source; + private final List entries; + private final List regions; + private final List zones; + private final List rooms; + private final List roomExits; + private final List generationRules; + private final List spawnBindings; + + private WorldCanonicalInstanceTopologyPlan( + WorldCanonicalFrozenTopology source, + List entries, + List regions, + List zones, + List rooms, + List roomExits, + List generationRules, + List spawnBindings) { + this.source = source; + this.entries = List.copyOf(entries); + this.regions = List.copyOf(regions); + this.zones = List.copyOf(zones); + this.rooms = List.copyOf(rooms); + this.roomExits = List.copyOf(roomExits); + this.generationRules = List.copyOf(generationRules); + this.spawnBindings = List.copyOf(spawnBindings); + } + + /** + * Projects every row from the exact frozen graph, retaining its original binding and ordering. + * + *

Rows and parent references use family-qualified authored UUIDs. The source's private storage + * keys are not used to derive instance identities or Entity references. + */ + public static WorldCanonicalInstanceTopologyPlan create(WorldCanonicalFrozenTopology source) { + Objects.requireNonNull(source, "source"); + if (!WorldCanonicalFrozenTopology.STATUS.equals(source.status())) { + throw invalid("Source topology is not the unverified frozen component"); + } + var request = source.request(); + var plan = request.plan(); + var graph = source.graph(); + var input = plan.graph(); + if (!graph.tenantId().equals(input.tenantId()) + || !graph.versionId().equals(input.versionId()) + || !graph.tenantId().equals(plan.binding().target().canonicalTenantId()) + || !graph.versionId().equals(plan.binding().target().canonicalVersionId()) + || !graph.tenantId().equals(request.freeze().canonicalTenantId()) + || !graph.versionId().equals(request.freeze().canonicalVersionId())) { + throw invalid("Frozen graph differs from its complete canonical source binding"); + } + + Map expected = new HashMap<>(); + for (var node : input.nodes()) { + Template identity = + new Template(family(node.mutation().getAggregateType()), node.templateId()); + if (expected.putIfAbsent(identity, node) != null) { + throw invalid("Complete source repeats a family-qualified authored identity"); + } + } + if (expected.size() != graph.rows().size()) { + throw invalid("Frozen topology omits or adds a complete source row"); + } + + Map payloadByRevision = new HashMap<>(); + for (var revision : plan.binding().revisions()) { + if (revision.owner() == Owner.WORLD_MANAGEMENT + && payloadByRevision.putIfAbsent(revision.revisionId(), revision) != null) { + throw invalid("Complete source repeats a World revision identity"); + } + } + + List entries = new ArrayList<>(); + List regions = new ArrayList<>(); + List zones = new ArrayList<>(); + List rooms = new ArrayList<>(); + List exits = new ArrayList<>(); + List generationRules = new ArrayList<>(); + List spawnBindings = new ArrayList<>(); + Map byIdentity = new HashMap<>(); + + for (Row row : graph.rows()) { + var authored = row.authored(); + Template identity = + new Template(family(authored.mutation().getAggregateType()), row.template().templateId()); + if (!identity.equals(row.template())) { + throw invalid("Frozen row identity confuses authored family or template ID"); + } + var expectedNode = expected.remove(identity); + if (expectedNode == null || !expectedNode.equals(authored)) { + throw invalid("Frozen row is missing, duplicated, or differs from its exact input"); + } + validateContentEnvelope(authored, row.content()); + var inputPayload = payloadByRevision.get(authored.revisionId()); + if (inputPayload == null) { + throw invalid("Frozen row has no exact retained authored payload"); + } + SourceRow sourceRow = + new SourceRow(identity, authored.mutation(), row.content(), inputPayload.payload()); + Entry entry = + project(sourceRow, authored.entityReference(), graph.tenantId(), graph.versionId()); + if (byIdentity.putIfAbsent(identity, entry) != null) { + throw invalid("Frozen topology repeats a family-qualified row identity"); + } + entries.add(entry); + switch (entry) { + case Region region -> regions.add(region); + case Zone zone -> zones.add(zone); + case Room room -> rooms.add(room); + case RoomExit roomExit -> exits.add(roomExit); + case GenerationRuleIntent generationRule -> generationRules.add(generationRule); + case SpawnBindingIntent spawnBinding -> spawnBindings.add(spawnBinding); + } + } + if (!expected.isEmpty()) { + throw invalid("Frozen topology does not cover every typed source row"); + } + + validateClosure(entries, byIdentity); + return new WorldCanonicalInstanceTopologyPlan( + source, entries, regions, zones, rooms, exits, generationRules, spawnBindings); + } + + /** The exact source request, full Draft binding, and freeze evidence retained by the capture. */ + public WorldCanonicalFrozenTopology.Request sourceBinding() { + return source.request(); + } + + public UUID captureId() { + return source.captureId(); + } + + public UUID tenantId() { + return source.graph().tenantId(); + } + + public UUID versionId() { + return source.graph().versionId(); + } + + public List entries() { + return entries; + } + + public List regions() { + return regions; + } + + public List zones() { + return zones; + } + + public List rooms() { + return rooms; + } + + public List roomExits() { + return roomExits; + } + + public List generationRules() { + return generationRules; + } + + public List spawnBindings() { + return spawnBindings; + } + + private static Entry project( + SourceRow source, + EntityTemplateReference entityReference, + UUID canonicalTenantId, + UUID canonicalVersionId) { + var authored = source.authoredRevision(); + var content = source.content(); + return switch (source.identity().family()) { + case REGION -> new Region(source, content.getRegion()); + case ZONE -> + new Zone( + source, + new Template(Family.REGION, uuid(authored.getZone().getRegionId())), + content.getZone()); + case ROOM -> + new Room( + source, + new Template(Family.ZONE, uuid(authored.getRoom().getZoneId())), + content.getRoom()); + case ROOM_EXIT -> + new RoomExit( + source, + new Template(Family.ROOM, uuid(authored.getRoomExit().getFromRoomId())), + new Template(Family.ROOM, uuid(authored.getRoomExit().getToRoomId())), + content.getRoomExit()); + case GENERATION_RULE -> + new GenerationRuleIntent(source, declaredScope(authored), authored.getGenerationRule()); + case WORLD_ENTITY_SPAWN_BINDING -> { + var spawn = authored.getWorldEntitySpawnBinding(); + if (entityReference == null + || entityReference.kind() != spawn.getEntityTemplateType() + || !entityReference.tenantId().equals(canonicalTenantId) + || !entityReference.versionId().equals(canonicalVersionId) + || !entityReference.templateId().equals(uuid(spawn.getEntityTemplateId()))) { + throw invalid("Spawn intent differs from its exact typed canonical Entity reference"); + } + yield new SpawnBindingIntent( + source, new Template(Family.ROOM, uuid(spawn.getRoomId())), entityReference, spawn); + } + }; + } + + private static void validateClosure(List entries, Map byIdentity) { + Map regionsByZone = new HashMap<>(); + Map zonesByRoom = new HashMap<>(); + Set> exitIdentities = new HashSet<>(); + Set> generationRuleIdentities = new HashSet<>(); + Set> spawnBindingIdentities = new HashSet<>(); + for (Entry entry : entries) { + if (entry instanceof Zone zone) { + requireEntry(byIdentity, zone.region(), Region.class, "zone parent region"); + regionsByZone.put(zone.identity(), zone.region()); + } else if (entry instanceof Room room) { + requireEntry(byIdentity, room.zone(), Zone.class, "room parent zone"); + zonesByRoom.put(room.identity(), room.zone()); + } + } + + for (Entry entry : entries) { + Template scope = declaredScope(entry.source().authoredRevision()); + if (entry instanceof Region || entry instanceof Zone || entry instanceof Room) { + requireWithinScope(scope, entry.identity(), regionsByZone, zonesByRoom); + } + if (entry instanceof RoomExit roomExit) { + requireEntry(byIdentity, roomExit.fromRoom(), Room.class, "exit source room"); + requireEntry(byIdentity, roomExit.toRoom(), Room.class, "exit destination room"); + if (!exitIdentities.add( + List.of( + roomExit.fromRoom().templateId().toString(), roomExit.content().getDirection()))) { + throw invalid("Frozen topology repeats a room/direction exit"); + } + requireWithinScope(scope, roomExit.fromRoom(), regionsByZone, zonesByRoom); + requireWithinScope(scope, roomExit.toRoom(), regionsByZone, zonesByRoom); + } else if (entry instanceof GenerationRuleIntent rule) { + requireEntry( + byIdentity, + rule.scope(), + scope.family() == Family.REGION ? Region.class : Zone.class, + "generation-rule scope"); + if (!scope.equals(rule.scope())) { + throw invalid("Generation-rule scope differs from its authored scope"); + } + if (!generationRuleIdentities.add( + List.of( + rule.scope().family().name(), + rule.scope().templateId().toString(), + rule.requiredIntent().getName()))) { + throw invalid("Frozen topology repeats a scoped generation rule"); + } + } else if (entry instanceof SpawnBindingIntent spawn) { + requireEntry(byIdentity, spawn.room(), Room.class, "spawn-binding room"); + if (!spawnBindingIdentities.add( + List.of( + spawn.room().templateId().toString(), + spawn.entityReference().kind().name(), + spawn.entityReference().templateId().toString()))) { + throw invalid("Frozen topology repeats a typed room/entity spawn binding"); + } + requireWithinScope(scope, spawn.room(), regionsByZone, zonesByRoom); + } + } + } + + private static void requireWithinScope( + Template scope, + Template child, + Map regionsByZone, + Map zonesByRoom) { + boolean contained; + if (scope.family() == Family.REGION) { + Template region = regionFor(child, regionsByZone, zonesByRoom); + contained = scope.equals(region); + } else if (scope.family() == Family.ZONE) { + Template zone = zoneFor(child, zonesByRoom); + contained = scope.equals(zone); + } else { + throw invalid("World subtree scope must be a REGION or ZONE"); + } + if (!contained) { + throw invalid("Authored row or exit endpoint falls outside its declared subtree scope"); + } + } + + private static Template regionFor( + Template child, Map regionsByZone, Map zonesByRoom) { + if (child.family() == Family.REGION) { + return child; + } + Template zone = child.family() == Family.ZONE ? child : zonesByRoom.get(child); + Template region = zone == null ? null : regionsByZone.get(zone); + if (region == null) { + throw invalid("Authored parent chain is incomplete at its REGION"); + } + return region; + } + + private static Template zoneFor(Template child, Map zonesByRoom) { + if (child.family() == Family.ZONE) { + return child; + } + Template zone = zonesByRoom.get(child); + if (zone == null) { + throw invalid("Authored parent chain is incomplete at its ZONE"); + } + return zone; + } + + private static void requireEntry( + Map entries, + Template identity, + Class expectedType, + String relationship) { + Entry found = entries.get(identity); + if (found == null || !expectedType.isInstance(found)) { + throw invalid("Missing or type-confused " + relationship); + } + } + + private static void validateContentEnvelope( + WorldDraftTopologyInputGraph.Node authored, WorldDesignMutationRevision content) { + var mutation = authored.mutation(); + var expected = mutation.toBuilder(); + switch (mutation.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> { + if (mutation.getRegion().getSpacingMultiplier() == 0) { + expected.setRegion(mutation.getRegion().toBuilder().setSpacingMultiplier(1.0)); + } + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> { + if (mutation.getRoomExit().getCost() == 0) { + expected.setRoomExit(mutation.getRoomExit().toBuilder().setCost(1)); + } + } + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> { + if (mutation.getWorldEntitySpawnBinding().getSpawnCount() == 0) { + expected.setWorldEntitySpawnBinding( + mutation.getWorldEntitySpawnBinding().toBuilder().setSpawnCount(1)); + } + } + default -> {} + } + if (!content.equals(expected.build())) { + throw invalid("Frozen content differs from its exact authored/default projection"); + } + } + + private static Template declaredScope(WorldDesignMutationRevision revision) { + return switch (revision.getScopeType()) { + case WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE -> + new Template(Family.REGION, uuid(revision.getScopeId())); + case WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE -> + new Template(Family.ZONE, uuid(revision.getScopeId())); + default -> throw invalid("Unsupported World topology scope"); + }; + } + + private static Family family(WorldDesignAggregateType aggregate) { + return switch (aggregate) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> Family.REGION; + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> Family.ZONE; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> Family.ROOM; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> Family.ROOM_EXIT; + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> Family.GENERATION_RULE; + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> + Family.WORLD_ENTITY_SPAWN_BINDING; + default -> throw invalid("Unsupported topology family"); + }; + } + + private static UUID uuid(String value) { + try { + UUID id = UUID.fromString(value); + if (!id.toString().equals(value) || id.equals(new UUID(0, 0))) { + throw invalid("Canonical topology references require non-nil UUIDs"); + } + return id; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Canonical topology references require non-nil UUIDs", exception); + } + } + + private static void requireScopeFamily(Template scope) { + Objects.requireNonNull(scope, "scope"); + if (scope.family() != Family.REGION && scope.family() != Family.ZONE) { + throw invalid("World subtree scope must be a REGION or ZONE"); + } + } + + private static void requireFamily(SourceRow source, Family expected) { + Objects.requireNonNull(source, "source"); + requireFamily(source.identity(), expected); + } + + private static void requireFamily(Template identity, Family expected) { + Objects.requireNonNull(identity, "identity"); + if (identity.family() != expected) { + throw invalid("Expected " + expected + " family-qualified identity"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidence.java new file mode 100644 index 0000000000..1148443f7f --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidence.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; + +/** + * Immutable component storage evidence; never Account permission, APPLIED, or fence release proof. + */ +public final class WorldDraftTopologyCommitEvidence { + public static final String STATUS = "STORED_PERMISSION_UNVERIFIED"; + + private final DraftCommitBinding binding; + private final OwnerBinding ownerBinding; + private final byte[] graphBytes; + private final byte[] resultBytes; + + WorldDraftTopologyCommitEvidence( + DraftCommitBinding binding, + OwnerBinding ownerBinding, + byte[] graphBytes, + byte[] resultBytes) { + this.binding = Objects.requireNonNull(binding, "binding"); + this.ownerBinding = Objects.requireNonNull(ownerBinding, "ownerBinding"); + this.graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + this.resultBytes = Objects.requireNonNull(resultBytes, "resultBytes").clone(); + if (graphBytes.length == 0 || resultBytes.length == 0) { + throw new IllegalArgumentException("Complete graph and storage result bytes are required"); + } + } + + public DraftCommitBinding binding() { + return binding; + } + + public OwnerBinding ownerBinding() { + return ownerBinding; + } + + public byte[] graphBytes() { + return graphBytes.clone(); + } + + public byte[] resultBytes() { + return resultBytes.clone(); + } + + public String status() { + return STATUS; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java new file mode 100644 index 0000000000..f828dfa3ad --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java @@ -0,0 +1,362 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.EntityTemplateReference; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Pure UUID-qualified validation of complete fresh six-family World input: PURE_UNVERIFIED only. + * + *

This does not authenticate source or Entity evidence, authorize Account commits, allocate or + * read storage, report APPLIED, expose a public handler, capture released content, or establish + * lifecycle/runtime readiness. Existing numeric REGION plans and historical graph bytes are + * separate. Free-text and localized JSON fields are preserved, not semantically validated. Zero + * spacing, exit cost and spawn count preserve the existing owner-default input convention; a future + * writer must apply those defaults without changing the original binding. + */ +public final class WorldDraftTopologyCommitPlan { + private static final ObjectMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final String TYPE_PREFIX = "WORLD_DESIGN_AGGREGATE_TYPE_"; + private static final String SCOPE_PREFIX = "WORLD_DESIGN_SCOPE_TYPE_"; + + private record ObjectReference(WorldDesignAggregateType kind, UUID templateId) {} + + private final DraftCommitBinding binding; + private final OwnerBinding ownerBinding; + private final WorldDraftTopologyInputGraph graph; + + private WorldDraftTopologyCommitPlan( + DraftCommitBinding binding, OwnerBinding ownerBinding, WorldDraftTopologyInputGraph graph) { + this.binding = binding; + this.ownerBinding = ownerBinding; + this.graph = graph; + } + + /** + * Validates the exact supplied target and complete fresh input, without consulting any owner. All + * World references must close inside this graph; existing mappings are never guessed. + */ + public static WorldDraftTopologyCommitPlan create( + DraftCommitBinding binding, OwnerBinding ownerBinding) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(ownerBinding, "ownerBinding"); + var target = binding.target(); + if (!target.canonicalTenantId().equals(ownerBinding.canonicalTenantId()) + || !target.canonicalVersionId().equals(ownerBinding.canonicalVersionId()) + || target.gameDesignVersionRowId() != ownerBinding.gameDesignVersionId() + || !"NEW_GAME_ROW".equals(target.sourceProvenanceKind())) { + throw invalid("Fresh World input differs from its supplied canonical target/source kind"); + } + + Map nodes = new LinkedHashMap<>(); + Set revisionIds = new HashSet<>(); + List expected = new ArrayList<>(); + for (var revision : binding.revisions()) { + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + continue; + } + WorldDesignMutationRevision mutation = parse(revision.payload()); + if (!binding.commitId().toString().equals(mutation.getCommitId()) + || !revision.revisionId().toString().equals(mutation.getLogicalRevisionId()) + || !revisionIds.add(revision.revisionId())) { + throw invalid("World payload commit/revision identity differs from its complete input"); + } + validateShape(mutation); + UUID id = uuid(mutation.getAggregateId()); + UUID scope = uuid(mutation.getScopeId()); + EntityTemplateReference entity = null; + if (mutation.hasWorldEntitySpawnBinding()) { + var spawn = mutation.getWorldEntitySpawnBinding(); + entity = + new EntityTemplateReference( + spawn.getEntityTemplateType(), target.canonicalTenantId(), + target.canonicalVersionId(), uuid(spawn.getEntityTemplateId())); + } + Node node = + new Node(revision.revisionOrder(), revision.revisionId(), id, scope, mutation, entity); + if (nodes.putIfAbsent(new ObjectReference(mutation.getAggregateType(), id), node) != null) { + throw invalid("Fresh graph repeats an authored identity within the same World family"); + } + String type = mutation.getAggregateType().name().substring(TYPE_PREFIX.length()); + expected.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, type, id.toString(), "AGGREGATE", id.toString(), "0")); + expected.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + type, + id.toString(), + mutation.getScopeType().name().substring(SCOPE_PREFIX.length()), + scope.toString(), + "0")); + } + if (nodes.isEmpty()) { + throw invalid("Fresh graph requires World input; an empty binding is not topology"); + } + validateClosure(nodes); + List actual = binding.affectedUnits(Owner.WORLD_MANAGEMENT); + if (actual.size() != expected.size() + || !new HashSet<>(actual).equals(new HashSet<>(expected))) { + throw invalid("World affected units omit or change a derived aggregate/containing scope"); + } + return new WorldDraftTopologyCommitPlan( + binding, + ownerBinding, + new WorldDraftTopologyInputGraph( + target.canonicalTenantId(), + target.canonicalVersionId(), + new ArrayList<>(nodes.values()))); + } + + /** Exact immutable enclosing binding, including other owners and original payload bytes. */ + public DraftCommitBinding binding() { + return binding; + } + + /** Supplied source-qualified binding, retained unchanged and still unauthenticated. */ + public OwnerBinding ownerBinding() { + return ownerBinding; + } + + /** PURE_UNVERIFIED logical input only; no private row IDs or released snapshot. */ + public WorldDraftTopologyInputGraph graph() { + return graph; + } + + private static WorldDesignMutationRevision parse(String payload) { + try { + var parsed = STRICT_JSON.readTree(payload); + if (parsed == null || !parsed.isObject()) { + throw invalid("World typed payload must be an object"); + } + var builder = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(payload, builder); + return builder.build(); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalArgumentException("Unsupported World typed JSON", exception); + } catch (tools.jackson.core.JacksonException exception) { + throw new IllegalArgumentException( + "World typed JSON is not strict complete input", exception); + } + } + + private static void validateShape(WorldDesignMutationRevision m) { + if (m.getOperation() != WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT + || m.getScopeMutationPolicy() + != WorldDesignScopeMutationPolicy.WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED + || (m.getScopeType() != WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE + && m.getScopeType() != WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE) + || m.getExpectedDraftRevisionEpoch() != 0 + || m.getExpectedDraftScopeRevisionEpoch() != 0) { + throw invalid( + "Fresh input supports scoped UPSERT with zero epochs and no replacement policy"); + } + switch (m.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> { + require(m.hasRegion(), "REGION payload required"); + var p = m.getRegion(); + text(p.getName(), 100); + require( + p.getWeather().codePointCount(0, p.getWeather().length()) <= 50 + && p.getGeneratorType().codePointCount(0, p.getGeneratorType().length()) <= 50, + "Region weather/generator exceeds storage range"); + require( + p.getShardId() >= 0 + && Double.isFinite(p.getSpacingMultiplier()) + && p.getSpacingMultiplier() >= 0, + "Invalid region shard/spacing"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> { + require(m.hasZone(), "ZONE payload required"); + text(m.getZone().getName(), 100); + uuid(m.getZone().getRegionId()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> { + require(m.hasRoom(), "ROOM payload required"); + text(m.getRoom().getName(), 100); + uuid(m.getRoom().getZoneId()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> { + require(m.hasRoomExit(), "ROOM_EXIT payload required"); + var p = m.getRoomExit(); + uuid(p.getFromRoomId()); + uuid(p.getToRoomId()); + text(p.getDirection(), 32); + require(p.getCost() >= 0, "Exit cost must be nonnegative; zero retains the owner default"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> { + require(m.hasGenerationRule(), "GENERATION_RULE payload required"); + text(m.getGenerationRule().getName(), 100); + require( + m.getGenerationRule() + .getValue() + .codePointCount(0, m.getGenerationRule().getValue().length()) + <= 255, + "Rule value exceeds storage range"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> { + require(m.hasWorldEntitySpawnBinding(), "SPAWN payload required"); + var p = m.getWorldEntitySpawnBinding(); + uuid(p.getRoomId()); + uuid(p.getEntityTemplateId()); + require( + (p.getEntityTemplateType() + == EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM + || p.getEntityTemplateType() + == EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + && p.getSpawnCount() >= 0 + && p.getRespawnDelaySeconds() >= 0, + "Invalid spawn type/count/delay"); + } + default -> + throw invalid("Unsupported fresh World family; generated subtrees are not full input"); + } + } + + private static void validateClosure(Map nodes) { + Map zoneRegions = new HashMap<>(); + Map roomZones = new HashMap<>(); + for (Node node : nodes.values()) { + var m = node.mutation(); + if (m.hasZone()) { + UUID region = uuid(m.getZone().getRegionId()); + parent(nodes, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION); + zoneRegions.put(node.templateId(), region); + } else if (m.hasRoom()) { + UUID zone = uuid(m.getRoom().getZoneId()); + parent(nodes, zone, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE); + roomZones.put(node.templateId(), zone); + } + } + Set> rules = new HashSet<>(); + Set> spawns = new HashSet<>(); + Set> exits = new HashSet<>(); + for (Node node : nodes.values()) { + var m = node.mutation(); + boolean regionScope = + m.getScopeType() == WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE; + parent( + nodes, + node.scopeId(), + regionScope + ? WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + : WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE); + switch (m.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> + require( + regionScope && node.templateId().equals(node.scopeId()), + "Region scope must be itself"); + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> + require( + regionScope + ? node.scopeId().equals(zoneRegions.get(node.templateId())) + : node.scopeId().equals(node.templateId()), + "Zone is outside declared scope"); + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> + roomInScope(node.templateId(), node, roomZones, zoneRegions); + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> { + var p = m.getRoomExit(); + UUID from = uuid(p.getFromRoomId()); + UUID to = uuid(p.getToRoomId()); + roomInScope(from, node, roomZones, zoneRegions); + roomInScope(to, node, roomZones, zoneRegions); + require( + exits.add(List.of(from.toString(), p.getDirection())), + "Duplicate room/direction exit"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> + require( + rules.add( + List.of( + m.getScopeType().name(), + node.scopeId().toString(), + m.getGenerationRule().getName())), + "Duplicate scoped generation rule"); + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> { + var p = m.getWorldEntitySpawnBinding(); + roomInScope(uuid(p.getRoomId()), node, roomZones, zoneRegions); + require( + spawns.add( + List.of( + p.getRoomId(), p.getEntityTemplateType().name(), p.getEntityTemplateId())), + "Duplicate typed room/entity spawn binding"); + } + default -> throw invalid("Unsupported World family"); + } + } + } + + private static void roomInScope( + UUID room, Node node, Map rooms, Map zones) { + UUID zone = rooms.get(room); + require(zone != null, "Room reference is not in the complete fresh graph"); + UUID containing = + node.mutation().getScopeType() == WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE + ? zone + : zones.get(zone); + require(node.scopeId().equals(containing), "Room or exit endpoint is outside declared scope"); + } + + private static void parent( + Map nodes, UUID id, WorldDesignAggregateType type) { + Node node = nodes.get(new ObjectReference(type, id)); + require(node != null, "Missing or wrong-family reference in complete fresh graph"); + } + + private static UUID uuid(String value) { + try { + UUID id = UUID.fromString(value); + require( + id.toString().equals(value) && !id.equals(new UUID(0, 0)), + "World logical IDs require canonical non-nil UUIDs"); + return id; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "World logical IDs require canonical non-nil UUIDs", exception); + } + } + + private static void text(String value, int maximum) { + require( + !value.isBlank() && value.codePointCount(0, value.length()) <= maximum, + "Required World text is blank or exceeds storage range"); + } + + private static void require(boolean condition, String message) { + if (!condition) { + throw invalid(message); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java new file mode 100644 index 0000000000..3e1dbfb900 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java @@ -0,0 +1,589 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.OpenOwner; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Actual fresh six-family storage; explicitly unwired, with owner-internal private keys. */ +public class WorldDraftTopologyCommitRepository { + private final DSLContext dsl; + private final WorldDesignPublicationFenceRepository fence; + private final ObjectMapper mapper; + + @SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW", justification = "No resources or finalizer.") + public WorldDraftTopologyCommitRepository( + DSLContext dsl, WorldDesignPublicationFenceRepository fence, ObjectMapper mapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.fence = Objects.requireNonNull(fence, "fence"); + this.mapper = Objects.requireNonNull(mapper, "mapper"); + } + + /** Independent committed reconciliation: absence is UNKNOWN, never definitive abort. */ + public Optional readCommitted( + WorldDraftTopologyCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage readback requires no active caller transaction"); + } + return Optional.ofNullable(find(plan, mapper.writeValueAsString(plan.ownerBinding()))); + } + + /** Caller already holds the exact shared V25 FROZEN owner lock; no writer is entered. */ + WorldDraftTopologyCommitEvidence readUnderFrozenLock(WorldDraftTopologyCommitPlan plan) { + requireTransaction(); + WorldDraftTopologyCommitEvidence stored = + find(plan, mapper.writeValueAsString(plan.ownerBinding())); + if (stored == null) { + throw new ConflictException("World frozen capture has no committed complete topology result"); + } + return stored; + } + + /** Validates historical bytes without consulting current content, epochs or owner phase. */ + WorldCanonicalAuthoredGraph verifyImmutableBytes( + WorldDraftTopologyCommitPlan plan, byte[] graph, byte[] result) { + WorldCanonicalAuthoredGraph decoded = new WorldCanonicalAuthoredGraphReader().read(plan, graph); + if (!Arrays.equals(result, encodeResult(plan, graph))) { + throw new ConflictException("World historical topology result differs from original input"); + } + return decoded; + } + + WorldDraftTopologyCommitEvidence store(WorldDraftTopologyCommitPlan plan) { + requireTransaction(); + String ownerJson = mapper.writeValueAsString(plan.ownerBinding()); + WorldDraftTopologyCommitEvidence prior = find(plan, ownerJson); + if (prior != null) { + return prior; + } + OpenOwner owner = fence.lockOpenAndResolve(plan.ownerBinding()); + var source = owner.receipt().source(); + var target = plan.binding().target(); + if (target.sourceGameRowId() != source.sourceGameRowId() + || !target.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !target.sourceProvenanceKind().equals(source.provenanceKind())) { + throw new ConflictException("World topology differs from retained intake source provenance"); + } + // Reconcile again after the shared OPEN/freeze lock: an exact first claimant may have won. + prior = find(plan, ownerJson); + if (prior != null) { + return prior; + } + dsl.resultQuery( + "SELECT world_store_guarded_uuid_topology(?::jsonb, ?::jsonb, ?::jsonb)", + ownerJson, + plan.binding().canonicalJson(), + mapper.writeValueAsString(executionRevisions(plan))) + .fetch(); + byte[] graph = readAndVerifyGraph(plan, owner.localTenantKey(), owner.localVersionKey()); + byte[] result = encodeResult(plan, graph); + dsl.execute( + "INSERT INTO world_topology_draft_commit (request_id,commit_id,version_identity_operation_id," + + "target_namespace,canonical_tenant_id,canonical_version_id,local_tenant_key,local_version_key," + + "owner_binding_json,binding_json,binding_digest,graph_bytes,graph_sha256,result_bytes,storage_status) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + plan.binding().requestId(), + plan.binding().commitId(), + plan.ownerBinding().versionIdentityOperationId(), + plan.ownerBinding().targetNamespace(), + target.canonicalTenantId(), + target.canonicalVersionId(), + owner.localTenantKey(), + owner.localVersionKey(), + ownerJson, + plan.binding().canonicalJson(), + plan.binding().digest(), + graph, + sha256(graph), + result, + WorldDraftTopologyCommitEvidence.STATUS); + return new WorldDraftTopologyCommitEvidence(plan.binding(), plan.ownerBinding(), graph, result); + } + + /** + * Trusted local typed projection, like V29's typed component changes. The complete original + * binding remains unchanged. SQL checks revision identities/order/owner; before storing history, + * actual rows are independently checked against the original parsed plan, so altered projected + * semantics roll back the complete transaction. This is never an input from a public caller. + */ + List executionRevisions(WorldDraftTopologyCommitPlan plan) { + List revisions = new ArrayList<>(); + for (Node node : plan.graph().nodes()) { + try { + revisions.add( + new DraftCommitBinding.RevisionPayload( + node.revisionOrder(), + node.revisionId(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(node.mutation()))); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException( + "World typed execution projection could not be encoded", exception); + } + } + return List.copyOf(revisions); + } + + private WorldDraftTopologyCommitEvidence find( + WorldDraftTopologyCommitPlan plan, String ownerJson) { + List records = + dsl.resultQuery( + "SELECT c.*, to_jsonb(v)::text AS identity_json, " + + "to_jsonb(i)::text AS intake_json FROM world_topology_draft_commit c " + + "JOIN world_authored_version_identity v ON v.operation_id=c.version_identity_operation_id " + + "JOIN world_authored_source_intake i ON i.operation_id=v.intake_operation_id " + + "WHERE c.request_id=? OR c.commit_id=?", + plan.binding().requestId(), + plan.binding().commitId()) + .fetch(); + if (records.isEmpty()) { + return null; + } + if (records.size() != 1) { + throw new ConflictException("World complete request and commit select conflicting history"); + } + Record row = records.getFirst(); + DraftCommitBinding binding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("binding_digest", String.class)); + if (!binding.equals(plan.binding()) + || !ownerJson.equals(row.get("owner_binding_json", String.class))) { + throw new ConflictException( + "World complete request or commit was reused with changed full input or source"); + } + WorldAuthoredVersionIdentityReceipt original = + verifyOriginalSource( + plan, row.get("identity_json", String.class), row.get("intake_json", String.class)); + long tenant = original.sourceIntakeReceipt().localTenantKey(); + long version = original.localVersionKey(); + var o = plan.ownerBinding(); + if (tenant <= 0 + || version <= 0 + || !Objects.equals(row.get("request_id", UUID.class), binding.requestId()) + || !Objects.equals(row.get("commit_id", UUID.class), binding.commitId()) + || !Objects.equals(row.get("target_namespace", String.class), o.targetNamespace()) + || !Objects.equals(row.get("canonical_tenant_id", UUID.class), o.canonicalTenantId()) + || !Objects.equals(row.get("canonical_version_id", UUID.class), o.canonicalVersionId()) + || !Objects.equals(row.get("local_tenant_key", Long.class), tenant) + || !Objects.equals(row.get("local_version_key", Long.class), version) + || !WorldDraftTopologyCommitEvidence.STATUS.equals( + row.get("storage_status", String.class))) { + throw new ConflictException("World immutable topology identity provenance is inconsistent"); + } + byte[] graph = row.get("graph_bytes", byte[].class); + byte[] result = row.get("result_bytes", byte[].class); + if (!sha256(graph).equals(row.get("graph_sha256", String.class)) + || !Arrays.equals(graph, readAndVerifyGraph(plan, tenant, version)) + || !Arrays.equals(result, encodeResult(plan, graph))) { + throw new ConflictException("World immutable topology payload, graph or result differs"); + } + return new WorldDraftTopologyCommitEvidence(binding, o, graph, result); + } + + /** Reuses the original closed source and Version evidence validators for detached history. */ + WorldAuthoredVersionIdentityReceipt verifyOriginalSource( + WorldDraftTopologyCommitPlan plan, String identityJson, String intakeJson) { + DraftCommitBinding binding = plan.binding(); + JsonNode identity = mapper.readTree(identityJson); + JsonNode intake = mapper.readTree(intakeJson); + var o = plan.ownerBinding(); + requireField(identity, "operation_id", o.versionIdentityOperationId()); + requireField(identity, "target_namespace", o.targetNamespace()); + requireField(identity, "canonical_tenant_id", o.canonicalTenantId()); + requireField(identity, "canonical_version_id", o.canonicalVersionId()); + requireField(identity, "game_design_version_id", o.gameDesignVersionId()); + requireField(identity, "intake_operation_id", o.intakeOperationId()); + requireField(identity, "intake_request_id", o.intakeRequestId()); + requireField(identity, "intake_request_digest", o.intakeRequestDigest()); + requireField(identity, "source_operation_id", o.sourceOperationId()); + requireField(identity, "source_evidence_digest", o.sourceEvidenceDigest()); + requireField(identity, "intake_receipt_digest", o.intakeReceiptDigest()); + requireField(intake, "operation_id", o.intakeOperationId()); + requireField(intake, "intake_request_id", o.intakeRequestId()); + requireField(intake, "target_namespace", o.targetNamespace()); + requireField(intake, "canonical_tenant_id", o.canonicalTenantId()); + requireField(intake, "request_digest", o.intakeRequestDigest()); + requireField(intake, "source_operation_id", o.sourceOperationId()); + requireField(intake, "source_evidence_digest", o.sourceEvidenceDigest()); + requireField(intake, "receipt_digest", o.intakeReceiptDigest()); + requireField(intake, "source_game_row_id", binding.target().sourceGameRowId()); + requireField(intake, "source_game_tenant_key", binding.target().sourceGameTenantKey()); + requireField(intake, "source_provenance_kind", binding.target().sourceProvenanceKind()); + long tenant = identity.path("local_tenant_key").asLong(); + long version = identity.path("local_version_key").asLong(); + requireField(intake, "local_tenant_key", tenant); + // Reuse the existing closed source/receipt validators; these are original local evidence, + // not a current upstream Version or permission check. + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + intake.path("source_schema_version").asInt(), + o.targetNamespace(), + UUID.fromString(intake.path("source_registration_request_id").asText()), + o.sourceOperationId(), + intake.path("source_request_digest").asText(), + o.canonicalTenantId(), + intake.path("tenant_slug").asText(), + intake.path("world_slug").asText(), + intake.path("world_display_name").asText(), + binding.target().sourceGameRowId(), + binding.target().sourceGameTenantKey(), + binding.target().sourceProvenanceKind(), + o.sourceEvidenceDigest()); + WorldAuthoredSourceIntakeReceipt receipt = + new WorldAuthoredSourceIntakeReceipt( + intake.path("schema_version").asInt(), + o.targetNamespace(), + o.intakeRequestId(), + o.intakeOperationId(), + o.canonicalTenantId(), + source.worldSlug(), + o.sourceOperationId(), + o.sourceEvidenceDigest(), + o.intakeRequestDigest(), + o.intakeReceiptDigest(), + tenant, + source); + AuthoredWorldVersionStateEvidence state = + mapper.readValue( + identity.path("version_state_evidence_json").asText(), + AuthoredWorldVersionStateEvidence.class); + WorldAuthoredVersionIdentityReceipt retainedIdentity = + new WorldAuthoredVersionIdentityReceipt( + 1, o.versionIdentityOperationId(), version, receipt, state); + requireField(identity, "version_state_schema_version", state.request().schemaVersion()); + requireField(identity, "version_state_read_request_id", state.request().readRequestId()); + requireField(identity, "version_state_epoch", state.versionStateEpoch()); + requireField(identity, "version_state_evidence_digest", state.evidenceDigest()); + requireField( + identity, + "version_state_state", + state.versionState().name().replace("VERSION_LIFECYCLE_STATE_", "")); + requireField(identity, "world_slug", source.worldSlug()); + if (!retainedIdentity.canonicalVersionId().equals(o.canonicalVersionId()) + || retainedIdentity.gameDesignVersionId() != o.gameDesignVersionId()) { + throw new ConflictException( + "World topology differs from retained closed Version/source evidence"); + } + return retainedIdentity; + } + + private byte[] readAndVerifyGraph(WorldDraftTopologyCommitPlan plan, long tenant, long version) { + List mappings = + dsl.resultQuery( + "SELECT to_jsonb(m)::text AS mapping_json FROM " + + "world_authored_topology_identity m WHERE request_id=? ORDER BY revision_order::numeric", + plan.binding().requestId()) + .fetch(); + if (mappings.size() != plan.graph().nodes().size()) { + throw new ConflictException("World topology has missing or extra exact UUID mappings"); + } + for (var type : + List.of( + "REGION", + "ZONE", + "ROOM", + "ROOM_EXIT", + "GENERATION_RULE", + "WORLD_ENTITY_SPAWN_BINDING")) { + long expected = plan.graph().nodes().stream().filter(n -> family(n).equals(type)).count(); + Long actual = + dsl.resultQuery( + "SELECT count(*) FROM " + + type.toLowerCase(java.util.Locale.ROOT) + + " WHERE tenant_id=? AND version_id=?", + tenant, + version) + .fetchOne(0, Long.class); + if (!Objects.equals(actual, expected)) { + throw new ConflictException("World topology contains extra or missing actual family rows"); + } + } + Map keys = new HashMap<>(); + List identities = new ArrayList<>(); + for (int i = 0; i < mappings.size(); i++) { + Node node = plan.graph().nodes().get(i); + JsonNode m = mapper.readTree(mappings.get(i).get("mapping_json", String.class)); + String family = family(node); + requireField(m, "target_namespace", plan.ownerBinding().targetNamespace()); + requireField(m, "canonical_tenant_id", plan.graph().tenantId()); + requireField(m, "canonical_version_id", plan.graph().versionId()); + requireField(m, "family", family); + requireField(m, "template_id", node.templateId()); + requireField(m, "tenant_id", tenant); + requireField(m, "version_id", version); + requireField( + m, "version_identity_operation_id", plan.ownerBinding().versionIdentityOperationId()); + requireField(m, "request_id", plan.binding().requestId()); + requireField(m, "commit_id", plan.binding().commitId()); + requireField(m, "revision_id", node.revisionId()); + requireField(m, "revision_order", node.revisionOrder()); + long key = m.path("private_row_key").asLong(); + if (key <= 0 + || m.path("id").asLong() <= 0 + || keys.put(family + ":" + node.templateId(), key) != null) { + throw new ConflictException("World UUID mapping is not one-to-one"); + } + identities.add(m); + } + List> rows = new ArrayList<>(); + for (int i = 0; i < identities.size(); i++) { + Node node = plan.graph().nodes().get(i); + String family = family(node); + long key = keys.get(family + ":" + node.templateId()); + // The table name is selected only from the closed protobuf family enumeration. + Record row = + dsl.resultQuery( + "SELECT to_jsonb(t)::text AS content_json FROM " + + family.toLowerCase(java.util.Locale.ROOT) + + " t WHERE id=?", + key) + .fetchOne(); + if (row == null) { + throw new ConflictException("World UUID association has no actual allocated row"); + } + JsonNode actual = mapper.readTree(row.get("content_json", String.class)); + JsonNode expected = mapper.valueToTree(expectedContent(node, keys, tenant, version)); + if (!sameContent(actual, expected)) { + throw new ConflictException("World allocated row differs from every exact payload field"); + } + Map item = new LinkedHashMap<>(); + item.put("mapping", identities.get(i)); + item.put("content", actual); + rows.add(item); + } + for (Node node : plan.graph().nodes()) { + Long epoch = + dsl.resultQuery( + "SELECT draft_revision_epoch FROM world_design_aggregate_epoch " + + "WHERE tenant_id=? AND version_id=? AND aggregate_type=? AND aggregate_id=?", + tenant, + version, + family(node), + keys.get(family(node) + ":" + node.templateId())) + .fetchOne(0, Long.class); + if (!Objects.equals(epoch, 1L)) { + throw new ConflictException( + "World topology aggregate epoch differs from exact stored result"); + } + } + Long aggregateCount = + dsl.resultQuery( + "SELECT count(*) FROM world_design_aggregate_epoch " + + "WHERE tenant_id=? AND version_id=?", + tenant, + version) + .fetchOne(0, Long.class); + long scopeCountExpected = + plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .filter(u -> !u.scopeType().equals("AGGREGATE")) + .map(u -> u.scopeType() + ":" + u.scopeId()) + .distinct() + .count(); + Long scopeCount = + dsl.resultQuery( + "SELECT count(*) FROM world_design_scope_epoch " + + "WHERE tenant_id=? AND version_id=?", + tenant, + version) + .fetchOne(0, Long.class); + if (!Objects.equals(aggregateCount, (long) plan.graph().nodes().size()) + || !Objects.equals(scopeCount, scopeCountExpected)) { + throw new ConflictException("World topology has extra or missing exact epoch fences"); + } + for (var unit : plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT)) { + if (!unit.scopeType().equals("AGGREGATE")) { + Long epoch = + dsl.resultQuery( + "SELECT draft_scope_revision_epoch FROM world_design_scope_epoch " + + "WHERE tenant_id=? AND version_id=? AND scope_type=? AND scope_id=?", + tenant, + version, + unit.scopeType(), + unit.scopeId()) + .fetchOne(0, Long.class); + if (!Objects.equals(epoch, 1L)) { + throw new ConflictException( + "World topology scope epoch differs from exact stored result"); + } + } + } + Map graph = new LinkedHashMap<>(); + graph.put("schemaVersion", "2"); + graph.put("canonicalTenantId", plan.graph().tenantId().toString()); + graph.put("canonicalVersionId", plan.graph().versionId().toString()); + graph.put("rows", rows); + return mapper.writeValueAsBytes(graph); + } + + static Map expectedContent( + Node node, Map keys, long tenant, long version) { + Map row = new LinkedHashMap<>(); + var m = node.mutation(); + row.put("id", keys.get(family(node) + ":" + node.templateId())); + row.put("tenant_id", tenant); + row.put("version_id", version); + row.put("version", 0); + switch (m.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> { + var p = m.getRegion(); + row.put("name", p.getName()); + row.put("shard_id", p.getShardId()); + row.put("weather", p.getWeather()); + row.put("generation_seed", p.getGenerationSeed()); + row.put("generator_type", p.getGeneratorType()); + row.put("generator_params", p.getGeneratorParams()); + row.put( + "spacing_multiplier", p.getSpacingMultiplier() == 0 ? 1.0 : p.getSpacingMultiplier()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> { + row.put("name", m.getZone().getName()); + row.put("region_id", lookup(keys, "REGION", m.getZone().getRegionId())); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> { + var p = m.getRoom(); + row.put("name", p.getName()); + row.put("description", p.getDescription()); + row.put("zone_id", lookup(keys, "ZONE", p.getZoneId())); + row.put("name_localized_variants_json", p.getNameLocalizedVariantsJson()); + row.put("description_localized_variants_json", p.getDescriptionLocalizedVariantsJson()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> { + var p = m.getRoomExit(); + row.put("from_room_id", lookup(keys, "ROOM", p.getFromRoomId())); + row.put("to_room_id", lookup(keys, "ROOM", p.getToRoomId())); + row.put("direction", p.getDirection()); + row.put("cost", p.getCost() == 0 ? 1 : p.getCost()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> { + var p = m.getGenerationRule(); + row.put("name", p.getName()); + row.put("value", p.getValue()); + String scope = m.getScopeType().name().replace("WORLD_DESIGN_SCOPE_TYPE_", ""); + row.put("scope_type", scope); + row.put( + "scope_id", + lookup( + keys, + scope.equals("REGION_SUBTREE") ? "REGION" : "ZONE", + node.scopeId().toString()) + .toString()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> { + var p = m.getWorldEntitySpawnBinding(); + var e = node.entityReference(); + row.put("room_id", lookup(keys, "ROOM", p.getRoomId())); + row.put( + "entity_template_type", e.kind().name().replace("ENTITY_TEMPLATE_REFERENCE_TYPE_", "")); + row.put("entity_template_id", null); + row.put("entity_canonical_tenant_id", e.tenantId().toString()); + row.put("entity_canonical_version_id", e.versionId().toString()); + row.put("entity_canonical_template_id", e.templateId().toString()); + row.put("spawn_count", p.getSpawnCount() == 0 ? 1 : p.getSpawnCount()); + row.put("respawn_delay_seconds", p.getRespawnDelaySeconds()); + } + default -> throw new ConflictException("Unsupported exact World family"); + } + return row; + } + + private static Long lookup(Map keys, String family, String id) { + return Objects.requireNonNull( + keys.get(family + ":" + UUID.fromString(id)), "typed parent mapping"); + } + + static String family(Node node) { + return node.mutation().getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + } + + private void requireField(JsonNode node, String name, Object expected) { + if (!node.hasNonNull(name) || !node.path(name).asText().equals(expected.toString())) { + throw new ConflictException("World immutable topology provenance differs at " + name); + } + } + + static boolean sameContent(JsonNode actual, JsonNode expected) { + if (actual.size() != expected.size()) { + return false; + } + for (var entry : expected.properties()) { + JsonNode value = actual.get(entry.getKey()); + JsonNode required = entry.getValue(); + if (value == null + || (value.isNumber() && required.isNumber() + ? value.decimalValue().compareTo(required.decimalValue()) != 0 + : !value.equals(required))) { + return false; + } + } + return true; + } + + private byte[] encodeResult(WorldDraftTopologyCommitPlan plan, byte[] graph) { + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", "2"); + result.put("status", WorldDraftTopologyCommitEvidence.STATUS); + result.put("requestId", plan.binding().requestId().toString()); + result.put("commitId", plan.binding().commitId().toString()); + result.put("bindingDigest", plan.binding().digest()); + result.put("ownerBinding", plan.ownerBinding()); + result.put("graphSha256", sha256(graph)); + result.put( + "affectedEpochsAfter", + plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> { + Map after = new LinkedHashMap<>(); + after.put("aggregateType", u.aggregateType()); + after.put("aggregateId", u.aggregateId()); + after.put("scopeType", u.scopeType()); + after.put("scopeId", u.scopeId()); + after.put("epoch", "1"); + return after; + }) + .toList()); + return mapper.writeValueAsBytes(result); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Objects.equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(), + java.sql.Connection.TRANSACTION_READ_COMMITTED)) { + throw new ConflictException( + "World complete storage requires writable READ COMMITTED transaction"); + } + } + + private String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitService.java new file mode 100644 index 0000000000..81ea939468 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitService.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired complete owner-local storage component, with a fail-closed permission seam. + */ +public final class WorldDraftTopologyCommitService { + /** + * Must fail unless the exact complete operation has durable Account ordering that remains held + * continuously through its terminal reconciliation. A preflight permission check is not reusable + * authorization for a later commit. No authenticated implementation is supplied in this slice; + * fixture implementations establish component storage prerequisites only. + */ + @FunctionalInterface + public interface PermissionVerifier { + void verify(WorldDraftTopologyCommitPlan plan); + } + + private final WorldDraftTopologyCommitRepository repository; + private final PermissionVerifier verifier; + private final TransactionTemplate transaction; + + /** Builds an unwired, denied component by default. */ + public WorldDraftTopologyCommitService( + WorldDraftTopologyCommitRepository repository, PlatformTransactionManager manager) { + this( + repository, + manager, + plan -> { + throw new ConflictException( + "Authenticated Account Draft commit permission is unavailable"); + }); + } + + public WorldDraftTopologyCommitService( + WorldDraftTopologyCommitRepository repository, + PlatformTransactionManager manager, + PermissionVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + transaction = new TransactionTemplate(Objects.requireNonNull(manager, "manager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + /** Verifies before opening the dedicated transaction; no external call runs while it is open. */ + public WorldDraftTopologyCommitEvidence store(WorldDraftTopologyCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage cannot start inside an existing transaction"); + } + verifier.verify(plan); + return Objects.requireNonNull(transaction.execute(status -> repository.store(plan))); + } + + /** + * Reads original committed storage evidence without invoking permission verification or a writer + * transaction. The result remains permission-unverified; absence is unknown rather than an abort + * or definitive no-commit outcome. + */ + public Optional readCommitted( + WorldDraftTopologyCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage readback requires no active caller transaction"); + } + return repository.readCommitted(plan); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java new file mode 100644 index 0000000000..e22f69c59d --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; + +/** + * Immutable PURE_UNVERIFIED logical input, never a stored or released World graph. + * + *

No numeric allocation, source authentication, Account authorization, APPLIED result, + * synchronized visibility, public handler, lifecycle or runtime readiness follows from this value. + * Its protobuf values preserve every supplied payload field without normalizing defaults. + * Preserving free-text and localized JSON fields does not validate their semantics. + */ +public final class WorldDraftTopologyInputGraph { + public static final String STATUS = "PURE_UNVERIFIED"; + + /** A typed canonical Entity reference; existence and owner authority remain unverified. */ + public record EntityTemplateReference( + EntityTemplateReferenceType kind, UUID tenantId, UUID versionId, UUID templateId) { + public EntityTemplateReference { + Objects.requireNonNull(kind, "kind"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(versionId, "versionId"); + Objects.requireNonNull(templateId, "templateId"); + } + } + + /** One complete immutable logical mutation in its original enclosing revision position. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable value messages.") + public record Node( + String revisionOrder, + UUID revisionId, + UUID templateId, + UUID scopeId, + WorldDesignMutationRevision mutation, + EntityTemplateReference entityReference) { + public Node { + Objects.requireNonNull(revisionOrder, "revisionOrder"); + Objects.requireNonNull(revisionId, "revisionId"); + Objects.requireNonNull(templateId, "templateId"); + Objects.requireNonNull(scopeId, "scopeId"); + Objects.requireNonNull(mutation, "mutation"); + } + } + + private final UUID tenantId; + private final UUID versionId; + private final List nodes; + + WorldDraftTopologyInputGraph(UUID tenantId, UUID versionId, List nodes) { + this.tenantId = Objects.requireNonNull(tenantId, "tenantId"); + this.versionId = Objects.requireNonNull(versionId, "versionId"); + this.nodes = List.copyOf(nodes); + } + + public UUID tenantId() { + return tenantId; + } + + public UUID versionId() { + return versionId; + } + + /** All six families in original canonical revision order, including interleaved families. */ + public List nodes() { + return nodes; + } + + /** An immutable family view retaining original order; an empty family is not readiness proof. */ + public List family(WorldDesignAggregateType kind) { + Objects.requireNonNull(kind, "kind"); + return nodes.stream().filter(node -> node.mutation().getAggregateType() == kind).toList(); + } +} diff --git a/services/world-management-service/src/main/resources/application.yml b/services/world-management-service/src/main/resources/application.yml index db840be505..0fdc199c5d 100644 --- a/services/world-management-service/src/main/resources/application.yml +++ b/services/world-management-service/src/main/resources/application.yml @@ -87,6 +87,9 @@ firemud: grpc: public-methods: - world_management.v1.WorldManagementService/Ping + # This bypasses bearer JWT only; the digest handler still requires the exact + # Game Design mTLS peer. + - world_management.v1.WorldManagementService/GetDraftDesignDigest 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/world-management-service/src/main/resources/db/migration/V30__world_guarded_uuid_topology_commits.sql b/services/world-management-service/src/main/resources/db/migration/V30__world_guarded_uuid_topology_commits.sql new file mode 100644 index 0000000000..361bee13d2 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V30__world_guarded_uuid_topology_commits.sql @@ -0,0 +1,490 @@ +-- Fresh authored UUID topology is component storage, never permission/release evidence. +-- Retained numeric rows stay unmapped; no canonical identity is inferred from a private key. +ALTER TABLE world_entity_spawn_binding ALTER COLUMN entity_template_id DROP NOT NULL; +ALTER TABLE world_entity_spawn_binding + ADD COLUMN entity_canonical_tenant_id UUID, + ADD COLUMN entity_canonical_version_id UUID, + ADD COLUMN entity_canonical_template_id UUID, + ADD CONSTRAINT ck_world_spawn_reference_representation CHECK ( + (entity_template_id IS NOT NULL AND entity_canonical_tenant_id IS NULL + AND entity_canonical_version_id IS NULL AND entity_canonical_template_id IS NULL) + OR (entity_template_id IS NULL AND entity_canonical_tenant_id IS NOT NULL + AND entity_canonical_version_id IS NOT NULL AND entity_canonical_template_id IS NOT NULL + AND entity_canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND entity_canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND entity_canonical_template_id <> '00000000-0000-0000-0000-000000000000'::UUID) + ); +CREATE UNIQUE INDEX uq_world_spawn_canonical_reference ON world_entity_spawn_binding + (tenant_id, version_id, room_id, entity_template_type, + entity_canonical_tenant_id, entity_canonical_version_id, entity_canonical_template_id) + WHERE entity_template_id IS NULL; + +CREATE TABLE world_topology_draft_commit ( + request_id UUID PRIMARY KEY, + commit_id UUID NOT NULL UNIQUE, + version_identity_operation_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL CHECK (local_tenant_key > 0), + local_version_key BIGINT NOT NULL CHECK (local_version_key > 0), + owner_binding_json TEXT NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + graph_bytes BYTEA NOT NULL CHECK (octet_length(graph_bytes) > 0), + graph_sha256 VARCHAR(64) NOT NULL CHECK (graph_sha256 ~ '^[0-9a-f]{64}$'), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + storage_status VARCHAR(32) NOT NULL CHECK (storage_status = 'STORED_PERMISSION_UNVERIFIED'), + stored_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (request_id, commit_id, version_identity_operation_id, + target_namespace, canonical_tenant_id, canonical_version_id, local_tenant_key, local_version_key), + FOREIGN KEY (version_identity_operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, local_version_key) + REFERENCES world_authored_version_identity(operation_id, target_namespace, + canonical_tenant_id, canonical_version_id, local_version_key) +); +CREATE TABLE world_authored_topology_identity ( + id BIGSERIAL PRIMARY KEY, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + family VARCHAR(50) NOT NULL CHECK (family IN ( + 'REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING')), + template_id UUID NOT NULL CHECK (template_id <> '00000000-0000-0000-0000-000000000000'::UUID), + private_row_key BIGINT NOT NULL CHECK (private_row_key > 0), + tenant_id BIGINT NOT NULL, + version_id BIGINT NOT NULL, + version_identity_operation_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + revision_id UUID NOT NULL, + revision_order TEXT NOT NULL, + UNIQUE (target_namespace, canonical_tenant_id, canonical_version_id, family, template_id), + UNIQUE (family, private_row_key), + FOREIGN KEY (request_id, commit_id, version_identity_operation_id, + target_namespace, canonical_tenant_id, canonical_version_id, tenant_id, version_id) + REFERENCES world_topology_draft_commit(request_id, commit_id, version_identity_operation_id, + target_namespace, canonical_tenant_id, canonical_version_id, local_tenant_key, local_version_key) + DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (version_identity_operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, version_id) + REFERENCES world_authored_version_identity(operation_id, target_namespace, + canonical_tenant_id, canonical_version_id, local_version_key) +); + +-- [jooq ignore start] +-- Reuse V29's exact OLD/NEW, source-qualified, transaction-local, consumed manifest. +ALTER TABLE world_region_draft_execution_manifest + DROP CONSTRAINT world_region_draft_execution_manifest_table_name_check, + DROP CONSTRAINT world_region_draft_execution_manifest_check; +ALTER TABLE world_region_draft_execution_manifest + ADD CONSTRAINT ck_world_execution_table CHECK (table_name IN ( + 'region','zone','room','room_exit','generation_rule','world_entity_spawn_binding', + 'world_authored_topology_identity','world_design_aggregate_epoch','world_design_scope_epoch')), + ADD CONSTRAINT ck_world_execution_transition CHECK ( + (row_operation = 'INSERT' AND expected_old IS NULL) + OR (row_operation = 'UPDATE' AND expected_old IS NOT NULL + AND table_name IN ('region','world_design_aggregate_epoch','world_design_scope_epoch'))); + +CREATE TRIGGER trg_world_topology_history_immutable BEFORE UPDATE OR DELETE + ON world_topology_draft_commit FOR EACH ROW + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_topology_history_no_truncate BEFORE TRUNCATE + ON world_topology_draft_commit FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_protect_topology_identity() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF TG_OP = 'INSERT' AND "${serviceSchema}".world_consume_region_execution_manifest( + TG_TABLE_NAME, TG_OP, NULL, to_jsonb(NEW)) THEN RETURN NEW; END IF; + RAISE EXCEPTION 'World UUID mapping requires an exact fresh execution manifest and is immutable' + USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER trg_world_topology_identity_guard BEFORE INSERT OR UPDATE OR DELETE + ON world_authored_topology_identity FOR EACH ROW EXECUTE FUNCTION world_protect_topology_identity(); +CREATE TRIGGER trg_world_topology_identity_no_truncate BEFORE TRUNCATE + ON world_authored_topology_identity FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_protect_mapped_topology_row() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity + WHERE family = CASE TG_TABLE_NAME WHEN 'world_entity_spawn_binding' + THEN 'WORLD_ENTITY_SPAWN_BINDING' ELSE upper(TG_TABLE_NAME) END + AND private_row_key = OLD.id) THEN + RAISE EXCEPTION 'Mapped UUID World content cannot be changed by numeric writers' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_region_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON region + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_zone_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON zone + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_room_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON room + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_room_exit_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON room_exit + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_generation_rule_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON generation_rule + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_world_entity_spawn_binding_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON world_entity_spawn_binding + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +-- The trusted local parsed projection uses canonical protobuf JSON for execution only. +-- Exact original full binding/payload bytes remain the manifest/history authority. As in V29, +-- this typed component seam is not a public caller field or permission evidence; the repository +-- verifies every actual stored payload against the original parsed plan before recording history. +CREATE FUNCTION world_store_guarded_uuid_topology( + p_owner JSONB, p_binding JSONB, p_execution_revisions JSONB +) +RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + mapping "${serviceSchema}".world_authored_topology_identity%ROWTYPE; + revision JSONB; + mutation JSONB; + payload JSONB; + family TEXT; + table_name TEXT; + content JSONB; + complete_row JSONB; + scope_key BIGINT; + parent_key BIGINT; + other_key BIGINT; + scope_type TEXT; + scope_uuid UUID; + expected_units JSONB := '[]'::JSONB; + supplied_units JSONB; + expected_sorted JSONB; + epoch_row JSONB; + nodes JSONB; + original_revision_identities JSONB; + execution_revision_identities JSONB; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'World topology requires writable READ COMMITTED' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT identity_row FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id = (p_owner->>'versionIdentityOperationId')::UUID FOR SHARE; + SELECT * INTO STRICT intake_row FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id = identity_row.intake_operation_id; + IF p_owner IS DISTINCT FROM jsonb_build_object( + 'targetNamespace', identity_row.target_namespace, + 'canonicalTenantId', identity_row.canonical_tenant_id, + 'canonicalVersionId', identity_row.canonical_version_id, + 'versionIdentityOperationId', identity_row.operation_id, + 'gameDesignVersionId', identity_row.game_design_version_id, + 'intakeRequestId', identity_row.intake_request_id, + 'intakeOperationId', identity_row.intake_operation_id, + 'intakeRequestDigest', identity_row.intake_request_digest, + 'sourceOperationId', identity_row.source_operation_id, + 'sourceEvidenceDigest', identity_row.source_evidence_digest, + 'intakeReceiptDigest', identity_row.intake_receipt_digest) + OR p_binding->>'canonicalTenantId' IS DISTINCT FROM identity_row.canonical_tenant_id::TEXT + OR p_binding->>'canonicalVersionId' IS DISTINCT FROM identity_row.canonical_version_id::TEXT + OR p_binding->'target' IS DISTINCT FROM jsonb_build_object( + 'gameDesignVersionRowId', identity_row.game_design_version_id::TEXT, + 'gameDesignVersionTenantKey', intake_row.source_game_tenant_key, + 'sourceGameRowId', intake_row.source_game_row_id::TEXT, + 'sourceGameTenantKey', intake_row.source_game_tenant_key, + 'sourceProvenanceKind', intake_row.source_provenance_kind) + THEN + RAISE EXCEPTION 'Complete World region source binding differs from retained intake/V27' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = identity_row.target_namespace + AND canonical_tenant_id = identity_row.canonical_tenant_id + AND local_tenant_key = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key FOR UPDATE; + IF owner_row.owner_freeze_phase <> 'OPEN' OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'World topology storage requires the shared OPEN owner row' + USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest + WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'World complete region storage already has an execution manifest' + USING ERRCODE = '23514'; + END IF; + + IF jsonb_typeof(p_execution_revisions) IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'World typed execution projection must be an array' USING ERRCODE = '23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('revisionOrder',value->>'revisionOrder', + 'revisionId',value->>'revisionId','owner',value->>'owner') + ORDER BY ordinal) INTO original_revision_identities + FROM jsonb_array_elements(p_binding->'revisions') WITH ORDINALITY AS original(value,ordinal) + WHERE value->>'owner' = 'WORLD_MANAGEMENT'; + SELECT jsonb_agg(jsonb_build_object('revisionOrder',value->>'revisionOrder', + 'revisionId',value->>'revisionId','owner',value->>'owner') + ORDER BY ordinal) INTO execution_revision_identities + FROM jsonb_array_elements(p_execution_revisions) WITH ORDINALITY AS execution(value,ordinal); + IF original_revision_identities IS NULL + OR execution_revision_identities IS DISTINCT FROM original_revision_identities THEN + RAISE EXCEPTION 'World typed execution projection differs from exact original revision identities/order/owner' + USING ERRCODE = '23514'; + END IF; + SELECT jsonb_agg(value ORDER BY (value->>'revisionOrder')::NUMERIC) INTO nodes + FROM jsonb_array_elements(p_execution_revisions); + IF nodes IS NULL OR intake_row.source_provenance_kind <> 'NEW_GAME_ROW' THEN + RAISE EXCEPTION 'Fresh topology requires World input and exact fresh source' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_commit + WHERE request_id = (p_binding->>'requestId')::UUID OR commit_id = (p_binding->>'commitId')::UUID) THEN + RAISE EXCEPTION 'World request/commit already has retained numeric history' USING ERRCODE = '23514'; + END IF; + -- Require a wholly fresh local Version. Retained content is never relabelled or overwritten. + IF EXISTS (SELECT 1 FROM "${serviceSchema}".region + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained region' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".zone + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained zone' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".room + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained room' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".room_exit + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained room_exit' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".generation_rule + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained generation_rule' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_entity_spawn_binding + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained world_entity_spawn_binding' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained world_design_aggregate_epoch' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained world_design_scope_epoch' USING ERRCODE = '23514'; + END IF; + + FOR revision IN SELECT value FROM jsonb_array_elements(nodes) LOOP + mutation := (revision->>'payload')::JSONB; + family := replace(mutation->>'aggregateType', 'WORLD_DESIGN_AGGREGATE_TYPE_', ''); + scope_type := replace(mutation->>'scopeType', 'WORLD_DESIGN_SCOPE_TYPE_', ''); + IF family NOT IN ('REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING') + OR scope_type NOT IN ('REGION_SUBTREE','ZONE_SUBTREE') + OR mutation->>'operation' IS DISTINCT FROM 'WORLD_DESIGN_MUTATION_OPERATION_UPSERT' + OR mutation->>'commitId' IS DISTINCT FROM p_binding->>'commitId' + OR mutation->>'logicalRevisionId' IS DISTINCT FROM revision->>'revisionId' + OR coalesce(mutation->>'expectedDraftRevisionEpoch','0') <> '0' + OR coalesce(mutation->>'expectedDraftScopeRevisionEpoch','0') <> '0' + OR coalesce(mutation->>'scopeMutationPolicy','WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED') + <> 'WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED' THEN + RAISE EXCEPTION 'Unsupported exact fresh World revision' USING ERRCODE = '23514'; + END IF; + table_name := lower(family); + mapping.id := nextval('"${serviceSchema}".world_authored_topology_identity_id_seq'); + mapping.target_namespace := identity_row.target_namespace; + mapping.canonical_tenant_id := identity_row.canonical_tenant_id; + mapping.canonical_version_id := identity_row.canonical_version_id; + mapping.family := family; + mapping.template_id := (mutation->>'aggregateId')::UUID; + mapping.private_row_key := nextval( + format('%I.%I', '${serviceSchema}', table_name || '_id_seq')::REGCLASS); + mapping.tenant_id := identity_row.local_tenant_key; + mapping.version_id := identity_row.local_version_key; + mapping.version_identity_operation_id := identity_row.operation_id; + mapping.request_id := (p_binding->>'requestId')::UUID; + mapping.commit_id := (p_binding->>'commitId')::UUID; + mapping.revision_id := (revision->>'revisionId')::UUID; + mapping.revision_order := revision->>'revisionOrder'; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), mapping.commit_id, 'world_authored_topology_identity', mapping.id, 'INSERT', + identity_row.operation_id, mapping.tenant_id, mapping.version_id, + p_owner, p_binding, NULL, to_jsonb(mapping)); + INSERT INTO "${serviceSchema}".world_authored_topology_identity SELECT (mapping).*; + expected_units := expected_units || jsonb_build_array( + jsonb_build_object('owner','WORLD_MANAGEMENT','aggregateType',family, + 'aggregateId',mapping.template_id::TEXT,'scopeType','AGGREGATE', + 'scopeId',mapping.template_id::TEXT,'expectedEpoch','0'), + jsonb_build_object('owner','WORLD_MANAGEMENT','aggregateType',family, + 'aggregateId',mapping.template_id::TEXT,'scopeType',scope_type, + 'scopeId',mutation->>'scopeId','expectedEpoch','0')); + END LOOP; + SELECT jsonb_agg(value ORDER BY value->>'aggregateType',value->>'aggregateId',value->>'scopeType',value->>'scopeId') + INTO expected_sorted FROM jsonb_array_elements(expected_units); + SELECT jsonb_agg(value ORDER BY value->>'aggregateType',value->>'aggregateId',value->>'scopeType',value->>'scopeId') + INTO supplied_units FROM jsonb_array_elements(p_binding->'affectedUnits') + WHERE value->>'owner' = 'WORLD_MANAGEMENT'; + IF expected_sorted IS DISTINCT FROM supplied_units THEN + RAISE EXCEPTION 'World topology requires the exact aggregate and containing tuples' + USING ERRCODE = '23514'; + END IF; + -- Typed mappings are allocated first, then content is inserted in parent-before-child order. + FOR mapping IN SELECT m.* FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = (p_binding->>'requestId')::UUID + ORDER BY CASE m.family WHEN 'REGION' THEN 1 WHEN 'ZONE' THEN 2 WHEN 'ROOM' THEN 3 + WHEN 'ROOM_EXIT' THEN 4 WHEN 'GENERATION_RULE' THEN 5 ELSE 6 END, m.revision_order::NUMERIC + LOOP + SELECT value INTO STRICT revision FROM jsonb_array_elements(nodes) + WHERE value->>'revisionId' = mapping.revision_id::TEXT; + mutation := (revision->>'payload')::JSONB; + family := mapping.family; + table_name := lower(family); + scope_type := replace(mutation->>'scopeType','WORLD_DESIGN_SCOPE_TYPE_',''); + scope_uuid := (mutation->>'scopeId')::UUID; + SELECT m.private_row_key INTO STRICT scope_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.template_id = scope_uuid + AND m.family = CASE scope_type WHEN 'REGION_SUBTREE' THEN 'REGION' ELSE 'ZONE' END; + content := jsonb_build_object('id',mapping.private_row_key,'tenant_id',mapping.tenant_id, + 'version_id',mapping.version_id,'version',0); + CASE family + + WHEN 'REGION' THEN + payload := mutation->'region'; + IF scope_type <> 'REGION_SUBTREE' OR scope_uuid <> mapping.template_id THEN + RAISE EXCEPTION 'Region scope substitution' USING ERRCODE = '23514'; + END IF; + content := content || jsonb_build_object( + 'name',coalesce(payload->>'name',''),'shard_id',coalesce((payload->>'shardId')::INT,0), + 'weather',coalesce(payload->>'weather',''),'generation_seed',coalesce((payload->>'generationSeed')::BIGINT,0), + 'generator_type',coalesce(payload->>'generatorType',''),'generator_params',coalesce(payload->>'generatorParams',''), + 'spacing_multiplier',coalesce(nullif((payload->>'spacingMultiplier')::FLOAT8,0),1)); + WHEN 'ZONE' THEN + payload := mutation->'zone'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'REGION' + AND m.template_id = (payload->>'regionId')::UUID; + IF (scope_type = 'REGION_SUBTREE' AND scope_key <> parent_key) + OR (scope_type = 'ZONE_SUBTREE' AND scope_uuid <> mapping.template_id) THEN + RAISE EXCEPTION 'Zone scope substitution' USING ERRCODE = '23514'; + END IF; + content := content || jsonb_build_object('name',coalesce(payload->>'name',''),'region_id',parent_key); + WHEN 'ROOM' THEN + payload := mutation->'room'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ZONE' + AND m.template_id = (payload->>'zoneId')::UUID; + SELECT z.region_id INTO STRICT other_key FROM "${serviceSchema}".zone z WHERE z.id = parent_key; + IF scope_key <> (CASE scope_type WHEN 'REGION_SUBTREE' THEN other_key ELSE parent_key END) THEN + RAISE EXCEPTION 'Room scope substitution' USING ERRCODE = '23514'; + END IF; + content := content || jsonb_build_object('name',coalesce(payload->>'name',''), + 'description',coalesce(payload->>'description',''),'zone_id',parent_key, + 'name_localized_variants_json',coalesce(payload->>'nameLocalizedVariantsJson',''), + 'description_localized_variants_json',coalesce(payload->>'descriptionLocalizedVariantsJson','')); + WHEN 'ROOM_EXIT' THEN + payload := mutation->'roomExit'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ROOM' + AND m.template_id = (payload->>'fromRoomId')::UUID; + SELECT m.private_row_key INTO STRICT other_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ROOM' + AND m.template_id = (payload->>'toRoomId')::UUID; + content := content || jsonb_build_object('from_room_id',parent_key,'to_room_id',other_key, + 'direction',coalesce(payload->>'direction',''),'cost',coalesce(nullif((payload->>'cost')::INT,0),1)); + WHEN 'GENERATION_RULE' THEN + payload := mutation->'generationRule'; + content := content || jsonb_build_object('name',coalesce(payload->>'name',''), + 'value',coalesce(payload->>'value',''),'scope_type',scope_type,'scope_id',scope_key::TEXT); + WHEN 'WORLD_ENTITY_SPAWN_BINDING' THEN + payload := mutation->'worldEntitySpawnBinding'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ROOM' + AND m.template_id = (payload->>'roomId')::UUID; + content := content || jsonb_build_object('room_id',parent_key, + 'entity_template_type',replace(payload->>'entityTemplateType','ENTITY_TEMPLATE_REFERENCE_TYPE_',''), + 'entity_template_id',NULL,'entity_canonical_tenant_id',mapping.canonical_tenant_id, + 'entity_canonical_version_id',mapping.canonical_version_id, + 'entity_canonical_template_id',(payload->>'entityTemplateId')::UUID, + 'spawn_count',coalesce(nullif((payload->>'spawnCount')::INT,0),1), + 'respawn_delay_seconds',coalesce((payload->>'respawnDelaySeconds')::INT,0)); + ELSE RAISE EXCEPTION 'Unsupported World family'; + END CASE; + IF payload IS NULL + OR (content ? 'name' AND btrim(content->>'name') = '') + OR coalesce((content->>'shard_id')::INT,0) < 0 + OR coalesce((content->>'spacing_multiplier')::FLOAT8,1) <= 0 + OR coalesce((content->>'spacing_multiplier')::FLOAT8,1) IN ('NaN'::FLOAT8,'Infinity'::FLOAT8) + OR coalesce((content->>'cost')::INT,1) < 1 + OR coalesce((content->>'spawn_count')::INT,1) < 1 + OR coalesce((content->>'respawn_delay_seconds')::INT,0) < 0 + OR (family = 'WORLD_ENTITY_SPAWN_BINDING' AND content->>'entity_template_type' NOT IN ('ITEM','NPC')) + OR (family = 'ROOM_EXIT' AND btrim(content->>'direction') = '') THEN + RAISE EXCEPTION 'Invalid fresh World payload' USING ERRCODE = '23514'; + END IF; + IF family IN ('ROOM_EXIT','WORLD_ENTITY_SPAWN_BINDING') THEN + IF NOT EXISTS (SELECT 1 FROM "${serviceSchema}".room r + JOIN "${serviceSchema}".zone z ON z.id = r.zone_id + WHERE r.id = parent_key AND CASE scope_type + WHEN 'REGION_SUBTREE' THEN z.region_id ELSE z.id END = scope_key) + OR (family = 'ROOM_EXIT' AND NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".room r JOIN "${serviceSchema}".zone z ON z.id = r.zone_id + WHERE r.id = other_key AND CASE scope_type + WHEN 'REGION_SUBTREE' THEN z.region_id ELSE z.id END = scope_key)) THEN + RAISE EXCEPTION 'World endpoint outside exact scope' USING ERRCODE = '23514'; + END IF; + END IF; + -- Populate the full physical row type so the manifest includes every actual column. + EXECUTE format('SELECT to_jsonb(jsonb_populate_record(NULL::%I.%I, $1))', + '${serviceSchema}',table_name) INTO complete_row USING content; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), mapping.commit_id, table_name, mapping.private_row_key, 'INSERT', + identity_row.operation_id, mapping.tenant_id, mapping.version_id, + p_owner, p_binding, NULL, complete_row); + EXECUTE format('INSERT INTO %I.%I SELECT (jsonb_populate_record(NULL::%I.%I,$1)).*', + '${serviceSchema}',table_name,'${serviceSchema}',table_name) USING complete_row; + epoch_row := jsonb_build_object( + 'id',nextval('"${serviceSchema}".world_design_aggregate_epoch_id_seq'), + 'tenant_id',mapping.tenant_id,'version_id',mapping.version_id, + 'aggregate_type',family,'aggregate_id',mapping.private_row_key, + 'draft_revision_epoch',1,'updated_at',CURRENT_TIMESTAMP::TIMESTAMP); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), mapping.commit_id, 'world_design_aggregate_epoch',(epoch_row->>'id')::BIGINT,'INSERT', + identity_row.operation_id,mapping.tenant_id,mapping.version_id,p_owner,p_binding,NULL,epoch_row); + INSERT INTO "${serviceSchema}".world_design_aggregate_epoch + SELECT (jsonb_populate_record(NULL::"${serviceSchema}".world_design_aggregate_epoch,epoch_row)).*; + END LOOP; + -- Each distinct containing fence advances once, even when multiple affected tuples share it. + FOR revision IN SELECT DISTINCT jsonb_build_object('scope_type',value->>'scopeType','scope_id',value->>'scopeId') + FROM jsonb_array_elements(expected_units) WHERE value->>'scopeType' <> 'AGGREGATE' + LOOP + epoch_row := jsonb_build_object( + 'id',nextval('"${serviceSchema}".world_design_scope_epoch_id_seq'), + 'tenant_id',identity_row.local_tenant_key,'version_id',identity_row.local_version_key, + 'scope_type',revision->>'scope_type','scope_id',revision->>'scope_id', + 'draft_scope_revision_epoch',1,'updated_at',CURRENT_TIMESTAMP::TIMESTAMP); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(),(p_binding->>'commitId')::UUID,'world_design_scope_epoch',(epoch_row->>'id')::BIGINT,'INSERT', + identity_row.operation_id,identity_row.local_tenant_key,identity_row.local_version_key, + p_owner,p_binding,NULL,epoch_row); + INSERT INTO "${serviceSchema}".world_design_scope_epoch + SELECT (jsonb_populate_record(NULL::"${serviceSchema}".world_design_scope_epoch,epoch_row)).*; + END LOOP; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest + WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'Unconsumed World topology execution manifest' USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_store_guarded_uuid_topology(JSONB,JSONB,JSONB) FROM PUBLIC; +REVOKE ALL ON FUNCTION world_protect_topology_identity() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_protect_mapped_topology_row() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V31__world_canonical_frozen_topology.sql b/services/world-management-service/src/main/resources/db/migration/V31__world_canonical_frozen_topology.sql new file mode 100644 index 0000000000..6b72524bfe --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V31__world_canonical_frozen_topology.sql @@ -0,0 +1,96 @@ +-- Immutable component capture only. The V25 checkpoint is retained, never redefined as graph hash. +CREATE TABLE world_canonical_frozen_topology ( + capture_id UUID PRIMARY KEY CHECK (capture_id <> '00000000-0000-0000-0000-000000000000'::UUID), + publication_fence UUID NOT NULL UNIQUE REFERENCES world_design_publication_fence_attempt(publication_fence), + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + freeze_request_json TEXT NOT NULL, + owner_binding_json TEXT NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + identity_json TEXT NOT NULL, + intake_json TEXT NOT NULL, + graph_bytes BYTEA NOT NULL CHECK (octet_length(graph_bytes) > 0), + graph_sha256 VARCHAR(64) NOT NULL CHECK (graph_sha256 ~ '^[0-9a-f]{64}$'), + storage_result_bytes BYTEA NOT NULL CHECK (octet_length(storage_result_bytes) > 0), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + capture_status VARCHAR(32) NOT NULL CHECK (capture_status = 'CAPTURED_UNVERIFIED'), + captured_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (request_id) REFERENCES world_topology_draft_commit(request_id), + FOREIGN KEY (commit_id) REFERENCES world_topology_draft_commit(commit_id), + FOREIGN KEY (version_identity_operation_id) REFERENCES world_authored_version_identity(operation_id) +); + +-- [jooq ignore start] +CREATE FUNCTION world_check_canonical_frozen_capture() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + commit_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + frozen_evidence JSONB; + identity TEXT; + intake TEXT; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'Canonical frozen capture requires writable READ COMMITTED' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT commit_row FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id=NEW.request_id AND commit_id=NEW.commit_id + AND version_identity_operation_id=NEW.version_identity_operation_id; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE local_tenant_key=commit_row.local_tenant_key AND version_id=commit_row.local_version_key FOR UPDATE; + SELECT * INTO STRICT attempt FROM "${serviceSchema}".world_design_publication_fence_attempt + WHERE publication_fence=NEW.publication_fence; + SELECT to_jsonb(v)::text, to_jsonb(i)::text INTO STRICT identity, intake + FROM "${serviceSchema}".world_authored_version_identity v + JOIN "${serviceSchema}".world_authored_source_intake i ON i.operation_id=v.intake_operation_id + WHERE v.operation_id=NEW.version_identity_operation_id; + frozen_evidence := NEW.freeze_request_json::jsonb; + IF owner_row.owner_freeze_phase <> 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence + OR attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR attempt.local_tenant_key IS DISTINCT FROM commit_row.local_tenant_key + OR attempt.version_id IS DISTINCT FROM commit_row.local_version_key + OR attempt.version_identity_operation_id IS DISTINCT FROM NEW.version_identity_operation_id + OR attempt.canonical_tenant_id IS DISTINCT FROM commit_row.canonical_tenant_id + OR attempt.canonical_version_id IS DISTINCT FROM commit_row.canonical_version_id + OR attempt.target_namespace IS DISTINCT FROM commit_row.target_namespace + OR attempt.applied_commit_id IS DISTINCT FROM NEW.commit_id::text + OR frozen_evidence->>'targetNamespace' IS DISTINCT FROM attempt.target_namespace + OR frozen_evidence->>'canonicalTenantId' IS DISTINCT FROM attempt.canonical_tenant_id::text + OR frozen_evidence->>'canonicalVersionId' IS DISTINCT FROM attempt.canonical_version_id::text + OR frozen_evidence->>'intakeRequestId' IS DISTINCT FROM attempt.intake_request_id::text + OR frozen_evidence->>'publicationFence' IS DISTINCT FROM attempt.publication_fence::text + OR frozen_evidence->>'publicationRequestId' IS DISTINCT FROM attempt.publication_request_id + OR frozen_evidence->>'requestDigest' IS DISTINCT FROM attempt.request_digest + OR frozen_evidence->>'versionStateEpoch' IS DISTINCT FROM attempt.version_state_epoch::text + OR frozen_evidence->>'publishWorkflowId' IS DISTINCT FROM attempt.publish_workflow_id + OR frozen_evidence->>'appliedCommitId' IS DISTINCT FROM attempt.applied_commit_id + OR frozen_evidence->>'contentDigest' IS DISTINCT FROM attempt.content_digest + OR frozen_evidence->>'digestSchemaVersion' IS DISTINCT FROM attempt.digest_schema_version::text + OR NEW.owner_binding_json IS DISTINCT FROM commit_row.owner_binding_json + OR NEW.binding_json IS DISTINCT FROM commit_row.binding_json + OR NEW.binding_digest IS DISTINCT FROM commit_row.binding_digest + OR NEW.graph_bytes IS DISTINCT FROM commit_row.graph_bytes + OR NEW.graph_sha256 IS DISTINCT FROM commit_row.graph_sha256 + OR NEW.storage_result_bytes IS DISTINCT FROM commit_row.result_bytes + OR NEW.identity_json IS DISTINCT FROM identity OR NEW.intake_json IS DISTINCT FROM intake THEN + RAISE EXCEPTION 'Canonical frozen capture differs from exact original storage and FROZEN checkpoint' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_canonical_frozen_insert BEFORE INSERT + ON world_canonical_frozen_topology FOR EACH ROW + EXECUTE FUNCTION world_check_canonical_frozen_capture(); +CREATE TRIGGER trg_world_canonical_frozen_immutable BEFORE UPDATE OR DELETE + ON world_canonical_frozen_topology FOR EACH ROW + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_canonical_frozen_no_truncate BEFORE TRUNCATE + ON world_canonical_frozen_topology 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/V32__world_digest_schema3_capture.sql b/services/world-management-service/src/main/resources/db/migration/V32__world_digest_schema3_capture.sql new file mode 100644 index 0000000000..e920f23870 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V32__world_digest_schema3_capture.sql @@ -0,0 +1,39 @@ +-- Preserve exact immutable schema-2 history; only new captures use schema 3. +ALTER TABLE world_authored_graph_snapshot + DROP CONSTRAINT ck_world_authored_graph_snapshot_scope; +ALTER TABLE world_authored_graph_snapshot + ADD CONSTRAINT ck_world_authored_graph_snapshot_scope CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_id > 0 + AND local_version_key > 0 + AND local_tenant_key > 0 + AND owner_binding_schema_version = 1 + AND version_state_epoch > 0 + AND digest_schema_version IN (2, 3) + ); + +-- [jooq ignore start] +CREATE FUNCTION world_require_new_digest_schema3_capture() RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_TABLE_NAME = 'world_authored_graph_snapshot' THEN + IF NEW.digest_schema_version IS DISTINCT FROM 3 THEN + RAISE EXCEPTION 'New World graph capture requires digest schema 3' USING ERRCODE = '23514'; + END IF; + ELSE + IF (NEW.freeze_request_json::jsonb)->>'digestSchemaVersion' IS DISTINCT FROM '3' THEN + RAISE EXCEPTION 'New canonical graph capture requires digest schema 3' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_authored_graph_snapshot_schema3 BEFORE INSERT + ON world_authored_graph_snapshot FOR EACH ROW + EXECUTE FUNCTION world_require_new_digest_schema3_capture(); +CREATE TRIGGER trg_world_canonical_frozen_00_schema3 BEFORE INSERT + ON world_canonical_frozen_topology FOR EACH ROW + EXECUTE FUNCTION world_require_new_digest_schema3_capture(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V34__world_canonical_instance_association.sql b/services/world-management-service/src/main/resources/db/migration/V34__world_canonical_instance_association.sql new file mode 100644 index 0000000000..d3e4459c95 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V34__world_canonical_instance_association.sql @@ -0,0 +1,506 @@ +-- Canonical creation identity is insert-born. Existing numeric lifecycle rows stay unmapped. +ALTER TABLE world_instance + ADD COLUMN canonical_game_instance_id UUID, + ADD COLUMN canonical_target_namespace VARCHAR(63), + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN canonical_world_slug VARCHAR(120), + ADD COLUMN playable_state_namespace_id UUID, + ADD COLUMN playable_state_scope VARCHAR(16), + ADD COLUMN public_production BOOLEAN, + ADD COLUMN playtest_lifecycle_id UUID, + ADD COLUMN playtest_state_generation BIGINT, + ADD COLUMN canonical_launch_binding_operation_id UUID; + +ALTER TABLE world_instance + ADD CONSTRAINT fk_world_instance_canonical_launch_binding + FOREIGN KEY (canonical_launch_binding_operation_id) + REFERENCES world_complete_launch_binding (binding_operation_id) + ON DELETE RESTRICT, + ADD CONSTRAINT uq_world_instance_canonical_game_instance + UNIQUE (canonical_game_instance_id), + ADD CONSTRAINT uq_world_instance_canonical_binding + UNIQUE (canonical_launch_binding_operation_id), + ADD CONSTRAINT uq_world_instance_canonical_association_fk + UNIQUE ( + id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id + ), + ADD CONSTRAINT ck_world_instance_canonical_creation_identity CHECK ( + ( + canonical_game_instance_id IS NULL + AND canonical_target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND canonical_world_slug IS NULL + AND playable_state_namespace_id IS NULL + AND playable_state_scope IS NULL + AND public_production IS NULL + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + AND canonical_launch_binding_operation_id IS NULL + ) + OR + ( + canonical_game_instance_id IS NOT NULL + AND canonical_target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_world_slug IS NOT NULL + AND playable_state_namespace_id IS NOT NULL + AND playable_state_scope IS NOT NULL + AND public_production IS TRUE + AND canonical_launch_binding_operation_id IS NOT NULL + -- The current Game Session owner-read projection does not carry playtest identity. + -- This foundation therefore admits only SHARED, non-playtest creation rows. + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(canonical_world_slug) BETWEEN 1 AND 120 + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_scope = 'SHARED' + AND canonical_launch_binding_operation_id + <> '00000000-0000-0000-0000-000000000000'::UUID + ) + ); + +-- A canonical World version key must remain explicitly tied to its immutable UUID association. +ALTER TABLE world_authored_version_identity + ADD CONSTRAINT uq_world_authored_version_identity_instance_binding + UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + local_tenant_key, + local_version_key + ); + +CREATE TABLE world_canonical_instance_association ( + schema_version SMALLINT NOT NULL, + canonical_game_instance_id UUID NOT NULL, + canonical_target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_world_slug VARCHAR(120) NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(16) NOT NULL, + public_production BOOLEAN NOT NULL, + playtest_lifecycle_id UUID, + playtest_state_generation BIGINT, + control_plane_request_id VARCHAR(128) NOT NULL, + world_instance_id BIGINT NOT NULL, + canonical_launch_binding_operation_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + private_game_instance_key BIGINT NOT NULL, + game_template_id BIGINT NOT NULL, + launch_descriptor_id VARCHAR(64) NOT NULL, + local_version_key BIGINT NOT NULL, + script_patch_version VARCHAR(100), + runtime_flags_json TEXT NOT NULL, + generation_config_revision VARCHAR(128) NOT NULL, + release_bundle_id BIGINT NOT NULL, + published_release_bundle_ref VARCHAR(128) NOT NULL, + version_state_epoch BIGINT NOT NULL, + remap_set_id VARCHAR(64), + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_request_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, + CONSTRAINT pk_world_canonical_instance_association + PRIMARY KEY (canonical_game_instance_id), + CONSTRAINT uq_world_canonical_instance_association_scoped + UNIQUE ( + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + canonical_game_instance_id + ), + CONSTRAINT uq_world_canonical_instance_association_request + UNIQUE (canonical_target_namespace, canonical_tenant_id, control_plane_request_id), + CONSTRAINT uq_world_canonical_instance_association_row UNIQUE (world_instance_id), + CONSTRAINT uq_world_canonical_instance_association_binding + UNIQUE (canonical_launch_binding_operation_id), + CONSTRAINT fk_world_canonical_instance_association_world_row + FOREIGN KEY ( + world_instance_id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id + ) REFERENCES world_instance ( + id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id + ) ON DELETE RESTRICT, + CONSTRAINT fk_world_canonical_instance_association_launch_binding + FOREIGN KEY (canonical_launch_binding_operation_id) + REFERENCES world_complete_launch_binding (binding_operation_id) + ON DELETE RESTRICT, + CONSTRAINT fk_world_canonical_instance_association_version_identity + FOREIGN KEY ( + version_identity_operation_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + canonical_version_id, + local_tenant_key, + local_version_key + ) REFERENCES world_authored_version_identity ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + local_tenant_key, + local_version_key + ) ON DELETE RESTRICT, + CONSTRAINT ck_world_canonical_instance_association_schema + CHECK (schema_version = 1), + CONSTRAINT ck_world_canonical_instance_association_ids CHECK ( + canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_launch_binding_operation_id + <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_identity_operation_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 + ), + CONSTRAINT ck_world_canonical_instance_association_scope CHECK ( + canonical_target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(canonical_world_slug) BETWEEN 1 AND 120 + AND playable_state_scope = 'SHARED' + AND public_production IS TRUE + AND length(btrim(control_plane_request_id)) BETWEEN 1 AND 128 + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + ), + CONSTRAINT ck_world_canonical_instance_association_owner_keys CHECK ( + world_instance_id > 0 + AND local_tenant_key > 0 + AND private_game_instance_key > 0 + AND game_template_id > 0 + AND local_version_key > 0 + AND release_bundle_id > 0 + AND version_state_epoch > 0 + AND length(btrim(launch_descriptor_id)) BETWEEN 1 AND 64 + AND length(btrim(runtime_flags_json)) > 0 + AND length(btrim(generation_config_revision)) BETWEEN 1 AND 128 + AND length(btrim(published_release_bundle_ref)) BETWEEN 1 AND 128 + AND (script_patch_version IS NULL OR length(btrim(script_patch_version)) BETWEEN 1 AND 100) + AND (remap_set_id IS NULL OR length(btrim(remap_set_id)) BETWEEN 1 AND 64) + ), + CONSTRAINT ck_world_canonical_instance_association_digests CHECK ( + source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_request_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}$' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION world_validate_canonical_prepare_identity() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + binding world_complete_launch_binding%ROWTYPE; + version_identity world_authored_version_identity%ROWTYPE; + descriptor JSONB; + release_attestation JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.canonical_game_instance_id IS NOT NULL THEN + RAISE EXCEPTION 'Canonical World instance creation identity is retained' + USING ERRCODE = '55000'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF OLD.canonical_game_instance_id IS NULL THEN + IF NEW.canonical_game_instance_id IS NOT NULL + OR NEW.canonical_target_namespace IS NOT NULL + OR NEW.canonical_tenant_id IS NOT NULL + OR NEW.canonical_world_slug IS NOT NULL + OR NEW.playable_state_namespace_id IS NOT NULL + OR NEW.playable_state_scope IS NOT NULL + OR NEW.public_production IS NOT NULL + OR NEW.playtest_lifecycle_id IS NOT NULL + OR NEW.playtest_state_generation IS NOT NULL + OR NEW.canonical_launch_binding_operation_id IS NOT NULL THEN + RAISE EXCEPTION 'A retained World instance cannot acquire canonical creation identity' + USING ERRCODE = '55000'; + END IF; + RETURN NEW; + END IF; + + IF OLD.id IS DISTINCT FROM NEW.id + OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id + OR OLD.game_instance_id IS DISTINCT FROM NEW.game_instance_id + OR OLD.game_template_id IS DISTINCT FROM NEW.game_template_id + OR OLD.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR OLD.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR OLD.version_id IS DISTINCT FROM NEW.version_id + OR OLD.script_patch_version IS DISTINCT FROM NEW.script_patch_version + OR OLD.runtime_flags_json IS DISTINCT FROM NEW.runtime_flags_json + OR OLD.generation_config_revision IS DISTINCT FROM NEW.generation_config_revision + OR OLD.release_bundle_id IS DISTINCT FROM NEW.release_bundle_id + OR OLD.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR OLD.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch + OR OLD.remap_set_id IS DISTINCT FROM NEW.remap_set_id + OR OLD.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR OLD.canonical_target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR OLD.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR OLD.canonical_world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR OLD.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR OLD.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR OLD.public_production IS DISTINCT FROM NEW.public_production + OR OLD.playtest_lifecycle_id IS DISTINCT FROM NEW.playtest_lifecycle_id + OR OLD.playtest_state_generation IS DISTINCT FROM NEW.playtest_state_generation + OR OLD.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id THEN + RAISE EXCEPTION 'Canonical World instance creation and prepare inputs are immutable' + USING ERRCODE = '55000'; + END IF; + RETURN NEW; + END IF; + + IF NEW.canonical_game_instance_id IS NULL THEN + RETURN NEW; + END IF; + + SELECT * INTO binding + FROM world_complete_launch_binding + WHERE binding_operation_id = NEW.canonical_launch_binding_operation_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Canonical World instance requires its exact retained launch binding' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO version_identity + FROM world_authored_version_identity + WHERE target_namespace = NEW.canonical_target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND world_slug = NEW.canonical_world_slug + AND canonical_version_id = binding.canonical_version_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Canonical World instance requires its exact UUID-to-private-Version association' + USING ERRCODE = '23514'; + END IF; + + descriptor := binding.descriptor_json::jsonb; + release_attestation := binding.release_attestation_json::jsonb; + IF binding.target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR binding.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR binding.world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR binding.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR binding.local_tenant_key IS DISTINCT FROM NEW.tenant_id + OR version_identity.intake_operation_id IS DISTINCT FROM binding.intake_operation_id + OR version_identity.intake_request_id IS DISTINCT FROM binding.intake_request_id + OR version_identity.intake_request_digest IS DISTINCT FROM ( + SELECT request_digest FROM world_authored_source_intake + WHERE operation_id = binding.intake_operation_id + ) + OR version_identity.source_operation_id IS DISTINCT FROM binding.source_operation_id + OR version_identity.source_evidence_digest IS DISTINCT FROM binding.source_evidence_digest + OR version_identity.intake_receipt_digest IS DISTINCT FROM binding.intake_receipt_digest + OR version_identity.local_tenant_key IS DISTINCT FROM NEW.tenant_id + OR version_identity.local_version_key IS DISTINCT FROM NEW.version_id + OR version_identity.canonical_version_id IS DISTINCT FROM binding.canonical_version_id + OR version_identity.game_design_version_id::text IS DISTINCT FROM descriptor->>'versionId' + OR descriptor->>'targetNamespace' IS DISTINCT FROM NEW.canonical_target_namespace + OR descriptor->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::text + OR descriptor->>'worldSlug' IS DISTINCT FROM NEW.canonical_world_slug + OR descriptor->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR descriptor->>'authoredWorldSourceOperationId' + IS DISTINCT FROM binding.source_operation_id::text + OR descriptor->>'authoredWorldSourceEvidenceDigest' + IS DISTINCT FROM binding.source_evidence_digest + OR descriptor->>'requestDigest' IS DISTINCT FROM binding.descriptor_request_digest + OR descriptor->>'resultDigest' IS DISTINCT FROM binding.descriptor_result_digest + OR descriptor->>'launchDescriptorId' IS DISTINCT FROM NEW.launch_descriptor_id + OR descriptor->>'gameTemplateId' IS DISTINCT FROM NEW.game_template_id::text + OR descriptor->>'runtimeFlagsJson' IS DISTINCT FROM NEW.runtime_flags_json + OR descriptor->>'generationConfigRevision' IS DISTINCT FROM NEW.generation_config_revision + OR descriptor->>'releaseBundleId' IS DISTINCT FROM NEW.release_bundle_id::text + OR descriptor->>'publishedReleaseBundleRef' IS DISTINCT FROM NEW.published_release_bundle_ref + OR descriptor->>'versionStateEpoch' IS DISTINCT FROM NEW.version_state_epoch::text + OR ( + CASE WHEN descriptor->>'scriptPatchVersionPresent' = 'true' + THEN descriptor->>'scriptPatchVersion' + ELSE NULL + END + ) IS DISTINCT FROM NEW.script_patch_version + OR ( + CASE WHEN descriptor->>'remapSetIdPresent' = 'true' + THEN descriptor->>'remapSetId' + ELSE NULL + END + ) IS DISTINCT FROM NEW.remap_set_id + OR release_attestation->>'targetNamespace' IS DISTINCT FROM NEW.canonical_target_namespace + OR release_attestation->>'descriptorResultDigest' + IS DISTINCT FROM binding.descriptor_result_digest + OR release_attestation->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::text + OR release_attestation->>'canonicalVersionId' IS DISTINCT FROM binding.canonical_version_id::text + OR release_attestation->>'worldSlug' IS DISTINCT FROM NEW.canonical_world_slug + OR release_attestation->>'authoredWorldSourceOperationId' + IS DISTINCT FROM binding.source_operation_id::text + OR release_attestation->>'authoredWorldSourceEvidenceDigest' + IS DISTINCT FROM binding.source_evidence_digest + OR release_attestation->>'launchDescriptorId' IS DISTINCT FROM NEW.launch_descriptor_id + OR release_attestation->>'publishedReleaseBundleRef' + IS DISTINCT FROM NEW.published_release_bundle_ref + OR release_attestation->>'versionStateEpoch' IS DISTINCT FROM NEW.version_state_epoch::text + OR release_attestation->>'generationConfigRevision' + IS DISTINCT FROM NEW.generation_config_revision + OR release_attestation->>'evidenceDigest' IS DISTINCT FROM binding.release_attestation_digest THEN + RAISE EXCEPTION 'Canonical World instance prepare fields differ from immutable launch/source history' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_instance_canonical_prepare_identity + BEFORE INSERT OR UPDATE OR DELETE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_prepare_identity(); + +CREATE FUNCTION world_validate_canonical_instance_association() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + instance world_instance%ROWTYPE; + binding world_complete_launch_binding%ROWTYPE; + version_identity world_authored_version_identity%ROWTYPE; +BEGIN + SELECT * INTO instance FROM world_instance WHERE id = NEW.world_instance_id FOR KEY SHARE; + IF NOT FOUND OR instance.canonical_game_instance_id IS NULL THEN + RAISE EXCEPTION 'Canonical instance association requires an insert-born canonical World row' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO binding + FROM world_complete_launch_binding + WHERE binding_operation_id = NEW.canonical_launch_binding_operation_id; + SELECT * INTO version_identity + FROM world_authored_version_identity + WHERE operation_id = NEW.version_identity_operation_id; + + IF NOT FOUND + OR instance.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR instance.canonical_target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR instance.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR instance.canonical_world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR instance.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR instance.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR instance.public_production IS DISTINCT FROM NEW.public_production + OR instance.playtest_lifecycle_id IS DISTINCT FROM NEW.playtest_lifecycle_id + OR instance.playtest_state_generation IS DISTINCT FROM NEW.playtest_state_generation + OR instance.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR instance.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id + OR instance.tenant_id IS DISTINCT FROM NEW.local_tenant_key + OR instance.game_instance_id IS DISTINCT FROM NEW.private_game_instance_key + OR instance.game_template_id IS DISTINCT FROM NEW.game_template_id + OR instance.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR instance.version_id IS DISTINCT FROM NEW.local_version_key + OR instance.script_patch_version IS DISTINCT FROM NEW.script_patch_version + OR instance.runtime_flags_json IS DISTINCT FROM NEW.runtime_flags_json + OR instance.generation_config_revision IS DISTINCT FROM NEW.generation_config_revision + OR instance.release_bundle_id IS DISTINCT FROM NEW.release_bundle_id + OR instance.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR instance.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch + OR instance.remap_set_id IS DISTINCT FROM NEW.remap_set_id + OR binding.target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR binding.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR binding.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR binding.world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR binding.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR binding.intake_operation_id IS DISTINCT FROM NEW.intake_operation_id + OR binding.intake_request_id IS DISTINCT FROM NEW.intake_request_id + OR binding.local_tenant_key IS DISTINCT FROM NEW.local_tenant_key + OR binding.source_operation_id IS DISTINCT FROM NEW.source_operation_id + OR binding.source_evidence_digest IS DISTINCT FROM NEW.source_evidence_digest + OR binding.intake_receipt_digest IS DISTINCT FROM NEW.intake_receipt_digest + OR binding.descriptor_request_digest IS DISTINCT FROM NEW.descriptor_request_digest + OR binding.descriptor_result_digest IS DISTINCT FROM NEW.descriptor_result_digest + OR binding.release_attestation_digest IS DISTINCT FROM NEW.release_attestation_digest + OR version_identity.target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR version_identity.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR version_identity.world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR version_identity.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR version_identity.local_tenant_key IS DISTINCT FROM NEW.local_tenant_key + OR version_identity.local_version_key IS DISTINCT FROM NEW.local_version_key + OR version_identity.intake_operation_id IS DISTINCT FROM binding.intake_operation_id + OR version_identity.intake_request_id IS DISTINCT FROM binding.intake_request_id + OR version_identity.source_operation_id IS DISTINCT FROM binding.source_operation_id + OR version_identity.source_evidence_digest IS DISTINCT FROM binding.source_evidence_digest + OR version_identity.intake_receipt_digest IS DISTINCT FROM binding.intake_receipt_digest THEN + RAISE EXCEPTION 'Canonical instance association differs from exact owner creation, source, Version, or release rows' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_canonical_instance_association_exact_insert + BEFORE INSERT ON world_canonical_instance_association + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_instance_association(); + +CREATE TRIGGER trg_world_canonical_instance_association_immutable + BEFORE UPDATE OR DELETE ON world_canonical_instance_association + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_canonical_instance_association_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_association + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_reject_canonical_world_instance_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World instance creation identity cannot be truncated' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_instance_canonical_no_truncate + BEFORE TRUNCATE ON world_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_canonical_world_instance_truncate(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V35__world_guarded_canonical_instance_preparation.sql b/services/world-management-service/src/main/resources/db/migration/V35__world_guarded_canonical_instance_preparation.sql new file mode 100644 index 0000000000..dc71fa0d17 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V35__world_guarded_canonical_instance_preparation.sql @@ -0,0 +1,858 @@ +-- Canonical preparation is an insert-born, owner-private materialization boundary. The existing +-- V24 reserved-tenant guard remains closed except for exact single-use rows emitted below. +ALTER TABLE region_instance ADD COLUMN canonical_region_instance_id UUID; +ALTER TABLE zone_instance ADD COLUMN canonical_zone_instance_id UUID; +CREATE UNIQUE INDEX uq_region_instance_canonical_runtime_id + ON region_instance (canonical_region_instance_id) + WHERE canonical_region_instance_id IS NOT NULL; +CREATE UNIQUE INDEX uq_zone_instance_canonical_runtime_id + ON zone_instance (canonical_zone_instance_id) + WHERE canonical_zone_instance_id IS NOT NULL; + +CREATE SEQUENCE world_canonical_private_game_instance_key_seq AS BIGINT MINVALUE 1; +SELECT setval( + 'world_canonical_private_game_instance_key_seq'::REGCLASS, + coalesce(max(game_instance_id), 0) + 1, + FALSE) +FROM world_instance; + +CREATE TABLE world_canonical_instance_preparation_execution_manifest ( + transaction_id BIGINT NOT NULL, + table_name VARCHAR(64) NOT NULL, + row_id BIGINT NOT NULL, + canonical_game_instance_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + capture_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + input_digest VARCHAR(71) NOT NULL, + expected_new JSONB NOT NULL, + PRIMARY KEY (transaction_id, table_name, row_id), + CHECK (table_name IN ( + 'world_instance', 'region_instance', 'zone_instance', 'room_instance', + 'room_instance_exit', 'world_canonical_instance_topology_identity', + 'world_canonical_instance_preparation')), + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (capture_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (local_tenant_key > 0), + CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE TABLE world_canonical_instance_topology_identity ( + id BIGSERIAL PRIMARY KEY, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + canonical_game_instance_id UUID NOT NULL, + family VARCHAR(32) NOT NULL CHECK (family IN ('REGION', 'ZONE', 'ROOM', 'ROOM_EXIT')), + template_id UUID NOT NULL CHECK (template_id <> '00000000-0000-0000-0000-000000000000'::UUID), + template_private_row_key BIGINT NOT NULL CHECK (template_private_row_key > 0), + runtime_row_id BIGINT NOT NULL CHECK (runtime_row_id > 0), + runtime_identity UUID, + runtime_room_instance_id BIGINT, + UNIQUE (world_instance_id, family, template_id), + UNIQUE (family, runtime_row_id), + FOREIGN KEY (canonical_game_instance_id) REFERENCES world_instance(canonical_game_instance_id) + ON DELETE RESTRICT, + CHECK ( + (family = 'REGION' AND runtime_identity IS NOT NULL AND runtime_room_instance_id IS NULL) + OR (family = 'ZONE' AND runtime_identity IS NOT NULL AND runtime_room_instance_id IS NULL) + OR (family = 'ROOM' AND runtime_identity IS NULL AND runtime_room_instance_id > 0) + OR (family = 'ROOM_EXIT' AND runtime_identity IS NULL AND runtime_room_instance_id IS NULL) + ) +); +CREATE INDEX idx_world_canonical_instance_topology_world + ON world_canonical_instance_topology_identity(world_instance_id, family, id); + +CREATE TABLE world_canonical_instance_preparation ( + id BIGSERIAL PRIMARY KEY, + canonical_game_instance_id UUID NOT NULL UNIQUE, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_version_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + capture_id UUID NOT NULL REFERENCES world_canonical_frozen_topology(capture_id) ON DELETE RESTRICT, + graph_bytes BYTEA NOT NULL CHECK (octet_length(graph_bytes) > 0), + graph_sha256 VARCHAR(64) NOT NULL CHECK (graph_sha256 ~ '^[0-9a-f]{64}$'), + input_digest VARCHAR(71) NOT NULL CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + input_json TEXT NOT NULL CHECK (length(input_json) > 0), + world_instance_id BIGINT NOT NULL UNIQUE REFERENCES world_instance(id) ON DELETE RESTRICT, + private_game_instance_key BIGINT NOT NULL CHECK (private_game_instance_key > 0), + region_count INTEGER NOT NULL CHECK (region_count > 0), + zone_count INTEGER NOT NULL CHECK (zone_count >= 0), + room_count INTEGER NOT NULL CHECK (room_count >= 0), + exit_count INTEGER NOT NULL CHECK (exit_count >= 0), + storage_status VARCHAR(32) NOT NULL CHECK (storage_status = 'MATERIALIZED_UNVERIFIED'), + prepared_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (target_namespace, canonical_tenant_id, control_plane_request_id), + FOREIGN KEY (version_identity_operation_id) + REFERENCES world_authored_version_identity(operation_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_game_instance_id) + REFERENCES world_canonical_instance_association(canonical_game_instance_id) + DEFERRABLE INITIALLY DEFERRED +); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_preparation_execution_manifest FROM PUBLIC; + +CREATE FUNCTION world_consume_canonical_prepare_execution_manifest( + actual_table TEXT, actual_operation TEXT, actual_old JSONB, actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed BIGINT; +BEGIN + IF actual_operation <> 'INSERT' OR actual_old IS NOT NULL OR actual_new IS NULL THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest m + USING "${serviceSchema}".world_authored_version_identity v, + "${serviceSchema}".world_canonical_frozen_topology f, + "${serviceSchema}".world_authored_source_tenant_key_reservation r + WHERE m.transaction_id = txid_current() + AND m.table_name = actual_table + AND m.row_id = (actual_new->>'id')::BIGINT + AND m.expected_new = actual_new + AND v.operation_id = m.version_identity_operation_id + AND v.target_namespace = m.target_namespace + AND v.canonical_tenant_id = m.canonical_tenant_id + AND v.canonical_version_id = m.canonical_version_id + AND v.local_tenant_key = m.local_tenant_key + AND f.capture_id = m.capture_id + AND f.version_identity_operation_id = v.operation_id + AND f.capture_status = 'CAPTURED_UNVERIFIED' + AND r.tenant_key = m.local_tenant_key + AND r.claim_kind = 'CANONICAL_AUTHORED_SOURCE' + AND ( + (actual_table = 'world_instance' + AND actual_new->>'canonical_game_instance_id' = m.canonical_game_instance_id::TEXT + AND actual_new->>'canonical_target_namespace' = m.target_namespace + AND actual_new->>'canonical_tenant_id' = m.canonical_tenant_id::TEXT + AND actual_new->>'tenant_id' = m.local_tenant_key::TEXT) + OR (actual_table IN ('region_instance', 'zone_instance', 'room_instance', 'room_instance_exit') + AND actual_new->>'tenant_id' = m.local_tenant_key::TEXT + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance wi + WHERE wi.canonical_game_instance_id = m.canonical_game_instance_id + AND wi.tenant_id = m.local_tenant_key + AND wi.game_instance_id = (actual_new->>'game_instance_id')::BIGINT + AND wi.canonical_target_namespace = m.target_namespace + AND wi.canonical_tenant_id = m.canonical_tenant_id)) + OR (actual_table IN ('world_canonical_instance_topology_identity', 'world_canonical_instance_preparation') + AND actual_new->>'canonical_game_instance_id' = m.canonical_game_instance_id::TEXT + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance wi + WHERE wi.id = (actual_new->>'world_instance_id')::BIGINT + AND wi.canonical_game_instance_id = m.canonical_game_instance_id + AND wi.tenant_id = m.local_tenant_key + AND wi.canonical_target_namespace = m.target_namespace + AND wi.canonical_tenant_id = m.canonical_tenant_id)) + ) + RETURNING m.row_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_consume_canonical_prepare_execution_manifest(TEXT, TEXT, JSONB, JSONB) + FROM PUBLIC; + +-- V24's reserved-source denial is preserved. Only V29's existing exact draft manifest and this +-- V35 exact insert manifest may consume a canonical tenant mutation; legacy tenants retain the +-- original numeric reservation behavior. +CREATE OR REPLACE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + claimed_key BIGINT; + old_row JSONB; + new_row JSONB; + canonical_old BOOLEAN := FALSE; + canonical_new BOOLEAN := FALSE; +BEGIN + IF TG_OP <> 'INSERT' THEN + old_row := to_jsonb(OLD); + SELECT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_old; + END IF; + IF TG_OP <> 'DELETE' THEN + new_row := to_jsonb(NEW); + SELECT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_new; + END IF; + IF canonical_old OR canonical_new THEN + IF TG_TABLE_SCHEMA = '${serviceSchema}' + AND "${serviceSchema}".world_consume_region_execution_manifest( + TG_TABLE_NAME, TG_OP, old_row, new_row) THEN + RETURN NEW; + END IF; + IF TG_TABLE_SCHEMA = '${serviceSchema}' + AND "${serviceSchema}".world_consume_canonical_prepare_execution_manifest( + TG_TABLE_NAME, TG_OP, old_row, new_row) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION + 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + INSERT INTO "${serviceSchema}".world_authored_source_tenant_key_reservation AS reservation + (tenant_key, claim_kind) VALUES (NEW.tenant_id, 'LEGACY_NUMERIC') + ON CONFLICT (tenant_key) DO UPDATE SET tenant_key = EXCLUDED.tenant_key + WHERE reservation.claim_kind = 'LEGACY_NUMERIC' + RETURNING reservation.tenant_key INTO claimed_key; + IF claimed_key IS NULL THEN + RAISE EXCEPTION 'World tenant key % is reserved for a canonical authored source', NEW.tenant_id + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION world_validate_canonical_preparation_row() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed BOOLEAN; +BEGIN + IF TG_OP = 'INSERT' THEN + consumed := "${serviceSchema}".world_consume_canonical_prepare_execution_manifest( + TG_TABLE_NAME, TG_OP, NULL, to_jsonb(NEW)); + IF consumed THEN RETURN NEW; END IF; + RAISE EXCEPTION 'Canonical topology/preparation rows require the exact V35 owner operation' + USING ERRCODE = '23514'; + END IF; + RAISE EXCEPTION 'Canonical topology/preparation history is immutable' + USING ERRCODE = '55000'; +END; +$$; +CREATE TRIGGER trg_world_canonical_instance_topology_identity_exact_insert + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_instance_topology_identity + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_preparation_row(); +CREATE TRIGGER trg_world_canonical_instance_topology_identity_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_topology_identity + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_canonical_instance_preparation_exact_insert + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_instance_preparation + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_preparation_row(); +CREATE TRIGGER trg_world_canonical_instance_preparation_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_preparation + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +-- Exact insert-only materialization. Configured generation and spawn intent are rejected before +-- any sequence allocation or write. All parent and template selectors come from typed, exact +-- UUID-to-private-key mappings committed by V30; no numeric/UUID inference occurs here. +CREATE FUNCTION world_prepare_canonical_instance(p_input_json TEXT, p_input_digest TEXT) +RETURNS TABLE(world_instance_id BIGINT, private_game_instance_key BIGINT) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + p JSONB; + ident JSONB; + gs_request JSONB; + gs_evidence JSONB; + launch JSONB; + version_input JSONB; + topology JSONB; + source_input JSONB; + source_evidence_input JSONB; + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + binding_row "${serviceSchema}".world_complete_launch_binding%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + capture_row "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; + publication_owner "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + prior "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + world_row "${serviceSchema}".world_instance%ROWTYPE; + region_runtime "${serviceSchema}".region_instance%ROWTYPE; + zone_runtime "${serviceSchema}".zone_instance%ROWTYPE; + room_runtime "${serviceSchema}".room_instance%ROWTYPE; + exit_runtime "${serviceSchema}".room_instance_exit%ROWTYPE; + topology_identity "${serviceSchema}".world_canonical_instance_topology_identity%ROWTYPE; + preparation_row "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + source_region RECORD; + source_zone RECORD; + source_room RECORD; + source_exit RECORD; + parent_row RECORD; + other_row RECORD; + full_row JSONB; + template_count BIGINT; + region_count BIGINT; + zone_count BIGINT; + room_count BIGINT; + exit_count BIGINT; + generation_count BIGINT; + spawn_count BIGINT; + local_game_instance_key BIGINT; + runtime_id BIGINT; + runtime_uuid UUID; + new_world_instance_id BIGINT; + new_result_id BIGINT; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'Canonical preparation requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + IF p_input_json IS NULL OR length(p_input_json) = 0 OR p_input_digest IS NULL + OR p_input_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Canonical preparation input/digest is malformed' USING ERRCODE = '23514'; + END IF; + p := p_input_json::JSONB; + IF p->>'schemaVersion' IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Unsupported canonical preparation input schema' USING ERRCODE = '23514'; + END IF; + ident := p->'identity'; + gs_request := p->'gameSessionReadRequest'; + gs_evidence := p->'gameSessionReadEvidence'; + launch := p->'launchBinding'; + version_input := p->'versionIdentity'; + topology := p->'topology'; + source_input := p->'sourceIntake'; + source_evidence_input := source_input->'sourceEvidence'; + IF ident IS NULL OR gs_request IS NULL OR gs_evidence IS NULL + OR launch IS NULL OR version_input IS NULL OR topology IS NULL + OR source_input IS NULL OR jsonb_typeof(source_input) IS DISTINCT FROM 'object' + OR source_evidence_input IS NULL + OR jsonb_typeof(source_evidence_input) IS DISTINCT FROM 'object' + OR ident->>'publicProduction' IS DISTINCT FROM 'true' + OR ident->>'playableStateScope' IS DISTINCT FROM 'SHARED' + OR ident->>'canonicalGameInstanceId' IS DISTINCT FROM gs_request->>'canonicalGameInstanceId' + OR ident->>'canonicalGameInstanceId' IS DISTINCT FROM gs_evidence->>'canonicalGameInstanceId' + OR ident->>'targetNamespace' IS DISTINCT FROM gs_request->>'targetNamespace' + OR ident->>'canonicalTenantId' IS DISTINCT FROM gs_request->>'canonicalTenantId' + OR ident->>'worldSlug' IS DISTINCT FROM gs_request->>'worldSlug' + OR ident->>'controlPlaneRequestId' IS DISTINCT FROM gs_request->>'controlPlaneRequestId' + OR gs_request->>'launchDescriptorId' IS DISTINCT FROM gs_evidence->>'launchDescriptorId' + OR gs_request->>'expectedDescriptorRequestDigest' IS DISTINCT FROM gs_evidence->>'descriptorRequestDigest' + OR gs_request->>'expectedDescriptorResultDigest' IS DISTINCT FROM gs_evidence->>'descriptorResultDigest' + OR gs_request->>'expectedReleaseAttestationEvidenceDigest' + IS DISTINCT FROM gs_evidence->>'releaseAttestationEvidenceDigest' + OR ident->>'playableStateNamespaceId' IS DISTINCT FROM gs_evidence->>'playableStateNamespaceId' + OR ident->>'playableStateScope' IS DISTINCT FROM gs_evidence->>'playableStateScope' + OR ident->>'publicProduction' IS DISTINCT FROM gs_evidence->>'publicProduction' + OR ident->>'targetNamespace' IS DISTINCT FROM launch->>'targetNamespace' + OR ident->>'canonicalTenantId' IS DISTINCT FROM launch->>'canonicalTenantId' + OR ident->>'worldSlug' IS DISTINCT FROM launch->>'worldSlug' + OR ident->>'controlPlaneRequestId' IS DISTINCT FROM launch->>'controlPlaneRequestId' + OR ident->>'controlPlaneRequestId' IS DISTINCT FROM gs_request->>'controlPlaneRequestId' + OR topology->>'captureId' IS NULL + OR topology->>'planDigest' IS NULL + OR topology->>'planDigest' !~ '^sha256:[0-9a-f]{64}$' + OR jsonb_typeof(topology->'regionCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'zoneCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'roomCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'exitCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'generationRuleCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'spawnBindingCount') IS DISTINCT FROM 'number' + OR (topology->>'regionCount')::BIGINT < 1 + OR (topology->>'zoneCount')::BIGINT < 0 + OR (topology->>'roomCount')::BIGINT < 0 + OR (topology->>'exitCount')::BIGINT < 0 + OR (topology->>'generationRuleCount')::BIGINT < 0 + OR (topology->>'spawnBindingCount')::BIGINT < 0 THEN + RAISE EXCEPTION 'Canonical preparation identity or exact Game Session echo differs' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT identity_row + FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id = (version_input->>'operationId')::UUID; + SELECT * INTO STRICT binding_row + FROM "${serviceSchema}".world_complete_launch_binding + WHERE binding_operation_id = (launch->>'operationId')::UUID; + SELECT * INTO STRICT intake_row + FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id = binding_row.intake_operation_id; + SELECT * INTO STRICT capture_row + FROM "${serviceSchema}".world_canonical_frozen_topology + WHERE capture_id = (topology->>'captureId')::UUID; + + IF identity_row.operation_id::TEXT IS DISTINCT FROM topology->>'versionIdentityOperationId' + OR identity_row.target_namespace IS DISTINCT FROM ident->>'targetNamespace' + OR identity_row.canonical_tenant_id::TEXT IS DISTINCT FROM ident->>'canonicalTenantId' + OR identity_row.world_slug IS DISTINCT FROM ident->>'worldSlug' + OR identity_row.canonical_version_id::TEXT IS DISTINCT FROM version_input->>'canonicalVersionId' + OR identity_row.canonical_version_id::TEXT IS DISTINCT FROM topology->>'canonicalVersionId' + OR identity_row.local_tenant_key IS DISTINCT FROM (launch->>'localTenantKey')::BIGINT + OR identity_row.local_version_key IS DISTINCT FROM (version_input->>'localVersionKey')::BIGINT + OR identity_row.game_design_version_id IS DISTINCT FROM (version_input->>'gameDesignVersionId')::BIGINT + OR identity_row.intake_operation_id IS DISTINCT FROM (launch->>'intakeOperationId')::UUID + OR identity_row.intake_request_id IS DISTINCT FROM (launch->>'intakeRequestId')::UUID + OR identity_row.source_operation_id IS DISTINCT FROM (launch->>'sourceOperationId')::UUID + OR identity_row.source_evidence_digest IS DISTINCT FROM launch->>'sourceEvidenceDigest' + OR identity_row.intake_request_digest IS DISTINCT FROM launch->>'intakeRequestDigest' + OR identity_row.intake_receipt_digest IS DISTINCT FROM launch->>'intakeReceiptDigest' + OR binding_row.target_namespace IS DISTINCT FROM ident->>'targetNamespace' + OR binding_row.canonical_tenant_id::TEXT IS DISTINCT FROM ident->>'canonicalTenantId' + OR binding_row.world_slug IS DISTINCT FROM ident->>'worldSlug' + OR binding_row.control_plane_request_id IS DISTINCT FROM ident->>'controlPlaneRequestId' + OR binding_row.descriptor_request_digest IS DISTINCT FROM gs_evidence->>'descriptorRequestDigest' + OR binding_row.descriptor_result_digest IS DISTINCT FROM gs_evidence->>'descriptorResultDigest' + OR binding_row.release_attestation_digest IS DISTINCT FROM gs_evidence->>'releaseAttestationEvidenceDigest' + OR binding_row.canonical_version_id::TEXT IS DISTINCT FROM version_input->>'canonicalVersionId' + OR binding_row.canonical_version_id::TEXT IS DISTINCT FROM launch->>'canonicalVersionId' + OR capture_row.request_id IS DISTINCT FROM (topology->>'requestId')::UUID + OR capture_row.commit_id IS DISTINCT FROM (topology->>'commitId')::UUID + OR capture_row.version_identity_operation_id IS DISTINCT FROM identity_row.operation_id + OR capture_row.binding_json IS DISTINCT FROM ( + SELECT binding_json FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id = capture_row.request_id) + OR capture_row.freeze_request_json::JSONB->>'publicationRequestId' + IS DISTINCT FROM topology->>'freezeRequestId' + OR capture_row.freeze_request_json::JSONB->>'publicationFence' + IS DISTINCT FROM topology->>'publicationFence' + OR capture_row.freeze_request_json::JSONB->>'requestDigest' + IS DISTINCT FROM topology->>'publicationRequestDigest' + OR capture_row.freeze_request_json::JSONB->>'appliedCommitId' + IS DISTINCT FROM topology->>'appliedCommitId' + OR capture_row.graph_sha256 !~ '^[0-9a-f]{64}$' + OR intake_row.source_provenance_kind <> 'NEW_GAME_ROW' + OR source_input->>'schemaVersion' IS DISTINCT FROM intake_row.schema_version::TEXT + OR source_input->>'targetNamespace' IS DISTINCT FROM intake_row.target_namespace + OR source_input->>'intakeRequestId' IS DISTINCT FROM intake_row.intake_request_id::TEXT + OR source_input->>'operationId' IS DISTINCT FROM intake_row.operation_id::TEXT + OR source_input->>'canonicalTenantId' IS DISTINCT FROM intake_row.canonical_tenant_id::TEXT + OR source_input->>'worldSlug' IS DISTINCT FROM intake_row.world_slug + OR source_input->>'sourceOperationId' IS DISTINCT FROM intake_row.source_operation_id::TEXT + OR source_input->>'sourceEvidenceDigest' IS DISTINCT FROM intake_row.source_evidence_digest + OR source_input->>'requestDigest' IS DISTINCT FROM intake_row.request_digest + OR source_input->>'receiptDigest' IS DISTINCT FROM intake_row.receipt_digest + OR source_input->>'localTenantKey' IS DISTINCT FROM intake_row.local_tenant_key::TEXT + OR source_evidence_input->>'schemaVersion' IS DISTINCT FROM intake_row.source_schema_version::TEXT + OR source_evidence_input->>'registrationRequestId' IS DISTINCT FROM intake_row.source_registration_request_id::TEXT + OR source_evidence_input->>'sourceOperationId' IS DISTINCT FROM intake_row.source_operation_id::TEXT + OR source_evidence_input->>'requestDigest' IS DISTINCT FROM intake_row.source_request_digest + OR source_evidence_input->>'canonicalTenantId' IS DISTINCT FROM intake_row.canonical_tenant_id::TEXT + OR source_evidence_input->>'tenantSlug' IS DISTINCT FROM intake_row.tenant_slug + OR source_evidence_input->>'worldSlug' IS DISTINCT FROM intake_row.world_slug + OR source_evidence_input->>'worldDisplayName' IS DISTINCT FROM intake_row.world_display_name + OR source_evidence_input->>'sourceGameRowId' IS DISTINCT FROM intake_row.source_game_row_id::TEXT + OR source_evidence_input->>'sourceGameTenantKey' IS DISTINCT FROM intake_row.source_game_tenant_key + OR source_evidence_input->>'provenanceKind' IS DISTINCT FROM intake_row.source_provenance_kind + OR source_evidence_input->>'evidenceDigest' IS DISTINCT FROM intake_row.source_evidence_digest + OR capture_row.graph_bytes IS NULL OR octet_length(capture_row.graph_bytes) = 0 + OR capture_row.graph_sha256 IS NULL OR capture_row.graph_sha256 !~ '^[0-9a-f]{64}$' + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation r + WHERE r.tenant_key = identity_row.local_tenant_key + AND r.claim_kind = 'CANONICAL_AUTHORED_SOURCE') THEN + RAISE EXCEPTION 'Canonical preparation differs from exact V26/V27 source, version, or frozen capture' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*) FILTER (WHERE family = 'REGION'), + count(*) FILTER (WHERE family = 'ZONE'), + count(*) FILTER (WHERE family = 'ROOM'), + count(*) FILTER (WHERE family = 'ROOM_EXIT'), + count(*) FILTER (WHERE family = 'GENERATION_RULE'), + count(*) FILTER (WHERE family = 'WORLD_ENTITY_SPAWN_BINDING'), + count(*) + INTO region_count, zone_count, room_count, exit_count, generation_count, spawn_count, template_count + FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = capture_row.request_id AND commit_id = capture_row.commit_id + AND version_identity_operation_id = identity_row.operation_id; + + -- Required intent is a hard pre-allocation rejection; there is no skip/default path. + IF generation_count <> 0 OR spawn_count <> 0 + OR generation_count <> (topology->>'generationRuleCount')::BIGINT + OR spawn_count <> (topology->>'spawnBindingCount')::BIGINT THEN + RAISE EXCEPTION 'Canonical generation-free preparation rejects configured generation/spawn intent' + USING ERRCODE = '23514'; + END IF; + IF region_count <> (topology->>'regionCount')::BIGINT + OR zone_count <> (topology->>'zoneCount')::BIGINT + OR room_count <> (topology->>'roomCount')::BIGINT + OR exit_count <> (topology->>'exitCount')::BIGINT + OR template_count <> region_count + zone_count + room_count + exit_count + OR region_count = 0 THEN + RAISE EXCEPTION 'Canonical preparation plan omits or adds a selected frozen graph row' + USING ERRCODE = '23514'; + END IF; + + -- The capture's V25 version owner is the serialization fence shared with every V29 writer. + -- Hold it through this transaction: a writer that began first completes before this row can be + -- locked (and its phase is then rechecked); a later writer cannot acquire its required UPDATE + -- lock until this exact immutable source graph has been materialized and committed. + SELECT * INTO STRICT publication_owner + FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE local_tenant_key = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key + FOR SHARE; + IF publication_owner.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR publication_owner.current_publication_fence IS DISTINCT FROM capture_row.publication_fence THEN + RAISE EXCEPTION 'Canonical preparation requires the exact still-FROZEN V25 source owner' + USING ERRCODE = '23514'; + END IF; + + -- Serialize exact canonical-id and request retries before checking prior identity or allocating + -- any private key/row identifier. These locks are entered only after the external verifier ran. + PERFORM pg_advisory_xact_lock(hashtextextended( + 'canonical-game-instance:' || (ident->>'canonicalGameInstanceId'), 0)); + PERFORM pg_advisory_xact_lock(hashtextextended( + 'canonical-prepare-request:' || (ident->>'targetNamespace') || ':' + || (ident->>'canonicalTenantId') || ':' || (ident->>'controlPlaneRequestId'), 0)); + + SELECT * INTO prior FROM "${serviceSchema}".world_canonical_instance_preparation + WHERE canonical_game_instance_id = (ident->>'canonicalGameInstanceId')::UUID FOR UPDATE; + IF FOUND THEN + IF prior.input_json IS DISTINCT FROM p_input_json + OR prior.input_digest IS DISTINCT FROM p_input_digest + OR prior.capture_id IS DISTINCT FROM capture_row.capture_id + OR prior.graph_bytes IS DISTINCT FROM capture_row.graph_bytes + OR prior.graph_sha256 IS DISTINCT FROM capture_row.graph_sha256 THEN + RAISE EXCEPTION 'Canonical gameInstanceId is already bound to a different preparation' + USING ERRCODE = '23505'; + END IF; + world_instance_id := prior.world_instance_id; + private_game_instance_key := prior.private_game_instance_key; + RETURN NEXT; + RETURN; + END IF; + IF EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation + WHERE target_namespace = ident->>'targetNamespace' + AND canonical_tenant_id = (ident->>'canonicalTenantId')::UUID + AND control_plane_request_id = ident->>'controlPlaneRequestId') + OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance + WHERE canonical_game_instance_id = (ident->>'canonicalGameInstanceId')::UUID) + OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance + WHERE tenant_id = identity_row.local_tenant_key + AND control_plane_request_id = ident->>'controlPlaneRequestId') THEN + RAISE EXCEPTION 'Canonical game instance or request identity is already reserved' + USING ERRCODE = '23505'; + END IF; + + LOOP + local_game_instance_key := nextval('"${serviceSchema}".world_canonical_private_game_instance_key_seq'); + EXIT WHEN NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance + WHERE tenant_id = identity_row.local_tenant_key + AND game_instance_id = local_game_instance_key); + END LOOP; + new_world_instance_id := nextval('"${serviceSchema}".world_instance_id_seq'); + world_row := jsonb_populate_record(NULL::"${serviceSchema}".world_instance, + jsonb_build_object( + 'id', new_world_instance_id, + 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, + 'game_template_id', (binding_row.descriptor_json::JSONB->>'gameTemplateId')::BIGINT, + 'control_plane_request_id', ident->>'controlPlaneRequestId', + 'launch_descriptor_id', binding_row.descriptor_json::JSONB->>'launchDescriptorId', + 'version_id', identity_row.local_version_key, + 'script_patch_version', CASE WHEN binding_row.descriptor_json::JSONB->>'scriptPatchVersionPresent' = 'true' + THEN binding_row.descriptor_json::JSONB->>'scriptPatchVersion' ELSE NULL END, + 'runtime_flags_json', binding_row.descriptor_json::JSONB->>'runtimeFlagsJson', + 'generation_config_revision', binding_row.descriptor_json::JSONB->>'generationConfigRevision', + 'release_bundle_id', (binding_row.descriptor_json::JSONB->>'releaseBundleId')::BIGINT, + 'published_release_bundle_ref', binding_row.descriptor_json::JSONB->>'publishedReleaseBundleRef', + 'version_state_epoch', (binding_row.descriptor_json::JSONB->>'versionStateEpoch')::BIGINT, + 'lifecycle_epoch', 1, + 'status', 'PREPARING', + 'failure_reason', NULL, + 'created_at', CURRENT_TIMESTAMP::TIMESTAMP, + 'updated_at', CURRENT_TIMESTAMP::TIMESTAMP, + 'row_version', 0, + 'termination_request_id', NULL, + 'terminated_at', NULL, + 'remap_set_id', CASE WHEN binding_row.descriptor_json::JSONB->>'remapSetIdPresent' = 'true' + THEN binding_row.descriptor_json::JSONB->>'remapSetId' ELSE NULL END, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'canonical_target_namespace', ident->>'targetNamespace', + 'canonical_tenant_id', (ident->>'canonicalTenantId')::UUID, + 'canonical_world_slug', ident->>'worldSlug', + 'playable_state_namespace_id', (ident->>'playableStateNamespaceId')::UUID, + 'playable_state_scope', 'SHARED', + 'public_production', TRUE, + 'playtest_lifecycle_id', NULL, + 'playtest_state_generation', NULL, + 'canonical_launch_binding_operation_id', binding_row.binding_operation_id)); + full_row := to_jsonb(world_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_instance', new_world_instance_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_instance, full_row)).*; + + FOR source_region IN + SELECT m.template_id, m.private_row_key, r.shard_id, r.name, r.weather, + r.generation_seed, r.generator_type, r.generator_params, r.spacing_multiplier + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".region r ON r.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'REGION' + AND r.tenant_id = identity_row.local_tenant_key AND r.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + runtime_id := nextval('"${serviceSchema}".region_instance_id_seq'); + runtime_uuid := gen_random_uuid(); + region_runtime := jsonb_populate_record(NULL::"${serviceSchema}".region_instance, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, 'world_instance_id', new_world_instance_id, + 'shard_id', source_region.shard_id, 'name', source_region.name, + 'weather', source_region.weather, 'generation_seed', source_region.generation_seed, + 'generator_type', source_region.generator_type, + 'generator_params', source_region.generator_params, + 'spacing_multiplier', source_region.spacing_multiplier, 'version', 0, + 'canonical_region_instance_id', runtime_uuid)); + full_row := to_jsonb(region_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'region_instance', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".region_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".region_instance, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'REGION', 'template_id', source_region.template_id, + 'template_private_row_key', source_region.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', runtime_uuid, + 'runtime_room_instance_id', NULL)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + FOR source_zone IN + SELECT m.template_id, m.private_row_key, z.region_id, z.name + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".zone z ON z.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'ZONE' + AND z.tenant_id = identity_row.local_tenant_key AND z.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + SELECT ti.runtime_row_id INTO STRICT parent_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'REGION' + AND ti.template_private_row_key = source_zone.region_id; + runtime_id := nextval('"${serviceSchema}".zone_instance_id_seq'); + runtime_uuid := gen_random_uuid(); + zone_runtime := jsonb_populate_record(NULL::"${serviceSchema}".zone_instance, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, 'zone_instance_id', runtime_id, + 'template_zone_id', source_zone.private_row_key, + 'region_instance_id', parent_row.runtime_row_id, + 'name', source_zone.name, 'version', 0, + 'canonical_zone_instance_id', runtime_uuid)); + full_row := to_jsonb(zone_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'zone_instance', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".zone_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".zone_instance, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'ZONE', 'template_id', source_zone.template_id, + 'template_private_row_key', source_zone.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', runtime_uuid, + 'runtime_room_instance_id', NULL)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + FOR source_room IN + SELECT m.template_id, m.private_row_key, r.zone_id, r.name, r.description, + r.name_localized_variants_json, r.description_localized_variants_json + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'ROOM' + AND r.tenant_id = identity_row.local_tenant_key AND r.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + SELECT ti.runtime_row_id INTO STRICT parent_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'ZONE' + AND ti.template_private_row_key = source_room.zone_id; + SELECT ti.runtime_row_id INTO STRICT other_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + JOIN "${serviceSchema}".zone z ON z.id = source_room.zone_id + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'REGION' + AND ti.template_private_row_key = z.region_id; + runtime_id := nextval('"${serviceSchema}".room_instance_id_seq'); + room_runtime := jsonb_populate_record(NULL::"${serviceSchema}".room_instance, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, 'room_instance_row_id', runtime_id, + 'template_room_id', source_room.private_row_key, + 'region_instance_id', other_row.runtime_row_id, + 'zone_instance_id', parent_row.runtime_row_id, + 'name', source_room.name, 'description', source_room.description, + 'name_localized_variants_json', source_room.name_localized_variants_json, + 'description_localized_variants_json', source_room.description_localized_variants_json, + 'version', 0)); + full_row := to_jsonb(room_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'room_instance', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".room_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".room_instance, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'ROOM', 'template_id', source_room.template_id, + 'template_private_row_key', source_room.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', NULL, + 'runtime_room_instance_id', runtime_id)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + FOR source_exit IN + SELECT m.template_id, m.private_row_key, e.from_room_id, e.to_room_id, e.direction, e.cost + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room_exit e ON e.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'ROOM_EXIT' + AND e.tenant_id = identity_row.local_tenant_key AND e.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + SELECT ti.runtime_room_instance_id INTO STRICT parent_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'ROOM' + AND ti.template_private_row_key = source_exit.from_room_id; + SELECT ti.runtime_room_instance_id INTO STRICT other_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'ROOM' + AND ti.template_private_row_key = source_exit.to_room_id; + runtime_id := nextval('"${serviceSchema}".room_instance_exit_id_seq'); + exit_runtime := jsonb_populate_record(NULL::"${serviceSchema}".room_instance_exit, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, + 'from_room_instance_record_id', parent_row.runtime_room_instance_id, + 'to_room_instance_record_id', other_row.runtime_room_instance_id, + 'direction', source_exit.direction, 'cost', source_exit.cost, 'version', 0)); + full_row := to_jsonb(exit_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'room_instance_exit', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".room_instance_exit SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".room_instance_exit, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'ROOM_EXIT', 'template_id', source_exit.template_id, + 'template_private_row_key', source_exit.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', NULL, + 'runtime_room_instance_id', NULL)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + IF (SELECT count(*) FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest + WHERE transaction_id = txid_current()) <> 0 THEN + RAISE EXCEPTION 'Canonical preparation left an unconsumed exact execution manifest' + USING ERRCODE = '23514'; + END IF; + + new_result_id := nextval('"${serviceSchema}".world_canonical_instance_preparation_id_seq'); + preparation_row := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_preparation, + jsonb_build_object( + 'id', new_result_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'target_namespace', ident->>'targetNamespace', + 'canonical_tenant_id', (ident->>'canonicalTenantId')::UUID, + 'world_slug', ident->>'worldSlug', + 'control_plane_request_id', ident->>'controlPlaneRequestId', + 'canonical_version_id', identity_row.canonical_version_id, + 'version_identity_operation_id', identity_row.operation_id, + 'capture_id', capture_row.capture_id, + 'graph_bytes', capture_row.graph_bytes, + 'graph_sha256', capture_row.graph_sha256, + 'input_digest', p_input_digest, + 'input_json', p_input_json, + 'world_instance_id', new_world_instance_id, + 'private_game_instance_key', local_game_instance_key, + 'region_count', region_count, + 'zone_count', zone_count, + 'room_count', room_count, + 'exit_count', exit_count, + 'storage_status', 'MATERIALIZED_UNVERIFIED', + 'prepared_at', CURRENT_TIMESTAMP)); + full_row := to_jsonb(preparation_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_preparation', new_result_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_preparation, full_row)).*; + + IF (SELECT count(*) FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest + WHERE transaction_id = txid_current()) <> 0 THEN + RAISE EXCEPTION 'Canonical preparation left an unconsumed result manifest' + USING ERRCODE = '23514'; + END IF; + world_instance_id := new_world_instance_id; + private_game_instance_key := local_game_instance_key; + RETURN NEXT; +END; +$$; +REVOKE ALL ON FUNCTION world_prepare_canonical_instance(TEXT, TEXT) FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java index df24106f7b..e20deac775 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java @@ -6,9 +6,14 @@ import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.JsonFormat; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; +import java.util.HexFormat; +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; @@ -54,12 +59,18 @@ import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; @@ -114,6 +125,10 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private WorldDraftDesignDigestService draftDigestService; @Autowired private ObjectMapper objectMapper; + @Autowired + private net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository + spawnRepository; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; @MockitoBean(enforceOverride = true) @@ -170,6 +185,7 @@ void exactSnapshotSurvivesRollbackAndConcurrentRetryWithFullGraphReadback() thro WorldAuthoredGraphSnapshot firstSnapshot = first.get(20, TimeUnit.SECONDS); WorldAuthoredGraphSnapshot retrySnapshot = second.get(20, TimeUnit.SECONDS); assertThat(retrySnapshot.snapshotId()).isEqualTo(firstSnapshot.snapshotId()); + assertThat(retrySnapshot.digestSchemaVersion()).isEqualTo(3); assertThat(retrySnapshot.graphBytes()).containsExactly(firstSnapshot.graphBytes()); assertThat(retrySnapshot.ownerCommitProofStatus()) .isEqualTo(WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED); @@ -810,6 +826,299 @@ private WorldAuthoredGraphSnapshotCapture captureComponent() { dsl, draftDigestService, snapshotRepository, objectMapper); } + @Test + void retainedNumericSpawnSqlMappingAndPrimaryKeyDigestOrderRemainExact() { + Fixture fixture = fixture(false); + long first = positiveLong() / 2 + 1; + long second = first + 1; + ownerTransaction() + .execute( + status -> { + dsl.execute("SET LOCAL session_replication_role='replica'"); + for (long id : new long[] {Math.max(first, second), Math.min(first, second)}) { + dsl.execute( + "INSERT INTO world_entity_spawn_binding (id, tenant_id, version_id, room_id, entity_template_type, entity_template_id) " + + "SELECT ?, tenant_id, version_id, room_id, entity_template_type, entity_template_id + ? FROM world_entity_spawn_binding " + + "WHERE tenant_id=? AND version_id=? AND entity_template_id=?", + id, + id == first ? 1 : 2, + fixture.intakeReceipt().localTenantKey(), + fixture.localVersionKey(), + LARGE_VALUE); + } + dsl.execute("SET LOCAL session_replication_role='origin'"); + return null; + }); + var rows = + spawnRepository.findByTenantIdAndVersionIdOrderByIdAsc( + fixture.intakeReceipt().localTenantKey(), fixture.localVersionKey()); + assertThat(rows).hasSize(3); + assertThat( + rows.stream() + .map(net.firedevops.firemud.worldmanagement.entity.WorldEntitySpawnBinding::getId) + .toList()) + .isSorted(); + for (var row : rows) { + assertThat(row.getEntityTemplateId()).isPositive(); + assertThat(row.getEntityCanonicalTenantId()).isNull(); + assertThat(row.getEntityCanonicalVersionId()).isNull(); + assertThat(row.getEntityCanonicalTemplateId()).isNull(); + assertThat(spawnRepository.findById(row.getId()).orElseThrow()).isEqualTo(row); + } + var digest = + draftDigestService.getDraftDesignDigest( + Long.toString(fixture.intakeReceipt().localTenantKey()), + Long.toString(fixture.localVersionKey())); + assertThat(digest.digestSchemaVersion()).isEqualTo(3); + assertThat(digest) + .isEqualTo(draftDigestService.getDraftDesignDigest(digest.tenantId(), digest.scopeValue())); + assertGuardedSessionReplicationRole(); + } + + @Test + void newSchema2NumericSnapshotIsRejectedBeforeContentOrRevisionReads() { + Fixture fixture = fixture(false, false); + CaptureRequest r = fixture.request(); + CaptureRequest historical = + new CaptureRequest( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + r.publicationRequestId(), + r.requestDigest(), + r.versionStateEpoch(), + r.publishWorkflowId(), + r.appliedCommitId(), + r.contentDigest(), + 2, + r.suppliedOwnedAffectedTuples()); + Fixture old = + new Fixture( + historical, + fixture.localVersionKey(), + fixture.gameDesignVersionId(), + fixture.versionIdentityOperationId(), + fixture.intakeReceipt()); + CaptureRequest frozen = ownerTransaction().execute(status -> freezeOpenFixture(old)); + assertThatThrownBy( + () -> ownerTransaction().execute(status -> captureComponent().capture(frozen))) + .hasMessageContaining("requires digest schema 3"); + assertThat(snapshotCount(frozen.publicationFence())).isZero(); + } + + @Test + void mismatchedReturnedPrivateVersionDigestCannotCreateSnapshot() { + Fixture fixture = fixture(false); + var capture = + new WorldAuthoredGraphSnapshotCapture( + dsl, + (tenant, version) -> + new WorldDraftDesignDigest( + tenant, + Long.toString(fixture.localVersionKey() + 1), + fixture.request().appliedCommitId(), + fixture.request().contentDigest(), + 3), + snapshotRepository, + objectMapper); + assertThatThrownBy( + () -> ownerTransaction().execute(status -> capture.capture(fixture.request()))) + .hasMessageContaining("differs from the V25 frozen checkpoint"); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + } + + @Test + void v32PreservesOriginalSchema2SnapshotBytesAndExactRetry() throws Exception { + Fixture fixture = fixture(false); + WorldAuthoredGraphSnapshot original = + ownerTransaction().execute(status -> captureComponent().capture(fixture.request())); + CaptureRequest r = fixture.request(); + CaptureRequest historical = + new CaptureRequest( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + r.publicationRequestId(), + r.requestDigest(), + r.versionStateEpoch(), + r.publishWorkflowId(), + r.appliedCommitId(), + r.contentDigest(), + 2, + r.suppliedOwnedAffectedTuples()); + String schema = "retained_snapshot2_" + UUID.randomUUID().toString().replace("-", ""); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("28")) + .load() + .migrate(); + List tables = + List.of( + "world_authored_source_tenant_association", + "world_authored_source_intake", + "world_authored_version_identity", + "world_design_publication_fence_attempt", + "world_design_publication_fence_owner"); + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + DSLContext retained = DSL.using(connection, SQLDialect.POSTGRES); + retained.execute("SET search_path TO " + schema + ", public"); + connection.setAutoCommit(false); + retained.execute("SET LOCAL session_replication_role='replica'"); + for (String table : tables) { + String override = + table.equals("world_authored_version_identity") ? " OVERRIDING SYSTEM VALUE" : ""; + retained.execute( + "INSERT INTO " + + table + + override + + " SELECT * FROM world_management_service." + + table + + " WHERE local_tenant_key=?", + fixture.intakeReceipt().localTenantKey()); + } + retained.execute( + "INSERT INTO world_authored_source_tenant_key_reservation SELECT * " + + "FROM world_management_service.world_authored_source_tenant_key_reservation WHERE tenant_key=?", + fixture.intakeReceipt().localTenantKey()); + retained.execute( + "UPDATE world_design_publication_fence_attempt SET digest_schema_version=2 WHERE publication_fence=?", + r.publicationFence()); + // Install an original synthetic schema-2 capture under V28 before testing its forward + // migration. + retained.execute( + "INSERT INTO world_authored_graph_snapshot SELECT (jsonb_populate_record(NULL::world_authored_graph_snapshot, " + + "to_jsonb(t) || jsonb_build_object('digest_schema_version', 2, 'capture_request_digest', ?))).* " + + "FROM world_management_service.world_authored_graph_snapshot t WHERE publication_fence=?", + historicalCaptureDigest(original), + r.publicationFence()); + retained.execute("SET LOCAL session_replication_role='origin'"); + connection.commit(); + connection.setAutoCommit(true); + String before = + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_authored_graph_snapshot t"), + "expected retained schema-2 snapshot row") + .get(0, String.class); + String attemptBefore = + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_design_publication_fence_attempt t"), + "expected retained publication-fence attempt row") + .get(0, String.class); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat( + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_authored_graph_snapshot t"), + "expected retained schema-2 snapshot row") + .get(0, String.class)) + .isEqualTo(before); + assertThat( + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_design_publication_fence_attempt t"), + "expected retained publication-fence attempt row") + .get(0, String.class)) + .isEqualTo(attemptBefore); + var repo = new WorldAuthoredGraphSnapshotRepository(retained); + var capture = + new WorldAuthoredGraphSnapshotCapture( + retained, + (tenant, version) -> { + throw new AssertionError("Historical retry must never recompute content digest"); + }, + repo, + objectMapper); + var tx = + new TransactionTemplate( + new DataSourceTransactionManager(new SingleConnectionDataSource(connection, true))); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var recovered = tx.execute(status -> capture.capture(historical)); + assertThat(recovered.digestSchemaVersion()).isEqualTo(2); + assertThat(recovered.snapshotId()).isEqualTo(original.snapshotId()); + assertThat(recovered.graphBytes()).containsExactly(original.graphBytes()); + assertThat(recovered.ownerRevisionEvidenceJson()) + .isEqualTo(original.ownerRevisionEvidenceJson()); + assertThat( + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_authored_graph_snapshot t"), + "expected retained schema-2 snapshot row") + .get(0, String.class)) + .isEqualTo(before); + assertThatThrownBy(() -> tx.execute(status -> capture.capture(r))) + .isInstanceOf(SnapshotConflictException.class); + // INSERT-only guard rejects schema 2 (and unsupported values), preserving retained reads. + for (int denied : new int[] {2, 4}) { + assertThatThrownBy( + () -> + retained.execute( + "INSERT INTO world_authored_graph_snapshot SELECT " + + "(jsonb_populate_record(NULL::world_authored_graph_snapshot, to_jsonb(t) || jsonb_build_object('snapshot_id', ?, " + + "'digest_schema_version', ?))).* FROM world_authored_graph_snapshot t", + UUID.randomUUID(), + denied)) + .hasStackTraceContaining("requires digest schema 3"); + } + } finally { + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private String historicalCaptureDigest(WorldAuthoredGraphSnapshot snapshot) throws Exception { + // Independent original V28 capture-request preimage: exact ordered fields, no mutable content. + var fields = objectMapper.valueToTree(snapshot); + Map binding = new LinkedHashMap<>(); + for (String name : + List.of( + "targetNamespace", + "canonicalTenantId", + "canonicalVersionId", + "versionIdentityOperationId", + "worldSlug", + "gameDesignVersionId", + "localVersionKey", + "localTenantKey", + "intakeOperationId", + "intakeRequestId", + "intakeRequestDigest", + "sourceOperationId", + "sourceEvidenceDigest", + "intakeReceiptDigest", + "publicationFence", + "publicationRequestId", + "requestDigest", + "versionStateEpoch", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "suppliedOwnedAffectedTuplesJson")) { + binding.put(name, name.equals("digestSchemaVersion") ? 2 : fields.get(name)); + } + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(objectMapper.writeValueAsBytes(binding))); + } + private WorldAuthoredGraphSnapshot captureWithGuardedSessionRole( WorldAuthoredGraphSnapshotCapture capture, CaptureRequest request) { assertGuardedSessionReplicationRole(); 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 index acdfd1a4ae..9436b9c4c4 100644 --- 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 @@ -930,7 +930,7 @@ private static CompleteLaunchBindingEvidence evidence( String commit = "commit-launch-binding"; List participants = List.of( - participant("WORLD_MANAGEMENT", 2, "a", false, commit), + participant("WORLD_MANAGEMENT", 3, "a", false, commit), participant("ENTITY_MANAGEMENT", 2, "b", false, commit), participant("GAME_LOGIC", 1, "c", true, commit), participant("AUTOMATION_SCRIPTING", 5, "d", false, commit), diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java index 02801037d3..38117d1a40 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java @@ -60,7 +60,7 @@ class WorldDesignPublicationFenceIntegrationTest { private static final long GAME_DESIGN_VERSION_A = 9_000_000_042L; private static final long GAME_DESIGN_VERSION_B = 9_000_000_043L; private static final Checkpoint SYNTHETIC_CHECKPOINT = - new Checkpoint("synthetic-commit-42", "c".repeat(64), 2); + new Checkpoint("synthetic-commit-42", "c".repeat(64), 3); @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -112,6 +112,7 @@ void rollbackAndCommittedExactReadbackRetainOneImmutableAttempt() { .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT)); assertThat(frozen).isNotNull(); assertThat(repository.readAttempt(request)).contains(frozen); + assertThat(frozen.checkpoint().digestSchemaVersion()).isEqualTo(3); assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo("FROZEN"); WorldAuthoredVersionIdentityReceipt identity = identity(receipt, GAME_DESIGN_VERSION_A); assertThat(identity.localVersionKey()).isNotEqualTo(GAME_DESIGN_VERSION_A); @@ -142,7 +143,7 @@ void rollbackAndCommittedExactReadbackRetainOneImmutableAttempt() { request, () -> { retryRecapturedCheckpoint.set(true); - return new Checkpoint("synthetic-new-commit", "d".repeat(64), 3); + return new Checkpoint("synthetic-new-commit", "d".repeat(64), 2); })); assertThat(retry).isEqualTo(frozen); assertThat(retryRecapturedCheckpoint).isFalse(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldLifecyclePreparationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldLifecyclePreparationPostgresIntegrationTest.java new file mode 100644 index 0000000000..484f189ee7 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldLifecyclePreparationPostgresIntegrationTest.java @@ -0,0 +1,610 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; +import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; +import net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +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.PreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; +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.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof for the legacy numeric lifecycle prepare component and its local transaction. + * The Game Design release and version responses below are synthetic test evidence; this test does + * not establish authored publication authority or PREPARING eligibility. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = {"spring.grpc.server.port=0"}) +class WorldLifecyclePreparationPostgresIntegrationTest { + private static final long RELEASE_BUNDLE_ID = 7301L; + private static final long VERSION_STATE_EPOCH = 91L; + private static final String RELEASE_BUNDLE_REF = "synthetic-release-bundle-ref"; + private static final String MANIFEST_HASH = "synthetic-manifest-hash"; + private static final String GENERATION_CONFIG_REVISION = "synthetic-generation-revision"; + + @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 WorldLifecycleCommandService lifecycleCommandService; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void materializesEverySelectedLegacyRowAndExactRetryAddsNoRows() { + long tenantId = uniquePositiveKey(); + long versionId = uniquePositiveKey(); + long gameInstanceId = uniquePositiveKey(); + TopologyFixture topology = insertSelectedTopology(tenantId, versionId); + insertOutOfScopeTopology(tenantId, versionId + 1L); + AuthoredRows authoredBefore = authoredRows(tenantId); + PreparedWorldInstanceRequest request = request(tenantId, versionId, gameInstanceId); + stubPublishedEvidence(tenantId, versionId); + + var prepared = lifecycleCommandService.prepareWorldInstance(request); + + assertThat(prepared.status()).isEqualTo("PREPARING"); + assertThat(prepared.lifecycleEpoch()).isEqualTo(1L); + long worldInstanceId = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT id FROM world_instance WHERE tenant_id = ? AND game_instance_id = ?", + tenantId, + gameInstanceId) + .fetchOne(0, Long.class)); + long regionInstanceId = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT id FROM region_instance WHERE tenant_id = ? AND game_instance_id = ?", + tenantId, + gameInstanceId) + .fetchOne(0, Long.class)); + assertThat(worldInstanceId).isPositive(); + assertThat(regionInstanceId).isPositive(); + assertThat( + dsl.resultQuery( + "SELECT world_instance_id FROM region_instance WHERE id = ?", regionInstanceId) + .fetchOne(0, Long.class)) + .isEqualTo(worldInstanceId); + + List actualZones = runtimeZones(tenantId, gameInstanceId); + assertThat(actualZones) + .containsExactlyInAnyOrderElementsOf( + topology.zones().stream() + .map( + zone -> + new RuntimeZone( + tenantId, + gameInstanceId, + zone.id(), + zone.id(), + regionInstanceId, + zone.name())) + .toList()); + + List actualRooms = runtimeRooms(tenantId, gameInstanceId); + assertThat(actualRooms) + .containsExactlyInAnyOrderElementsOf( + topology.rooms().stream() + .map( + room -> + new RuntimeRoom( + tenantId, + gameInstanceId, + room.id(), + room.id(), + room.zoneId(), + room.name(), + room.description())) + .toList()); + + List actualExits = runtimeExits(tenantId, gameInstanceId); + assertThat(actualExits) + .containsExactlyInAnyOrderElementsOf( + topology.exits().stream() + .map( + exit -> + new RuntimeExit( + tenantId, + gameInstanceId, + exit.fromRoomId(), + exit.toRoomId(), + exit.direction(), + exit.cost())) + .toList()); + + RuntimeRows firstRuntimeRows = runtimeRows(tenantId, gameInstanceId); + assertThat(firstRuntimeRows.worlds()).hasSize(1); + assertThat(firstRuntimeRows.regions()).hasSize(1); + var retry = lifecycleCommandService.prepareWorldInstance(request); + + assertThat(retry).isEqualTo(prepared); + assertThat(runtimeRows(tenantId, gameInstanceId)).isEqualTo(firstRuntimeRows); + assertThat(authoredRows(tenantId)).isEqualTo(authoredBefore); + verify(gameDesignClient, times(1)).getPublishedReleaseBundle(tenantId, versionId); + verify(gameDesignClient, times(1)).getVersionAssetArtifactState(tenantId, versionId); + verify(gameDesignClient, times(1)).getVersionState(tenantId, versionId); + } + + @Test + void rejectsSelectedRoomWhoseZoneBelongsToAnotherVersionBeforeRuntimeWrites() { + long tenantId = uniquePositiveKey(); + long versionId = uniquePositiveKey(); + long gameInstanceId = uniquePositiveKey(); + long regionId = insertRegion(tenantId, versionId, "selected-region"); + insertZone(tenantId, versionId, regionId, "selected-zone"); + long wrongVersionZoneId = insertZone(tenantId, versionId + 1L, regionId, "other-version-zone"); + insertRoom(tenantId, versionId, wrongVersionZoneId, "mis-scoped-room", "authored"); + AuthoredRows authoredBefore = authoredRows(tenantId); + stubPublishedEvidence(tenantId, versionId); + + Throwable failure = + catchThrowable( + () -> + lifecycleCommandService.prepareWorldInstance( + request(tenantId, versionId, gameInstanceId))); + + assertThat(failure) + .isNotNull() + .hasMessageContaining("FAILED_PRECONDITION: INCOMPLETE_WORLD_TOPOLOGY") + .hasMessageContaining("references a missing selected zone"); + assertNoRuntimeRows(tenantId, gameInstanceId); + assertThat(authoredRows(tenantId)).isEqualTo(authoredBefore); + } + + @Test + void rejectsSelectedExitWhoseEndpointBelongsToAnotherVersionBeforeRuntimeWrites() { + long tenantId = uniquePositiveKey(); + long versionId = uniquePositiveKey(); + long gameInstanceId = uniquePositiveKey(); + long regionId = insertRegion(tenantId, versionId, "selected-region"); + long zoneId = insertZone(tenantId, versionId, regionId, "selected-zone"); + long selectedRoomId = insertRoom(tenantId, versionId, zoneId, "selected-room", "selected"); + long otherVersionRoomId = + insertRoom(tenantId, versionId + 1L, zoneId, "other-version-room", "unselected"); + insertExit(tenantId, versionId, selectedRoomId, otherVersionRoomId, "NORTH", 3); + AuthoredRows authoredBefore = authoredRows(tenantId); + stubPublishedEvidence(tenantId, versionId); + + Throwable failure = + catchThrowable( + () -> + lifecycleCommandService.prepareWorldInstance( + request(tenantId, versionId, gameInstanceId))); + + assertThat(failure) + .isNotNull() + .hasMessageContaining("FAILED_PRECONDITION: INCOMPLETE_WORLD_TOPOLOGY") + .hasMessageContaining("exit to room is not in the selected topology"); + assertNoRuntimeRows(tenantId, gameInstanceId); + assertThat(authoredRows(tenantId)).isEqualTo(authoredBefore); + } + + @Test + void lateExitPersistenceFailureRollsBackWorldAndAllEarlierRuntimeRows() { + long tenantId = uniquePositiveKey(); + long versionId = uniquePositiveKey(); + long gameInstanceId = uniquePositiveKey(); + TopologyFixture topology = insertSelectedTopology(tenantId, versionId); + AuthoredRows authoredBefore = authoredRows(tenantId); + stubPublishedEvidence(tenantId, versionId); + String suffix = UUID.randomUUID().toString().replace("-", ""); + String functionName = "w_test_late_exit_" + suffix; + String triggerName = "t_test_late_exit_" + suffix; + Throwable failure; + try { + createLateExitFailureTrigger(functionName, triggerName, tenantId, gameInstanceId, topology); + failure = + catchThrowable( + () -> + lifecycleCommandService.prepareWorldInstance( + request(tenantId, versionId, gameInstanceId))); + } finally { + dsl.execute("DROP TRIGGER IF EXISTS " + triggerName + " ON room_instance_exit"); + dsl.execute("DROP FUNCTION IF EXISTS " + functionName + "()"); + } + + assertThat(failure).isNotNull(); + assertThat(exceptionMessages(failure)).contains("forced late runtime exit persistence failure"); + assertNoRuntimeRows(tenantId, gameInstanceId); + assertThat(authoredRows(tenantId)).isEqualTo(authoredBefore); + } + + private void stubPublishedEvidence(long tenantId, long versionId) { + when(gameDesignClient.getPublishedReleaseBundle(tenantId, versionId)) + .thenReturn( + GetPublishedReleaseBundleResponse.newBuilder() + .setBundle( + PublishedReleaseBundle.newBuilder() + .setId(RELEASE_BUNDLE_ID) + .setVersionId(versionId) + .setAttestationSchemaVersion("v1") + .setManifestHash(MANIFEST_HASH) + .addRequiredManifestAssetKeys("manifest.json") + .setGenerationConfigRevision(GENERATION_CONFIG_REVISION) + .setPublishedReleaseBundleRef(RELEASE_BUNDLE_REF) + .build()) + .build()); + when(gameDesignClient.getVersionAssetArtifactState(tenantId, versionId)) + .thenReturn( + GetVersionAssetArtifactStateResponse.newBuilder() + .setArtifactState( + VersionAssetArtifactState.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setVersionId(versionId) + .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setStateEpoch(4L) + .setManifestHash(MANIFEST_HASH) + .addExportedManifestAssetKeys("manifest.json") + .build()) + .build()); + when(gameDesignClient.getVersionState(tenantId, versionId)) + .thenReturn( + GetVersionStateResponse.newBuilder() + .setVersionState( + VersionStateSnapshot.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setVersionId(versionId) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(VERSION_STATE_EPOCH) + .build()) + .build()); + } + + private PreparedWorldInstanceRequest request(long tenantId, long versionId, long gameInstanceId) { + return new PreparedWorldInstanceRequest( + tenantId, + gameInstanceId, + versionId + 100L, + "prepare-" + gameInstanceId, + "descriptor-" + gameInstanceId, + versionId, + "script-patch-" + versionId, + "{}", + GENERATION_CONFIG_REVISION, + RELEASE_BUNDLE_ID, + RELEASE_BUNDLE_REF, + VERSION_STATE_EPOCH); + } + + private TopologyFixture insertSelectedTopology(long tenantId, long versionId) { + long regionId = insertRegion(tenantId, versionId, "selected-region"); + long westZoneId = insertZone(tenantId, versionId, regionId, "West Wing"); + long eastZoneId = insertZone(tenantId, versionId, regionId, "East Wing"); + long antechamberId = + insertRoom(tenantId, versionId, westZoneId, "Antechamber", "A quiet stone room."); + long smithyId = insertRoom(tenantId, versionId, westZoneId, "Smithy", "A warm forge."); + long gardenId = insertRoom(tenantId, versionId, eastZoneId, "Garden", "A walled garden."); + List exits = + List.of( + new ExitSpec(antechamberId, smithyId, "NORTH", 2), + new ExitSpec(smithyId, antechamberId, "SOUTH", 2), + new ExitSpec(gardenId, antechamberId, "WEST", 4)); + for (ExitSpec exit : exits) { + insertExit( + tenantId, versionId, exit.fromRoomId(), exit.toRoomId(), exit.direction(), exit.cost()); + } + return new TopologyFixture( + List.of(new ZoneSpec(westZoneId, "West Wing"), new ZoneSpec(eastZoneId, "East Wing")), + List.of( + new RoomSpec(antechamberId, westZoneId, "Antechamber", "A quiet stone room."), + new RoomSpec(smithyId, westZoneId, "Smithy", "A warm forge."), + new RoomSpec(gardenId, eastZoneId, "Garden", "A walled garden.")), + exits); + } + + private void insertOutOfScopeTopology(long tenantId, long otherVersionId) { + long regionId = insertRegion(tenantId, otherVersionId, "other-version-region"); + long zoneId = insertZone(tenantId, otherVersionId, regionId, "Other Version Zone"); + insertRoom(tenantId, otherVersionId, zoneId, "Other Version Room", "out of scope"); + } + + private long insertRegion(long tenantId, long versionId, String name) { + return insertedId( + "INSERT INTO region (tenant_id, version_id, name) VALUES (?, ?, ?) RETURNING id", + tenantId, + versionId, + name); + } + + private long insertZone(long tenantId, long versionId, long regionId, String name) { + return insertedId( + "INSERT INTO zone (tenant_id, version_id, region_id, name) VALUES (?, ?, ?, ?) RETURNING id", + tenantId, + versionId, + regionId, + name); + } + + private long insertRoom( + long tenantId, long versionId, long zoneId, String name, String description) { + return insertedId( + "INSERT INTO room (tenant_id, version_id, zone_id, name, description) " + + "VALUES (?, ?, ?, ?, ?) RETURNING id", + tenantId, + versionId, + zoneId, + name, + description); + } + + private long insertExit( + long tenantId, long versionId, long fromRoomId, long toRoomId, String direction, int cost) { + return insertedId( + "INSERT INTO room_exit (tenant_id, version_id, from_room_id, to_room_id, direction, cost) " + + "VALUES (?, ?, ?, ?, ?, ?) RETURNING id", + tenantId, + versionId, + fromRoomId, + toRoomId, + direction, + cost); + } + + private long insertedId(String sql, Object... values) { + Record row = + Objects.requireNonNull(dsl.fetchOne(sql, values), "authored insert must return its row"); + return row.get("id", Long.class); + } + + private AuthoredRows authoredRows(long tenantId) { + return new AuthoredRows( + authoredTableRows("region", tenantId), + authoredTableRows("zone", tenantId), + authoredTableRows("room", tenantId), + authoredTableRows("room_exit", tenantId)); + } + + private List> authoredTableRows(String tableName, long tenantId) { + return dsl.fetch("SELECT * FROM " + tableName + " WHERE tenant_id = ? ORDER BY id", tenantId) + .intoMaps(); + } + + private List runtimeZones(long tenantId, long gameInstanceId) { + return dsl.fetch( + "SELECT tenant_id, game_instance_id, zone_instance_id, template_zone_id, " + + "region_instance_id, name FROM zone_instance " + + "WHERE tenant_id = ? OR game_instance_id = ? ORDER BY id", + tenantId, + gameInstanceId) + .map( + row -> + new RuntimeZone( + row.get("tenant_id", Long.class), + row.get("game_instance_id", Long.class), + row.get("zone_instance_id", Long.class), + row.get("template_zone_id", Long.class), + row.get("region_instance_id", Long.class), + row.get("name", String.class))); + } + + private List runtimeRooms(long tenantId, long gameInstanceId) { + return dsl.fetch( + "SELECT r.tenant_id, r.game_instance_id, r.room_instance_row_id, " + + "r.template_room_id, z.template_zone_id, r.name, r.description " + + "FROM room_instance r JOIN zone_instance z ON z.id = r.zone_instance_id " + + "WHERE r.tenant_id = ? OR r.game_instance_id = ? ORDER BY r.id", + tenantId, + gameInstanceId) + .map( + row -> + new RuntimeRoom( + row.get("tenant_id", Long.class), + row.get("game_instance_id", Long.class), + row.get("room_instance_row_id", Long.class), + row.get("template_room_id", Long.class), + row.get("template_zone_id", Long.class), + row.get("name", String.class), + row.get("description", String.class))); + } + + private List runtimeExits(long tenantId, long gameInstanceId) { + return dsl.fetch( + "SELECT e.tenant_id, e.game_instance_id, f.room_instance_row_id AS from_room_id, " + + "t.room_instance_row_id AS to_room_id, e.direction, e.cost " + + "FROM room_instance_exit e " + + "JOIN room_instance f ON f.id = e.from_room_instance_record_id " + + "JOIN room_instance t ON t.id = e.to_room_instance_record_id " + + "WHERE e.tenant_id = ? OR e.game_instance_id = ? ORDER BY e.id", + tenantId, + gameInstanceId) + .map( + row -> + new RuntimeExit( + row.get("tenant_id", Long.class), + row.get("game_instance_id", Long.class), + row.get("from_room_id", Long.class), + row.get("to_room_id", Long.class), + row.get("direction", String.class), + row.get("cost", Integer.class))); + } + + private RuntimeRows runtimeRows(long tenantId, long gameInstanceId) { + return new RuntimeRows( + runtimeTableRows("world_instance", tenantId, gameInstanceId), + runtimeTableRows("region_instance", tenantId, gameInstanceId), + runtimeTableRows("zone_instance", tenantId, gameInstanceId), + runtimeTableRows("room_instance", tenantId, gameInstanceId), + runtimeTableRows("room_instance_exit", tenantId, gameInstanceId)); + } + + private List> runtimeTableRows( + String tableName, long tenantId, long gameInstanceId) { + return dsl.fetch( + "SELECT * FROM " + + tableName + + " WHERE tenant_id = ? OR game_instance_id = ? ORDER BY id", + tenantId, + gameInstanceId) + .intoMaps(); + } + + private void assertNoRuntimeRows(long tenantId, long gameInstanceId) { + RuntimeRows rows = runtimeRows(tenantId, gameInstanceId); + assertThat(rows.worlds()).isEmpty(); + assertThat(rows.regions()).isEmpty(); + assertThat(rows.zones()).isEmpty(); + assertThat(rows.rooms()).isEmpty(); + assertThat(rows.exits()).isEmpty(); + } + + private void createLateExitFailureTrigger( + String functionName, + String triggerName, + long tenantId, + long gameInstanceId, + TopologyFixture topology) { + String functionSql = + "CREATE FUNCTION " + + functionName + + "() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN " + + "IF NEW.tenant_id = " + + tenantId + + " AND NEW.game_instance_id = " + + gameInstanceId + + " THEN " + + "IF NOT EXISTS (SELECT 1 FROM world_instance WHERE tenant_id = " + + tenantId + + " AND game_instance_id = " + + gameInstanceId + + ") OR NOT EXISTS (SELECT 1 FROM region_instance WHERE tenant_id = " + + tenantId + + " AND game_instance_id = " + + gameInstanceId + + ") OR (SELECT count(*) FROM zone_instance WHERE tenant_id = " + + tenantId + + " AND game_instance_id = " + + gameInstanceId + + ") <> " + + topology.zones().size() + + " OR (SELECT count(*) FROM room_instance WHERE tenant_id = " + + tenantId + + " AND game_instance_id = " + + gameInstanceId + + ") <> " + + topology.rooms().size() + + " THEN RAISE EXCEPTION 'late exit trigger did not observe earlier runtime writes'; " + + "END IF; RAISE EXCEPTION 'forced late runtime exit persistence failure'; " + + "END IF; RETURN NEW; END; $$"; + dsl.execute(functionSql); + dsl.execute( + "CREATE TRIGGER " + + triggerName + + " BEFORE INSERT ON room_instance_exit FOR EACH ROW EXECUTE FUNCTION " + + functionName + + "()"); + } + + private String exceptionMessages(Throwable failure) { + StringBuilder messages = new StringBuilder(); + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current.getMessage() != null) { + messages.append(current.getMessage()).append('\n'); + } + } + return messages.toString(); + } + + private static long uniquePositiveKey() { + return 8_000_000_000L + Math.abs(UUID.randomUUID().getLeastSignificantBits() % 1_000_000_000L); + } + + private record ZoneSpec(long id, String name) {} + + private record RoomSpec(long id, long zoneId, String name, String description) {} + + private record ExitSpec(long fromRoomId, long toRoomId, String direction, int cost) {} + + private record TopologyFixture( + List zones, List rooms, List exits) {} + + private record AuthoredRows( + List> regions, + List> zones, + List> rooms, + List> exits) {} + + private record RuntimeZone( + long tenantId, + long gameInstanceId, + long zoneInstanceId, + long templateZoneId, + long regionInstanceId, + String name) {} + + private record RuntimeRoom( + long tenantId, + long gameInstanceId, + long roomInstanceRowId, + long templateRoomId, + long templateZoneId, + String name, + String description) {} + + private record RuntimeExit( + long tenantId, + long gameInstanceId, + long fromRoomId, + long toRoomId, + String direction, + int cost) {} + + private record RuntimeRows( + List> worlds, + List> regions, + List> zones, + List> rooms, + List> exits) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java new file mode 100644 index 0000000000..b4971c9f3c --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java @@ -0,0 +1,1173 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.sql.DriverManager; +import java.util.ArrayList; +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.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +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.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +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.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +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; +import tools.jackson.databind.ObjectMapper; + +/** + * Actual V30 rows and V31/V32 capture, with synthetic source/permission and computed schema-3 V25 + * content checkpoints. Selected commit identities remain synthetic complete-application evidence. + * Fixture-only trigger bypasses model terminal/corrupt storage unavailable through the current + * owner API; origin triggers are restored before every tested capture/read boundary. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldCanonicalFrozenTopologyPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final long GAME_DESIGN_VERSION = 9_000_000_000_000_001L; + + @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 manager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository fence; + @Autowired private WorldAuthoredGraphSnapshotRepository snapshots; + @Autowired private ObjectMapper mapper; + + @Autowired + private net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository + spawnRepository; + + @Autowired + private net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService + digestService; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void capturesActualSixFamilyGraphAndOriginalFullInputWithExactRetry() { + Fixture f = fixture(); + var p = plan(f); + var stored = component().store(p); + Request request = freeze(p); + var capture = frozen().capture(request); + assertThat(capture.status()).isEqualTo("CAPTURED_UNVERIFIED"); + assertThat(capture.request().freeze().digestSchemaVersion()).isEqualTo(3); + assertThat(capture.graphBytes()).containsExactly(stored.graphBytes()); + assertThat(capture.storageResultBytes()).containsExactly(stored.resultBytes()); + assertThat(capture.request().plan().binding().canonicalBytes()) + .containsExactly(p.binding().canonicalBytes()); + assertThat(capture.sourceIdentity()).isEqualTo(f.version()); + assertThat(capture.graph().rows()).hasSize(7); + assertThat(capture.graph().family(Family.ROOM)).hasSize(2); + for (Family family : Family.values()) assertThat(capture.graph().family(family)).isNotEmpty(); + var region = capture.graph().family(Family.REGION).getFirst(); + var spawn = capture.graph().family(Family.WORLD_ENTITY_SPAWN_BINDING).getFirst(); + assertThat(region.content().getRegion().getSpacingMultiplier()).isEqualTo(1.0); + assertThat(spawn.content().getWorldEntitySpawnBinding().getSpawnCount()).isEqualTo(1); + assertThat(spawn.entityReference()).isEqualTo(p.graph().nodes().getFirst().entityReference()); + assertThat( + capture.graph().family(Family.ROOM_EXIT).getFirst().content().getRoomExit().getCost()) + .isEqualTo(1); + assertThat(new String(capture.resultBytes(), StandardCharsets.UTF_8)) + .contains( + "ACCOUNT_AUTHORIZATION", "COMPLETE_PARTICIPANT_COMMIT", "PUBLICATION_CHECKPOINT_DIGEST") + .doesNotContain("\"APPLIED\"", "permissionFenceReleased", "\"PREPARING\""); + byte[] exposed = capture.graphBytes(); + exposed[0] = 0; + assertThat(capture.graphBytes()).containsExactly(stored.graphBytes()); + assertThat(frozen().capture(request).resultBytes()).containsExactly(capture.resultBytes()); + assertThat(countCaptures(request)).isEqualTo(1); + assertOrigin(); + } + + @Test + void canonicalSpawnSqlMappingIsLosslessAndProducesSchema3DigestWithoutWriteBypass() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + var spawns = + spawnRepository.findByTenantIdAndVersionIdOrderByIdAsc( + f.intake().localTenantKey(), f.version().localVersionKey()); + assertThat(spawns).hasSize(1); + var spawn = spawns.getFirst(); + var row = dsl.fetchOne("SELECT * FROM world_entity_spawn_binding WHERE id=?", spawn.getId()); + assertThat(spawn.getEntityTemplateId()).isNull(); + assertThat(spawn.getEntityCanonicalTenantId()) + .isEqualTo(row.get("entity_canonical_tenant_id", UUID.class)); + assertThat(spawn.getEntityCanonicalVersionId()) + .isEqualTo(row.get("entity_canonical_version_id", UUID.class)); + assertThat(spawn.getEntityCanonicalTemplateId()) + .isEqualTo(row.get("entity_canonical_template_id", UUID.class)); + var digest = + digestService.getDraftDesignDigest( + Long.toString(spawn.getTenantId()), Long.toString(spawn.getVersionId())); + assertThat(digest.digestSchemaVersion()).isEqualTo(3); + assertThat(digest.contentDigest()).matches("[0-9a-f]{64}"); + assertThat(spawnRepository.findById(spawn.getId()).orElseThrow()).isEqualTo(spawn); + assertThatThrownBy(() -> spawnRepository.save(spawn)).isInstanceOf(RuntimeException.class); + assertThat(spawnRepository.findById(spawn.getId()).orElseThrow()).isEqualTo(spawn); + assertOrigin(); + } + + @Test + void freshSchema2CaptureIsDeniedByApplicationAndDatabase() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p, 2); + assertThat(frozen().readCommitted(request)).isEmpty(); + assertThatThrownBy(() -> frozen().capture(request)) + .hasMessageContaining("requires digest schema 3"); + assertThat(countCaptures(request)).isZero(); + var templatePlan = plan(fixture()); + component().store(templatePlan); + Request template = freeze(templatePlan); + // Supply a complete otherwise-valid insertion from an existing schema-3 journal. + frozen().capture(template); + for (int denied : new int[] {2, 4}) { + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO world_canonical_frozen_topology SELECT (jsonb_populate_record(NULL::world_canonical_frozen_topology, " + + "to_jsonb(t) || jsonb_build_object('capture_id', ?, 'freeze_request_json', " + + "replace(freeze_request_json, '\"digestSchemaVersion\":3', ?)))).* " + + "FROM world_canonical_frozen_topology t WHERE publication_fence=?", + UUID.randomUUID(), + "\"digestSchemaVersion\":" + denied, template.freeze().publicationFence())) + .hasStackTraceContaining("requires digest schema 3"); + } + assertOrigin(); + } + + @Test + void newSchema3CaptureRejectsChangedContentDigestAndEveryReturnedScopeField() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + for (int changed = 0; changed < 4; changed++) { + int field = changed; + var bad = + frozen( + (tenant, version) -> + new net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService + .WorldDraftDesignDigest( + field == 0 ? "999999999" : tenant, + field == 1 ? "999999999" : version, + "version:" + version, + field == 2 ? "c".repeat(64) : request.freeze().contentDigest(), + field == 3 ? 2 : 3)); + assertThatThrownBy(() -> bad.capture(request)) + .hasMessageContaining("differs from exact schema-3 frozen content checkpoint"); + assertThat(countCaptures(request)).isZero(); + } + var captured = frozen().capture(request); + assertThat(captured.request().freeze().digestSchemaVersion()).isEqualTo(3); + assertThat( + frozen( + (tenant, version) -> { + throw new AssertionError("Exact retry must use retained journal"); + }) + .capture(request) + .resultBytes()) + .containsExactly(captured.resultBytes()); + } + + @Test + void changedCompleteBindingOrAnyFreezeCheckpointFieldCannotReplayCapture() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request original = freeze(p); + frozen().capture(original); + var b = p.binding(); + var changed = + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + b.target(), + b.requestId(), + b.commitId(), + b.baseCommitId() + "-changed", + b.revisions(), + b.affectedUnits()), + p.ownerBinding()); + assertThatThrownBy(() -> frozen().readCommitted(new Request(changed, original.freeze()))) + .hasMessageContaining("changed complete input"); + CaptureRequest r = original.freeze(); + for (CaptureRequest bad : + List.of( + copy( + r, + r.requestDigest(), + r.contentDigest(), + r.versionStateEpoch() + 1, + r.publicationRequestId(), + r.publishWorkflowId()), + copy( + r, + "c".repeat(64), + r.contentDigest(), + r.versionStateEpoch(), + r.publicationRequestId(), + r.publishWorkflowId()), + copy( + r, + r.requestDigest(), + "c".repeat(64), + r.versionStateEpoch(), + r.publicationRequestId(), + r.publishWorkflowId()), + copy( + r, + r.requestDigest(), + r.contentDigest(), + r.versionStateEpoch(), + r.publicationRequestId() + "-changed", + r.publishWorkflowId() + "-changed"))) { + assertThatThrownBy(() -> frozen().capture(new Request(p, bad))) + .isInstanceOf(RuntimeException.class); + } + assertThat(countCaptures(original)).isEqualTo(1); + } + + @Test + void historicalReadAndExactRetryAfterEveryTerminalPhaseUseOnlyOriginalJournal() { + for (String phase : List.of("PUBLISHED", "ABORTED", "RECONCILIATION_REQUIRED")) { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + byte[] original = frozen().capture(request).resultBytes(); + bypass( + "UPDATE world_design_publication_fence_owner SET owner_freeze_phase=? WHERE local_tenant_key=?", + phase, + f.intake().localTenantKey()); + bypass( + "UPDATE region SET weather='corrupt-current-row' WHERE tenant_id=?", + f.intake().localTenantKey()); + bypass( + "UPDATE world_topology_draft_commit SET result_bytes='corrupt-original-history'::bytea WHERE request_id=?", + p.binding().requestId()); + assertThat(frozen().readCommitted(request).orElseThrow().resultBytes()) + .containsExactly(original); + assertThat(frozen().capture(request).resultBytes()).containsExactly(original); + assertThat(countCaptures(request)).isEqualTo(1); + assertOrigin(); + } + } + + @Test + void noNewCaptureAfterTerminalAndAbsentJournalRemainsUnknown() { + for (String phase : List.of("PUBLISHED", "ABORTED", "RECONCILIATION_REQUIRED")) { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + bypass( + "UPDATE world_design_publication_fence_owner SET owner_freeze_phase=? WHERE local_tenant_key=?", + phase, + f.intake().localTenantKey()); + assertThat(frozen().readCommitted(request)).isEmpty(); + assertThatThrownBy(() -> frozen().capture(request)).hasMessageContaining("current FROZEN"); + assertThat(countCaptures(request)).isZero(); + } + } + + @Test + void captureRejectsActualRowTamperingAndMismatchedCurrentFenceBeforeJournalInsert() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + bypass("UPDATE room_exit SET cost=99 WHERE tenant_id=?", f.intake().localTenantKey()); + assertThatThrownBy(() -> frozen().capture(request)).hasMessageContaining("payload field"); + assertThat(countCaptures(request)).isZero(); + Fixture second = fixture(); + var secondPlan = plan(second); + component().store(secondPlan); + Request exact = freeze(secondPlan); + bypass( + "UPDATE world_design_publication_fence_owner SET current_publication_fence=? WHERE local_tenant_key=?", + UUID.randomUUID(), + second.intake().localTenantKey()); + assertThatThrownBy(() -> frozen().capture(exact)) + .hasMessageContaining("retained V25 owner binding"); + assertThat(countCaptures(exact)).isZero(); + } + + @Test + void frozenCheckpointWithoutCommittedCompleteStorageCannotCreateCapture() { + Fixture f = fixture(); + var p = plan(f); + Request request = freeze(p); + assertThat(frozen().readCommitted(request)).isEmpty(); + assertThatThrownBy(() -> frozen().capture(request)) + .hasMessageContaining("no committed complete topology result"); + assertThat(countCaptures(request)).isZero(); + } + + @Test + void v31UpgradePreservesExistingV30SourceRowsMappingsResultsAndFrozenCheckpoint() + throws Exception { + Fixture f = fixture(); + var p = plan(f); + var stored = component().store(p); + Request request = freeze(p); + String schema = "retained_capture_" + UUID.randomUUID().toString().replace("-", ""); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("30")) + .load() + .migrate(); + Map tables = new LinkedHashMap<>(); + for (String table : + List.of( + "world_authored_source_tenant_association", + "world_authored_source_intake", + "world_authored_version_identity", + "world_design_publication_fence_attempt", + "world_design_publication_fence_owner", + "world_topology_draft_commit")) tables.put(table, "local_tenant_key"); + tables.put("world_authored_source_tenant_key_reservation", "tenant_key"); + for (String table : + List.of( + "world_authored_topology_identity", + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_design_aggregate_epoch", + "world_design_scope_epoch")) { + tables.put(table, "tenant_id"); + } + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + DSLContext retained = DSL.using(connection, SQLDialect.POSTGRES); + retained.execute("SET search_path TO " + schema + ", public"); + connection.setAutoCommit(false); + retained.execute("SET LOCAL session_replication_role='replica'"); + for (var table : tables.entrySet()) { + String override = + table.getKey().equals("world_authored_version_identity") + ? " OVERRIDING SYSTEM VALUE" + : ""; + retained.execute( + "INSERT INTO " + + table.getKey() + + override + + " SELECT * FROM world_management_service." + + table.getKey() + + " WHERE " + + table.getValue() + + "=?", + f.intake().localTenantKey()); + } + retained.execute("SET LOCAL session_replication_role='origin'"); + connection.commit(); + connection.setAutoCommit(true); + Map> before = retainedRows(retained, tables); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat(retainedRows(retained, tables)).isEqualTo(before); + assertThat( + retained + .resultQuery("SELECT count(*) FROM world_canonical_frozen_topology") + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + retained + .resultQuery("SELECT graph_bytes FROM world_topology_draft_commit") + .fetchOne(0, byte[].class)) + .containsExactly(stored.graphBytes()); + assertThat( + retained + .resultQuery("SELECT result_bytes FROM world_topology_draft_commit") + .fetchOne(0, byte[].class)) + .containsExactly(stored.resultBytes()); + assertThat( + retained + .resultQuery( + "SELECT publication_fence FROM world_design_publication_fence_attempt") + .fetchOne(0, UUID.class)) + .isEqualTo(request.freeze().publicationFence()); + } finally { + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private Map> retainedRows(DSLContext database, Map tables) { + Map> rows = new LinkedHashMap<>(); + for (String table : tables.keySet()) { + rows.put( + table, + database + .resultQuery( + "SELECT to_jsonb(t)::text FROM " + table + " t ORDER BY to_jsonb(t)::text") + .fetch(0, String.class)); + } + return rows; + } + + @Test + void immutableJournalDeniesWritesAndHistoricalReadRejectsEveryTamperedField() { + Map mutations = new LinkedHashMap<>(); + mutations.put("result_bytes", "result_bytes='corrupt'::bytea"); + mutations.put("storage_result_bytes", "storage_result_bytes='corrupt'::bytea"); + mutations.put("binding_digest", "binding_digest='sha256:" + "f".repeat(64) + "'"); + mutations.put( + "binding_json", "binding_json=replace(binding_json,'retained-base','tampered-base')"); + mutations.put( + "identity_json", + "identity_json=replace(identity_json,'local_version_key','unsupported_key')"); + mutations.put( + "intake_json", + "intake_json=replace(intake_json,'Synthetic component world','changed source')"); + mutations.put( + "owner_binding_json", "owner_binding_json=replace(owner_binding_json,'firemud','other')"); + mutations.put("freeze_request_json contentDigest", null); + mutations.put("graph_sha256", "graph_sha256='" + "d".repeat(64) + "'"); + + for (var mutation : mutations.entrySet()) { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + frozen().capture(request); + String set = mutation.getValue(); + if (set == null) { + String originalDigest = request.freeze().contentDigest(); + String changedDigest = + (originalDigest.charAt(0) == '0' ? "1" : "0") + originalDigest.substring(1); + assertThat(changedDigest) + .as("replacement for %s differs from the actual schema-3 digest", mutation.getKey()) + .isNotEqualTo(originalDigest); + set = + "freeze_request_json=replace(freeze_request_json,'" + + originalDigest + + "','" + + changedDigest + + "')"; + } + String before = + dsl.resultQuery( + "SELECT to_jsonb(t)::text FROM world_canonical_frozen_topology t " + + "WHERE publication_fence=?", + request.freeze().publicationFence()) + .fetchOne(0, String.class); + assertThat(before).as("original journal row exists for %s", mutation.getKey()).isNotNull(); + String update = "UPDATE world_canonical_frozen_topology SET " + set; + assertThatThrownBy( + () -> + dsl.execute( + update + " WHERE publication_fence=?", request.freeze().publicationFence())) + .as("origin trigger rejects direct update of %s", mutation.getKey()) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.freeze().publicationFence())) + .as("origin trigger rejects direct delete while testing %s", mutation.getKey()) + .isInstanceOf(RuntimeException.class); + bypass(update + " WHERE publication_fence=?", request.freeze().publicationFence()); + String after = + dsl.resultQuery( + "SELECT to_jsonb(t)::text FROM world_canonical_frozen_topology t WHERE publication_fence=?", + request.freeze().publicationFence()) + .fetchOne(0, String.class); + assertThat(after) + .as("bypass mutation changes the complete original journal row for %s", mutation.getKey()) + .isNotNull() + .isNotEqualTo(before); + assertThatThrownBy(() -> frozen().readCommitted(request)) + .as("historical read rejects tampered %s", mutation.getKey()) + .isInstanceOf(RuntimeException.class); + assertOrigin(); + } + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_canonical_frozen_topology")) + .isInstanceOf(RuntimeException.class); + } + + @Test + void recomputedGraphChecksumCannotHideTypedEndpointOrCanonicalEntityTampering() { + for (String replacement : List.of("\"to_room_id\": 0", "\"entity_template_id\": 123")) { + // The replacement string is selected from test constants, never a caller-supplied selector. + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + var captured = frozen().capture(request); + String graph = new String(captured.graphBytes(), StandardCharsets.UTF_8); + String bad = + replacement.startsWith("\"to_room_id\"") + ? graph.replaceAll("\"to_room_id\"\\s*:\\s*[0-9]+", "\"to_room_id\":0") + : graph.replace("\"entity_template_id\":null", "\"entity_template_id\":123"); + assertThat(bad).isNotEqualTo(graph); + byte[] badBytes = bad.getBytes(StandardCharsets.UTF_8); + bypass( + "UPDATE world_canonical_frozen_topology SET graph_bytes=?,graph_sha256=? WHERE publication_fence=?", + badBytes, + WorldAuthoredGraphSnapshotCapture.sha256(badBytes), + request.freeze().publicationFence()); + assertThatThrownBy(() -> frozen().readCommitted(request)) + .hasMessageContaining("exact typed original payload"); + } + } + + @Test + void twoConcurrentCapturesReturnOneOriginalImmutableResult() throws Exception { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + CountDownLatch start = new CountDownLatch(1); + try (var pool = Executors.newFixedThreadPool(2)) { + var first = + pool.submit( + () -> { + assertThat(start.await(15, TimeUnit.SECONDS)).isTrue(); + return frozen().capture(request); + }); + var second = + pool.submit( + () -> { + assertThat(start.await(15, TimeUnit.SECONDS)).isTrue(); + return frozen().capture(request); + }); + start.countDown(); + var one = first.get(20, TimeUnit.SECONDS); + var two = second.get(20, TimeUnit.SECONDS); + assertThat(one.captureId()).isEqualTo(two.captureId()); + assertThat(one.resultBytes()).containsExactly(two.resultBytes()); + } + assertThat(countCaptures(request)).isEqualTo(1); + } + + private WorldCanonicalFrozenTopologyService frozen() { + return frozen(digestService); + } + + private WorldCanonicalFrozenTopologyService frozen( + net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService producer) { + return new WorldCanonicalFrozenTopologyService( + new WorldCanonicalFrozenTopologyRepository(dsl, snapshots, repository(), producer), + manager); + } + + @Test + void v32PreservesOriginalSchema2FrozenJournalAndExactHistoricalRetries() throws Exception { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request current = freeze(p); + var captured = frozen().capture(current); + CaptureRequest r = current.freeze(); + Request historical = + new Request( + p, + new CaptureRequest( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + r.publicationRequestId(), + r.requestDigest(), + r.versionStateEpoch(), + r.publishWorkflowId(), + r.appliedCommitId(), + r.contentDigest(), + 2, + r.suppliedOwnedAffectedTuples())); + String schema = "retained_schema2_" + UUID.randomUUID().toString().replace("-", ""); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("31")) + .load() + .migrate(); + Map tables = new LinkedHashMap<>(); + for (String table : + List.of( + "world_authored_source_tenant_association", + "world_authored_source_intake", + "world_authored_version_identity", + "world_design_publication_fence_attempt", + "world_design_publication_fence_owner", + "world_topology_draft_commit")) tables.put(table, "local_tenant_key"); + tables.put("world_authored_source_tenant_key_reservation", "tenant_key"); + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + DSLContext retained = DSL.using(connection, SQLDialect.POSTGRES); + retained.execute("SET search_path TO " + schema + ", public"); + connection.setAutoCommit(false); + retained.execute("SET LOCAL session_replication_role='replica'"); + for (var table : tables.entrySet()) { + String override = + table.getKey().equals("world_authored_version_identity") + ? " OVERRIDING SYSTEM VALUE" + : ""; + retained.execute( + "INSERT INTO " + + table.getKey() + + override + + " SELECT * FROM world_management_service." + + table.getKey() + + " WHERE " + + table.getValue() + + "=?", + f.intake().localTenantKey()); + } + // Synthetic original schema-2 evidence is installed before V32, never upgraded or rehashed by + // it. + retained.execute( + "UPDATE world_design_publication_fence_attempt SET digest_schema_version=2 WHERE publication_fence=?", + r.publicationFence()); + byte[] originalResult = + new String(captured.resultBytes(), StandardCharsets.UTF_8) + .replace("\"digestSchemaVersion\":3", "\"digestSchemaVersion\":2") + .getBytes(StandardCharsets.UTF_8); + retained.execute( + "INSERT INTO world_canonical_frozen_topology SELECT (jsonb_populate_record(NULL::world_canonical_frozen_topology, " + + "to_jsonb(t) || jsonb_build_object('freeze_request_json', replace(freeze_request_json, '\"digestSchemaVersion\":3', '\"digestSchemaVersion\":2'), " + + "'result_bytes', ?::bytea))).* FROM world_management_service.world_canonical_frozen_topology t WHERE publication_fence=?", + originalResult, + r.publicationFence()); + retained.execute("SET LOCAL session_replication_role='origin'"); + connection.commit(); + connection.setAutoCommit(true); + tables.put("world_canonical_frozen_topology", "publication_fence"); + var before = retainedRows(retained, tables); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat(retainedRows(retained, tables)).isEqualTo(before); + var repo = + new WorldCanonicalFrozenTopologyRepository( + retained, + new WorldAuthoredGraphSnapshotRepository(retained), + new WorldDraftTopologyCommitRepository( + retained, + new WorldDesignPublicationFenceRepository( + retained, new WorldAuthoredSourceIntakeRepository(retained)), + mapper), + (tenant, version) -> { + throw new AssertionError("Historical retry must never recompute content"); + }); + var service = new WorldCanonicalFrozenTopologyService(repo, manager); + assertThat(service.readCommitted(historical).orElseThrow().resultBytes()) + .containsExactly(originalResult); + assertThat(service.capture(historical).resultBytes()).containsExactly(originalResult); + assertThat(service.capture(historical).request().freeze().digestSchemaVersion()).isEqualTo(2); + assertThatThrownBy(() -> service.readCommitted(current)) + .hasMessageContaining("changed complete input"); + assertThat(retainedRows(retained, tables)).isEqualTo(before); + } finally { + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private Request freeze(WorldDraftTopologyCommitPlan p) { + return freeze(p, 3); + } + + private Request freeze(WorldDraftTopologyCommitPlan p, int schema) { + var o = p.ownerBinding(); + String publicationRequest = "capture-" + UUID.randomUUID(); + var evidence = + new WorldDesignPublicationFenceEvidence( + o.targetNamespace(), + o.canonicalTenantId(), + o.canonicalVersionId(), + o.versionIdentityOperationId(), + o.gameDesignVersionId(), + o.intakeRequestId(), + o.intakeOperationId(), + o.intakeRequestDigest(), + o.sourceOperationId(), + o.sourceEvidenceDigest(), + o.intakeReceiptDigest(), + publicationRequest, + "a".repeat(64), + 1, + "publish:" + o.canonicalTenantId() + ":publish-request:" + publicationRequest); + // Compute content under the exact owner lock; selected commit is still not complete APPLIED. + var attempt = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, + () -> { + var keys = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT local_tenant_key, local_version_key FROM world_authored_version_identity WHERE operation_id=?", + o.versionIdentityOperationId()), + "expected owner version-identity row"); + var digest = + digestService.getDraftDesignDigest( + Long.toString(keys.get("local_tenant_key", Long.class)), + Long.toString(keys.get("local_version_key", Long.class))); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + p.binding().commitId().toString(), + digest.contentDigest(), + schema); + }))); + var tuples = + p.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + new OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList(); + return new Request( + p, + new CaptureRequest( + o.targetNamespace(), + o.canonicalTenantId(), + o.canonicalVersionId(), + o.intakeRequestId(), + attempt.publicationFence(), + publicationRequest, + evidence.requestDigest(), + evidence.versionStateEpoch(), + evidence.publishWorkflowId(), + attempt.checkpoint().appliedCommitId(), + attempt.checkpoint().contentDigest(), + attempt.checkpoint().digestSchemaVersion(), + tuples)); + } + + private CaptureRequest copy( + CaptureRequest r, + String digest, + String content, + long epoch, + String publication, + String workflow) { + return new CaptureRequest( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + publication, + digest, + epoch, + workflow, + r.appliedCommitId(), + content, + r.digestSchemaVersion(), + r.suppliedOwnedAffectedTuples()); + } + + private void bypass(String sql, Object... values) { + ownerTransaction() + .execute( + status -> { + dsl.execute("SET LOCAL session_replication_role='replica'"); + try { + dsl.execute(sql, values); + } finally { + dsl.execute("SET LOCAL session_replication_role='origin'"); + } + return null; + }); + assertOrigin(); + } + + private long countCaptures(Request request) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT count(*) FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.freeze().publicationFence()) + .fetchOne(0, Long.class)); + } + + private Fixture fixture() { + UUID tenant = UUID.randomUUID(); + UUID registration = UUID.randomUUID(); + UUID sourceOperation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + long sourceRow = Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + String sourceTenant = "gd-row-" + sourceRow; + String digest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, "Synthetic component world"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW", + evidenceDigest); + UUID intakeRequest = UUID.randomUUID(); + ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, intakeRequest, source)); + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository.read(NAMESPACE, intakeRequest).orElseThrow(); + return Objects.requireNonNull( + ownerTransaction() + .execute( + status -> { + UUID canonicalVersion = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + worldSlug, + sourceOperation, + evidenceDigest, + GAME_DESIGN_VERSION); + WorldAuthoredVersionIdentityReceipt version = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + tenant, + canonicalVersion, + version.operationId(), + GAME_DESIGN_VERSION, + intakeRequest, + intake.operationId(), + intake.requestDigest(), + sourceOperation, + evidenceDigest, + intake.receiptDigest()); + assertOrigin(); + return new Fixture(intake, version, owner); + })); + } + + private WorldDraftTopologyCommitPlan plan(Fixture f) { + UUID logical = UUID.randomUUID(); + UUID secondRoom = UUID.randomUUID(); + UUID entity = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + List values = new ArrayList<>(); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("region") + .setWeather("rain") + .setShardId(7) + .setGenerationSeed(9_007_199_254_740_999L) + .setGeneratorType("synthetic") + .setGeneratorParams("{\"seed\":1}")) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder().setName("zone").setRegionId(logical.toString())) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("room") + .setZoneId(logical.toString()) + .setDescription("description") + .setNameLocalizedVariantsJson("{\"en\":\"room\"}") + .setDescriptionLocalizedVariantsJson("{\"en\":\"description\"}")) + .build()); + values.add( + mutation( + commit, + secondRoom, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder().setName("second").setZoneId(logical.toString())) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(logical.toString()) + .setToRoomId(secondRoom.toString()) + .setDirection("NORTH")) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder().setName("rule").setValue("seeded")) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(logical.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(entity.toString()) + .setRespawnDelaySeconds(17)) + .build()); + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + "synthetic opaque Entity input; existence and permission remain unverified")); + units.add( + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "NPC", + entity.toString(), + "AGGREGATE", + entity.toString(), + "0")); + // Original input order deliberately places children before their parents. + for (var m : values.reversed()) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(m.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + json(m))); + String family = m.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "AGGREGATE", + m.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "REGION_SUBTREE", + m.getScopeId(), + "0")); + } + var s = f.intake().source(); + var target = + new DraftCommitBinding.TargetProof( + f.owner().canonicalTenantId(), + f.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + s.sourceGameTenantKey(), + s.sourceGameRowId(), + s.sourceGameTenantKey(), + s.provenanceKind()); + return WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + target, UUID.randomUUID(), commit, "retained-base", revisions, units), + f.owner()); + } + + private WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID id, UUID scope, WorldDesignAggregateType type) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(id.toString()) + .setAggregateType(type) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(scope.toString()); + } + + private WorldDraftTopologyCommitService component() { + return new WorldDraftTopologyCommitService( + repository(), + manager, + p -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertOrigin(); + // Synthetic local-storage fixture only; no Account permission or Entity existence proof. + }); + } + + private WorldDraftTopologyCommitRepository repository() { + return new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate tx = new TransactionTemplate(manager); + tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return tx; + } + + private void assertOrigin() { + assertThat( + dsl.resultQuery("SELECT current_setting('session_replication_role')") + .fetchOne(0, String.class)) + .isEqualTo("origin"); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new AssertionError(exception); + } + } + + private record Fixture( + WorldAuthoredSourceIntakeReceipt intake, + WorldAuthoredVersionIdentityReceipt version, + OwnerBinding owner) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java new file mode 100644 index 0000000000..61d0c14e2e --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -0,0 +1,1847 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +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.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.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +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.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +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.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +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.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** + * Focused PostgreSQL proof for guarded, immutable, non-authorizing canonical materialization and + * World canonical-instance association. + * + *

Upstream Game Design, Game Session, publication checkpoint, and held-authority evidence here + * is explicitly synthetic fixture evidence. World source intake, complete launch pair, Version + * identity, frozen graph, guarded V35 runtime materialization, association, migration, constraints, + * and independent committed readback use actual migrated PostgreSQL repositories and tables. This + * fixture does not claim authenticated producer/delivery evidence, Account commit authority, + * lifecycle transition success, actor authority, or gameplay admission. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldCanonicalInstanceAssociationPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final long VERSION_EPOCH = 7L; + + @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 WorldDesignPublicationFenceRepository publicationFence; + @Autowired private WorldAuthoredGraphSnapshotRepository graphSnapshots; + + @Autowired + private net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService + digestService; + + @Autowired private ObjectMapper objectMapper; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + private WorldAuthoredSourceIntakeRepository sourceRepository; + private WorldCompleteLaunchBindingRepository launchBindingRepository; + private WorldAuthoredVersionIdentityRepository versionIdentityRepository; + private WorldCanonicalInstanceAssociationRepository associationRepository; + private final Map frozenPlans = + new java.util.HashMap<>(); + + @BeforeEach + void createRepositories() { + sourceRepository = new WorldAuthoredSourceIntakeRepository(dsl); + launchBindingRepository = new WorldCompleteLaunchBindingRepository(dsl); + versionIdentityRepository = new WorldAuthoredVersionIdentityRepository(dsl); + associationRepository = + new WorldCanonicalInstanceAssociationRepository( + dsl, launchBindingRepository, sourceRepository, versionIdentityRepository); + } + + @Test + void retainsFullCanonicalAssociationAndReadsItAfterTheOwnerCommit() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Result preparation = + prepareCanonicalWorldRow( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); + long worldInstanceId = preparation.association().worldInstanceId(); + assertThat(preparation.storageStatus()).isEqualTo("MATERIALIZED_UNVERIFIED"); + assertThat(preparation.regionCount()).isEqualTo(1); + assertThat(preparation.zoneCount()).isEqualTo(1); + assertThat(preparation.roomCount()).isEqualTo(2); + assertThat(preparation.exitCount()).isEqualTo(1); + WorldCanonicalInstanceAssociation.Claim claim = + claim( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + worldInstanceId, + 1L, + "GS_FIXTURE"); + + ownerTransaction() + .executeWithoutResult(status -> associationRepository.retainClaimInOwnerTransaction(claim)); + + assertThat(associationCount(canonicalGameInstanceId)).isEqualTo(1L); + WorldCanonicalInstanceAssociation stored = + associationRepository.readOwnerAssociation(canonicalGameInstanceId).orElseThrow(); + assertThat(stored.identity()).isEqualTo(claim.identity()); + assertThat(stored.worldInstanceId()).isEqualTo(worldInstanceId); + assertThat(stored.canonicalVersionId()) + .isEqualTo(fixture.binding().evidence().releaseAttestation().canonicalVersionId()); + assertThat(stored.launchBindingOperationId()).isEqualTo(fixture.binding().operationId()); + assertThat(stored.versionIdentityOperationId()) + .isEqualTo(fixture.versionIdentity().operationId()); + assertThat(stored.completeLaunchBinding()).isEqualTo(fixture.binding()); + assertThat(stored.versionIdentity()).isEqualTo(fixture.versionIdentity()); + assertThat(stored.worldPrepareFields().privateTenantKey()) + .isEqualTo(fixture.source().receipt().localTenantKey()); + assertThat(stored.worldPrepareFields().privateGameInstanceKey()).isPositive(); + assertThat(stored.worldPrepareFields().localVersionKey()) + .isEqualTo(fixture.versionIdentity().localVersionKey()); + assertThat(stored.worldPrepareFields().launchDescriptorId()) + .isEqualTo(fixture.binding().descriptor().launchDescriptorId()); + + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT canonical_game_instance_id, canonical_target_namespace, canonical_tenant_id, " + + "canonical_world_slug, playable_state_namespace_id, playable_state_scope, " + + "public_production, " + + "playtest_lifecycle_id, playtest_state_generation, control_plane_request_id, " + + "world_instance_id, local_tenant_key, local_version_key, " + + "canonical_launch_binding_operation_id, version_identity_operation_id, " + + "source_operation_id, source_evidence_digest, descriptor_request_digest, " + + "descriptor_result_digest, release_attestation_digest " + + "FROM world_canonical_instance_association WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId), + "canonical instance association row missing after committed readback"); + assertThat(row.get("canonical_game_instance_id", UUID.class)) + .isEqualTo(canonicalGameInstanceId); + assertThat(row.get("canonical_target_namespace", String.class)).isEqualTo(NAMESPACE); + assertThat(row.get("canonical_tenant_id", UUID.class)) + .isEqualTo(fixture.source().source().canonicalTenantId()); + assertThat(row.get("canonical_world_slug", String.class)) + .isEqualTo(fixture.source().source().worldSlug()); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(playableStateNamespaceId); + assertThat(row.get("playable_state_scope", String.class)).isEqualTo("SHARED"); + assertThat(row.get("public_production", Boolean.class)).isTrue(); + assertThat(row.get("playtest_lifecycle_id", UUID.class)).isNull(); + assertThat(row.get("playtest_state_generation", Long.class)).isNull(); + assertThat(row.get("world_instance_id", Long.class)).isEqualTo(worldInstanceId); + assertThat(row.get("local_tenant_key", Long.class)) + .isEqualTo(fixture.source().receipt().localTenantKey()); + assertThat(row.get("local_version_key", Long.class)) + .isEqualTo(fixture.versionIdentity().localVersionKey()); + assertThat(row.get("canonical_launch_binding_operation_id", UUID.class)) + .isEqualTo(fixture.binding().operationId()); + assertThat(row.get("version_identity_operation_id", UUID.class)) + .isEqualTo(fixture.versionIdentity().operationId()); + assertThat(row.get("source_operation_id", UUID.class)) + .isEqualTo(fixture.source().receipt().sourceOperationId()); + assertThat(row.get("source_evidence_digest", String.class)) + .isEqualTo(fixture.source().receipt().sourceEvidenceDigest()); + assertThat(row.get("descriptor_request_digest", String.class)) + .isEqualTo(fixture.binding().descriptor().requestDigest()); + assertThat(row.get("descriptor_result_digest", String.class)) + .isEqualTo(fixture.binding().descriptor().resultDigest()); + assertThat(row.get("release_attestation_digest", String.class)) + .isEqualTo(fixture.binding().evidence().releaseAttestation().evidenceDigest()); + Record worldRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT public_production FROM world_instance WHERE id = ?", worldInstanceId), + "canonical World instance row missing after committed readback"); + assertThat(worldRow.get("public_production", Boolean.class)).isTrue(); + long privateGameInstanceKey = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT game_instance_id FROM world_instance WHERE id = ?", worldInstanceId), + "canonical World row missing private instance key") + .get("game_instance_id", Long.class); + Record region = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, canonical_region_instance_id, name, weather, generation_seed " + + "FROM region_instance WHERE tenant_id = ? AND game_instance_id = ?", + fixture.source().receipt().localTenantKey(), + privateGameInstanceKey), + "canonical runtime region missing"); + Record zone = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, canonical_zone_instance_id, template_zone_id, region_instance_id, name " + + "FROM zone_instance WHERE tenant_id = ? AND game_instance_id = ?", + fixture.source().receipt().localTenantKey(), + privateGameInstanceKey), + "canonical runtime zone missing"); + Record room = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT ri.id, ri.room_instance_row_id, ri.template_room_id, ri.region_instance_id, " + + "ri.zone_instance_id, ri.name, ri.description " + + "FROM room_instance ri WHERE ri.tenant_id = ? AND ri.game_instance_id = ? " + + "AND ri.name = 'synthetic room'", + fixture.source().receipt().localTenantKey(), + privateGameInstanceKey), + "canonical runtime room missing"); + assertThat(region.get("canonical_region_instance_id", UUID.class)).isNotNull(); + assertThat(zone.get("canonical_zone_instance_id", UUID.class)).isNotNull(); + assertThat(region.get("name", String.class)).isEqualTo("synthetic region"); + assertThat(region.get("weather", String.class)).isEqualTo("rain"); + assertThat(region.get("generation_seed", Long.class)).isEqualTo(9001L); + assertThat(zone.get("name", String.class)).isEqualTo("synthetic zone"); + assertThat(zone.get("region_instance_id", Long.class)).isEqualTo(region.get("id", Long.class)); + assertThat(room.get("name", String.class)).isEqualTo("synthetic room"); + assertThat(room.get("description", String.class)).isEqualTo("synthetic materialization proof"); + assertThat(room.get("region_instance_id", Long.class)).isEqualTo(region.get("id", Long.class)); + assertThat(room.get("zone_instance_id", Long.class)).isEqualTo(zone.get("id", Long.class)); + List roomRows = + dsl.fetch( + "SELECT room_instance_row_id, template_room_id, region_instance_id, zone_instance_id, name " + + "FROM room_instance WHERE tenant_id = ? AND game_instance_id = ? ORDER BY name", + fixture.source().receipt().localTenantKey(), + privateGameInstanceKey); + assertThat(roomRows).hasSize(2); + assertThat(roomRows) + .allSatisfy( + roomRow -> { + assertThat(roomRow.get("region_instance_id", Long.class)) + .isEqualTo(region.get("id", Long.class)); + assertThat(roomRow.get("zone_instance_id", Long.class)) + .isEqualTo(zone.get("id", Long.class)); + }); + assertThat(roomRows) + .extracting(roomRow -> roomRow.get("name", String.class)) + .containsExactly("synthetic destination", "synthetic room"); + Record exit = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, from_room_instance_record_id, to_room_instance_record_id, direction, cost " + + "FROM room_instance_exit WHERE tenant_id = ? AND game_instance_id = ?", + fixture.source().receipt().localTenantKey(), + privateGameInstanceKey), + "canonical runtime room exit missing"); + assertThat(exit.get("from_room_instance_record_id", Long.class)) + .isEqualTo(room.get("room_instance_row_id", Long.class)); + assertThat(exit.get("to_room_instance_record_id", Long.class)) + .isNotEqualTo(exit.get("from_room_instance_record_id", Long.class)); + assertThat(exit.get("direction", String.class)).isEqualTo("EAST"); + assertThat(exit.get("cost", Integer.class)).isEqualTo(3); + var frozenPlan = frozenPlans.get(fixture.versionIdentity().operationId()); + assertThat(region.get("canonical_region_instance_id", UUID.class)) + .isNotEqualTo(frozenPlan.regions().getFirst().identity().templateId()); + assertThat(zone.get("canonical_zone_instance_id", UUID.class)) + .isNotEqualTo(frozenPlan.zones().getFirst().identity().templateId()); + Record regionIdentity = + topologyIdentity( + worldInstanceId, "REGION", frozenPlan.regions().getFirst().identity().templateId()); + Record zoneIdentity = + topologyIdentity( + worldInstanceId, "ZONE", frozenPlan.zones().getFirst().identity().templateId()); + Record roomIdentity = + topologyIdentity( + worldInstanceId, + "ROOM", + frozenPlan.rooms().stream() + .filter(item -> item.content().getName().equals("synthetic room")) + .findFirst() + .orElseThrow() + .identity() + .templateId()); + Record exitIdentity = + topologyIdentity( + worldInstanceId, + "ROOM_EXIT", + frozenPlan.roomExits().getFirst().identity().templateId()); + assertThat(regionIdentity.get("runtime_row_id", Long.class)) + .isEqualTo(region.get("id", Long.class)); + assertThat(regionIdentity.get("runtime_identity", UUID.class)) + .isEqualTo(region.get("canonical_region_instance_id", UUID.class)); + assertThat(zoneIdentity.get("runtime_row_id", Long.class)) + .isEqualTo(zone.get("id", Long.class)); + assertThat(zoneIdentity.get("runtime_identity", UUID.class)) + .isEqualTo(zone.get("canonical_zone_instance_id", UUID.class)); + assertThat(roomIdentity.get("runtime_room_instance_id", Long.class)) + .isEqualTo(room.get("room_instance_row_id", Long.class)); + assertThat(roomIdentity.get("template_private_row_key", Long.class)) + .isEqualTo(room.get("template_room_id", Long.class)); + assertThat(zoneIdentity.get("template_private_row_key", Long.class)) + .isEqualTo(zone.get("template_zone_id", Long.class)); + assertThat(exitIdentity.get("runtime_row_id", Long.class)) + .isEqualTo(exit.get("id", Long.class)); + Record mappedFamilies = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) AS row_count, COUNT(DISTINCT family) AS family_count " + + "FROM world_canonical_instance_topology_identity WHERE world_instance_id = ?", + worldInstanceId), + "canonical source/runtime association rows missing"); + assertThat(mappedFamilies.get("row_count", Long.class)).isEqualTo(5L); + assertThat(mappedFamilies.get("family_count", Long.class)).isEqualTo(4L); + } + + @Test + void exactRetryReusesOriginalAssociationAfterReadMetadataChangeWithoutLifecycleMutation() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Result originalPreparation = + prepareCanonicalWorldRow( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); + long worldInstanceId = originalPreparation.association().worldInstanceId(); + WorldCanonicalInstanceAssociation.Claim originalClaim = + claim( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + worldInstanceId, + 1L, + "GS_FIXTURE"); + ownerTransaction() + .executeWithoutResult( + status -> associationRepository.retainClaimInOwnerTransaction(originalClaim)); + WorldCanonicalInstanceAssociation original = + associationRepository.readOwnerAssociation(canonicalGameInstanceId).orElseThrow(); + + // This is only a fresh, synthetic Game Session observation/read correlation. No World + // lifecycle owner operation is forged; the current guarded lifecycle transition remains a + // separate unimplemented execution path. + WorldCanonicalInstancePreparation.Result changedObservation = + prepareCanonicalWorldRow( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_RETRIED_FIXTURE", 2L); + assertThat(changedObservation.association()).isEqualTo(original); + assertThat(changedObservation.inputDigest()).isEqualTo(originalPreparation.inputDigest()); + WorldCanonicalInstanceAssociation.Claim retry = + claim( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + worldInstanceId, + 2L, + "GS_RETRIED_FIXTURE"); + ownerTransaction() + .executeWithoutResult(status -> associationRepository.retainClaimInOwnerTransaction(retry)); + + assertThat(associationRepository.readOwnerAssociation(canonicalGameInstanceId)) + .contains(original); + assertThat(associationCount(canonicalGameInstanceId)).isEqualTo(1L); + Record runtime = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT status, lifecycle_epoch, row_version FROM world_instance WHERE id = ?", + worldInstanceId), + "World instance row missing after exact retry"); + assertThat(runtime.get("status", String.class)).isEqualTo("PREPARING"); + assertThat(runtime.get("lifecycle_epoch", Long.class)).isEqualTo(1L); + assertThat(runtime.get("row_version", Long.class)).isZero(); + assertThat(retry.gameSessionRead().readRequestId()) + .isNotEqualTo(originalClaim.gameSessionRead().readRequestId()); + assertThat(retry.gameSessionRead().currentGameSessionStatus()).isEqualTo("GS_RETRIED_FIXTURE"); + } + + @Test + void rejectsChangedRequestEchoDescriptorAttestationAndPlayableScopeWithoutMutation() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + long worldInstanceId = + insertCanonicalWorldRow(fixture, canonicalGameInstanceId, playableStateNamespaceId); + WorldCanonicalInstanceAssociation.Claim valid = + claim( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + worldInstanceId, + 1L, + "GS_FIXTURE"); + ownerTransaction() + .executeWithoutResult(status -> associationRepository.retainClaimInOwnerTransaction(valid)); + WorldCanonicalInstanceAssociation originalStored = + associationRepository.readOwnerAssociation(canonicalGameInstanceId).orElseThrow(); + + var originalRequest = valid.gameSessionRequest(); + var response = valid.gameSessionRead(); + var changedRequest = + new WorldCanonicalInstanceAssociation.GameSessionReadRequest( + originalRequest.readRequestId(), + originalRequest.targetNamespace(), + originalRequest.canonicalTenantId(), + originalRequest.worldSlug(), + originalRequest.canonicalGameInstanceId(), + originalRequest.controlPlaneRequestId(), + "substituted-descriptor", + originalRequest.expectedDescriptorRequestDigest(), + originalRequest.expectedDescriptorResultDigest(), + originalRequest.expectedReleaseAttestationEvidenceDigest()); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.Claim( + changedRequest, + response, + worldInstanceId, + fixture.binding(), + fixture.versionIdentity())) + .isInstanceOf(IllegalArgumentException.class); + + CompleteLaunchBindingEvidence changedDescriptor = + completeEvidence( + fixture.source().source(), + fixture.binding().controlPlaneRequestId(), + fixture.versionIdentity().gameDesignVersionId(), + fixture.versionIdentity().canonicalVersionId(), + VERSION_EPOCH, + "substituted-descriptor", + "synthetic-alternate-descriptor"); + UUID changedDescriptorReadId = UUID.randomUUID(); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.Claim( + requestFor(changedDescriptor, canonicalGameInstanceId, changedDescriptorReadId), + responseFor( + changedDescriptor, + canonicalGameInstanceId, + playableStateNamespaceId, + changedDescriptorReadId, + "GS_FIXTURE", + 1L), + worldInstanceId, + fixture.binding(), + fixture.versionIdentity())) + .isInstanceOf(IllegalArgumentException.class); + + AuthoredWorldReleaseAttestationEvidence changedAttestation = + attestation( + fixture.binding().descriptor(), + fixture.source().source(), + fixture.versionIdentity().canonicalVersionId(), + "synthetic-alternate-attestation"); + CompleteLaunchBindingEvidence changedPair = + new CompleteLaunchBindingEvidence(fixture.binding().descriptor(), changedAttestation); + UUID changedAttestationReadId = UUID.randomUUID(); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.Claim( + requestFor(changedPair, canonicalGameInstanceId, changedAttestationReadId), + responseFor( + changedPair, + canonicalGameInstanceId, + playableStateNamespaceId, + changedAttestationReadId, + "GS_FIXTURE", + 1L), + worldInstanceId, + fixture.binding(), + fixture.versionIdentity())) + .isInstanceOf(IllegalArgumentException.class); + + var changedScopeResponse = + new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + response.readRequestId(), + response.targetNamespace(), + response.canonicalTenantId(), + response.worldSlug(), + response.canonicalGameInstanceId(), + response.controlPlaneRequestId(), + response.launchDescriptorId(), + response.descriptorRequestDigest(), + response.descriptorResultDigest(), + response.releaseAttestationEvidenceDigest(), + UUID.randomUUID(), + "SHARED", + true, + response.currentGameSessionStatus(), + response.currentGameSessionRowVersion(), + response.descriptor(), + response.releaseAttestation()); + var changedScopeClaim = + new WorldCanonicalInstanceAssociation.Claim( + valid.gameSessionRequest(), + changedScopeResponse, + worldInstanceId, + fixture.binding(), + fixture.versionIdentity()); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + response.readRequestId(), + response.targetNamespace(), + response.canonicalTenantId(), + response.worldSlug(), + response.canonicalGameInstanceId(), + response.controlPlaneRequestId(), + response.launchDescriptorId(), + response.descriptorRequestDigest(), + response.descriptorResultDigest(), + response.releaseAttestationEvidenceDigest(), + response.playableStateNamespaceId(), + "ISOLATED", + true, + response.currentGameSessionStatus(), + response.currentGameSessionRowVersion(), + response.descriptor(), + response.releaseAttestation())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + associationRepository.retainClaimInOwnerTransaction(changedScopeClaim))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class); + + assertThat(associationCount(canonicalGameInstanceId)).isEqualTo(1L); + assertThat(associationRepository.readOwnerAssociation(canonicalGameInstanceId)) + .contains(originalStored); + } + + @Test + void rejectsMissingPublicProductionAndPrivatePlaytestClassificationBeforeMutation() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + // Invalid public-production evidence is rejected before invoking the owner producer. A + // canonical row cannot be fabricated here just to create an association-free fixture. + UUID readRequestId = UUID.randomUUID(); + + assertThatThrownBy( + () -> + responseFor( + fixture.binding().evidence(), + canonicalGameInstanceId, + playableStateNamespaceId, + readRequestId, + "GS_FIXTURE", + 1L, + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("explicit public-production evidence"); + + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + readRequestId, + NAMESPACE, + fixture.source().source().canonicalTenantId(), + fixture.source().source().worldSlug(), + canonicalGameInstanceId, + fixture.binding().controlPlaneRequestId(), + fixture.binding().descriptor().launchDescriptorId(), + fixture.binding().descriptor().requestDigest(), + fixture.binding().descriptor().resultDigest(), + fixture.binding().evidence().releaseAttestation().evidenceDigest(), + playableStateNamespaceId, + "ISOLATED", + true, + "GS_FIXTURE", + 1L, + fixture.binding().descriptor(), + fixture.binding().evidence().releaseAttestation())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("accepts SHARED only"); + + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + assertThat(associationRepository.readOwnerAssociation(canonicalGameInstanceId)).isEmpty(); + } + + @Test + void rejectsStructurallyValidPlanFromAnotherFrozenCaptureBeforeAllocation() { + Fixture selected = fixture(); + Fixture substitutedSource = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + var selectedPair = new SeededPair(selected.binding(), selected.versionIdentity()); + var request = request(selectedPair, canonicalGameInstanceId, UUID.randomUUID()); + var response = + responseFor( + selected.binding().evidence(), + canonicalGameInstanceId, + playableStateNamespaceId, + request.readRequestId(), + "GS_FIXTURE", + 1L); + WorldCanonicalInstanceTopologyPlan validOtherCapture = frozenPlan(substitutedSource); + + assertThatThrownBy( + () -> + new WorldCanonicalInstancePreparation.Input( + request, + response, + selected.binding(), + selected.versionIdentity(), + validOtherCapture)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact V27 identity and frozen commit"); + + assertThat(preparationCount(canonicalGameInstanceId)).isZero(); + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + assertThat( + dsl.fetchOne( + "SELECT id FROM world_instance WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId)) + .isNull(); + } + + @Test + void rejectsDifferentBindingTenantVersionAndPrivateWorldRowWithoutMutation() { + Fixture original = fixture(); + UUID originalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + long originalWorldInstanceId = + insertCanonicalWorldRow(original, originalGameInstanceId, playableStateNamespaceId); + WorldCanonicalInstanceAssociation.Claim originalClaim = + claim( + original, + originalGameInstanceId, + playableStateNamespaceId, + originalWorldInstanceId, + 1L, + "GS_FIXTURE"); + ownerTransaction() + .executeWithoutResult( + status -> associationRepository.retainClaimInOwnerTransaction(originalClaim)); + + SeededPair secondBinding = + seedPair( + original.source(), + original.versionIdentity(), + controlRequest(), + "synthetic-second-binding", + "synthetic-second-binding-attestation"); + Fixture changedBindingFixture = + new Fixture(original.source(), secondBinding.binding(), secondBinding.versionIdentity()); + assertThatThrownBy( + () -> + prepareCanonicalWorldRow( + changedBindingFixture, + originalGameInstanceId, + playableStateNamespaceId, + "GS_FIXTURE", + 1L)) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class); + WorldCanonicalInstanceAssociation.Claim changedBindingClaim = + claim( + secondBinding, + originalGameInstanceId, + playableStateNamespaceId, + originalWorldInstanceId, + 1L, + "GS_FIXTURE"); + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + associationRepository.retainClaimInOwnerTransaction( + changedBindingClaim))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class); + + SeededPair otherVersion = + seedPair( + original.source(), + null, + controlRequest(), + "synthetic-version-descriptor", + "synthetic-version-attestation", + UUID.randomUUID(), + positiveLong()); + UUID otherGameInstanceId = UUID.randomUUID(); + UUID otherPlayableNamespaceId = UUID.randomUUID(); + long otherWorldInstanceId = + insertCanonicalWorldRow( + otherVersion, original.source(), otherGameInstanceId, otherPlayableNamespaceId); + assertThat(otherWorldInstanceId).isNotEqualTo(originalWorldInstanceId); + assertThat(dsl.fetchOne("SELECT id FROM world_instance WHERE id = ?", otherWorldInstanceId)) + .isNotNull(); + UUID wrongVersionReadId = UUID.randomUUID(); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.Claim( + request(otherVersion, otherGameInstanceId, wrongVersionReadId), + responseFor( + otherVersion.binding().evidence(), + otherGameInstanceId, + otherPlayableNamespaceId, + wrongVersionReadId, + "GS_FIXTURE", + 1L), + otherWorldInstanceId, + otherVersion.binding(), + original.versionIdentity())) + .isInstanceOf(IllegalArgumentException.class); + + WorldCanonicalInstanceAssociation.Claim wrongPrivateWorldRow = + claim( + original, + originalGameInstanceId, + playableStateNamespaceId, + otherWorldInstanceId, + 1L, + "GS_FIXTURE"); + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + associationRepository.retainClaimInOwnerTransaction( + wrongPrivateWorldRow))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class); + + Fixture otherTenant = fixture(); + UUID otherTenantGameInstanceId = UUID.randomUUID(); + WorldCanonicalInstanceAssociation.Claim wrongTenant = + claim( + otherTenant, + otherTenantGameInstanceId, + UUID.randomUUID(), + originalWorldInstanceId, + 1L, + "GS_FIXTURE"); + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> associationRepository.retainClaimInOwnerTransaction(wrongTenant))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class); + + assertThat(associationCount(originalGameInstanceId)).isEqualTo(1L); + assertThat(associationRepository.readOwnerAssociation(originalGameInstanceId)).isPresent(); + assertThat(associationRepository.readOwnerAssociation(otherGameInstanceId)) + .hasValueSatisfying( + association -> + assertThat(association.worldInstanceId()).isEqualTo(otherWorldInstanceId)); + assertThat(associationRepository.readOwnerAssociation(otherTenantGameInstanceId)).isEmpty(); + } + + @Test + void deniesLegacyNumericRowAndRejectsUpdatingItToCanonicalIdentity() throws SQLException { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + long legacyGameInstanceKey = positiveLong(); + long legacyWorldInstanceId = insertLegacyWorldRow(fixture, legacyGameInstanceKey); + WorldCanonicalInstanceAssociation.Claim legacyClaim = + claim( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + legacyWorldInstanceId, + 1L, + "GS_FIXTURE"); + + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> associationRepository.retainClaimInOwnerTransaction(legacyClaim))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class) + .hasMessageContaining("retained numeric rows cannot be associated"); + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET public_production = TRUE, canonical_game_instance_id = ?, " + + "canonical_target_namespace = ?, canonical_tenant_id = ?, " + + "canonical_world_slug = ?, playable_state_namespace_id = ?, " + + "playable_state_scope = 'SHARED', canonical_launch_binding_operation_id = ? " + + "WHERE id = ?", + canonicalGameInstanceId, + NAMESPACE, + fixture.source().source().canonicalTenantId(), + fixture.source().source().worldSlug(), + playableStateNamespaceId, + fixture.binding().operationId(), + legacyWorldInstanceId)) + .isInstanceOf(DataAccessException.class); + Record legacy = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_id, game_instance_id, version_id, public_production, canonical_game_instance_id, " + + "canonical_tenant_id FROM world_instance WHERE id = ?", + legacyWorldInstanceId), + "legacy World row missing after rejected association attempt"); + assertThat(legacy.get("tenant_id", Long.class)) + .isNotEqualTo(fixture.source().receipt().localTenantKey()); + assertThat(legacy.get("game_instance_id", Long.class)).isEqualTo(legacyGameInstanceKey); + assertThat(legacy.get("version_id", Long.class)) + .isEqualTo(fixture.versionIdentity().localVersionKey()); + assertThat(legacy.get("public_production", Boolean.class)).isNull(); + assertThat(legacy.get("canonical_game_instance_id", UUID.class)).isNull(); + assertThat(legacy.get("canonical_tenant_id", UUID.class)).isNull(); + assertThat(associationRepository.readOwnerAssociation(canonicalGameInstanceId)).isEmpty(); + } + + @Test + void rollsBackCompletePreparationWhenHeldCommitAuthorityIsLostBeforeCommit() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Input input = + preparationInput( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); + AtomicInteger heldChecks = new AtomicInteger(); + WorldCanonicalInstancePreparationService service = + preparationService( + () -> { + if (heldChecks.incrementAndGet() == 3) { + throw new IllegalStateException("synthetic held authority lost before commit"); + } + }); + + assertThatThrownBy(() -> service.prepare(input)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synthetic held authority lost before commit"); + + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + assertThat(associationRepository.readOwnerAssociation(canonicalGameInstanceId)).isEmpty(); + assertThat(preparationCount(canonicalGameInstanceId)).isZero(); + assertThat( + dsl.fetchOne( + "SELECT id FROM world_instance WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId)) + .isNull(); + } + + @Test + void concurrentExactPreparationsForTheSameCanonicalGameInstanceRetainOneOwnerResult() + throws Exception { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Input exactInput = + preparationInput( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); + WorldCanonicalInstancePreparationService firstService = preparationService(() -> {}); + WorldCanonicalInstancePreparationService secondService = preparationService(() -> {}); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> { + ready.countDown(); + await(start); + return firstService.prepare(exactInput); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + await(start); + return secondService.prepare(exactInput); + }); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + WorldCanonicalInstancePreparation.Result firstResult = first.get(25, TimeUnit.SECONDS); + WorldCanonicalInstancePreparation.Result secondResult = second.get(25, TimeUnit.SECONDS); + assertThat(firstResult.association().worldInstanceId()) + .isEqualTo(secondResult.association().worldInstanceId()); + assertThat(firstResult.inputDigest()).isEqualTo(secondResult.inputDigest()); + } + + assertThat(associationCount(canonicalGameInstanceId)).isEqualTo(1L); + assertThat(preparationCount(canonicalGameInstanceId)).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_instance WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId), + "Canonical World row count returned no result") + .get(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void forwardV32MigrationPreservesLegacyRowsWithoutInventingCanonicalMapping() + throws SQLException { + String schema = "world_canonical_instance_v32_" + UUID.randomUUID().toString().replace("-", ""); + long tenantKey = + 8_100_000_000L + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 100_000L); + long gameInstanceKey = positiveLong(); + long worldInstanceId; + try { + migrateFixture(schema, MigrationVersion.fromVersion("32")); + try (Connection connection = fixtureConnection(schema); + PreparedStatement insert = + 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 (?, ?, 71, 'retained-v32-request', " + + "'retained-v32-descriptor', 83, 'retained-v32-config', 97, " + + "'retained-v32-release', 5, 'LEGACY_FIXTURE') RETURNING id")) { + insert.setLong(1, tenantKey); + insert.setLong(2, gameInstanceKey); + try (ResultSet result = insert.executeQuery()) { + assertThat(result.next()).isTrue(); + worldInstanceId = result.getLong(1); + } + } + + migrateFixture(schema, null); + + try (Connection connection = fixtureConnection(schema)) { + try (PreparedStatement query = + connection.prepareStatement( + "SELECT tenant_id, game_instance_id, version_id, status, public_production, " + + "canonical_game_instance_id, canonical_target_namespace, canonical_tenant_id, " + + "canonical_world_slug, playable_state_namespace_id, playable_state_scope, " + + "playtest_lifecycle_id, playtest_state_generation, " + + "canonical_launch_binding_operation_id FROM world_instance WHERE id = ?")) { + query.setLong(1, worldInstanceId); + try (ResultSet retained = query.executeQuery()) { + assertThat(retained.next()).isTrue(); + assertThat(retained.getLong("tenant_id")).isEqualTo(tenantKey); + assertThat(retained.getLong("game_instance_id")).isEqualTo(gameInstanceKey); + assertThat(retained.getLong("version_id")).isEqualTo(83L); + assertThat(retained.getString("status")).isEqualTo("LEGACY_FIXTURE"); + assertThat(retained.getObject("public_production")).isNull(); + assertThat(retained.getObject("canonical_game_instance_id")).isNull(); + assertThat(retained.getString("canonical_target_namespace")).isNull(); + assertThat(retained.getObject("canonical_tenant_id")).isNull(); + assertThat(retained.getString("canonical_world_slug")).isNull(); + assertThat(retained.getObject("playable_state_namespace_id")).isNull(); + assertThat(retained.getString("playable_state_scope")).isNull(); + assertThat(retained.getObject("playtest_lifecycle_id")).isNull(); + assertThat(retained.getObject("playtest_state_generation")).isNull(); + assertThat(retained.getObject("canonical_launch_binding_operation_id")).isNull(); + assertThat(retained.next()).isFalse(); + } + } + try (Statement statement = connection.createStatement(); + ResultSet associations = + statement.executeQuery( + "SELECT COUNT(*) FROM world_canonical_instance_association")) { + assertThat(associations.next()).isTrue(); + assertThat(associations.getLong(1)).isZero(); + } + + UUID attemptedGameInstanceId = UUID.randomUUID(); + UUID attemptedTenantId = UUID.randomUUID(); + UUID attemptedPlayableNamespaceId = UUID.randomUUID(); + UUID attemptedBindingId = UUID.randomUUID(); + assertThatThrownBy( + () -> { + try (PreparedStatement update = + connection.prepareStatement( + "UPDATE world_instance SET public_production = TRUE, canonical_game_instance_id = ?, " + + "canonical_target_namespace = 'firemud', canonical_tenant_id = ?, " + + "canonical_world_slug = 'retained-v32-world', " + + "playable_state_namespace_id = ?, playable_state_scope = 'SHARED', " + + "canonical_launch_binding_operation_id = ? WHERE id = ?")) { + update.setObject(1, attemptedGameInstanceId); + update.setObject(2, attemptedTenantId); + update.setObject(3, attemptedPlayableNamespaceId); + update.setObject(4, attemptedBindingId); + update.setLong(5, worldInstanceId); + update.executeUpdate(); + } + }) + .isInstanceOf(SQLException.class); + } + + try (Connection connection = fixtureConnection(schema); + Statement statement = connection.createStatement(); + ResultSet count = + statement.executeQuery("SELECT COUNT(*) FROM world_canonical_instance_association")) { + assertThat(count.next()).isTrue(); + assertThat(count.getLong(1)).isZero(); + } + } finally { + dropFixtureSchema(schema); + } + } + + private Fixture fixture() { + SourceFixture source = sourceFixture(); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = positiveLong(); + WorldAuthoredVersionIdentityReceipt identity = + seedVersionIdentity(source, canonicalVersionId, gameDesignVersionId, VERSION_EPOCH); + SeededPair pair = + seedPair( + source, + identity, + controlRequest(), + "synthetic-launch-descriptor", + "synthetic-release-attestation"); + return new Fixture(source, pair.binding(), pair.versionIdentity()); + } + + private SourceFixture sourceFixture() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt receipt = + ownerTransaction() + .execute(status -> sourceRepository.acceptFresh(NAMESPACE, UUID.randomUUID(), source)); + return new SourceFixture( + source, Objects.requireNonNull(receipt, "source intake returned no receipt")); + } + + private SeededPair seedPair( + SourceFixture source, + WorldAuthoredVersionIdentityReceipt identity, + String controlPlaneRequestId, + String launchDescriptorId, + String attestationCommit) { + return seedPair( + source, + identity, + controlPlaneRequestId, + launchDescriptorId, + attestationCommit, + identity.canonicalVersionId(), + identity.gameDesignVersionId()); + } + + private SeededPair seedPair( + SourceFixture source, + WorldAuthoredVersionIdentityReceipt identity, + String controlPlaneRequestId, + String launchDescriptorId, + String attestationCommit, + UUID canonicalVersionId, + long gameDesignVersionId) { + WorldAuthoredVersionIdentityReceipt resolvedIdentity = + identity == null + ? seedVersionIdentity(source, canonicalVersionId, gameDesignVersionId, VERSION_EPOCH) + : identity; + CompleteLaunchBindingEvidence evidence = + completeEvidence( + source.source(), + controlPlaneRequestId, + gameDesignVersionId, + canonicalVersionId, + VERSION_EPOCH, + launchDescriptorId, + attestationCommit); + WorldCompleteLaunchBindingReceipt binding = + ownerTransaction() + .execute( + status -> + launchBindingRepository.acceptFresh(NAMESPACE, source.receipt(), evidence)); + return new SeededPair( + Objects.requireNonNull(binding, "launch binding returned no receipt"), resolvedIdentity); + } + + private WorldAuthoredVersionIdentityReceipt seedVersionIdentity( + SourceFixture source, UUID canonicalVersionId, long gameDesignVersionId, long epoch) { + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + source.source().canonicalTenantId(), + source.source().worldSlug(), + source.source().operationId(), + source.source().evidenceDigest(), + gameDesignVersionId); + AuthoredWorldVersionStateEvidence evidence = + AuthoredWorldVersionStateEvidence.create( + request, + source.source(), + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + epoch); + return Objects.requireNonNull( + ownerTransaction() + .execute(status -> versionIdentityRepository.acceptFresh(source.receipt(), evidence)), + "Version identity returned no receipt"); + } + + private long insertCanonicalWorldRow( + Fixture fixture, UUID canonicalGameInstanceId, UUID playableStateNamespaceId) { + return prepareCanonicalWorldRow( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L) + .association() + .worldInstanceId(); + } + + private long insertCanonicalWorldRow( + SeededPair pair, + SourceFixture source, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId) { + Fixture fixture = new Fixture(source, pair.binding(), pair.versionIdentity()); + return insertCanonicalWorldRow(fixture, canonicalGameInstanceId, playableStateNamespaceId); + } + + private WorldCanonicalInstancePreparation.Result prepareCanonicalWorldRow( + Fixture fixture, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String observedGameSessionStatus, + long observedGameSessionRowVersion) { + return preparationService(() -> {}) + .prepare( + preparationInput( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + observedGameSessionStatus, + observedGameSessionRowVersion)); + } + + private WorldCanonicalInstancePreparation.Input preparationInput( + Fixture fixture, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String observedGameSessionStatus, + long observedGameSessionRowVersion) { + var request = + request( + new SeededPair(fixture.binding(), fixture.versionIdentity()), + canonicalGameInstanceId, + UUID.randomUUID()); + var response = + responseFor( + fixture.binding().evidence(), + canonicalGameInstanceId, + playableStateNamespaceId, + request.readRequestId(), + observedGameSessionStatus, + observedGameSessionRowVersion); + return new WorldCanonicalInstancePreparation.Input( + request, response, fixture.binding(), fixture.versionIdentity(), frozenPlan(fixture)); + } + + private WorldCanonicalInstancePreparationService preparationService(Runnable heldCheck) { + WorldCanonicalFrozenTopologyRepository frozenRepository = + new WorldCanonicalFrozenTopologyRepository( + dsl, + graphSnapshots, + new WorldDraftTopologyCommitRepository(dsl, publicationFence, objectMapper), + digestService); + WorldCanonicalInstancePreparationRepository preparationRepository = + new WorldCanonicalInstancePreparationRepository( + dsl, transactionManager, associationRepository, frozenRepository); + // Synthetic fixture handle only. This does not authenticate GS/GD source or delivery, prove + // APPLIED/IN_SYNC, or supply Account authority. + return new WorldCanonicalInstancePreparationService( + preparationRepository, + input -> + new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + @Override + public void requireHeld() { + heldCheck.run(); + } + + @Override + public void close() {} + }); + } + + private WorldCanonicalInstanceTopologyPlan frozenPlan(Fixture fixture) { + return frozenPlans.computeIfAbsent( + fixture.versionIdentity().operationId(), + ignored -> { + WorldDraftTopologyCommitPlan draft = topologyPlan(fixture); + new WorldDraftTopologyCommitService( + new WorldDraftTopologyCommitRepository(dsl, publicationFence, objectMapper), + transactionManager, + plan -> { + // Synthetic local storage permission only; no Account or Entity proof. + }) + .store(draft); + var owner = draft.ownerBinding(); + String publicationRequest = "preparation-capture-" + UUID.randomUUID(); + WorldDesignPublicationFenceEvidence evidence = + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + publicationRequest, + "a".repeat(64), + fixture.versionIdentity().versionStateEvidence().versionStateEpoch(), + "publish:" + + owner.canonicalTenantId() + + ":publish-request:" + + publicationRequest); + var attempt = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + publicationFence.claimFreeze( + evidence, + () -> { + var digest = + digestService.getDraftDesignDigest( + Long.toString( + fixture.source().receipt().localTenantKey()), + Long.toString( + fixture.versionIdentity().localVersionKey())); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + draft.binding().commitId().toString(), + digest.contentDigest(), + 3); + })), + "Synthetic frozen preparation fixture returned no publication checkpoint"); + List tuples = + draft.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + CaptureRequest captureRequest = + new CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + attempt.publicationFence(), + publicationRequest, + evidence.requestDigest(), + evidence.versionStateEpoch(), + evidence.publishWorkflowId(), + attempt.checkpoint().appliedCommitId(), + attempt.checkpoint().contentDigest(), + attempt.checkpoint().digestSchemaVersion(), + tuples); + WorldCanonicalFrozenTopology frozen = + new WorldCanonicalFrozenTopologyService( + new WorldCanonicalFrozenTopologyRepository( + dsl, + graphSnapshots, + new WorldDraftTopologyCommitRepository( + dsl, publicationFence, objectMapper), + digestService), + transactionManager) + .capture(new WorldCanonicalFrozenTopology.Request(draft, captureRequest)); + return WorldCanonicalInstanceTopologyPlan.create(frozen); + }); + } + + private WorldDraftTopologyCommitPlan topologyPlan(Fixture fixture) { + UUID commitId = UUID.randomUUID(); + UUID regionId = UUID.randomUUID(); + UUID zoneId = UUID.randomUUID(); + UUID roomId = UUID.randomUUID(); + UUID destinationRoomId = UUID.randomUUID(); + List mutations = + List.of( + mutation( + commitId, + regionId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + regionId) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("synthetic region") + .setWeather("rain") + .setShardId(7) + .setGenerationSeed(9001) + .setGeneratorType("synthetic") + .setGeneratorParams("{}")) + .build(), + mutation( + commitId, + zoneId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + regionId) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("synthetic zone") + .setRegionId(regionId.toString())) + .build(), + mutation( + commitId, + destinationRoomId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + regionId) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("synthetic destination") + .setZoneId(zoneId.toString()) + .setDescription("synthetic destination room")) + .build(), + mutation( + commitId, + roomId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + regionId) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("synthetic room") + .setZoneId(zoneId.toString()) + .setDescription("synthetic materialization proof")) + .build(), + mutation( + commitId, + UUID.randomUUID(), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + regionId) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(roomId.toString()) + .setToRoomId(destinationRoomId.toString()) + .setDirection("EAST") + .setCost(3)) + .build()); + List revisions = new java.util.ArrayList<>(); + List units = new java.util.ArrayList<>(); + for (WorldDesignMutationRevision mutation : mutations) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(mutation.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + json(mutation))); + String family = + mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "AGGREGATE", + mutation.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "REGION_SUBTREE", + mutation.getScopeId(), + "0")); + } + var source = fixture.source().source(); + var owner = + new OwnerBinding( + NAMESPACE, + source.canonicalTenantId(), + fixture.versionIdentity().canonicalVersionId(), + fixture.versionIdentity().operationId(), + fixture.versionIdentity().gameDesignVersionId(), + fixture.source().receipt().intakeRequestId(), + fixture.source().receipt().operationId(), + fixture.source().receipt().requestDigest(), + source.operationId(), + source.evidenceDigest(), + fixture.source().receipt().receiptDigest()); + var target = + new DraftCommitBinding.TargetProof( + source.canonicalTenantId(), + fixture.versionIdentity().canonicalVersionId(), + fixture.versionIdentity().gameDesignVersionId(), + source.sourceGameTenantKey(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + return WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + target, UUID.randomUUID(), commitId, "synthetic-base-commit", revisions, units), + owner); + } + + private static WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID aggregateId, WorldDesignAggregateType type, UUID containingRegionId) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(aggregateId.toString()) + .setAggregateType(type) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(containingRegionId.toString()); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new AssertionError(exception); + } + } + + private long preparationCount(UUID canonicalGameInstanceId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_canonical_instance_preparation " + + "WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId), + "World preparation count query returned no row") + .get(0, Long.class); + } + + private Record topologyIdentity(long worldInstanceId, String family, UUID templateId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT template_id, template_private_row_key, runtime_row_id, runtime_identity, " + + "runtime_room_instance_id FROM world_canonical_instance_topology_identity " + + "WHERE world_instance_id = ? AND family = ? AND template_id = ?", + worldInstanceId, + family, + templateId), + "canonical source/runtime identity mapping missing for " + + family + + " template " + + templateId); + } + + private long insertLegacyWorldRow(Fixture fixture, long gameInstanceKey) { + var descriptor = fixture.binding().descriptor(); + Record inserted = + 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, script_patch_version, " + + "runtime_flags_json, generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, remap_set_id, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'LEGACY_FIXTURE') RETURNING id", + 8_100_000_000L + + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 100_000L), + gameInstanceKey, + descriptor.gameTemplateId(), + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + fixture.versionIdentity().localVersionKey(), + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null, + descriptor.runtimeFlagsJson(), + descriptor.generationConfigRevision(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null), + "legacy World row insert returned no row"); + return inserted.get("id", Long.class); + } + + private WorldCanonicalInstanceAssociation.Claim claim( + Fixture fixture, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + long worldInstanceId, + long rowVersion, + String status) { + return claim( + new SeededPair(fixture.binding(), fixture.versionIdentity()), + canonicalGameInstanceId, + playableStateNamespaceId, + worldInstanceId, + rowVersion, + status); + } + + private WorldCanonicalInstanceAssociation.Claim claim( + SeededPair pair, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + long worldInstanceId, + long rowVersion, + String status) { + WorldCanonicalInstanceAssociation.GameSessionReadRequest request = + request(pair, canonicalGameInstanceId, UUID.randomUUID()); + WorldCanonicalInstanceAssociation.GameSessionReadEvidence response = + responseFor( + pair.binding().evidence(), + canonicalGameInstanceId, + playableStateNamespaceId, + request.readRequestId(), + status, + rowVersion); + return new WorldCanonicalInstanceAssociation.Claim( + request, response, worldInstanceId, pair.binding(), pair.versionIdentity()); + } + + private WorldCanonicalInstanceAssociation.GameSessionReadRequest request( + SeededPair pair, UUID canonicalGameInstanceId, UUID readRequestId) { + return requestFor(pair.binding().evidence(), canonicalGameInstanceId, readRequestId); + } + + private WorldCanonicalInstanceAssociation.GameSessionReadRequest requestFor( + CompleteLaunchBindingEvidence evidence, UUID canonicalGameInstanceId, UUID readRequestId) { + var descriptor = evidence.descriptor(); + var release = evidence.releaseAttestation(); + return new WorldCanonicalInstanceAssociation.GameSessionReadRequest( + readRequestId, + NAMESPACE, + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + canonicalGameInstanceId, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + } + + private WorldCanonicalInstanceAssociation.GameSessionReadEvidence responseFor( + CompleteLaunchBindingEvidence evidence, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + UUID readRequestId, + String status, + long rowVersion) { + return responseFor( + evidence, + canonicalGameInstanceId, + playableStateNamespaceId, + readRequestId, + status, + rowVersion, + true); + } + + private WorldCanonicalInstanceAssociation.GameSessionReadEvidence responseFor( + CompleteLaunchBindingEvidence evidence, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + UUID readRequestId, + String status, + long rowVersion, + boolean publicProduction) { + var descriptor = evidence.descriptor(); + var release = evidence.releaseAttestation(); + return new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + readRequestId, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + canonicalGameInstanceId, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest(), + playableStateNamespaceId, + "SHARED", + publicProduction, + status, + rowVersion, + descriptor, + release); + } + + private long associationCount(UUID canonicalGameInstanceId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId), + "World canonical association count query returned no row") + .get(0, Long.class); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private static CompleteLaunchBindingEvidence completeEvidence( + AuthoredWorldSourceEvidence source, + String controlPlaneRequestId, + long gameDesignVersionId, + UUID canonicalVersionId, + long epoch, + String launchDescriptorId, + String attestationCommit) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + 73L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + launchDescriptorId, + gameDesignVersionId, + false, + null, + "{}", + "generation-config-73", + epoch, + 79L, + "release-bundle-79", + false, + null); + return new CompleteLaunchBindingEvidence( + descriptor, attestation(descriptor, source, canonicalVersionId, attestationCommit)); + } + + private static AuthoredWorldReleaseAttestationEvidence attestation( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + String commit) { + List participants = + List.of( + participant("WORLD_MANAGEMENT", 3, "a", false, descriptor.versionId(), commit), + participant("ENTITY_MANAGEMENT", 2, "b", false, descriptor.versionId(), commit), + participant("GAME_LOGIC", 1, "c", true, descriptor.versionId(), commit), + participant("AUTOMATION_SCRIPTING", 5, "d", false, descriptor.versionId(), commit), + participant( + "GAME_DESIGN_CONTROL_PLANE", 1, "e", false, descriptor.versionId(), commit)); + return AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersionId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:synthetic:association-fixture", + commit, + participants, + digest('f'), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision()); + } + + private static AuthoredWorldReleaseAttestationEvidence.Participant participant( + String owner, + int schema, + String contentHex, + boolean hasAbilityDigest, + long descriptorVersion, + String commit) { + return new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptorVersion), + false, + null, + commit, + contentHex.repeat(64), + schema, + hasAbilityDigest, + hasAbilityDigest ? digest('c') : null); + } + + private static AuthoredWorldSourceEvidence source(UUID tenant, String worldSlug) { + UUID registrationRequest = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String displayName = "Synthetic 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 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 long positiveLong() { + return Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent canonical association barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent canonical association 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 record SourceFixture( + AuthoredWorldSourceEvidence source, WorldAuthoredSourceIntakeReceipt receipt) {} + + private record SeededPair( + WorldCompleteLaunchBindingReceipt binding, + WorldAuthoredVersionIdentityReceipt versionIdentity) {} + + private record Fixture( + SourceFixture source, + WorldCompleteLaunchBindingReceipt binding, + WorldAuthoredVersionIdentityReceipt versionIdentity) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java new file mode 100644 index 0000000000..3ddc2bebff --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java @@ -0,0 +1,202 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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 org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Actual V35 database denial proof; all external source/authentication data is synthetic. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldCanonicalInstancePreparationPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + + @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; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void v35PreservesReservedTenantDenialAndDoesNotExposePrepareFunctionToPublic() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID()); + WorldAuthoredSourceIntakeReceipt receipt = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + new WorldAuthoredSourceIntakeRepository(dsl) + .acceptFresh(NAMESPACE, UUID.randomUUID(), source)), + "synthetic World source fixture returned no intake receipt"); + + assertThatThrownBy(() -> insertInReservedCanonicalTenant(receipt.localTenantKey())) + .isInstanceOf(DataIntegrityViolationException.class) + .rootCause() + .isInstanceOf(PSQLException.class) + .hasMessageContaining(reservedTenantDenial()); + + long legacyInstance = insertLegacyRow(8_700_000_000L + positiveLong() % 100_000L); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET tenant_id = ? WHERE id = ?", + receipt.localTenantKey(), + legacyInstance)) + .isInstanceOf(DataIntegrityViolationException.class) + .rootCause() + .isInstanceOf(PSQLException.class) + .hasMessageContaining(reservedTenantDenial()); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_id FROM world_instance WHERE id = ?", legacyInstance), + "Legacy row missing after rejected canonical update") + .get("tenant_id", Long.class)) + .isNotEqualTo(receipt.localTenantKey()); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_proc p " + + "JOIN pg_namespace n ON n.oid = p.pronamespace " + + "CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) acl " + + "WHERE n.nspname = 'world_management_service' " + + "AND p.proname = 'world_prepare_canonical_instance' " + + "AND acl.grantee = 0 AND acl.privilege_type = 'EXECUTE')"), + "Prepare-function access query returned no result") + .get(0, Boolean.class)) + .isFalse(); + } + + private void insertInReservedCanonicalTenant(long tenantKey) { + dsl.execute( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, runtime_flags_json, " + + "generation_config_revision, release_bundle_id, published_release_bundle_ref, " + + "version_state_epoch, status) VALUES (?, ?, 71, 'direct-canonical-insert', " + + "'direct-canonical-descriptor', 83, '{}', 'direct-config', 97, " + + "'direct-release', 5, 'DIRECT_FIXTURE')", + tenantKey, + positiveLong()); + } + + private static String reservedTenantDenial() { + return "World tenant key is reserved for a canonical authored source; " + + "no exact transaction execution manifest"; + } + + private long insertLegacyRow(long tenantKey) { + return 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, " + + "runtime_flags_json, generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, status) " + + "VALUES (?, ?, 71, 'legacy-tenant-row', 'legacy-descriptor', 83, '{}', " + + "'legacy-config', 97, 'legacy-release', 5, 'LEGACY_FIXTURE') RETURNING id", + tenantKey, + positiveLong()), + "synthetic unrelated legacy fixture insert returned no row") + .get("id", Long.class); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return transaction; + } + + private static AuthoredWorldSourceEvidence source(UUID tenant) { + UUID registration = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + String display = "Synthetic guard fixture"; + long rowId = positiveLong(); + String sourceTenantKey = "gd-" + tenant.toString().replace("-", "").substring(0, 20); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, display); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + operation, + requestDigest, + tenant, + tenantSlug, + worldSlug, + display, + rowId, + sourceTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + operation, + requestDigest, + tenant, + tenantSlug, + worldSlug, + display, + rowId, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static long positiveLong() { + return Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java index 2af9707633..cb93a4a59b 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java @@ -534,11 +534,18 @@ void v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory() throw scope.getKey().equals("world_authored_version_identity") ? " OVERRIDING SYSTEM VALUE" : ""; + String columns = + scope.getKey().equals("world_entity_spawn_binding") + ? "id,tenant_id,version_id,room_id,entity_template_type,entity_template_id,spawn_count,respawn_delay_seconds,version" + : null; retained.execute( "INSERT INTO " + scope.getKey() + + (columns == null ? "" : " (" + columns + ")") + override - + " SELECT * FROM world_management_service." + + " SELECT " + + (columns == null ? "*" : columns) + + " FROM world_management_service." + scope.getKey() + " WHERE " + scope.getValue() @@ -564,7 +571,8 @@ void v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory() throw } connection.setAutoCommit(true); scopes.put("world_authored_graph_snapshot", "local_tenant_key"); - Map> before = retainedRows(retained, scopes.keySet().stream().toList()); + Map> before = + retainedRows(retained, scopes.keySet().stream().toList(), true); assertThat( retained .resultQuery( @@ -586,7 +594,13 @@ void v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory() throw .locations("classpath:db/migration") .load() .migrate(); - assertThat(retainedRows(retained, scopes.keySet().stream().toList())).isEqualTo(before); + assertThat(retainedRows(retained, scopes.keySet().stream().toList(), true)).isEqualTo(before); + assertThat( + retained + .resultQuery( + "SELECT COUNT(*) FROM world_entity_spawn_binding WHERE entity_canonical_tenant_id IS NOT NULL OR entity_canonical_version_id IS NOT NULL OR entity_canonical_template_id IS NOT NULL") + .fetchOne(0, Long.class)) + .isZero(); SingleConnectionDataSource dataSource = new SingleConnectionDataSource(connection, true); DataSourceTransactionManager retainedManager = new DataSourceTransactionManager(dataSource); DriverManagerDataSource committedReadDataSource = @@ -618,7 +632,7 @@ void v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory() throw assertThatThrownBy( () -> deniedFrozen.store(plan(f, List.of(f.first()), 1, "must-remain-frozen"))) .hasMessageContaining("not open"); - assertThat(retainedRows(retained, scopes.keySet().stream().toList())).isEqualTo(before); + assertThat(retainedRows(retained, scopes.keySet().stream().toList(), true)).isEqualTo(before); assertThat( retained .resultQuery("SELECT COUNT(*) FROM world_region_draft_commit") @@ -631,13 +645,28 @@ void v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory() throw } private Map> retainedRows(DSLContext retained, List tables) { + return retainedRows(retained, tables, false); + } + + private Map> retainedRows( + DSLContext retained, List tables, boolean retainedSpawnColumnsOnly) { Map> rows = new LinkedHashMap<>(); for (String table : tables) { + String expression = + retainedSpawnColumnsOnly && table.equals("world_entity_spawn_binding") + ? "to_jsonb(t) - 'entity_canonical_tenant_id' - 'entity_canonical_version_id' - 'entity_canonical_template_id'" + : "to_jsonb(t)"; rows.put( table, retained .resultQuery( - "SELECT to_jsonb(t)::TEXT FROM " + table + " t ORDER BY to_jsonb(t)::TEXT") + "SELECT (" + + expression + + ")::TEXT FROM " + + table + + " t ORDER BY (" + + expression + + ")::TEXT") .fetch(0, String.class)); } return rows; diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPostgresIntegrationTest.java new file mode 100644 index 0000000000..3f60f1c759 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPostgresIntegrationTest.java @@ -0,0 +1,1368 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.util.ArrayList; +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 net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +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.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +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.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +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; +import tools.jackson.databind.ObjectMapper; + +/** + * Synthetic source/permission fixtures prove component storage only, never authenticated APPLIED. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldDraftTopologyCommitPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final long GAME_DESIGN_VERSION = 9_000_000_000_000_001L; + + @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 manager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository fence; + @Autowired private ObjectMapper mapper; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void allSixFamiliesAllocateTypedUuidRowsAndPreserveExactInputWithDefaults() { + Fixture f = fixture(); + var p = plan(f); + var e = component().store(p); + assertThat(e.binding()).isEqualTo(p.binding()); + assertThat(e.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + assertThat(count(f, "world_design_aggregate_epoch")).isEqualTo(7); + assertThat(count(f, "world_design_scope_epoch")).isEqualTo(1); + for (String t : + List.of("region", "zone", "room_exit", "generation_rule", "world_entity_spawn_binding")) { + assertThat(count(f, t)).isEqualTo(1); + } + assertThat(count(f, "room")).isEqualTo(2); + var nodes = p.graph().nodes(); + UUID logical = nodes.getLast().templateId(); + assertThat(nodes.stream().filter(n -> n.templateId().equals(logical)).toList()).hasSize(6); + for (var n : nodes) { + String family = + n.mutation().getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + assertThat(privateKey(p, family, n.templateId())).isPositive(); + assertThat(n.templateId().toString()).contains("-"); + } + assertThat( + dsl.resultQuery( + "SELECT spacing_multiplier FROM region WHERE tenant_id=?", + f.intake().localTenantKey()) + .fetchOne(0, Double.class)) + .isEqualTo(1.0); + assertThat( + dsl.resultQuery( + "SELECT cost FROM room_exit WHERE tenant_id=?", f.intake().localTenantKey()) + .fetchOne(0, Integer.class)) + .isEqualTo(1); + var spawn = nodes.getFirst().entityReference(); + var row = + dsl.resultQuery( + "SELECT * FROM world_entity_spawn_binding WHERE tenant_id=?", + f.intake().localTenantKey()) + .fetchOne(); + assertThat(row).isNotNull(); + assertThat(row.get("entity_template_id")).isNull(); + assertThat(row.get("entity_canonical_template_id", UUID.class)).isEqualTo(spawn.templateId()); + assertThat(row.get("entity_canonical_tenant_id", UUID.class)).isEqualTo(spawn.tenantId()); + assertThat(row.get("entity_canonical_version_id", UUID.class)).isEqualTo(spawn.versionId()); + assertThat(row.get("spawn_count", Integer.class)).isEqualTo(1); + assertThat(new String(e.graphBytes(), StandardCharsets.UTF_8)) + .contains( + "\"schemaVersion\":\"2\"", + "entity_canonical_template_id", + spawn.templateId().toString()); + assertThat(new String(e.resultBytes(), StandardCharsets.UTF_8)) + .contains(p.binding().digest(), "\"epoch\":\"1\"") + .doesNotContain("\"APPLIED\"", "permissionFenceReleased"); + // The retained numeric graph/v1 decoder must fail closed on canonical Entity UUID references. + assertThatThrownBy( + () -> + new WorldAuthoredGraphReader(dsl) + .readAndValidateGraph( + f.intake().localTenantKey(), f.version().localVersionKey())) + .hasMessageContaining("entity_template_id"); + // No canonical Entity private mapping or authenticated Account proof was manufactured. + assertThat( + dsl.resultQuery("SELECT count(*) FROM world_region_draft_execution_manifest") + .fetchOne(0, Long.class)) + .isZero(); + } + + @Test + void snakeCaseAndNumericEnumsStoreDefaultsAndRetainOriginalRawBindingAndRetry() + throws InvalidProtocolBufferException { + Fixture f = fixture(); + var printerPlan = plan(f); + var original = printerPlan.binding(); + List rawRevisions = new ArrayList<>(); + for (var revision : original.revisions()) { + String raw = revision.payload(); + if (revision.owner() == Owner.WORLD_MANAGEMENT) { + var node = + printerPlan.graph().nodes().stream() + .filter(n -> n.revisionId().equals(revision.revisionId())) + .findFirst() + .orElseThrow(); + raw = + JsonFormat.printer() + .preservingProtoFieldNames() + .printingEnumsAsInts() + .omittingInsignificantWhitespace() + .print(node.mutation()); + } + rawRevisions.add( + new DraftCommitBinding.RevisionPayload( + revision.revisionOrder(), revision.revisionId(), revision.owner(), raw)); + } + var rawBinding = + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + rawRevisions, + original.affectedUnits()); + var rawPlan = WorldDraftTopologyCommitPlan.create(rawBinding, printerPlan.ownerBinding()); + var rawFirst = rawBinding.revisions().get(1).payload(); + assertThat(rawFirst) + .contains( + "\"aggregate_type\":" + + rawPlan.graph().nodes().getFirst().mutation().getAggregateType().getNumber(), + "\"entity_template_type\":"); + var stored = component().store(rawPlan); + assertThat(stored.binding().canonicalBytes()).containsExactly(rawBinding.canonicalBytes()); + assertThat(stored.binding().digest()) + .isEqualTo(rawBinding.digest()) + .isNotEqualTo(original.digest()); + var history = + dsl.resultQuery( + "SELECT binding_json,binding_digest FROM world_topology_draft_commit WHERE request_id=?", + rawBinding.requestId()) + .fetchOne(); + assertThat(history).isNotNull(); + assertThat(history.get("binding_json", String.class)).isEqualTo(rawBinding.canonicalJson()); + assertThat(history.get("binding_digest", String.class)).isEqualTo(rawBinding.digest()); + assertThat( + dsl.resultQuery( + "SELECT spacing_multiplier FROM region WHERE tenant_id=?", + f.intake().localTenantKey()) + .fetchOne(0, Double.class)) + .isEqualTo(1.0); + assertThat( + dsl.resultQuery( + "SELECT cost FROM room_exit WHERE tenant_id=?", f.intake().localTenantKey()) + .fetchOne(0, Integer.class)) + .isEqualTo(1); + assertThat( + dsl.resultQuery( + "SELECT spawn_count FROM world_entity_spawn_binding WHERE tenant_id=?", + f.intake().localTenantKey()) + .fetchOne(0, Integer.class)) + .isEqualTo(1); + var retry = component().store(rawPlan); + assertThat(retry.resultBytes()).containsExactly(stored.resultBytes()); + assertThat(retry.graphBytes()).containsExactly(stored.graphBytes()); + var readback = + new WorldDraftTopologyCommitService(repository(), manager) + .readCommitted(rawPlan) + .orElseThrow(); + assertThat(readback.resultBytes()).containsExactly(stored.resultBytes()); + assertThat(readback.binding().revisions()).isEqualTo(rawRevisions); + assertThat(new String(stored.resultBytes(), StandardCharsets.UTF_8)) + .contains(rawBinding.digest()); + // Same parsed semantics with different raw bytes remains a changed complete operation. + rejectReplay(printerPlan); + assertThat(count(f, "world_topology_draft_commit")).isEqualTo(1); + } + + @Test + void alteredTrustedProjectionSemanticsRollBackAgainstOriginalParsedPlan() + throws InvalidProtocolBufferException { + Fixture f = fixture(); + var p = plan(f); + var tampered = + new WorldDraftTopologyCommitRepository(dsl, fence, mapper) { + @Override + List executionRevisions( + WorldDraftTopologyCommitPlan input) { + var revisions = new ArrayList<>(super.executionRevisions(input)); + var node = input.graph().nodes().getFirst(); + var changed = + node.mutation().toBuilder() + .setWorldEntitySpawnBinding( + node.mutation().getWorldEntitySpawnBinding().toBuilder().setSpawnCount(2)) + .build(); + var original = revisions.getFirst(); + revisions.set( + 0, + new DraftCommitBinding.RevisionPayload( + original.revisionOrder(), + original.revisionId(), + original.owner(), + json(changed))); + return revisions; + } + }; + assertThatThrownBy( + () -> new WorldDraftTopologyCommitService(tampered, manager, x -> {}).store(p)) + .hasMessageContaining("every exact payload field"); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_authored_topology_identity", + "world_design_aggregate_epoch", + "world_design_scope_epoch", + "world_topology_draft_commit")) { + assertThat(count(f, table)).as(table).isZero(); + } + assertThat(new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .isEmpty(); + component().store(p); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + } + + @Test + void lostAckAndIndependentFrozenReadbackReturnOriginalExactEvidence() { + Fixture f = fixture(); + var p = plan(f); + var denied = new WorldDraftTopologyCommitService(repository(), manager); + assertThat(denied.readCommitted(p)).isEmpty(); + var first = component().store(p); + var retry = component().store(p); + assertThat(retry.graphBytes()).containsExactly(first.graphBytes()); + assertThat(retry.resultBytes()).containsExactly(first.resultBytes()); + freeze(f); + var read = denied.readCommitted(p).orElseThrow(); + assertThat(read.graphBytes()).containsExactly(first.graphBytes()); + assertThat(read.resultBytes()).containsExactly(first.resultBytes()); + assertThat(component().store(p).resultBytes()).containsExactly(first.resultBytes()); + assertThat(count(f, "world_topology_draft_commit")).isEqualTo(1); + } + + @Test + void completeReplayRejectsChangedBasePayloadOrderAffectedAndSource() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + var b = p.binding(); + var changedBase = + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + b.target(), + b.requestId(), + b.commitId(), + b.baseCommitId() + "-changed", + b.revisions(), + b.affectedUnits()), + p.ownerBinding()); + rejectReplay(changedBase); + var t = b.target(); + var changedTarget = + new DraftCommitBinding.TargetProof( + t.canonicalTenantId(), + t.canonicalVersionId(), + t.gameDesignVersionRowId(), + t.gameDesignVersionTenantKey(), + t.sourceGameRowId() + 1, + t.sourceGameTenantKey(), + t.sourceProvenanceKind()); + rejectReplay( + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + changedTarget, + b.requestId(), + b.commitId(), + b.baseCommitId(), + b.revisions(), + b.affectedUnits()), + p.ownerBinding())); + var revisions = new ArrayList<>(b.revisions()); + var other = revisions.getFirst(); + revisions.set( + 0, + new DraftCommitBinding.RevisionPayload( + other.revisionOrder(), other.revisionId(), other.owner(), other.payload() + "changed")); + rejectReplay( + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + b.target(), + b.requestId(), + b.commitId(), + b.baseCommitId(), + revisions, + b.affectedUnits()), + p.ownerBinding())); + revisions = new ArrayList<>(b.revisions()); + var one = revisions.get(1); + var two = revisions.get(2); + revisions.set( + 1, + new DraftCommitBinding.RevisionPayload("1", two.revisionId(), two.owner(), two.payload())); + revisions.set( + 2, + new DraftCommitBinding.RevisionPayload("2", one.revisionId(), one.owner(), one.payload())); + rejectReplay( + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + b.target(), + b.requestId(), + b.commitId(), + b.baseCommitId(), + revisions, + b.affectedUnits()), + p.ownerBinding())); + assertThatThrownBy( + () -> + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + b.target(), + b.requestId(), + b.commitId(), + b.baseCommitId(), + b.revisions(), + b.affectedUnits().subList(1, b.affectedUnits().size())), + p.ownerBinding())) + .isInstanceOf(IllegalArgumentException.class); + var o = p.ownerBinding(); + var source = + new OwnerBinding( + o.targetNamespace(), + o.canonicalTenantId(), + o.canonicalVersionId(), + o.versionIdentityOperationId(), + o.gameDesignVersionId(), + o.intakeRequestId(), + o.intakeOperationId(), + o.intakeRequestDigest(), + UUID.randomUUID(), + o.sourceEvidenceDigest(), + o.intakeReceiptDigest()); + rejectReplay(WorldDraftTopologyCommitPlan.create(b, source)); + assertThat(count(f, "world_topology_draft_commit")).isEqualTo(1); + } + + private void rejectReplay(WorldDraftTopologyCommitPlan p) { + assertThatThrownBy(() -> component().store(p)) + .hasMessageContaining("changed full input or source"); + assertThatThrownBy( + () -> new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .hasMessageContaining("changed full input or source"); + } + + @Test + void lateFailureRollsBackAllFamiliesMappingsEpochsAndHistory() { + Fixture f = fixture(); + var p = plan(f); + var failing = + new WorldDraftTopologyCommitRepository(dsl, fence, mapper) { + @Override + WorldDraftTopologyCommitEvidence store(WorldDraftTopologyCommitPlan input) { + super.store(input); + throw new IllegalStateException("late complete result conflict"); + } + }; + assertThatThrownBy( + () -> new WorldDraftTopologyCommitService(failing, manager, x -> {}).store(p)) + .hasMessage("late complete result conflict"); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_authored_topology_identity", + "world_design_aggregate_epoch", + "world_design_scope_epoch", + "world_topology_draft_commit")) { + assertThat(count(f, table)).as(table).isZero(); + } + assertThat(new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .isEmpty(); + component().store(p); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + } + + @Test + void exactConcurrentFirstClaimReturnsOneOriginalResult() throws Exception { + Fixture f = fixture(); + var p = plan(f); + CountDownLatch begin = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future one = + executor.submit( + () -> { + await(begin); + return component().store(p); + }); + Future two = + executor.submit( + () -> { + await(begin); + return component().store(p); + }); + begin.countDown(); + var first = one.get(20, TimeUnit.SECONDS); + var second = two.get(20, TimeUnit.SECONDS); + assertThat(second.resultBytes()).containsExactly(first.resultBytes()); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + assertThat(count(f, "world_topology_draft_commit")).isEqualTo(1); + } finally { + begin.countDown(); + executor.shutdownNow(); + } + } + + @Test + void conflictingFirstClaimsCannotRemapPreviouslyAllocatedRows() throws Exception { + Fixture f = fixture(); + var first = plan(f); + var second = plan(f); + CountDownLatch begin = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future one = executor.submit(() -> contend(first, begin)); + Future two = executor.submit(() -> contend(second, begin)); + begin.countDown(); + assertThat(List.of(one.get(20, TimeUnit.SECONDS), two.get(20, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + assertThat(count(f, "world_topology_draft_commit")).isEqualTo(1); + } finally { + begin.countDown(); + executor.shutdownNow(); + } + } + + private boolean contend(WorldDraftTopologyCommitPlan p, CountDownLatch begin) { + await(begin); + try { + component().store(p); + return true; + } catch (RuntimeException exception) { + assertThat(exception).hasStackTraceContaining("conflicts with retained"); + return false; + } + } + + @Test + void freezeFirstDeniesAndWriterFirstSerializesFreezeUntilAtomicCommit() throws Exception { + Fixture frozen = fixture(); + freeze(frozen); + assertThatThrownBy(() -> component().store(plan(frozen))).hasMessageContaining("not open"); + assertThat(count(frozen, "world_authored_topology_identity")).isZero(); + Fixture f = fixture(); + var p = plan(f); + CountDownLatch locked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch freezing = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var paused = + new WorldDraftTopologyCommitRepository(dsl, fence, mapper) { + @Override + WorldDraftTopologyCommitEvidence store(WorldDraftTopologyCommitPlan input) { + var result = super.store(input); + locked.countDown(); + await(release); + return result; + } + }; + Future writer = + executor.submit( + () -> new WorldDraftTopologyCommitService(paused, manager, x -> {}).store(p)); + assertThat(locked.await(15, TimeUnit.SECONDS)).isTrue(); + Future freeze = + executor.submit( + () -> { + freezing.countDown(); + freeze(f); + }); + assertThat(freezing.await(15, TimeUnit.SECONDS)).isTrue(); + assertThat(freeze.isDone()).isFalse(); + assertThat(count(f, "region")).isZero(); + assertThat(count(f, "world_topology_draft_commit")).isZero(); + release.countDown(); + writer.get(20, TimeUnit.SECONDS); + freeze.get(20, TimeUnit.SECONDS); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + assertThat(new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .isPresent(); + } finally { + release.countDown(); + executor.shutdownNow(); + } + } + + @Test + void ordinaryWritesMappedMovesEpochTamperAndTruncateStayDenied() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + long tenant = f.intake().localTenantKey(); + long version = f.version().localVersionKey(); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding")) { + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + s -> + dsl.execute( + "INSERT INTO " + + table + + " SELECT (jsonb_populate_record(NULL::" + + table + + ",to_jsonb(t)||'{\"id\":-987654321}'::jsonb)).*" + + " FROM " + + table + + " t WHERE tenant_id=" + + tenant))) + .hasStackTraceContaining("no exact transaction execution manifest"); + for (String statement : + List.of( + "UPDATE " + table + " SET version=99 WHERE tenant_id=" + tenant, + "UPDATE " + table + " SET tenant_id=123456789 WHERE tenant_id=" + tenant, + "DELETE FROM " + table + " WHERE tenant_id=" + tenant, + "TRUNCATE " + table)) { + assertThatThrownBy(() -> ownerTransaction().execute(s -> dsl.execute(statement))) + .isInstanceOf(RuntimeException.class); + } + } + for (String statement : + List.of( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('unmanifested'," + + tenant + + "," + + version + + ")", + "UPDATE world_design_aggregate_epoch SET draft_revision_epoch=99 WHERE tenant_id=" + + tenant, + "DELETE FROM world_design_scope_epoch WHERE tenant_id=" + tenant, + "UPDATE world_authored_topology_identity SET private_row_key=999 WHERE tenant_id=" + + tenant, + "DELETE FROM world_authored_topology_identity WHERE tenant_id=" + tenant, + "TRUNCATE world_authored_topology_identity", + "TRUNCATE world_topology_draft_commit", + "TRUNCATE world_design_aggregate_epoch", + "TRUNCATE world_design_scope_epoch")) { + assertThatThrownBy(() -> ownerTransaction().execute(s -> dsl.execute(statement))) + .isInstanceOf(RuntimeException.class); + } + assertThat(new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .isPresent(); + } + + @Test + void staleOrWrongInsertManifestCannotAuthorizeOrdinaryFreshRows() { + Fixture f = fixture(); + var p = plan(f); + ownerTransaction() + .execute( + s -> { + fence.lockOpen(f.owner()); + return null; + }); + for (boolean stale : List.of(true, false)) { + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + s -> { + dsl.execute( + "INSERT INTO world_region_draft_execution_manifest " + + "SELECT txid_current()+?,?,'region',987654321,'INSERT',?,?,?,?::jsonb,?::jsonb,NULL," + + "to_jsonb(jsonb_populate_record(NULL::region,'{\"id\":987654321,\"name\":\"expected\"}'::jsonb))", + stale ? 1 : 0, + p.binding().commitId(), + f.version().operationId(), + f.intake().localTenantKey(), + f.version().localVersionKey(), + mapper.writeValueAsString(f.owner()), + p.binding().canonicalJson()); + return dsl.execute( + "INSERT INTO region(id,name,tenant_id,version_id) VALUES (987654321,'wrong',?,?)", + f.intake().localTenantKey(), + f.version().localVersionKey()); + })) + .hasStackTraceContaining("no exact transaction execution manifest"); + } + assertThat(count(f, "region")).isZero(); + } + + @Test + void retainedRowsArePreservedUnmappedAndDenyFreshContent() { + Fixture f = fixture(); + var p = plan(f); + ownerTransaction() + .execute( + s -> { + dsl.execute("SET LOCAL session_replication_role='replica'"); + try { + dsl.execute( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('retained',?,?)", + f.intake().localTenantKey(), + f.version().localVersionKey()); + } finally { + dsl.execute("SET LOCAL session_replication_role='origin'"); + } + return null; + }); + assertOrigin(); + assertThatThrownBy(() -> component().store(p)) + .hasStackTraceContaining("conflicts with retained region"); + assertThat(count(f, "region")).isEqualTo(1); + assertThat(count(f, "world_authored_topology_identity")).isZero(); + assertThat(count(f, "world_topology_draft_commit")).isZero(); + } + + @Test + void deniedPermissionAndCallerTransactionCannotClaimOrReadOwnerStorage() { + Fixture f = fixture(); + var p = plan(f); + var denied = new WorldDraftTopologyCommitService(repository(), manager); + assertThatThrownBy(() -> denied.store(p)).hasMessageContaining("permission is unavailable"); + assertThatThrownBy(() -> ownerTransaction().execute(s -> component().store(p))) + .hasMessageContaining("existing transaction"); + assertThatThrownBy(() -> ownerTransaction().execute(s -> denied.readCommitted(p))) + .hasMessageContaining("no active caller transaction"); + assertThat(count(f, "world_authored_topology_identity")).isZero(); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM world_design_publication_fence_owner WHERE local_tenant_key=?", + f.intake().localTenantKey()) + .fetchOne(0, Long.class)) + .isZero(); + } + + @Test + void v29ToV30PreservesNumericRowsSourceEpochsAndOriginalRegionHistory() throws Exception { + Fixture f = fixture(); + long region = + Objects.requireNonNull( + ownerTransaction() + .execute( + s -> { + dsl.execute("SET LOCAL session_replication_role='replica'"); + try { + long r = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('retained',?,?) RETURNING id", + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetchOne(0, Long.class), + "Missing returned region fixture key"); + long z = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO zone(region_id,name,tenant_id,version_id) VALUES (?,'zone',?,?) RETURNING id", + r, + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetchOne(0, Long.class), + "Missing returned zone fixture key"); + long room = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO room(zone_id,name,tenant_id,version_id) VALUES (?,'room',?,?) RETURNING id", + z, + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetchOne(0, Long.class), + "Missing returned room fixture key"); + dsl.execute( + "INSERT INTO room_exit(tenant_id,version_id,from_room_id,to_room_id) VALUES (?,?,?,?)", + f.intake().localTenantKey(), + f.version().localVersionKey(), + room, + room); + dsl.execute( + "INSERT INTO generation_rule(tenant_id,version_id,name,scope_type,scope_id,value) VALUES (?,?,'rule','REGION_SUBTREE',?,'seeded')", + f.intake().localTenantKey(), + f.version().localVersionKey(), + Long.toString(r)); + dsl.execute( + "INSERT INTO world_entity_spawn_binding(tenant_id,version_id,room_id,entity_template_type,entity_template_id) VALUES (?,?,?,'NPC',123)", + f.intake().localTenantKey(), + f.version().localVersionKey(), + room); + return r; + } finally { + dsl.execute("SET LOCAL session_replication_role='origin'"); + } + })); + UUID commit = UUID.randomUUID(); + UUID revision = UUID.randomUUID(); + var mutation = + WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(revision.toString()) + .setAggregateId(Long.toString(region)) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(Long.toString(region)) + .setRegion(RegionDesignMutation.newBuilder().setName("retained-v29")) + .build(); + var source = f.intake().source(); + var target = + new DraftCommitBinding.TargetProof( + f.owner().canonicalTenantId(), + f.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + source.sourceGameTenantKey(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + commit, + "retained-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", revision, Owner.WORLD_MANAGEMENT, json(mutation))), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + Long.toString(region), + "AGGREGATE", + Long.toString(region), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + Long.toString(region), + "REGION_SUBTREE", + Long.toString(region), + "0"))); + var retainedPlan = WorldDraftRegionCommitPlan.create(binding, f.owner()); + var prior = + new WorldDraftRegionCommitService( + new WorldDraftRegionCommitRepository(dsl, fence, mapper), manager, x -> {}) + .store(retainedPlan); + String schema = "uuid_upgrade_" + UUID.randomUUID().toString().replace("-", ""); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("29")) + .load() + .migrate(); + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + connection.setSchema(schema); + DSLContext retained = DSL.using(connection, SQLDialect.POSTGRES); + connection.setAutoCommit(false); + retained.execute("SET LOCAL session_replication_role='replica'"); + List sourceTables = + List.of( + "world_authored_source_tenant_association", + "world_authored_source_tenant_key_reservation", + "world_authored_source_intake", + "world_authored_version_identity", + "world_design_publication_fence_owner", + "world_region_draft_commit"); + List contentTables = + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_design_aggregate_epoch", + "world_design_scope_epoch"); + try { + for (String table : sourceTables) { + String key = + table.equals("world_authored_source_tenant_key_reservation") + ? "tenant_key" + : "local_tenant_key"; + String override = + table.equals("world_authored_version_identity") ? " OVERRIDING SYSTEM VALUE" : ""; + retained.execute( + "INSERT INTO " + + table + + override + + " SELECT * FROM world_management_service." + + table + + " WHERE " + + key + + "=?", + f.intake().localTenantKey()); + } + for (String table : contentTables) { + if (table.equals("world_entity_spawn_binding")) { + retained.execute( + "INSERT INTO world_entity_spawn_binding (id,tenant_id,version_id,room_id,entity_template_type,entity_template_id,spawn_count,respawn_delay_seconds,version) " + + "SELECT id,tenant_id,version_id,room_id,entity_template_type,entity_template_id,spawn_count,respawn_delay_seconds,version " + + "FROM world_management_service.world_entity_spawn_binding WHERE tenant_id=?", + f.intake().localTenantKey()); + } else { + retained.execute( + "INSERT INTO " + + table + + " SELECT * FROM world_management_service." + + table + + " WHERE tenant_id=?", + f.intake().localTenantKey()); + } + } + retained.execute("SET LOCAL session_replication_role='origin'"); + connection.commit(); + } catch (RuntimeException exception) { + connection.rollback(); + throw exception; + } + connection.setAutoCommit(true); + List all = new ArrayList<>(sourceTables); + all.addAll(contentTables); + Map> before = retainedState(retained, all); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + Map> after = retainedState(retained, all); + assertThat(after).isEqualTo(before); + assertThat( + retained + .resultQuery("SELECT count(*) FROM world_authored_topology_identity") + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + retained + .resultQuery("SELECT entity_template_id FROM world_entity_spawn_binding") + .fetchOne(0, Long.class)) + .isEqualTo(123); + assertThat( + retained + .resultQuery( + "SELECT entity_canonical_template_id FROM world_entity_spawn_binding") + .fetchOne(0, UUID.class)) + .isNull(); + assertThat( + retained + .resultQuery("SELECT result_bytes FROM world_region_draft_commit") + .fetchOne(0, byte[].class)) + .containsExactly(prior.resultBytes()); + assertThatThrownBy(() -> retained.execute("UPDATE region SET name='denied'")) + .isInstanceOf(RuntimeException.class); + } finally { + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private Map> retainedState(DSLContext db, List tables) { + Map> state = new LinkedHashMap<>(); + for (String table : tables) { + String projection = + table.equals("world_entity_spawn_binding") + ? "to_jsonb(t)-'entity_canonical_tenant_id'-'entity_canonical_version_id'-'entity_canonical_template_id'" + : "to_jsonb(t)"; + state.put( + table, + db.resultQuery( + "SELECT (" + + projection + + ")::text FROM " + + table + + " t ORDER BY (" + + projection + + ")::text") + .fetch(0, String.class)); + } + return state; + } + + @Test + void immutableHistoryAndEveryStoredPayloadAreVerifiedOnIndependentReadback() { + for (String corrupt : + List.of( + "UPDATE region SET weather='tampered'", + "UPDATE zone SET name='tampered'", + "UPDATE room SET description_localized_variants_json='tampered'", + "UPDATE room_exit SET cost=19", + "UPDATE generation_rule SET value='tampered'", + "UPDATE world_entity_spawn_binding SET entity_canonical_template_id='" + + UUID.randomUUID() + + "'", + "UPDATE world_authored_topology_identity SET revision_order='99'", + "UPDATE world_design_aggregate_epoch SET draft_revision_epoch=2", + "UPDATE world_design_scope_epoch SET draft_scope_revision_epoch=2", + "UPDATE world_topology_draft_commit SET result_bytes='tampered'::bytea")) { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + String column = + corrupt.contains("world_topology_draft_commit") ? "local_tenant_key" : "tenant_id"; + String statement = corrupt + " WHERE " + column + "=" + f.intake().localTenantKey(); + assertThatThrownBy(() -> dsl.execute(statement)).isInstanceOf(RuntimeException.class); + ownerTransaction() + .execute( + s -> { + dsl.execute("SET LOCAL session_replication_role='replica'"); + try { + dsl.execute(statement); + } finally { + dsl.execute("SET LOCAL session_replication_role='origin'"); + } + return null; + }); + assertOrigin(); + assertThatThrownBy( + () -> new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .isInstanceOf(RuntimeException.class); + } + } + + private Fixture fixture() { + UUID tenant = UUID.randomUUID(); + UUID registration = UUID.randomUUID(); + UUID sourceOperation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + long sourceRow = Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + String sourceTenant = "gd-row-" + sourceRow; + String digest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, "Synthetic component world"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW", + evidenceDigest); + UUID intakeRequest = UUID.randomUUID(); + ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, intakeRequest, source)); + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository.read(NAMESPACE, intakeRequest).orElseThrow(); + return Objects.requireNonNull( + ownerTransaction() + .execute( + status -> { + UUID canonicalVersion = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + worldSlug, + sourceOperation, + evidenceDigest, + GAME_DESIGN_VERSION); + WorldAuthoredVersionIdentityReceipt version = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + tenant, + canonicalVersion, + version.operationId(), + GAME_DESIGN_VERSION, + intakeRequest, + intake.operationId(), + intake.requestDigest(), + sourceOperation, + evidenceDigest, + intake.receiptDigest()); + assertOrigin(); + return new Fixture(intake, version, owner); + })); + } + + private void freeze(Fixture f) { + OwnerBinding o = f.owner(); + String request = "freeze-" + UUID.randomUUID(); + WorldDesignPublicationFenceEvidence evidence = + new WorldDesignPublicationFenceEvidence( + o.targetNamespace(), + o.canonicalTenantId(), + o.canonicalVersionId(), + o.versionIdentityOperationId(), + o.gameDesignVersionId(), + o.intakeRequestId(), + o.intakeOperationId(), + o.intakeRequestDigest(), + o.sourceOperationId(), + o.sourceEvidenceDigest(), + o.intakeReceiptDigest(), + request, + "a".repeat(64), + 1, + "publish:" + o.canonicalTenantId() + ":publish-request:" + request); + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "synthetic-unverified-checkpoint", "b".repeat(64), 2))); + } + + private WorldDraftTopologyCommitPlan plan(Fixture f) { + UUID logical = UUID.randomUUID(); + UUID secondRoom = UUID.randomUUID(); + UUID entity = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + List values = new ArrayList<>(); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("region") + .setWeather("rain") + .setShardId(7) + .setGenerationSeed(9_007_199_254_740_999L) + .setGeneratorType("synthetic") + .setGeneratorParams("{\"seed\":1}")) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder().setName("zone").setRegionId(logical.toString())) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("room") + .setZoneId(logical.toString()) + .setDescription("description") + .setNameLocalizedVariantsJson("{\"en\":\"room\"}") + .setDescriptionLocalizedVariantsJson("{\"en\":\"description\"}")) + .build()); + values.add( + mutation( + commit, + secondRoom, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder().setName("second").setZoneId(logical.toString())) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(logical.toString()) + .setToRoomId(secondRoom.toString()) + .setDirection("NORTH")) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder().setName("rule").setValue("seeded")) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(logical.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(entity.toString()) + .setRespawnDelaySeconds(17)) + .build()); + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + "synthetic opaque Entity input; existence and permission remain unverified")); + units.add( + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "NPC", + entity.toString(), + "AGGREGATE", + entity.toString(), + "0")); + // Original input order deliberately places children before their parents. + for (var m : values.reversed()) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(m.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + json(m))); + String family = m.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "AGGREGATE", + m.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "REGION_SUBTREE", + m.getScopeId(), + "0")); + } + var s = f.intake().source(); + var target = + new DraftCommitBinding.TargetProof( + f.owner().canonicalTenantId(), + f.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + s.sourceGameTenantKey(), + s.sourceGameRowId(), + s.sourceGameTenantKey(), + s.provenanceKind()); + return WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + target, UUID.randomUUID(), commit, "retained-base", revisions, units), + f.owner()); + } + + private WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID id, UUID scope, WorldDesignAggregateType type) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(id.toString()) + .setAggregateType(type) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(scope.toString()); + } + + private WorldDraftTopologyCommitService component() { + return new WorldDraftTopologyCommitService( + repository(), + manager, + p -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertOrigin(); + // Synthetic local-storage fixture only; no Account permission or Entity existence proof. + }); + } + + private WorldDraftTopologyCommitRepository repository() { + return new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate tx = new TransactionTemplate(manager); + tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return tx; + } + + private void assertOrigin() { + assertThat( + dsl.resultQuery("SELECT current_setting('session_replication_role')") + .fetchOne(0, String.class)) + .isEqualTo("origin"); + } + + private long count(Fixture f, String table) { + String tenant = table.equals("world_topology_draft_commit") ? "local_tenant_key" : "tenant_id"; + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT count(*) FROM " + table + " WHERE " + tenant + "=?", + f.intake().localTenantKey()) + .fetchOne(0, Long.class)); + } + + private long privateKey(WorldDraftTopologyCommitPlan p, String family, UUID id) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT private_row_key FROM world_authored_topology_identity " + + "WHERE request_id=? AND family=? AND template_id=?", + p.binding().requestId(), + family, + id) + .fetchOne(0, Long.class)); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new AssertionError(exception); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(15, TimeUnit.SECONDS)) throw new IllegalStateException("Fixture timed out"); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(exception); + } + } + + private record Fixture( + WorldAuthoredSourceIntakeReceipt intake, + WorldAuthoredVersionIdentityReceipt version, + OwnerBinding owner) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java index 0ddd055ab5..ec02a0e2bb 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java @@ -3,7 +3,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.entity.Room; +import net.firedevops.firemud.worldmanagement.entity.WorldEntitySpawnBinding; import net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository; import net.firedevops.firemud.worldmanagement.repository.RegionRepository; import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; @@ -114,8 +120,136 @@ void computesDigestFromVersionScopedTemplateRows() { assertEquals("1", digest.tenantId()); assertEquals("7", digest.scopeValue()); assertEquals("version:7", digest.appliedCommitId()); - assertEquals(2, digest.digestSchemaVersion()); + assertEquals(3, digest.digestSchemaVersion()); Mockito.verify(regionRepository).findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L); Mockito.verify(regionRepository, Mockito.never()).findByTenantIdOrderByIdAsc(Mockito.anyLong()); } + + @Test + void canonicalEntityReferenceMatchesExactSortedSerializationVector() throws Exception { + WorldEntitySpawnBinding binding = binding(); + canonicalReference(binding); + assertEquals( + vector( + "{\"kind\":\"CANONICAL_UUID\",\"templateId\":\"33333333-3333-4333-8333-333333333333\",\"tenantId\":\"11111111-1111-4111-8111-111111111111\",\"versionId\":\"22222222-2222-4222-8222-222222222222\"}"), + digest(binding)); + } + + @Test + void retainedEntityReferenceMatchesExactSortedSerializationVector() throws Exception { + WorldEntitySpawnBinding binding = binding(); + binding.setEntityTemplateId(Long.MAX_VALUE); + assertEquals( + vector("{\"kind\":\"RETAINED_PRIVATE_KEY\",\"templateId\":\"9223372036854775807\"}"), + digest(binding)); + } + + @Test + void eachCanonicalEntityUuidContributesToDigest() { + WorldEntitySpawnBinding binding = binding(); + canonicalReference(binding); + String original = digest(binding); + for (int field = 0; field < 3; field++) { + canonicalReference(binding); + UUID changed = UUID.fromString("44444444-4444-4444-8444-444444444444"); + if (field == 0) binding.setEntityCanonicalTenantId(changed); + if (field == 1) binding.setEntityCanonicalVersionId(changed); + if (field == 2) binding.setEntityCanonicalTemplateId(changed); + org.junit.jupiter.api.Assertions.assertNotEquals(original, digest(binding)); + } + } + + @Test + void rejectsMissingNilMixedAndNonpositiveEntityReferences() { + WorldEntitySpawnBinding binding = binding(); + assertThrows(IllegalStateException.class, () -> digest(binding)); + for (int field = 0; field < 3; field++) { + for (UUID invalid : new UUID[] {null, new UUID(0L, 0L)}) { + canonicalReference(binding); + if (field == 0) binding.setEntityCanonicalTenantId(invalid); + if (field == 1) binding.setEntityCanonicalVersionId(invalid); + if (field == 2) binding.setEntityCanonicalTemplateId(invalid); + assertThrows(IllegalStateException.class, () -> digest(binding)); + } + } + canonicalReference(binding); + binding.setEntityTemplateId(9L); + assertThrows(IllegalStateException.class, () -> digest(binding)); + binding.setEntityCanonicalTenantId(null); + binding.setEntityCanonicalVersionId(null); + binding.setEntityCanonicalTemplateId(null); + for (long invalid : new long[] {0L, -1L}) { + binding.setEntityTemplateId(invalid); + assertThrows(IllegalStateException.class, () -> digest(binding)); + } + } + + @Test + void repeatedDigestsHaveStableFieldOrder() { + WorldEntitySpawnBinding binding = binding(); + canonicalReference(binding); + String expected = digest(binding); + for (int attempt = 0; attempt < 20; attempt++) assertEquals(expected, digest(binding)); + } + + @Test + void applicationMapperSettingsCannotChangeSchema3Serialization() { + WorldEntitySpawnBinding binding = binding(); + canonicalReference(binding); + var configured = + tools.jackson.databind.json.JsonMapper.builder() + .enable(tools.jackson.databind.SerializationFeature.INDENT_OUTPUT) + .enable(tools.jackson.databind.SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS) + .build(); + assertEquals(digest(binding), digest(binding, configured)); + } + + private String digest(WorldEntitySpawnBinding binding) { + return digest(binding, new ObjectMapper()); + } + + private String digest(WorldEntitySpawnBinding binding, ObjectMapper mapper) { + var spawns = Mockito.mock(WorldEntitySpawnBindingRepository.class); + Mockito.when(spawns.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of(binding)); + return new WorldDraftDesignDigestServiceImpl( + Mockito.mock(RegionRepository.class), + Mockito.mock(ZoneRepository.class), + Mockito.mock(RoomRepository.class), + Mockito.mock(RoomExitRepository.class), + Mockito.mock(GenerationRuleRepository.class), + spawns, + mapper) + .getDraftDesignDigest("1", "7") + .contentDigest(); + } + + private String vector(String entityReference) throws Exception { + String json = + "{\"regions\":[],\"zones\":[],\"rooms\":[],\"roomExits\":[],\"generationRules\":[],\"worldEntitySpawnBindings\":[{\"entityReference\":" + + entityReference + + ",\"entityTemplateType\":\"NPC\",\"id\":11,\"respawnDelaySeconds\":30,\"roomId\":5,\"spawnCount\":2}]}"; + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(json.getBytes(StandardCharsets.UTF_8))); + } + + private WorldEntitySpawnBinding binding() { + var binding = new WorldEntitySpawnBinding(); + var room = new Room(); + room.setId(5L); + binding.setId(11L); + binding.setRoom(room); + binding.setEntityTemplateType("NPC"); + binding.setSpawnCount(2); + binding.setRespawnDelaySeconds(30); + return binding; + } + + private void canonicalReference(WorldEntitySpawnBinding binding) { + binding.setEntityTemplateId(null); + binding.setEntityCanonicalTenantId(UUID.fromString("11111111-1111-4111-8111-111111111111")); + binding.setEntityCanonicalVersionId(UUID.fromString("22222222-2222-4222-8222-222222222222")); + binding.setEntityCanonicalTemplateId(UUID.fromString("33333333-3333-4333-8333-333333333333")); + } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index 734e967ae4..022554ac53 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -181,8 +181,8 @@ void prepareWorldInstanceMaterializesSeededRoomIdentityAndActivatesOwnerLifecycl when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L)) .thenReturn( List.of( - templateExit(42L, 11L, starterRoom, secondaryRoom, "NORTH"), - templateExit(42L, 11L, secondaryRoom, starterRoom, "SOUTH"))); + templateExit(42L, 11L, 1L, starterRoom, secondaryRoom, "NORTH"), + templateExit(42L, 11L, 2L, secondaryRoom, starterRoom, "SOUTH"))); AtomicReference storedInstance = new AtomicReference<>(); when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) .thenAnswer(invocation -> Optional.ofNullable(storedInstance.get())); @@ -281,6 +281,66 @@ void prepareWorldInstancePersistsPreparingLifecycle() { verify(roomInstanceRepository).save(any()); } + @Test + void prepareWorldInstanceRejectsRoomWhoseZoneIsNotSelectedBeforeWriting() { + Room room = templateRoom(42L, 1021L); + room.setZone(templateZone(42L, 99L)); + when(roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L)).thenReturn(List.of(room)); + + assertIncompleteTopologyRejectedBeforeWrites(); + } + + @Test + void prepareWorldInstanceRejectsMissingExitSourceBeforeWriting() { + Room selectedRoom = templateRoom(42L, 1021L); + Room missingRoom = templateRoom(42L, 2045L); + when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L)) + .thenReturn(List.of(templateExit(42L, 11L, 1L, missingRoom, selectedRoom, "NORTH"))); + + assertIncompleteTopologyRejectedBeforeWrites(); + } + + @Test + void prepareWorldInstanceRejectsMissingExitDestinationBeforeWriting() { + Room selectedRoom = templateRoom(42L, 1021L); + Room missingRoom = templateRoom(42L, 2045L); + when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L)) + .thenReturn(List.of(templateExit(42L, 11L, 1L, selectedRoom, missingRoom, "NORTH"))); + + assertIncompleteTopologyRejectedBeforeWrites(); + } + + @Test + void prepareWorldInstanceRejectsDuplicateSelectedZoneIdentityBeforeWriting() { + Zone zone = templateZone(42L, 11L); + Zone duplicate = templateZone(42L, 11L); + when(zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L)) + .thenReturn(List.of(zone, duplicate)); + + assertIncompleteTopologyRejectedBeforeWrites(); + } + + @Test + void prepareWorldInstanceRejectsOutOfScopeRoomBeforeWriting() { + Room room = templateRoom(42L, 1021L); + room.setTenantId(43L); + when(roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L)).thenReturn(List.of(room)); + + assertIncompleteTopologyRejectedBeforeWrites(); + } + + @Test + void prepareWorldInstanceRejectsDuplicateExitIdentityBeforeWriting() { + Room room = templateRoom(42L, 1021L); + when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L)) + .thenReturn( + List.of( + templateExit(42L, 11L, 1L, room, room, "NORTH"), + templateExit(42L, 11L, 1L, room, room, "SOUTH"))); + + assertIncompleteTopologyRejectedBeforeWrites(); + } + @Test void exactRetryRetainsPersistedOpaqueReleaseBundleReference() { AtomicReference persisted = new AtomicReference<>(); @@ -960,8 +1020,9 @@ private Room templateRoom(long tenantId, long roomId) { } private RoomExit templateExit( - long tenantId, long versionId, Room fromRoom, Room toRoom, String direction) { + long tenantId, long versionId, long exitId, Room fromRoom, Room toRoom, String direction) { RoomExit exit = new RoomExit(); + exit.setId(exitId); exit.setTenantId(tenantId); exit.setVersionId(versionId); exit.setFromRoom(fromRoom); @@ -970,6 +1031,37 @@ private RoomExit templateExit( return exit; } + private void assertIncompleteTopologyRejectedBeforeWrites() { + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + service.prepareWorldInstance( + new PreparedWorldInstanceRequest( + 42L, + 101L, + 7L, + "cp-1", + "ld-1", + 11L, + "patch-1", + "{}", + "genrev-11", + 77L, + PERSISTED_RELEASE_BUNDLE_REF, + 77L))); + + assertTrue(error.getMessage().startsWith("FAILED_PRECONDITION: INCOMPLETE_WORLD_TOPOLOGY:")); + verify(zoneRepository, times(1)).findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L); + verify(roomRepository, times(1)).findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L); + verify(roomExitRepository, times(1)).findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L); + verify(worldInstanceRepository, never()).save(any()); + verify(regionInstanceRepository, never()).save(any()); + verify(zoneInstanceRepository, never()).save(any()); + verify(roomInstanceRepository, never()).save(any()); + verify(roomInstanceExitRepository, never()).save(any()); + } + private Zone templateZone(long tenantId, long zoneId) { Zone zone = new Zone(); zone.setId(zoneId); 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 beec507cdb..5cc0b0f106 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 @@ -28,7 +28,6 @@ import net.firedevops.firemud.worldmanagement.service.PingService; import net.firedevops.firemud.worldmanagement.service.RoomService; import net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService; -import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; import net.firedevops.firemud.worldmanagement.service.WorldInstanceActivationService; import net.firedevops.firemud.worldmanagement.service.WorldUpgradeValidationService; import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldRequest; @@ -359,7 +358,6 @@ private static GetDraftDesignDigestRequest fullDigestRequest(String tenantId, St private WorldManagementGrpcService newService( PingService pingService, RoomService roomService, MeterRegistry meterRegistry) { - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); WorldInstanceActivationService activationService = Mockito.mock(WorldInstanceActivationService.class); GameplaySessionAttestationService attestationService = @@ -370,7 +368,6 @@ private WorldManagementGrpcService newService( pingService, roomService, activationService, - digestService, Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), attestationService, @@ -381,7 +378,6 @@ private WorldManagementGrpcService newService( private WorldManagementGrpcService newServiceWithoutContext( PingService pingService, RoomService roomService, MeterRegistry meterRegistry) { - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); WorldInstanceActivationService activationService = Mockito.mock(WorldInstanceActivationService.class); GameplaySessionAttestationService attestationService = @@ -392,7 +388,6 @@ private WorldManagementGrpcService newServiceWithoutContext( pingService, roomService, activationService, - digestService, Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), attestationService, @@ -402,15 +397,11 @@ private WorldManagementGrpcService newServiceWithoutContext( } @Test - void getDraftDesignDigestReturnsVersionScopedDigest() { + void getDraftDesignDigestDeniesValidBoundRequestWithoutCompleteAppliedCommitProof() { PingService pingService = Mockito.mock(PingService.class); RoomService roomService = Mockito.mock(RoomService.class); - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); + WorldDesignMutationService mutationService = Mockito.mock(WorldDesignMutationService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); - Mockito.when(digestService.getDraftDesignDigest("1", "7")) - .thenReturn( - new WorldDraftDesignDigestService.WorldDraftDesignDigest( - "1", "7", "version:7", "digest-world", 1)); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); WorldManagementGrpcService service = @@ -418,8 +409,7 @@ void getDraftDesignDigestReturnsVersionScopedDigest() { pingService, roomService, Mockito.mock(WorldInstanceActivationService.class), - digestService, - Mockito.mock(WorldDesignMutationService.class), + mutationService, Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), meterRegistry, @@ -429,19 +419,20 @@ void getDraftDesignDigestReturnsVersionScopedDigest() { AtomicReference ref = new AtomicReference<>(); runAsGameDesign(() -> ref.set(invokeDigest(service, fullDigestRequest("1", "7")))); - assertEquals("7", ref.get().getVersionId()); - assertEquals("version:7", ref.get().getAppliedCommitId()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + assertEquals( + "An authenticated complete World commit/publication checkpoint is unavailable.", + ref.get().getError().getMessage()); + Mockito.verifyNoInteractions(mutationService); } @Test void getDraftDesignDigestRejectsForgedInternalSessionClaimWithoutPeerIdentity() { - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); WorldManagementGrpcService service = new WorldManagementGrpcService( Mockito.mock(PingService.class), Mockito.mock(RoomService.class), Mockito.mock(WorldInstanceActivationService.class), - digestService, Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -452,12 +443,10 @@ void getDraftDesignDigestRejectsForgedInternalSessionClaimWithoutPeerIdentity() null, List.of(), Map.of(), true, "game-design-service", "test-instance"); GetDraftDesignDigestResponse response = invokeDigest(service, fullDigestRequest("1", "7")); assertEquals("PERMISSION_DENIED", response.getError().getCode()); - Mockito.verifyNoInteractions(digestService); } @Test void getDraftDesignDigestFailsClosedWhenWorkloadNamespaceIsMissingOrInvalid() { - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); for (String workloadNamespace : new String[] {null, " ", "not a namespace"}) { @@ -466,7 +455,6 @@ void getDraftDesignDigestFailsClosedWhenWorkloadNamespaceIsMissingOrInvalid() { Mockito.mock(PingService.class), Mockito.mock(RoomService.class), Mockito.mock(WorldInstanceActivationService.class), - digestService, Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -480,19 +468,16 @@ void getDraftDesignDigestFailsClosedWhenWorkloadNamespaceIsMissingOrInvalid() { .getError() .getCode(), "workload namespace: " + workloadNamespace); - Mockito.verifyNoInteractions(digestService); } } @Test - void getDraftDesignDigestRejectsWrongPeerBeforeReadingDigest() { - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); + void getDraftDesignDigestRejectsWrongPeer() { WorldManagementGrpcService service = new WorldManagementGrpcService( Mockito.mock(PingService.class), Mockito.mock(RoomService.class), Mockito.mock(WorldInstanceActivationService.class), - digestService, Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -507,18 +492,15 @@ void getDraftDesignDigestRejectsWrongPeerBeforeReadingDigest() { service, fullDigestRequest("1", "7"), peer("entity-management-service")); assertEquals("PERMISSION_DENIED", response.getError().getCode()); - Mockito.verifyNoInteractions(digestService); } @Test - void getDraftDesignDigestRejectsUserOrAdminJwtBeforeReadingDigest() { - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); + void getDraftDesignDigestRejectsUserOrAdminJwt() { WorldManagementGrpcService service = new WorldManagementGrpcService( Mockito.mock(PingService.class), Mockito.mock(RoomService.class), Mockito.mock(WorldInstanceActivationService.class), - digestService, Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -539,18 +521,15 @@ void getDraftDesignDigestRejectsUserOrAdminJwtBeforeReadingDigest() { "PERMISSION_DENIED", invokeDigest(service, fullDigestRequest("1", "7")).getError().getCode()); }); - Mockito.verifyNoInteractions(digestService); } @Test - void getDraftDesignDigestRejectsChangedBindingBeforeOwnerRead() { - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); + void getDraftDesignDigestRejectsChangedBinding() { WorldManagementGrpcService service = new WorldManagementGrpcService( Mockito.mock(PingService.class), Mockito.mock(RoomService.class), Mockito.mock(WorldInstanceActivationService.class), - digestService, Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -569,18 +548,15 @@ void getDraftDesignDigestRejectsChangedBindingBeforeOwnerRead() { .setRequestDigest("0".repeat(64)) .build()))); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - Mockito.verifyNoInteractions(digestService); } @Test void getDraftDesignDigestRejectsScriptPatchScope() { - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); WorldManagementGrpcService service = new WorldManagementGrpcService( Mockito.mock(PingService.class), Mockito.mock(RoomService.class), Mockito.mock(WorldInstanceActivationService.class), - digestService, Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -603,23 +579,17 @@ void getDraftDesignDigestRejectsScriptPatchScope() { AtomicReference ref = new AtomicReference<>(); runAsGameDesign(() -> ref.set(invokeDigest(service, request))); assertEquals("UNSUPPORTED_SCOPE", ref.get().getError().getCode()); - Mockito.verifyNoInteractions(digestService); } @Test - void getDraftDesignDigestRejectsOwnerTenantMismatch() { - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); - Mockito.when(digestService.getDraftDesignDigest("1", "7")) - .thenReturn( - new WorldDraftDesignDigestService.WorldDraftDesignDigest( - "other-tenant", "7", "version:7", "digest-world", 1)); + void getDraftDesignDigestValidRequestReturnsNoSuccessFieldsWithoutPublicationCheckpoint() { + WorldDesignMutationService mutationService = Mockito.mock(WorldDesignMutationService.class); WorldManagementGrpcService service = new WorldManagementGrpcService( Mockito.mock(PingService.class), Mockito.mock(RoomService.class), Mockito.mock(WorldInstanceActivationService.class), - digestService, - Mockito.mock(WorldDesignMutationService.class), + mutationService, Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), new SimpleMeterRegistry(), @@ -629,15 +599,20 @@ void getDraftDesignDigestRejectsOwnerTenantMismatch() { null, List.of(), Map.of(), true, "game-design-service", "test-instance"); AtomicReference ref = new AtomicReference<>(); runAsGameDesign(() -> ref.set(invokeDigest(service, fullDigestRequest("1", "7")))); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - Mockito.verify(digestService).getDraftDesignDigest("1", "7"); + GetDraftDesignDigestResponse response = ref.get(); + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals("", response.getTenantId()); + assertEquals("", response.getVersionId()); + assertEquals("", response.getAppliedCommitId()); + assertEquals("", response.getContentDigest()); + assertEquals(0, response.getDigestSchemaVersion()); + Mockito.verifyNoInteractions(mutationService); } @Test 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); @@ -647,7 +622,6 @@ void applyWorldDesignMutationDeniesCanonicalWritesWithoutAccountCommitAuthorizat pingService, roomService, activationService, - digestService, mutationService, Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -670,14 +644,13 @@ void applyWorldDesignMutationDeniesCanonicalWritesWithoutAccountCommitAuthorizat runAsGameDesign(() -> authenticatedPeerResponse.set(invokeMutation(service, request))); assertWorldMutationDenied(authenticatedPeerResponse.get()); - Mockito.verifyNoInteractions(mutationService, digestService, activationService); + Mockito.verifyNoInteractions(mutationService, activationService); } @Test void applyWorldDesignMutationRejectsZeroVersionIdBeforeMutation() { 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); @@ -689,7 +662,6 @@ void applyWorldDesignMutationRejectsZeroVersionIdBeforeMutation() { pingService, roomService, activationService, - digestService, mutationService, Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -713,14 +685,13 @@ void applyWorldDesignMutationRejectsZeroVersionIdBeforeMutation() { .build()); assertWorldMutationDenied(response); - Mockito.verifyNoInteractions(mutationService, digestService, activationService); + Mockito.verifyNoInteractions(mutationService, activationService); } @Test void prepareWorldInstanceReturnsLifecycleSnapshot() { PingService pingService = Mockito.mock(PingService.class); RoomService roomService = Mockito.mock(RoomService.class); - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); WorldInstanceActivationService activationService = Mockito.mock(WorldInstanceActivationService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); @@ -749,7 +720,6 @@ void prepareWorldInstanceReturnsLifecycleSnapshot() { pingService, roomService, activationService, - digestService, Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -803,7 +773,6 @@ void prepareWorldInstanceRejectsZeroTenantId() { pingService, roomService, activationService, - Mockito.mock(WorldDraftDesignDigestService.class), Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -858,7 +827,6 @@ void activatePreparedWorldInstanceRejectsMalformedGameInstanceId() { pingService, roomService, activationService, - Mockito.mock(WorldDraftDesignDigestService.class), Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -895,7 +863,6 @@ public void onCompleted() {} void validateWorldUpgradeMappingsReturnsCompatibilityPayload() { PingService pingService = Mockito.mock(PingService.class); RoomService roomService = Mockito.mock(RoomService.class); - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); WorldUpgradeValidationService validationService = Mockito.mock(WorldUpgradeValidationService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); @@ -916,7 +883,6 @@ void validateWorldUpgradeMappingsReturnsCompatibilityPayload() { pingService, roomService, Mockito.mock(WorldInstanceActivationService.class), - digestService, Mockito.mock(WorldDesignMutationService.class), validationService, Mockito.mock(GameplaySessionAttestationService.class), @@ -967,7 +933,6 @@ void validateWorldUpgradeMappingsRejectsZeroTargetVersionId() { pingService, roomService, Mockito.mock(WorldInstanceActivationService.class), - Mockito.mock(WorldDraftDesignDigestService.class), Mockito.mock(WorldDesignMutationService.class), validationService, Mockito.mock(GameplaySessionAttestationService.class), @@ -1153,7 +1118,6 @@ void getRoomRejectsMismatchedTenantIdsBeforeAttestationAndLookup() { pingService, roomService, Mockito.mock(WorldInstanceActivationService.class), - Mockito.mock(WorldDraftDesignDigestService.class), Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), attestationService, @@ -1206,7 +1170,6 @@ void getRoomSnapshotRejectsBlankGameInstanceIdBeforeAttestationAndLookup() { pingService, roomService, Mockito.mock(WorldInstanceActivationService.class), - Mockito.mock(WorldDraftDesignDigestService.class), Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), attestationService, @@ -1406,7 +1369,6 @@ void getRoomRejectsMalformedRuntimeRoomInstanceIdBeforeAttestationAndLookup() { pingService, roomService, Mockito.mock(WorldInstanceActivationService.class), - Mockito.mock(WorldDraftDesignDigestService.class), Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), attestationService, @@ -1449,7 +1411,6 @@ public void onCompleted() {} void getRoomRejectsNonInternalGameplayCaller() { PingService pingService = Mockito.mock(PingService.class); RoomService roomService = Mockito.mock(RoomService.class); - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); SessionContext.setContext("test-account", List.of(), Map.of("9", List.of("tenantAdmin"))); WorldManagementGrpcService service = @@ -1457,7 +1418,6 @@ void getRoomRejectsNonInternalGameplayCaller() { pingService, roomService, Mockito.mock(WorldInstanceActivationService.class), - digestService, Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), @@ -1511,7 +1471,6 @@ void requireTenantAccessWhenPresentRejectsMalformedCurrentAccountClaim() throws pingService, roomService, Mockito.mock(WorldInstanceActivationService.class), - Mockito.mock(WorldDraftDesignDigestService.class), Mockito.mock(WorldDesignMutationService.class), Mockito.mock(WorldUpgradeValidationService.class), Mockito.mock(GameplaySessionAttestationService.class), diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldPublicationDigestMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldPublicationDigestMtlsTest.java new file mode 100644 index 0000000000..84effcd480 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldPublicationDigestMtlsTest.java @@ -0,0 +1,466 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.MetadataUtils; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.math.BigInteger; +import java.net.InetSocketAddress; +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.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GameplaySessionAttestationService; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.PublicationReadGuard; +import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; +import net.firedevops.firemud.worldmanagement.service.PingService; +import net.firedevops.firemud.worldmanagement.service.RoomService; +import net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService; +import net.firedevops.firemud.worldmanagement.service.WorldInstanceActivationService; +import net.firedevops.firemud.worldmanagement.service.WorldUpgradeValidationService; +import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationRequest; +import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestResponse; +import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest; +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; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.FileSystemResource; +import tools.jackson.databind.ObjectMapper; + +/** + * Physical socket proof for the registered World digest RPC. The handler and transport + * authorization path are real, but owner collaborators are mocked; this proves denial behavior, not + * database state, authenticated APPLIED evidence, release completion, or live readiness. + */ +class WorldPublicationDigestMtlsTest { + private static final String NAMESPACE = "test"; + private static final String JWT_SECRET = "test-secret-key-test-secret-key-32-bytes"; + private static final String UNAVAILABLE_CHECKPOINT_MESSAGE = + "An authenticated complete World commit/publication checkpoint is unavailable."; + private static final String PEER_DENIAL_MESSAGE = + "Publication read requires only the authenticated Game Design workload peer identity"; + private static final String DIGEST_METHOD = + WorldManagementServiceGrpc.getGetDraftDesignDigestMethod().getFullMethodName(); + private static final Metadata.Key AUTHORIZATION = + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static TestPki pki; + + private final PingService pingService = mock(PingService.class); + private final RoomService roomService = mock(RoomService.class); + private final WorldInstanceActivationService worldInstanceActivationService = + mock(WorldInstanceActivationService.class); + private final WorldDesignMutationService worldDesignMutationService = + mock(WorldDesignMutationService.class); + private final WorldUpgradeValidationService worldUpgradeValidationService = + mock(WorldUpgradeValidationService.class); + private final GameplaySessionAttestationService gameplaySessionAttestationService = + mock(GameplaySessionAttestationService.class); + private final InitialAdmissionBindHoldService initialAdmissionBindHoldService = + mock(InitialAdmissionBindHoldService.class); + + private Server server; + + @BeforeAll + static void generateFreshTestPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeyPair = newRsaKeyPair(); + X500Name caName = new X500Name("CN=World Publication Digest Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null); + pki = + new TestPki( + caCertificate, + issueLeaf(caName, caKeyPair.getPrivate(), NAMESPACE, "world-management-service"), + issueLeaf(caName, caKeyPair.getPrivate(), NAMESPACE, "game-design-service"), + issueLeaf(caName, caKeyPair.getPrivate(), NAMESPACE, "account-service"), + issueLeaf(caName, caKeyPair.getPrivate(), "other-test", "game-design-service")); + } + + @BeforeEach + void startPhysicalReceiver() throws Exception { + WorldManagementGrpcService service = + new WorldManagementGrpcService( + pingService, + roomService, + worldInstanceActivationService, + worldDesignMutationService, + worldUpgradeValidationService, + gameplaySessionAttestationService, + new SimpleMeterRegistry(), + new ObjectMapper(), + new PublicationReadGuard(NAMESPACE)); + service.configureInitialAdmissionBindHoldBoundary(initialAdmissionBindHoldService, NAMESPACE); + + 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( + ServerInterceptors.intercept( + service, + new AuthTokenInterceptor( + new JwtUtil(JWT_SECRET, 60_000L), publicMethods("application.yml")), + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void exactGameDesignPeerGetsInBandCheckpointDenialWithoutSuccessFields() throws Exception { + ManagedChannel channel = channel(pki.gameDesignClient()); + try { + GetDraftDesignDigestResponse response = stub(channel).getDraftDesignDigest(validRequest()); + + assertCheckpointUnavailable(response); + } finally { + stopChannel(channel); + } + verifyNoOwnerCalls(); + } + + @Test + void forgedServiceNameJwtCannotBypassTheWrongWorkloadCertificate() throws Exception { + JwtUtil jwtUtil = new JwtUtil(JWT_SECRET, 60_000L); + String forgedServiceNameToken = + jwtUtil.generateToken( + "forged-workload", + Map.of( + "internalService", true, + "serviceName", "game-design-service", + "serviceInstanceId", "forged-instance")); + Metadata headers = new Metadata(); + headers.put(AUTHORIZATION, "Bearer " + forgedServiceNameToken); + + ManagedChannel channel = channel(pki.accountClient()); + try { + GetDraftDesignDigestResponse response = + stub(channel, headers).getDraftDesignDigest(validRequest()); + + assertPeerDenied(response); + } finally { + stopChannel(channel); + } + verifyNoOwnerCalls(); + } + + @Test + void foreignNamespaceGameDesignCertificateIsDenied() throws Exception { + ManagedChannel channel = channel(pki.foreignNamespaceGameDesignClient()); + try { + GetDraftDesignDigestResponse response = stub(channel).getDraftDesignDigest(validRequest()); + + assertPeerDenied(response); + } finally { + stopChannel(channel); + } + verifyNoOwnerCalls(); + } + + @Test + void authenticatedGameDesignPeerCannotChangeDigestOrTypedPublicationBinding() throws Exception { + GetDraftDesignDigestRequest validRequest = validRequest(); + String changedDigest = + (validRequest.getRequestDigest().charAt(0) == '0' ? "1" : "0") + + validRequest.getRequestDigest().substring(1); + GetDraftDesignDigestRequest changedDigestRequest = + validRequest.toBuilder().setRequestDigest(changedDigest).build(); + GetDraftDesignDigestRequest changedTypedBindingRequest = + validRequest.toBuilder().setPublishRequestId("different-publication-attempt").build(); + + ManagedChannel channel = channel(pki.gameDesignClient()); + try { + GetDraftDesignDigestResponse changedDigestResponse = + stub(channel).getDraftDesignDigest(changedDigestRequest); + assertInvalidBinding(changedDigestResponse, "requestDigest does not match canonical digest"); + + GetDraftDesignDigestResponse changedTypedBindingResponse = + stub(channel).getDraftDesignDigest(changedTypedBindingRequest); + assertInvalidBinding( + changedTypedBindingResponse, "derivedWorkflowIdentity does not match expected identity"); + } finally { + stopChannel(channel); + } + verifyNoOwnerCalls(); + } + + @Test + void worldGrpcYamlAllowsOnlyPingAndThePeerGuardedPublicationDigestWithoutBearer() + throws Exception { + assertThat(publicMethods("application.yml")) + .isEqualTo( + Set.of(WorldManagementServiceGrpc.getPingMethod().getFullMethodName(), DIGEST_METHOD)); + } + + @Test + void unrelatedMutationAndLifecycleRpcsStillRequireBearerAuthentication() throws Exception { + ManagedChannel channel = channel(pki.gameDesignClient()); + try { + assertMissingBearer( + () -> + stub(channel).prepareWorldInstance(PrepareWorldInstanceRequest.getDefaultInstance())); + assertMissingBearer( + () -> + stub(channel) + .applyWorldDesignMutation(ApplyWorldDesignMutationRequest.getDefaultInstance())); + } finally { + stopChannel(channel); + } + verifyNoOwnerCalls(); + } + + private WorldManagementServiceGrpc.WorldManagementServiceBlockingStub stub( + ManagedChannel channel) { + return WorldManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private WorldManagementServiceGrpc.WorldManagementServiceBlockingStub stub( + ManagedChannel channel, Metadata headers) { + return WorldManagementServiceGrpc.newBlockingStub(channel) + .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(headers)) + .withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private ManagedChannel channel(TestCertificate clientCertificate) throws Exception { + return NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager(clientCertificate.privateKey(), clientCertificate.certificate()) + .build()) + .build(); + } + + private static GetDraftDesignDigestRequest validRequest() { + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full("tenant-17", "17", "publication-attempt-17"); + return GetDraftDesignDigestRequest.newBuilder() + .setTenantId(binding.tenantId()) + .setVersionId(binding.versionId()) + .setPublishRequestId(binding.publishRequestId()) + .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) + .setRequestDigest(binding.requestDigest()) + .build(); + } + + private static void assertCheckpointUnavailable(GetDraftDesignDigestResponse response) { + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("FAILED_PRECONDITION"); + assertThat(response.getError().getMessage()).isEqualTo(UNAVAILABLE_CHECKPOINT_MESSAGE); + assertThat(response.getTenantId()).isEmpty(); + assertThat(response.getScopeCase()) + .isEqualTo(GetDraftDesignDigestResponse.ScopeCase.SCOPE_NOT_SET); + assertThat(response.getBaseVersionId()).isEmpty(); + assertThat(response.getAppliedCommitId()).isEmpty(); + assertThat(response.getContentDigest()).isEmpty(); + assertThat(response.getDigestSchemaVersion()).isZero(); + } + + private static void assertPeerDenied(GetDraftDesignDigestResponse response) { + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + assertThat(response.getError().getMessage()).isEqualTo(PEER_DENIAL_MESSAGE); + assertThat(response.getTenantId()).isEmpty(); + assertThat(response.getAppliedCommitId()).isEmpty(); + assertThat(response.getContentDigest()).isEmpty(); + assertThat(response.getDigestSchemaVersion()).isZero(); + } + + private static void assertInvalidBinding( + GetDraftDesignDigestResponse response, String expectedMessage) { + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(response.getError().getMessage()).isEqualTo(expectedMessage); + assertThat(response.getTenantId()).isEmpty(); + assertThat(response.getAppliedCommitId()).isEmpty(); + assertThat(response.getContentDigest()).isEmpty(); + assertThat(response.getDigestSchemaVersion()).isZero(); + } + + private static void assertMissingBearer(Runnable rpc) { + Throwable failure = null; + try { + rpc.run(); + } catch (Throwable throwable) { + failure = throwable; + } + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + Status status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(status.getDescription()).isEqualTo("Missing token"); + } + + private static Set publicMethods(String resourceName) throws Exception { + ConfigurableEnvironment environment = new StandardEnvironment(); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); + environment + .getPropertySources() + .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + for (var propertySource : + new YamlPropertySourceLoader() + .load(resourceName, new FileSystemResource("src/main/resources/" + resourceName))) { + environment.getPropertySources().addFirst(propertySource); + } + return Set.copyOf( + Binder.get(environment) + .bind("firemud.auth.grpc.public-methods", Bindable.listOf(String.class)) + .orElse(List.of())); + } + + private void verifyNoOwnerCalls() { + verifyNoInteractions( + pingService, + roomService, + worldInstanceActivationService, + worldDesignMutationService, + worldUpgradeValidationService, + gameplaySessionAttestationService, + initialAdmissionBindHoldService); + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String namespace, String serviceName) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + serviceName + ", O=FireMUD Test"); + GeneralNames subjectAltNames = + new GeneralNames( + new GeneralName[] { + new GeneralName( + GeneralName.uniformResourceIdentifier, + "spiffe://firemud/ns/" + namespace + "/sa/" + serviceName), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }); + X509Certificate certificate = + issueCertificate( + subject, keyPair.getPublic(), caName, caPrivateKey, false, subjectAltNames); + return new TestCertificate(keyPair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerPrivateKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant now = Instant.now().minusSeconds(60); + 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( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerPrivateKey))); + } + + private static KeyPair newRsaKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate worldServer, + TestCertificate gameDesignClient, + TestCertificate accountClient, + TestCertificate foreignNamespaceGameDesignClient) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java index 4fe77572b9..15bbf0f2e0 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java @@ -12,6 +12,32 @@ class WorldAuthoredGraphSnapshotTest { private static final String DIGEST = "a".repeat(64); + @Test + void acceptsRetainedSchema2AndCurrentSchema3ButRejectsUnsupportedSchemas() { + for (int schema : new int[] {2, 3}) + assertThat(request(schema).digestSchemaVersion()).isEqualTo(schema); + for (int schema : new int[] {0, 1, 4}) { + assertThatThrownBy(() -> request(schema)).isInstanceOf(IllegalArgumentException.class); + } + } + + private CaptureRequest request(int schema) { + return new CaptureRequest( + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "publish-request-1", + DIGEST, + 1L, + "publish:tenant:publish-request:publish-request-1", + "commit-1", + DIGEST, + schema, + List.of()); + } + @Test void captureRequestPreservesTypedEpochAndCanonicalizesTupleOrder() { OwnedAffectedTuple scope = diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReaderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReaderTest.java new file mode 100644 index 0000000000..5b496c83e8 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReaderTest.java @@ -0,0 +1,153 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +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.WorldDesignScopeType; +import org.junit.jupiter.api.Test; + +class WorldCanonicalAuthoredGraphReaderTest { + private static final UUID TENANT = new UUID(0, 1); + private static final UUID VERSION = new UUID(0, 2); + private static final UUID COMMIT = new UUID(0, 3); + private static final UUID REGION = new UUID(0, 4); + private static final UUID REVISION = new UUID(0, 5); + + @Test + void consumesClosedActualStorageViewWithPrivateKeysAndEffectiveDefaults() throws Exception { + var graph = new WorldCanonicalAuthoredGraphReader().read(plan(), bytes(graphJson())); + assertThat(graph.tenantId()).isEqualTo(TENANT); + assertThat(graph.localTenantKey()).isEqualTo(9007199254740993L); + assertThat(graph.family(Family.REGION)).hasSize(1); + var row = graph.rows().getFirst(); + assertThat(row.template().templateId()).isEqualTo(REGION); + assertThat(row.scope()).isEqualTo(row.template()); + assertThat(row.authored().mutation().getRegion().getSpacingMultiplier()).isZero(); + assertThat(row.content().getRegion().getSpacingMultiplier()).isEqualTo(1.0); + assertThatThrownBy(() -> graph.rows().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void rejectsUnknownMissingDuplicateTrailingAndWrongRepresentations() throws Exception { + String good = graphJson(); + for (String bad : + List.of( + good.replace("\"schemaVersion\":\"2\"", "\"schemaVersion\":\"1\""), + good.replace("\"schemaVersion\":\"2\"", "\"schemaVersion\":2"), + good.replace("\"schemaVersion\":\"2\"", "\"schemaVersion\":\"2\",\"extra\":true"), + good.replace( + "\"schemaVersion\":\"2\"", "\"schemaVersion\":\"2\",\"schemaVersion\":\"2\""), + good + " {}", + good.replace("\"family\":\"REGION\"", "\"family\":\"ROOM\""), + good.replace("\"private_row_key\":11", "\"private_row_key\":\"11\""), + good.replace("\"private_row_key\":11", "\"private_row_key\":0"), + good.replace("\"private_row_key\":11", "\"private_row_key\":9223372036854775808"), + good.replace("\"weather\":\"rain\"", "\"weather\":\"tampered\""), + good.replace("\"version_id\":31,\"version\":0", "\"version_id\":32,\"version\":0"), + good.replace( + "\"canonicalVersionId\":\"" + VERSION, "\"canonicalVersionId\":\"" + REGION), + good.replace("\"name\":\"region\"", "\"name\":\"region\",\"extra\":null"))) { + assertThatThrownBy(() -> new WorldCanonicalAuthoredGraphReader().read(plan(), bytes(bad))) + .isInstanceOf(RuntimeException.class); + } + } + + static WorldDraftTopologyCommitPlan plan() throws Exception { + var owner = + new OwnerBinding( + "firemud", + TENANT, + VERSION, + new UUID(0, 6), + 41, + new UUID(0, 7), + new UUID(0, 8), + "sha256:" + "a".repeat(64), + new UUID(0, 9), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + var mutation = + WorldDesignMutationRevision.newBuilder() + .setCommitId(COMMIT.toString()) + .setLogicalRevisionId(REVISION.toString()) + .setAggregateId(REGION.toString()) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(REGION.toString()) + .setRegion(RegionDesignMutation.newBuilder().setName("region").setWeather("rain")) + .build(); + var binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 41, "gd-source", 51, "gd-source", "NEW_GAME_ROW"), + new UUID(0, 10), + COMMIT, + "original-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + REVISION, + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(mutation))), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + REGION.toString(), + "AGGREGATE", + REGION.toString(), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + REGION.toString(), + "REGION_SUBTREE", + REGION.toString(), + "0"))); + return WorldDraftTopologyCommitPlan.create(binding, owner); + } + + // Synthetic bytes are deliberate decoder fixtures; real V30 storage is covered by PostgreSQL. + private String graphJson() { + return """ + {"schemaVersion":"2","canonicalTenantId":"%s","canonicalVersionId":"%s","rows":[ + {"mapping":{"id":1,"target_namespace":"firemud","canonical_tenant_id":"%s", + "canonical_version_id":"%s","family":"REGION","template_id":"%s","private_row_key":11, + "tenant_id":9007199254740993,"version_id":31,"version_identity_operation_id":"%s", + "request_id":"%s","commit_id":"%s","revision_id":"%s","revision_order":"0"}, + "content":{"id":11,"tenant_id":9007199254740993,"version_id":31,"version":0,"name":"region", + "shard_id":0,"weather":"rain","generation_seed":0,"generator_type":"","generator_params":"", + "spacing_multiplier":1.0}}]} + """ + .replace("\n", "") + .formatted( + TENANT, + VERSION, + TENANT, + VERSION, + REGION, + new UUID(0, 6), + new UUID(0, 10), + COMMIT, + REVISION); + } + + private byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyServiceTest.java new file mode 100644 index 0000000000..8c42c6a388 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyServiceTest.java @@ -0,0 +1,96 @@ +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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalFrozenTopologyServiceTest { + private final WorldCanonicalFrozenTopologyRepository repository = + mock(WorldCanonicalFrozenTopologyRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final WorldCanonicalFrozenTopology.Request request = + mock(WorldCanonicalFrozenTopology.Request.class); + private final WorldCanonicalFrozenTopology result = mock(WorldCanonicalFrozenTopology.class); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactHistoricalRetryNeverReentersWriterOrOwnerTransaction() { + when(repository.readCommitted(request)).thenReturn(Optional.of(result)); + var service = new WorldCanonicalFrozenTopologyService(repository, manager); + assertThat(service.capture(request)).isSameAs(result); + verifyNoInteractions(manager); + org.mockito.Mockito.verify(repository).readCommitted(request); + org.mockito.Mockito.verifyNoMoreInteractions(repository); + } + + @Test + void absentHistoricalReadRemainsUnknownAndCannotStartCapture() { + when(repository.readCommitted(request)).thenReturn(Optional.empty()); + assertThat(new WorldCanonicalFrozenTopologyService(repository, manager).readCommitted(request)) + .isEmpty(); + verifyNoInteractions(manager); + org.mockito.Mockito.verify(repository).readCommitted(request); + org.mockito.Mockito.verifyNoMoreInteractions(repository); + } + + @Test + void newCaptureUsesDedicatedWritableReadCommittedTransactionAndCommit() { + var status = mock(TransactionStatus.class); + when(repository.readCommitted(request)).thenReturn(Optional.empty()); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.capture(request)).thenReturn(result); + assertThat(new WorldCanonicalFrozenTopologyService(repository, manager).capture(request)) + .isSameAs(result); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + var order = inOrder(repository, manager); + order.verify(repository).readCommitted(request); + order.verify(manager).getTransaction(definition.capture()); + order.verify(repository).capture(request); + order.verify(manager).commit(status); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + } + + @Test + void lateFailureRollsBackWithoutReturningAResult() { + var status = mock(TransactionStatus.class); + when(repository.readCommitted(request)).thenReturn(Optional.empty()); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.capture(request)).thenThrow(new IllegalStateException("mismatched freeze")); + assertThatThrownBy( + () -> new WorldCanonicalFrozenTopologyService(repository, manager).capture(request)) + .hasMessage("mismatched freeze"); + org.mockito.Mockito.verify(manager).rollback(status); + } + + @Test + void rejectsActiveCallerBeforeReadOrCapture() { + TransactionSynchronizationManager.setActualTransactionActive(true); + var service = new WorldCanonicalFrozenTopologyService(repository, manager); + assertThatThrownBy(() -> service.capture(request)) + .hasMessageContaining("independent owner operation"); + assertThatThrownBy(() -> service.readCommitted(request)) + .hasMessageContaining("independent owner operation"); + verifyNoInteractions(repository, manager); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyTest.java new file mode 100644 index 0000000000..69446e4090 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyTest.java @@ -0,0 +1,64 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import org.junit.jupiter.api.Test; + +class WorldCanonicalFrozenTopologyTest { + @Test + void exactFreezeRetainsSyntheticCheckpointWithoutRelabelingItsDigest() throws Exception { + var plan = WorldCanonicalAuthoredGraphReaderTest.plan(); + var request = new Request(plan, freeze(plan, plan.binding().commitId().toString(), true)); + assertThat(request.freeze().contentDigest()).isEqualTo("b".repeat(64)); + assertThat(request.plan().binding()).isSameAs(plan.binding()); + assertThat(WorldCanonicalFrozenTopology.STATUS).isEqualTo("CAPTURED_UNVERIFIED"); + } + + @Test + void rejectsSyntheticAppliedIdentityAndOmittedOriginalAffectedSet() throws Exception { + var plan = WorldCanonicalAuthoredGraphReaderTest.plan(); + assertThatThrownBy(() -> new Request(plan, freeze(plan, "synthetic-commit", true))) + .hasMessageContaining("exact selected complete commit"); + assertThatThrownBy( + () -> new Request(plan, freeze(plan, plan.binding().commitId().toString(), false))) + .hasMessageContaining("every exact original World affected tuple"); + } + + private CaptureRequest freeze( + WorldDraftTopologyCommitPlan plan, String selectedCommit, boolean tuples) { + var owner = plan.ownerBinding(); + var affected = + plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + return new CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + UUID.randomUUID(), + "synthetic-capture", + "a".repeat(64), + 1, + "publish:" + owner.canonicalTenantId() + ":publish-request:synthetic-capture", + selectedCommit, + "b".repeat(64), + 3, + tuples ? affected : List.of()); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java new file mode 100644 index 0000000000..3bff8b942a --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.sql.Connection; +import java.util.UUID; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInstanceAssociationTest { + private final DSLContext dsl = mock(DSLContext.class); + private final WorldCompleteLaunchBindingRepository launchBindings = + mock(WorldCompleteLaunchBindingRepository.class); + private final WorldAuthoredSourceIntakeRepository sourceIntakes = + mock(WorldAuthoredSourceIntakeRepository.class); + private final WorldAuthoredVersionIdentityRepository versionIdentities = + mock(WorldAuthoredVersionIdentityRepository.class); + private final WorldCanonicalInstanceAssociationRepository repository = + new WorldCanonicalInstanceAssociationRepository( + dsl, launchBindings, sourceIntakes, versionIdentities); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void ownerWriteRequiresAnActiveTransactionBeforeAnyRepositoryAccess() { + assertThatThrownBy(() -> repository.retainClaimInOwnerTransaction(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active World owner transaction"); + + verifyNoInteractions(dsl, launchBindings, sourceIntakes, versionIdentities); + } + + @Test + void ownerWriteRejectsReadOnlyAndNonReadCommittedTransactionsBeforeOwnerAccess() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + + assertThatThrownBy(() -> repository.retainClaimInOwnerTransaction(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + + assertThatThrownBy(() -> repository.retainClaimInOwnerTransaction(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ COMMITTED isolation"); + + verifyNoInteractions(dsl, launchBindings, sourceIntakes, versionIdentities); + } + + @Test + void committedOwnerReadMustRunOutsideAnyTransactionAndRequiresNonNilIdentity() { + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.readOwnerAssociation(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent committed owner read"); + + TransactionSynchronizationManager.clear(); + assertThatThrownBy(() -> repository.readOwnerAssociation(new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + + verifyNoInteractions(dsl, launchBindings, sourceIntakes, versionIdentities); + } + + @Test + void canonicalIdentityRequiresExplicitPublicProductionClassification() { + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + UUID.randomUUID(), + "firemud", + UUID.randomUUID(), + "fixture-world", + UUID.randomUUID(), + "SHARED", + false, + "synthetic-control-request")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("explicit public-production evidence"); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java new file mode 100644 index 0000000000..dd0676bebf --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java @@ -0,0 +1,505 @@ +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.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.util.JsonFormat; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +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.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DuplicateKeyException; + +class WorldCanonicalInstancePreparationTest { + @Test + void translatesV35DifferentPreparationConflictAndPreservesCause() { + DuplicateKeyException databaseFailure = + duplicateKeyFailure( + "23505", "Canonical gameInstanceId is already bound to a different preparation"); + + RuntimeException translated = + WorldCanonicalInstancePreparationRepository.translateCanonicalPreparationConflict( + databaseFailure); + + assertThat(translated) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class); + assertThat(translated.getCause()).isSameAs(databaseFailure); + } + + @Test + void translatesV35ReservedIdentityConflictAndPreservesCause() { + DuplicateKeyException databaseFailure = + duplicateKeyFailure( + "23505", + "ERROR: Canonical game instance or request identity is already reserved\n Where: owner function"); + + RuntimeException translated = + WorldCanonicalInstancePreparationRepository.translateCanonicalPreparationConflict( + databaseFailure); + + assertThat(translated) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class); + assertThat(translated.getCause()).isSameAs(databaseFailure); + } + + @Test + void preservesUnrelatedDuplicateKeyFailures() { + DuplicateKeyException wrongSqlState = + duplicateKeyFailure( + "23503", "Canonical game instance or request identity is already reserved"); + DuplicateKeyException unrelatedUniqueViolation = + duplicateKeyFailure("23505", "Unexpected unique constraint violation"); + DuplicateKeyException unrelatedViolationWithMatchingDetail = + duplicateKeyFailure( + "23505", + "ERROR: duplicate key violates a different constraint\nDetail: Canonical game instance or request identity is already reserved"); + + assertThat( + WorldCanonicalInstancePreparationRepository.translateCanonicalPreparationConflict( + wrongSqlState)) + .isSameAs(wrongSqlState); + assertThat( + WorldCanonicalInstancePreparationRepository.translateCanonicalPreparationConflict( + unrelatedUniqueViolation)) + .isSameAs(unrelatedUniqueViolation); + assertThat( + WorldCanonicalInstancePreparationRepository.translateCanonicalPreparationConflict( + unrelatedViolationWithMatchingDetail)) + .isSameAs(unrelatedViolationWithMatchingDetail); + } + + @Test + void defaultServiceDeniesBeforeRepositoryAccess() { + WorldCanonicalInstancePreparationRepository repository = + mock(WorldCanonicalInstancePreparationRepository.class); + WorldCanonicalInstancePreparation.Input input = + mock(WorldCanonicalInstancePreparation.Input.class); + WorldCanonicalInstanceTopologyPlan plan = mock(WorldCanonicalInstanceTopologyPlan.class); + when(input.topologyPlan()).thenReturn(plan); + when(plan.generationRules()).thenReturn(List.of()); + when(plan.spawnBindings()).thenReturn(List.of()); + + assertThatThrownBy( + () -> new WorldCanonicalInstancePreparationService(repository).prepare(input)) + .isInstanceOf(WorldCanonicalInstancePreparationService.PreparationDeniedException.class) + .hasMessageContaining("no authenticated source/release and Account commit verifier"); + + verifyNoInteractions(repository); + } + + private static DuplicateKeyException duplicateKeyFailure(String sqlState, String message) { + return new DuplicateKeyException( + "Database rejected canonical preparation", new SQLException(message, sqlState)); + } + + @Test + void requiredGenerationIntentFailsClosedBeforeAnyPreparation() { + WorldCanonicalInstanceTopologyPlan plan = mock(WorldCanonicalInstanceTopologyPlan.class); + when(plan.generationRules()) + .thenReturn(List.of(mock(WorldCanonicalInstanceTopologyPlan.GenerationRuleIntent.class))); + when(plan.spawnBindings()).thenReturn(List.of()); + + assertThatThrownBy(() -> WorldCanonicalInstancePreparation.requireGenerationFree(plan)) + .isInstanceOf(WorldCanonicalInstancePreparation.GenerationIntentNotSupportedException.class) + .hasMessageContaining("configured generation or spawn intent"); + } + + @Test + void requiredSpawnIntentFailsClosedBeforeAnyPreparation() { + WorldCanonicalInstanceTopologyPlan plan = mock(WorldCanonicalInstanceTopologyPlan.class); + when(plan.generationRules()).thenReturn(List.of()); + when(plan.spawnBindings()) + .thenReturn(List.of(mock(WorldCanonicalInstanceTopologyPlan.SpawnBindingIntent.class))); + + assertThatThrownBy(() -> WorldCanonicalInstancePreparation.requireGenerationFree(plan)) + .isInstanceOf(WorldCanonicalInstancePreparation.GenerationIntentNotSupportedException.class) + .hasMessageContaining("configured generation or spawn intent"); + } + + @Test + void separatelyReconstructedFrozenSourceMatchesEveryValueButChangedPayloadIsDenied() + throws Exception { + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + UUID revisionId = UUID.randomUUID(); + UUID regionId = UUID.randomUUID(); + UUID secondRevisionId = UUID.randomUUID(); + UUID secondRegionId = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenantId, versionId, 41L, "gd-tenant", 42L, "gd-tenant", "NEW_GAME_ROW"); + var originalMutation = regionMutation(commitId, revisionId, regionId, "Original region"); + var secondMutation = + regionMutation(commitId, secondRevisionId, secondRegionId, "Second region"); + DraftCommitBinding binding = + draftBinding( + target, + requestId, + commitId, + revisionId, + regionId, + originalMutation, + secondRevisionId, + secondRegionId, + secondMutation); + OwnerBinding owner = ownerBinding(tenantId, versionId); + CaptureRequest freeze = freezeRequest(owner, binding); + WorldDraftTopologyInputGraph graph = + topologyGraph( + tenantId, + versionId, + revisionId, + regionId, + originalMutation, + secondRevisionId, + secondRegionId, + secondMutation); + Request supplied = sourceRequest(binding, owner, freeze, graph); + + DraftCommitBinding reconstructedBinding = + DraftCommitBinding.fromStored(binding.canonicalJson(), binding.digest()); + Request reconstructed = + sourceRequest( + reconstructedBinding, + copyOwnerBinding(owner), + copyFreezeRequest(freeze), + topologyGraph( + tenantId, + versionId, + revisionId, + regionId, + originalMutation, + secondRevisionId, + secondRegionId, + secondMutation)); + + assertThat(reconstructed).isNotEqualTo(supplied); + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, supplied)) + .isTrue(); + + var changedMutation = regionMutation(commitId, revisionId, regionId, "Changed region"); + Request changedSource = + sourceRequest( + draftBinding( + target, + requestId, + commitId, + revisionId, + regionId, + changedMutation, + secondRevisionId, + secondRegionId, + secondMutation), + owner, + freeze, + topologyGraph( + tenantId, + versionId, + revisionId, + regionId, + changedMutation, + secondRevisionId, + secondRegionId, + secondMutation)); + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, changedSource)) + .isFalse(); + + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, requestWithFreeze(supplied, withChangedAffectedTuple(freeze)))) + .isFalse(); + + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, + sourceRequest(binding, withChangedOwnerEvidence(owner), freeze, graph))) + .isFalse(); + + var changedGraphMutation = + regionMutation(commitId, revisionId, regionId, "Graph-only payload change"); + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, + sourceRequest( + binding, + owner, + freeze, + topologyGraph( + tenantId, + versionId, + revisionId, + regionId, + changedGraphMutation, + secondRevisionId, + secondRegionId, + secondMutation)))) + .isFalse(); + + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, sourceRequest(binding, owner, freeze, reverseTopologyGraph(graph)))) + .isFalse(); + } + + private static DraftCommitBinding draftBinding( + DraftCommitBinding.TargetProof target, + UUID requestId, + UUID commitId, + UUID revisionId, + UUID regionId, + WorldDesignMutationRevision mutation, + UUID secondRevisionId, + UUID secondRegionId, + WorldDesignMutationRevision secondMutation) + throws Exception { + return DraftCommitBinding.create( + target, + requestId, + commitId, + "base-commit", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", revisionId, Owner.WORLD_MANAGEMENT, JsonFormat.printer().print(mutation)), + new DraftCommitBinding.RevisionPayload( + "1", + secondRevisionId, + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().print(secondMutation))), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + regionId.toString(), + "AGGREGATE", + regionId.toString(), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + regionId.toString(), + "REGION_SUBTREE", + regionId.toString(), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + secondRegionId.toString(), + "AGGREGATE", + secondRegionId.toString(), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + secondRegionId.toString(), + "REGION_SUBTREE", + secondRegionId.toString(), + "0"))); + } + + private static WorldDesignMutationRevision regionMutation( + UUID commitId, UUID revisionId, UUID regionId, String name) { + return WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revisionId.toString()) + .setCommitId(commitId.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setAggregateId(regionId.toString()) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(regionId.toString()) + .setScopeMutationPolicy( + WorldDesignScopeMutationPolicy.WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED) + .setRegion(RegionDesignMutation.newBuilder().setName(name)) + .build(); + } + + private static WorldDraftTopologyInputGraph topologyGraph( + UUID tenantId, + UUID versionId, + UUID revisionId, + UUID regionId, + WorldDesignMutationRevision mutation, + UUID secondRevisionId, + UUID secondRegionId, + WorldDesignMutationRevision secondMutation) { + return new WorldDraftTopologyInputGraph( + tenantId, + versionId, + List.of( + new WorldDraftTopologyInputGraph.Node( + "0", revisionId, regionId, regionId, mutation, null), + new WorldDraftTopologyInputGraph.Node( + "1", secondRevisionId, secondRegionId, secondRegionId, secondMutation, null))); + } + + private static WorldDraftTopologyInputGraph reverseTopologyGraph( + WorldDraftTopologyInputGraph graph) { + return new WorldDraftTopologyInputGraph( + graph.tenantId(), graph.versionId(), List.of(graph.nodes().get(1), graph.nodes().get(0))); + } + + private static OwnerBinding ownerBinding(UUID tenantId, UUID versionId) { + return new OwnerBinding( + "firemud", + tenantId, + versionId, + UUID.randomUUID(), + 41L, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "1".repeat(64), + UUID.randomUUID(), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + } + + private static CaptureRequest freezeRequest(OwnerBinding owner, DraftCommitBinding binding) { + return new CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + UUID.randomUUID(), + "publication-request", + "4".repeat(64), + 7L, + PublicationDigestRequestBinding.full( + owner.canonicalTenantId().toString(), + Long.toString(owner.gameDesignVersionId()), + "publication-request") + .derivedWorkflowIdentity(), + binding.commitId().toString(), + "5".repeat(64), + 3, + binding.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList()); + } + + private static CaptureRequest copyFreezeRequest(CaptureRequest source) { + return new CaptureRequest( + source.targetNamespace(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.intakeRequestId(), + source.publicationFence(), + source.publicationRequestId(), + source.requestDigest(), + source.versionStateEpoch(), + source.publishWorkflowId(), + source.appliedCommitId(), + source.contentDigest(), + source.digestSchemaVersion(), + List.copyOf(source.suppliedOwnedAffectedTuples())); + } + + private static CaptureRequest withChangedAffectedTuple(CaptureRequest source) { + List tuples = new ArrayList<>(source.suppliedOwnedAffectedTuples()); + OwnedAffectedTuple first = tuples.get(0); + tuples.set( + 0, + new OwnedAffectedTuple( + first.owner(), + first.aggregateType(), + first.aggregateId(), + first.scopeType(), + first.scopeId(), + "1")); + return new CaptureRequest( + source.targetNamespace(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.intakeRequestId(), + source.publicationFence(), + source.publicationRequestId(), + source.requestDigest(), + source.versionStateEpoch(), + source.publishWorkflowId(), + source.appliedCommitId(), + source.contentDigest(), + source.digestSchemaVersion(), + tuples); + } + + private static OwnerBinding copyOwnerBinding(OwnerBinding source) { + return new OwnerBinding( + source.targetNamespace(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.versionIdentityOperationId(), + source.gameDesignVersionId(), + source.intakeRequestId(), + source.intakeOperationId(), + source.intakeRequestDigest(), + source.sourceOperationId(), + source.sourceEvidenceDigest(), + source.intakeReceiptDigest()); + } + + private static OwnerBinding withChangedOwnerEvidence(OwnerBinding source) { + return new OwnerBinding( + source.targetNamespace(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.versionIdentityOperationId(), + source.gameDesignVersionId(), + source.intakeRequestId(), + source.intakeOperationId(), + source.intakeRequestDigest(), + source.sourceOperationId(), + "sha256:" + "8".repeat(64), + source.intakeReceiptDigest()); + } + + private static Request requestWithFreeze(Request source, CaptureRequest freeze) { + Request request = mock(Request.class); + when(request.plan()).thenReturn(source.plan()); + when(request.freeze()).thenReturn(freeze); + return request; + } + + private static Request sourceRequest( + DraftCommitBinding binding, + OwnerBinding owner, + CaptureRequest freeze, + WorldDraftTopologyInputGraph graph) { + WorldDraftTopologyCommitPlan plan = mock(WorldDraftTopologyCommitPlan.class); + when(plan.binding()).thenReturn(binding); + when(plan.ownerBinding()).thenReturn(owner); + when(plan.graph()).thenReturn(graph); + return new Request(plan, freeze); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlanTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlanTest.java new file mode 100644 index 0000000000..8b1e9ab387 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlanTest.java @@ -0,0 +1,650 @@ +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.Mockito.mock; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Row; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Template; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.Entry; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.GenerationRuleIntent; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.SpawnBindingIntent; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +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.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.junit.jupiter.api.Test; + +/** + * These fixtures exercise the pure projection with synthetic frozen component values. They do not + * establish authenticated publication, persisted capture, release evidence, or instance writes. + */ +class WorldCanonicalInstanceTopologyPlanTest { + private static final UUID TENANT = uuid(1); + private static final UUID VERSION = uuid(2); + private static final UUID COMMIT = uuid(3); + private static final UUID REGION_A = uuid(10); + private static final UUID REGION_B = uuid(11); + private static final UUID ZONE_A1 = uuid(20); + private static final UUID ZONE_A2 = uuid(21); + private static final UUID ZONE_B = uuid(22); + private static final UUID ROOM_A1 = uuid(30); + private static final UUID ROOM_A2 = uuid(31); + private static final UUID ROOM_B = uuid(32); + private static final UUID EXIT_A = uuid(40); + private static final UUID RULE_A = uuid(50); + private static final UUID RULE_B = uuid(51); + private static final UUID SPAWN_A = uuid(60); + private static final UUID SPAWN_B = uuid(61); + private static final UUID ENTITY_ITEM = uuid(70); + private static final UUID ENTITY_NPC = uuid(71); + private static final byte[] GRAPH_BYTES = + "synthetic graph bytes".getBytes(StandardCharsets.UTF_8); + private static final byte[] STORAGE_BYTES = + "synthetic storage result".getBytes(StandardCharsets.UTF_8); + private static final byte[] RESULT_BYTES = + "synthetic capture result".getBytes(StandardCharsets.UTF_8); + + @Test + void projectsEveryFamilyWithAuthoredParentLinksAndExactRequiredIntents() throws Exception { + Fixture fixture = fixture(); + var projected = WorldCanonicalInstanceTopologyPlan.create(fixture.source()); + + assertThat(projected.regions()).hasSize(2); + assertThat(projected.zones()).hasSize(3); + assertThat(projected.rooms()).hasSize(3); + assertThat(projected.roomExits()).hasSize(1); + assertThat(projected.generationRules()).hasSize(2); + assertThat(projected.spawnBindings()).hasSize(2); + assertThat(projected.roomExits().getFirst().fromRoom()) + .isEqualTo(new Template(Family.ROOM, ROOM_A1)); + assertThat(projected.roomExits().getFirst().toRoom()) + .isEqualTo(new Template(Family.ROOM, ROOM_A2)); + assertThat(projected.roomExits().getFirst().source().identity()) + .isEqualTo(new Template(Family.ROOM_EXIT, EXIT_A)); + assertThat(projected.zones()) + .filteredOn(zone -> zone.identity().templateId().equals(ZONE_B)) + .singleElement() + .satisfies( + zone -> assertThat(zone.region()).isEqualTo(new Template(Family.REGION, REGION_B))); + assertThat(projected.rooms()) + .filteredOn(room -> room.identity().templateId().equals(ROOM_B)) + .singleElement() + .satisfies(room -> assertThat(room.zone()).isEqualTo(new Template(Family.ZONE, ZONE_B))); + + assertThat(projected.generationRules()) + .extracting(GenerationRuleIntent::requiredIntent) + .containsExactly( + GenerationRuleDesignMutation.newBuilder() + .setName("weather-profile") + .setValue("{ \"locale\" : \"Café\" }") + .build(), + GenerationRuleDesignMutation.newBuilder() + .setName("room-density") + .setValue("sparse") + .build()); + assertThat(projected.spawnBindings()) + .extracting(SpawnBindingIntent::requiredIntent) + .containsExactly( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(ROOM_A1.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM) + .setEntityTemplateId(ENTITY_ITEM.toString()) + .setSpawnCount(0) + .setRespawnDelaySeconds(300) + .build(), + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(ROOM_B.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(ENTITY_NPC.toString()) + .setSpawnCount(4) + .setRespawnDelaySeconds(60) + .build()); + assertThat( + projected + .spawnBindings() + .getFirst() + .source() + .content() + .getWorldEntitySpawnBinding() + .getSpawnCount()) + .isEqualTo(1); + assertThat(projected.spawnBindings().getFirst().entityReference().kind()) + .isEqualTo(EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM); + assertThat(projected.spawnBindings().getFirst().entityReference().tenantId()).isEqualTo(TENANT); + assertThat(projected.spawnBindings().getFirst().entityReference().versionId()) + .isEqualTo(VERSION); + assertThat(projected.spawnBindings().getFirst().entityReference().templateId()) + .isEqualTo(ENTITY_ITEM); + } + + @Test + void keepsSourceBindingPayloadBytesAndOrderingAcrossDeterministicRetries() throws Exception { + Fixture fixture = fixture(); + var first = WorldCanonicalInstanceTopologyPlan.create(fixture.source()); + var retry = WorldCanonicalInstanceTopologyPlan.create(fixture.source()); + + assertThat(first.captureId()).isEqualTo(uuid(100)); + assertThat(fixture.source().status()).isEqualTo(WorldCanonicalFrozenTopology.STATUS); + assertThat(first.sourceBinding()).isSameAs(fixture.source().request()); + assertThat(first.entries()).containsExactlyElementsOf(retry.entries()); + assertThat(first.entries()) + .extracting(Entry::identity) + .containsExactlyElementsOf(fixture.rows().stream().map(Row::template).toList()); + assertThat(fixture.source().graphBytes()).isEqualTo(GRAPH_BYTES); + assertThat(fixture.source().storageResultBytes()).isEqualTo(STORAGE_BYTES); + assertThat(fixture.source().resultBytes()).isEqualTo(RESULT_BYTES); + for (Entry entry : first.entries()) { + String exactPayload = + fixture.plan().binding().revisions().stream() + .filter( + revision -> + revision + .revisionId() + .equals( + uuidFrom(entry.source().authoredRevision().getLogicalRevisionId()))) + .findFirst() + .orElseThrow() + .payload(); + assertThat(entry.source().inputPayload()).isEqualTo(exactPayload); + assertThat(entry.source().inputPayloadBytes()) + .isEqualTo(exactPayload.getBytes(StandardCharsets.UTF_8)); + } + + var authoredRoom = + first.rooms().stream() + .filter(room -> room.identity().templateId().equals(ROOM_A1)) + .findFirst() + .orElseThrow(); + String expectedLocalizedName = "{ \"en-US\" : \"Café 🐉\", \"ja\" : \"雪\" }"; + String expectedLocalizedDescription = "{\"en-US\":\"A quiet room\"}"; + assertThat(authoredRoom.content().getNameLocalizedVariantsJson()) + .isEqualTo(expectedLocalizedName); + assertThat(authoredRoom.content().getDescriptionLocalizedVariantsJson()) + .isEqualTo(expectedLocalizedDescription); + assertThat(authoredRoom.source().authoredRevision().getRoom().getNameLocalizedVariantsJson()) + .isEqualTo(expectedLocalizedName); + } + + @Test + void rejectsMissingDuplicateAndTypeConfusedFrozenRows() throws Exception { + Fixture fixture = fixture(); + + List missingRegion = new ArrayList<>(fixture.rows()); + missingRegion.removeIf(row -> row.template().equals(new Template(Family.REGION, REGION_B))); + assertThatThrownBy( + () -> + WorldCanonicalInstanceTopologyPlan.create( + withRows(fixture, missingRegion).source())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("omits or adds"); + + List duplicated = new ArrayList<>(fixture.rows()); + duplicated.set(1, fixture.rows().getFirst()); + assertThatThrownBy( + () -> WorldCanonicalInstanceTopologyPlan.create(withRows(fixture, duplicated).source())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing, duplicated"); + + List typeConfused = new ArrayList<>(fixture.rows()); + Row zone = findRow(typeConfused, Family.ZONE, ZONE_A1); + int index = typeConfused.indexOf(zone); + typeConfused.set( + index, + new Row( + new Template(Family.REGION, ZONE_A1), + zone.mappingKey(), + zone.privateRowKey(), + zone.authored(), + zone.content())); + assertThatThrownBy( + () -> + WorldCanonicalInstanceTopologyPlan.create(withRows(fixture, typeConfused).source())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("confuses authored family"); + + List missingRoomReference = new ArrayList<>(fixture.rows()); + Row exit = findRow(missingRoomReference, Family.ROOM_EXIT, EXIT_A); + int exitIndex = missingRoomReference.indexOf(exit); + var badExitContent = + exit.content().toBuilder() + .setRoomExit(exit.content().getRoomExit().toBuilder().setToRoomId(uuid(999).toString())) + .build(); + missingRoomReference.set( + exitIndex, + new Row( + exit.template(), + exit.mappingKey(), + exit.privateRowKey(), + exit.authored(), + badExitContent)); + assertThatThrownBy( + () -> + WorldCanonicalInstanceTopologyPlan.create( + withRows(fixture, missingRoomReference).source())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Frozen content differs"); + } + + @Test + void sourceCommitPlanRejectsCrossRegionExitOutsideItsDeclaredSubtree() { + List mutations = mutations(); + for (int index = 0; index < mutations.size(); index++) { + var mutation = mutations.get(index); + if (UUID.fromString(mutation.getAggregateId()).equals(EXIT_A)) { + mutations.set( + index, + mutation.toBuilder() + .setRoomExit(mutation.getRoomExit().toBuilder().setToRoomId(ROOM_B.toString())) + .build()); + } + } + + assertThatThrownBy(() -> createPlan(mutations)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("outside declared scope"); + } + + private static Fixture fixture() throws Exception { + WorldDraftTopologyCommitPlan plan = createPlan(mutations()); + WorldCanonicalAuthoredGraph graph = graph(plan); + var request = new WorldCanonicalFrozenTopology.Request(plan, freeze(plan)); + WorldCanonicalFrozenTopology source = + new WorldCanonicalFrozenTopology( + uuid(100), + request, + mock(WorldAuthoredVersionIdentityReceipt.class), + graph, + GRAPH_BYTES, + STORAGE_BYTES, + RESULT_BYTES); + return new Fixture(source, plan, graph.rows()); + } + + private static Fixture withRows(Fixture original, List rows) { + WorldCanonicalAuthoredGraph graph = + new WorldCanonicalAuthoredGraph(TENANT, VERSION, 9001, 9002, rows); + WorldCanonicalFrozenTopology source = + new WorldCanonicalFrozenTopology( + original.source().captureId(), + original.source().request(), + mock(WorldAuthoredVersionIdentityReceipt.class), + graph, + GRAPH_BYTES, + STORAGE_BYTES, + RESULT_BYTES); + return new Fixture(source, original.plan(), rows); + } + + private static WorldDraftTopologyCommitPlan createPlan( + List mutations) throws InvalidProtocolBufferException { + List revisions = new ArrayList<>(); + List affected = new ArrayList<>(); + for (int index = 0; index < mutations.size(); index++) { + var mutation = mutations.get(index); + UUID revisionId = UUID.fromString(mutation.getLogicalRevisionId()); + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(index), + revisionId, + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(mutation))); + String aggregate = + mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + String scope = mutation.getScopeType().name().replace("WORLD_DESIGN_SCOPE_TYPE_", ""); + affected.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + aggregate, + mutation.getAggregateId(), + "AGGREGATE", + mutation.getAggregateId(), + "0")); + affected.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + aggregate, + mutation.getAggregateId(), + scope, + mutation.getScopeId(), + "0")); + } + DraftCommitBinding binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 41, "gd-tenant-41", 51, "gd-tenant-41", "NEW_GAME_ROW"), + uuid(80), + COMMIT, + "base-commit", + revisions, + affected); + return WorldDraftTopologyCommitPlan.create(binding, ownerBinding()); + } + + private static OwnerBinding ownerBinding() { + return new OwnerBinding( + "firemud", + TENANT, + VERSION, + uuid(81), + 41, + uuid(82), + uuid(83), + "sha256:" + "a".repeat(64), + uuid(84), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + } + + private static CaptureRequest freeze(WorldDraftTopologyCommitPlan plan) { + var owner = plan.ownerBinding(); + List affected = + plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + String publicationRequestId = "publication-request"; + return new CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + uuid(85), + publicationRequestId, + "d".repeat(64), + 7, + PublicationDigestRequestBinding.full( + TENANT.toString(), Long.toString(owner.gameDesignVersionId()), publicationRequestId) + .derivedWorkflowIdentity(), + plan.binding().commitId().toString(), + "e".repeat(64), + 3, + affected); + } + + private static WorldCanonicalAuthoredGraph graph(WorldDraftTopologyCommitPlan plan) { + List rows = new ArrayList<>(); + long key = 1; + for (var node : plan.graph().nodes()) { + Family family = family(node.mutation().getAggregateType()); + rows.add( + new Row( + new Template(family, node.templateId()), + key, + key + 1000, + node, + storageContent(node.mutation()))); + key++; + } + return new WorldCanonicalAuthoredGraph(TENANT, VERSION, 9001, 9002, rows); + } + + private static WorldDesignMutationRevision storageContent(WorldDesignMutationRevision mutation) { + return switch (mutation.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> + mutation.getRegion().getSpacingMultiplier() == 0 + ? mutation.toBuilder() + .setRegion(mutation.getRegion().toBuilder().setSpacingMultiplier(1.0)) + .build() + : mutation; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> + mutation.getRoomExit().getCost() == 0 + ? mutation.toBuilder() + .setRoomExit(mutation.getRoomExit().toBuilder().setCost(1)) + .build() + : mutation; + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> + mutation.getWorldEntitySpawnBinding().getSpawnCount() == 0 + ? mutation.toBuilder() + .setWorldEntitySpawnBinding( + mutation.getWorldEntitySpawnBinding().toBuilder().setSpawnCount(1)) + .build() + : mutation; + default -> mutation; + }; + } + + private static List mutations() { + String localizedName = "{ \"en-US\" : \"Café 🐉\", \"ja\" : \"雪\" }"; + String localizedDescription = "{\"en-US\":\"A quiet room\"}"; + List rows = new ArrayList<>(); + rows.add( + base( + 1, + REGION_A, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("Northern Reach") + .setWeather("snow") + .setGeneratorParams("{ \"seed\" : 17 }") + .setSpacingMultiplier(0)) + .build()); + rows.add( + base( + 2, + ZONE_A1, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setZone( + ZoneDesignMutation.newBuilder().setName("Harbor").setRegionId(REGION_A.toString())) + .build()); + rows.add( + base( + 3, + ROOM_A1, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("Quay") + .setDescription("Stone steps descend to the water.") + .setZoneId(ZONE_A1.toString()) + .setNameLocalizedVariantsJson(localizedName) + .setDescriptionLocalizedVariantsJson(localizedDescription)) + .build()); + rows.add( + base( + 4, + REGION_B, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_B) + .setRegion( + RegionDesignMutation.newBuilder().setName("Southern Reach").setWeather("clear")) + .build()); + rows.add( + base( + 5, + ZONE_B, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_B) + .setZone( + ZoneDesignMutation.newBuilder().setName("Lowland").setRegionId(REGION_B.toString())) + .build()); + rows.add( + base( + 6, + ROOM_B, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_B) + .setRoom(RoomDesignMutation.newBuilder().setName("Ford").setZoneId(ZONE_B.toString())) + .build()); + rows.add( + base( + 7, + ZONE_A2, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("Cliffside") + .setRegionId(REGION_A.toString())) + .build()); + rows.add( + base( + 8, + ROOM_A2, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setRoom( + RoomDesignMutation.newBuilder().setName("Beacon").setZoneId(ZONE_A2.toString())) + .build()); + rows.add( + base( + 9, + EXIT_A, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(ROOM_A1.toString()) + .setToRoomId(ROOM_A2.toString()) + .setDirection("east") + .setCost(0)) + .build()); + rows.add( + base( + 10, + RULE_A, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder() + .setName("weather-profile") + .setValue("{ \"locale\" : \"Café\" }")) + .build()); + rows.add( + base( + 11, + RULE_B, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE, + ZONE_B) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder() + .setName("room-density") + .setValue("sparse")) + .build()); + rows.add( + base( + 12, + SPAWN_A, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(ROOM_A1.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM) + .setEntityTemplateId(ENTITY_ITEM.toString()) + .setSpawnCount(0) + .setRespawnDelaySeconds(300)) + .build()); + rows.add( + base( + 13, + SPAWN_B, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE, + ZONE_B) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(ROOM_B.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(ENTITY_NPC.toString()) + .setSpawnCount(4) + .setRespawnDelaySeconds(60)) + .build()); + return rows; + } + + private static WorldDesignMutationRevision.Builder base( + int revision, + UUID identity, + WorldDesignAggregateType aggregate, + WorldDesignScopeType scopeType, + UUID scopeId) { + return WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(uuid(200 + revision).toString()) + .setCommitId(COMMIT.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(aggregate) + .setAggregateId(identity.toString()) + .setScopeType(scopeType) + .setScopeId(scopeId.toString()); + } + + private static Row findRow(List rows, Family family, UUID identity) { + return rows.stream() + .filter(row -> row.template().equals(new Template(family, identity))) + .findFirst() + .orElseThrow(); + } + + private static Family family(WorldDesignAggregateType aggregate) { + return switch (aggregate) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> Family.REGION; + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> Family.ZONE; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> Family.ROOM; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> Family.ROOM_EXIT; + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> Family.GENERATION_RULE; + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> + Family.WORLD_ENTITY_SPAWN_BINDING; + default -> throw new IllegalArgumentException("Unexpected test family"); + }; + } + + private static UUID uuidFrom(String value) { + return UUID.fromString(value); + } + + private static UUID uuid(int value) { + return UUID.fromString("00000000-0000-4000-8000-%012d".formatted(value)); + } + + private record Fixture( + WorldCanonicalFrozenTopology source, WorldDraftTopologyCommitPlan plan, List rows) {} +} 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 index 599d93df49..82e384c86b 100644 --- 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 @@ -728,7 +728,7 @@ private static CompleteLaunchBindingEvidence evidence( String commitId = "commit-41"; List participants = List.of( - participant("WORLD_MANAGEMENT", 2, "a", false), + participant("WORLD_MANAGEMENT", 3, "a", false), participant("ENTITY_MANAGEMENT", 2, "b", false), participant("GAME_LOGIC", 1, "c", true), participant("AUTOMATION_SCRIPTING", 5, "d", false), diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidenceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidenceTest.java new file mode 100644 index 0000000000..091f18dad8 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidenceTest.java @@ -0,0 +1,42 @@ +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.Mockito.mock; + +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +class WorldDraftTopologyCommitEvidenceTest { + @Test + void graphAndResultBytesAreDefensiveAndRemainExplicitlyUnverifiedPermission() { + byte[] graph = {1, 2}; + byte[] result = {3, 4}; + DraftCommitBinding binding = mock(DraftCommitBinding.class); + WorldDesignPublicationFenceEvidence.OwnerBinding owner = + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class); + WorldDraftTopologyCommitEvidence evidence = + new WorldDraftTopologyCommitEvidence(binding, owner, graph, result); + graph[0] = 9; + result[0] = 9; + evidence.graphBytes()[0] = 8; + evidence.resultBytes()[0] = 8; + assertThat(evidence.graphBytes()).containsExactly((byte) 1, (byte) 2); + assertThat(evidence.resultBytes()).containsExactly((byte) 3, (byte) 4); + assertThat(evidence.binding()).isSameAs(binding); + assertThat(evidence.ownerBinding()).isSameAs(owner); + assertThat(evidence.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + } + + @Test + void incompleteEvidenceCannotBeReturnedAsSuccessfulComponentStorage() { + assertThatThrownBy( + () -> + new WorldDraftTopologyCommitEvidence( + mock(DraftCommitBinding.class), + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class), + new byte[0], + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java new file mode 100644 index 0000000000..4d2954c886 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java @@ -0,0 +1,664 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.function.UnaryOperator; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPlan; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +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.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldGenerationSubtreeDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.junit.jupiter.api.Test; + +class WorldDraftTopologyCommitPlanTest { + private static final UUID TENANT = id(1); + private static final UUID VERSION = id(2); + private static final UUID COMMIT = id(3); + private static final UUID REGION = id(10); + private static final UUID ZONE = id(11); + private static final UUID ROOM = id(12); + private static final UUID OTHER_ROOM = id(13); + private static final UUID ENTITY = id(30); + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + void preservesCompleteMixedOwnerBindingAllFamiliesAndEveryPayloadField() { + List mutations = fresh(); + DraftCommitBinding binding = binding(mutations); + OwnerBinding owner = owner(); + var plan = WorldDraftTopologyCommitPlan.create(binding, owner); + + assertThat(plan.binding()).isSameAs(binding); + assertThat(plan.ownerBinding()).isSameAs(owner); + assertThat(plan.graph().tenantId()).isEqualTo(TENANT); + assertThat(plan.graph().versionId()).isEqualTo(VERSION); + assertThat(WorldDraftTopologyInputGraph.STATUS).isEqualTo("PURE_UNVERIFIED"); + assertThat(plan.graph().nodes()) + .extracting(WorldDraftTopologyInputGraph.Node::mutation) + .containsExactlyElementsOf(mutations); + assertThat(plan.graph().nodes()) + .extracting(WorldDraftTopologyInputGraph.Node::revisionOrder) + .containsExactly("1", "2", "3", "4", "5", "6", "7"); + assertThat(plan.graph().family(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM)) + .hasSize(2); + assertThat(plan.graph().nodes().getFirst().mutation().getRegion().getSpacingMultiplier()) + .isZero(); + var reference = plan.graph().nodes().getLast().entityReference(); + assertThat(reference.kind()) + .isEqualTo(EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC); + assertThat(reference.tenantId()).isEqualTo(TENANT); + assertThat(reference.versionId()).isEqualTo(VERSION); + assertThat(reference.templateId()).isEqualTo(ENTITY); + assertThat(plan.binding().baseCommitId()).isEqualTo("reviewed-base"); + assertThat(plan.binding().revisions().getFirst().payload()) + .isEqualTo("other-owner-byte-string"); + assertThatThrownBy(() -> plan.graph().nodes().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + plan.graph() + .family(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void acceptsOutOfParentOrderWithoutChangingCanonicalRevisionOrder() { + List mutations = fresh(); + List reversed = new ArrayList<>(mutations.reversed()); + var plan = WorldDraftTopologyCommitPlan.create(binding(reversed), owner()); + assertThat(plan.graph().nodes()) + .extracting(WorldDraftTopologyInputGraph.Node::mutation) + .containsExactlyElementsOf(reversed); + } + + @Test + void preservesZeroExitCostAndSpawnCountForTheExistingOwnerDefaults() { + var mutations = fresh(); + mutations.set( + 4, + mutations.get(4).toBuilder() + .setRoomExit(mutations.get(4).getRoomExit().toBuilder().setCost(0)) + .build()); + mutations.set( + 6, + mutations.get(6).toBuilder() + .setWorldEntitySpawnBinding( + mutations.get(6).getWorldEntitySpawnBinding().toBuilder().setSpawnCount(0)) + .build()); + var original = binding(mutations); + var plan = WorldDraftTopologyCommitPlan.create(original, owner()); + assertThat(plan.binding()).isSameAs(original); + assertThat(plan.graph().nodes().get(4).mutation().getRoomExit().getCost()).isZero(); + assertThat(plan.graph().nodes().get(6).mutation().getWorldEntitySpawnBinding().getSpawnCount()) + .isZero(); + assertThat(plan.graph().nodes()) + .extracting(WorldDraftTopologyInputGraph.Node::mutation) + .containsExactlyElementsOf(mutations); + assertThat(plan.binding().canonicalBytes()).isEqualTo(original.canonicalBytes()); + } + + @Test + void validatesZoneSubtreeAcrossAllDependentFamiliesAndDeniesNoWorldInput() { + var mutations = fresh(); + for (int index = 1; index < mutations.size(); index++) { + mutations.set( + index, + mutations.get(index).toBuilder() + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE) + .setScopeId(ZONE.toString()) + .build()); + } + var graph = WorldDraftTopologyCommitPlan.create(binding(mutations), owner()).graph(); + assertThat(graph.nodes().subList(1, graph.nodes().size())) + .extracting(WorldDraftTopologyInputGraph.Node::scopeId) + .containsOnly(ZONE); + rejected(binding(List.of())); + } + + @Test + void sameUuidInDifferentFamiliesResolvesOnlyThroughItsTypedParentReference() { + var mutations = fresh(); + mutations.set(1, mutations.get(1).toBuilder().setAggregateId(REGION.toString()).build()); + for (int index : List.of(2, 3)) { + mutations.set( + index, + mutations.get(index).toBuilder() + .setRoom(mutations.get(index).getRoom().toBuilder().setZoneId(REGION.toString())) + .build()); + } + var graph = WorldDraftTopologyCommitPlan.create(binding(mutations), owner()).graph(); + assertThat( + graph + .family(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .getFirst() + .templateId()) + .isEqualTo(REGION); + assertThat( + graph + .family(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .getFirst() + .templateId()) + .isEqualTo(REGION); + mutations.remove(1); + // The remaining REGION with that UUID cannot satisfy a typed ZONE parent reference. + rejected(binding(mutations)); + } + + @Test + void rejectsMissingAdditionalOrChangedDerivedScopeTuple() { + var mutations = fresh(); + List units = units(mutations); + units.removeLast(); + rejected(binding(mutations, units)); + units = units(mutations); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, "ROOM", ROOM.toString(), "ZONE_SUBTREE", ZONE.toString(), "0")); + rejected(binding(mutations, units)); + units = units(mutations); + AffectedUnit prior = units.get(1); + units.set( + 1, + new AffectedUnit( + prior.owner(), + prior.aggregateType(), + prior.aggregateId(), + prior.scopeType(), + prior.scopeId(), + "1")); + rejected(binding(mutations, units)); + } + + @Test + void rejectsEveryNumericNilUppercaseShortenedAndWhitespaceReference() { + for (String bad : + List.of( + "12", + "00000000-0000-0000-0000-000000000000", + "ABCDEFAB-0000-4000-8000-000000000001", + "1-0-4000-8000-1")) { + rejected(change(2, b -> b.setAggregateId(bad))); + rejected(change(1, b -> b.setScopeId(bad))); + rejected(change(1, b -> b.setZone(b.getZone().toBuilder().setRegionId(bad)))); + rejected(change(2, b -> b.setRoom(b.getRoom().toBuilder().setZoneId(bad)))); + rejected(change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setFromRoomId(bad)))); + rejected(change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setToRoomId(bad)))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder().setRoomId(bad)))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder().setEntityTemplateId(bad)))); + } + assertThatIllegalArgumentException() + .isThrownBy(() -> change(2, b -> b.setAggregateId(" " + ROOM))); + } + + @Test + void rejectsMissingAndWrongFamilyParentsOrScopeInsteadOfGuessingExistingRows() { + rejected(change(1, b -> b.setZone(b.getZone().toBuilder().setRegionId(id(99).toString())))); + rejected(change(2, b -> b.setRoom(b.getRoom().toBuilder().setZoneId(REGION.toString())))); + rejected( + change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setToRoomId(id(99).toString())))); + rejected(change(5, b -> b.setScopeId(ROOM.toString()))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder().setRoomId(id(99).toString())))); + List mutations = fresh(); + mutations.removeFirst(); + rejected(binding(mutations)); + } + + @Test + void requiresBothExitEndpointsWithinDeclaredZoneButSupportsTheirCommonRegion() { + List mutations = fresh(); + UUID secondZone = id(40); + mutations.add( + base(40, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("Other zone") + .setRegionId(REGION.toString())) + .build()); + mutations.set( + 3, + mutations.get(3).toBuilder() + .setRoom(mutations.get(3).getRoom().toBuilder().setZoneId(secondZone.toString())) + .build()); + assertThat(WorldDraftTopologyCommitPlan.create(binding(mutations), owner()).graph().nodes()) + .hasSize(8); + mutations.set( + 4, + mutations.get(4).toBuilder() + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE) + .setScopeId(ZONE.toString()) + .build()); + rejected(binding(mutations)); + } + + @Test + void rejectsCrossRegionExitAndMismatchedAncestry() { + List mutations = fresh(); + UUID otherRegion = id(41); + UUID otherZone = id(42); + mutations.add( + base(41, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setScopeId(otherRegion.toString()) + .setRegion(RegionDesignMutation.newBuilder().setName("South")) + .build()); + mutations.add( + base(42, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setScopeId(otherRegion.toString()) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("South zone") + .setRegionId(otherRegion.toString())) + .build()); + mutations.set( + 3, + mutations.get(3).toBuilder() + .setScopeId(otherRegion.toString()) + .setRoom(mutations.get(3).getRoom().toBuilder().setZoneId(otherZone.toString())) + .build()); + rejected(binding(mutations)); + rejected( + change( + 0, + b -> + b.setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE) + .setScopeId(ZONE.toString()))); + rejected( + change( + 1, + b -> + b.setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE) + .setScopeId(ROOM.toString()))); + } + + @Test + void rejectsDuplicateIdsRuleKeysSpawnKeysAndExitDirections() { + List mutations = fresh(); + mutations.add(mutations.get(2).toBuilder().setLogicalRevisionId(id(500).toString()).build()); + rejected(binding(mutations)); + for (int index : List.of(4, 5, 6)) { + mutations = fresh(); + mutations.add( + mutations.get(index).toBuilder() + .setAggregateId(id(60 + index).toString()) + .setLogicalRevisionId(id(600 + index).toString()) + .build()); + rejected(binding(mutations)); + } + mutations = fresh(); + mutations.set(2, mutations.get(2).toBuilder().setAggregateId(ZONE.toString()).build()); + rejected(binding(mutations)); + } + + @Test + void rejectsUnsupportedOperationsPoliciesFamiliesAndFreshNonzeroEpochs() { + rejected( + change( + 0, + b -> + b.setOperation( + WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_DELETE))); + rejected( + change( + 0, b -> b.setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_NEW_EMPTY_REGION))); + rejected( + change( + 0, + b -> + b.setScopeMutationPolicy( + WorldDesignScopeMutationPolicy + .WORLD_DESIGN_SCOPE_MUTATION_POLICY_REPLACE_SCOPE))); + rejected(change(0, b -> b.setExpectedDraftRevisionEpoch(1))); + rejected(change(0, b -> b.setExpectedDraftScopeRevisionEpoch(Long.MAX_VALUE))); + rejected(change(0, b -> b.setExpectedDraftRevisionEpoch(-1))); + rejected( + change( + 0, + b -> + b.setAggregateType( + WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_GENERATION_SUBTREE) + .setWorldGenerationSubtree( + WorldGenerationSubtreeDesignMutation.getDefaultInstance()))); + rejected(change(0, WorldDesignMutationRevision.Builder::clearRegion)); + rejected( + change( + 0, b -> b.setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM))); + } + + @Test + void rejectsInvalidRequiredPayloadRangesAndNonfiniteValues() { + for (double value : + List.of(Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, -1.0)) { + rejected(change(0, b -> b.setRegion(b.getRegion().toBuilder().setSpacingMultiplier(value)))); + } + rejected(change(0, b -> b.setRegion(b.getRegion().toBuilder().setShardId(-1)))); + rejected(change(0, b -> b.setRegion(b.getRegion().toBuilder().setName(" ")))); + rejected(change(0, b -> b.setRegion(b.getRegion().toBuilder().setWeather("x".repeat(51))))); + rejected( + change(0, b -> b.setRegion(b.getRegion().toBuilder().setGeneratorType("x".repeat(51))))); + rejected(change(1, b -> b.setZone(b.getZone().toBuilder().setName("x".repeat(101))))); + rejected(change(2, b -> b.setRoom(b.getRoom().toBuilder().setName("")))); + rejected(change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setCost(-1)))); + rejected(change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setDirection("")))); + rejected( + change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setDirection("x".repeat(33))))); + rejected(change(5, b -> b.setGenerationRule(b.getGenerationRule().toBuilder().setName("")))); + rejected( + change( + 5, + b -> b.setGenerationRule(b.getGenerationRule().toBuilder().setValue("x".repeat(256))))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder().setSpawnCount(-1)))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder().setRespawnDelaySeconds(-1)))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder() + .setEntityTemplateType( + EntityTemplateReferenceType + .ENTITY_TEMPLATE_REFERENCE_TYPE_UNSPECIFIED)))); + } + + @Test + void rejectsMalformedDuplicateUnknownAndTrailingJsonWithoutDroppingFields() { + for (String bad : + List.of( + "{", + "null", + "[]", + " ", + "{} {}", + "{\"commitId\":\"one\",\"commitId\":\"two\"}", + "{\"unknown\":true}")) { + var good = binding(fresh()); + var revisions = new ArrayList<>(good.revisions()); + var prior = revisions.get(1); + revisions.set( + 1, + new DraftCommitBinding.RevisionPayload( + prior.revisionOrder(), prior.revisionId(), prior.owner(), bad)); + rejected( + DraftCommitBinding.create( + good.target(), + good.requestId(), + good.commitId(), + good.baseCommitId(), + revisions, + good.affectedUnits())); + } + } + + @Test + void rejectsChangedTargetCommitRevisionAndRetainedSourceWhileKeepingOwnerEvidenceUnauthenticated() + throws InvalidProtocolBufferException { + rejected(change(0, b -> b.setCommitId(id(99).toString()))); + var good = binding(fresh()); + var changedIdentity = new ArrayList<>(good.revisions()); + var firstWorld = changedIdentity.get(1); + changedIdentity.set( + 1, + new DraftCommitBinding.RevisionPayload( + firstWorld.revisionOrder(), + firstWorld.revisionId(), + firstWorld.owner(), + JsonFormat.printer() + .print( + fresh().getFirst().toBuilder() + .setLogicalRevisionId(id(99).toString()) + .build()))); + rejected( + DraftCommitBinding.create( + good.target(), + good.requestId(), + good.commitId(), + good.baseCommitId(), + changedIdentity, + good.affectedUnits())); + var target = good.target(); + for (DraftCommitBinding.TargetProof changed : + List.of( + new DraftCommitBinding.TargetProof( + id(99), VERSION, 901, "source-key", 801, "source-key", "NEW_GAME_ROW"), + new DraftCommitBinding.TargetProof( + TENANT, id(99), 901, "source-key", 801, "source-key", "NEW_GAME_ROW"), + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 902, "source-key", 801, "source-key", "NEW_GAME_ROW"), + new DraftCommitBinding.TargetProof( + TENANT, + VERSION, + target.gameDesignVersionRowId(), + "source-key", + 801, + "source-key", + "RETAINED_GAME_V30"))) { + rejected( + DraftCommitBinding.create( + changed, + good.requestId(), + good.commitId(), + good.baseCommitId(), + good.revisions(), + good.affectedUnits())); + } + var revisions = new ArrayList<>(good.revisions()); + var prior = revisions.get(2); + revisions.set( + 2, + new DraftCommitBinding.RevisionPayload( + prior.revisionOrder(), revisions.get(1).revisionId(), prior.owner(), prior.payload())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + DraftCommitBinding.create( + good.target(), + good.requestId(), + good.commitId(), + good.baseCommitId(), + revisions, + good.affectedUnits())); + } + + private static List fresh() { + return new ArrayList<>( + List.of( + base(10, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("North") + .setWeather("snow") + .setShardId(2) + .setGenerationSeed(Long.MIN_VALUE) + .setGeneratorType("Dungeon") + .setGeneratorParams("{\"seed\":1}")) + .build(), + base(11, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("Cavern") + .setRegionId(REGION.toString())) + .build(), + base(12, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("Hall") + .setDescription("Original text") + .setZoneId(ZONE.toString()) + .setNameLocalizedVariantsJson("{\"fr\":\"Salle\"}") + .setDescriptionLocalizedVariantsJson("{\"fr\":\"Texte\"}")) + .build(), + base(13, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom(RoomDesignMutation.newBuilder().setName("Gate").setZoneId(ZONE.toString())) + .build(), + base(14, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(ROOM.toString()) + .setToRoomId(OTHER_ROOM.toString()) + .setDirection("NORTH") + .setCost(2)) + .build(), + base(15, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder().setName("density").setValue("sparse")) + .build(), + base( + 16, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(ROOM.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(ENTITY.toString()) + .setSpawnCount(3) + .setRespawnDelaySeconds(90)) + .build())); + } + + private static WorldDesignMutationRevision.Builder base( + int number, WorldDesignAggregateType kind) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(COMMIT.toString()) + .setLogicalRevisionId(id(100 + number).toString()) + .setAggregateId(id(number).toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(kind) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(REGION.toString()); + } + + private static DraftCommitBinding change( + int index, UnaryOperator change) { + List mutations = fresh(); + mutations.set(index, change.apply(mutations.get(index).toBuilder()).build()); + return binding(mutations); + } + + private static DraftCommitBinding binding(List mutations) { + return binding(mutations, units(mutations)); + } + + private static DraftCommitBinding binding( + List mutations, List units) { + List revisions = new ArrayList<>(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", id(700), Owner.GAME_LOGIC, "other-owner-byte-string")); + for (int index = 0; index < mutations.size(); index++) { + var mutation = mutations.get(index); + UUID revision = UUID.fromString(mutation.getLogicalRevisionId()); + try { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(index + 1), + revision, + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().print(mutation))); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException(exception); + } + } + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 901, "source-key", 801, "source-key", "NEW_GAME_ROW"), + id(4), + COMMIT, + "reviewed-base", + revisions, + units); + } + + private static List units(List mutations) { + List units = new ArrayList<>(); + units.add(new AffectedUnit(Owner.GAME_LOGIC, "ABILITY", "other", "AGGREGATE", "other", "0")); + // Deduplicate duplicate-object inputs so the owner plan, rather than this fixture, rejects + // them. + for (var mutation : mutations) { + String type = mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + AffectedUnit aggregate = + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + type, + mutation.getAggregateId(), + "AGGREGATE", + mutation.getAggregateId(), + "0"); + AffectedUnit scope = + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + type, + mutation.getAggregateId(), + mutation.getScopeType().name().replace("WORLD_DESIGN_SCOPE_TYPE_", ""), + mutation.getScopeId(), + "0"); + if (!units.contains(aggregate)) { + units.add(aggregate); + } + if (!units.contains(scope)) { + units.add(scope); + } + } + return units; + } + + private static OwnerBinding owner() { + return new OwnerBinding( + "firemud", TENANT, VERSION, id(50), 901, id(51), id(52), DIGEST, id(53), DIGEST, DIGEST); + } + + private static void rejected(DraftCommitBinding binding) { + assertThatIllegalArgumentException() + .isThrownBy(() -> WorldDraftTopologyCommitPlan.create(binding, owner())); + } + + private static UUID id(int number) { + return UUID.fromString(String.format("%08d-0000-4000-8000-%012d", number, number)); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepositoryTest.java new file mode 100644 index 0000000000..4565d34eb5 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepositoryTest.java @@ -0,0 +1,160 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.sql.Connection; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +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.WorldDesignScopeType; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.ResultQuery; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +class WorldDraftTopologyCommitRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final WorldDesignPublicationFenceRepository fence = + mock(WorldDesignPublicationFenceRepository.class); + private final ObjectMapper mapper = mock(ObjectMapper.class); + private final WorldDraftTopologyCommitRepository repository = + new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + private final WorldDraftTopologyCommitPlan plan = mock(WorldDraftTopologyCommitPlan.class); + + @AfterEach + void clearTransactionFixture() { + TransactionSynchronizationManager.clear(); + } + + @Test + void absentTransactionCannotResolveOrTouchHistory() { + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } + + @Test + void readOnlyTransactionCannotResolveOrTouchHistory() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } + + @Test + void repeatableReadCannotUseReadCommittedReplayAndOwnerLockOrdering() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_REPEATABLE_READ); + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } + + @Test + void committedReadbackRejectsActiveCallerBeforeStorageOrSourceResolution() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repository.readCommitted(plan)) + .hasMessageContaining("no active caller transaction"); + verifyNoInteractions(dsl, fence, mapper, plan); + } + + @Test + @SuppressWarnings("unchecked") + void missingCommittedOperationIsUnknownWithoutOwnerClaimOrMutation() { + DraftCommitBinding binding = mock(DraftCommitBinding.class); + WorldDesignPublicationFenceEvidence.OwnerBinding owner = + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class); + ResultQuery query = mock(ResultQuery.class); + Result rows = mock(Result.class); + when(plan.binding()).thenReturn(binding); + when(plan.ownerBinding()).thenReturn(owner); + when(binding.requestId()).thenReturn(UUID.randomUUID()); + when(binding.commitId()).thenReturn(UUID.randomUUID()); + when(mapper.writeValueAsString(owner)).thenReturn("synthetic-owner-json"); + when(dsl.resultQuery(anyString(), any(Object[].class))).thenReturn(query); + when(query.fetch()).thenReturn(rows); + when(rows.isEmpty()).thenReturn(true); + assertThat(repository.readCommitted(plan)).isEmpty(); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(dsl).resultQuery(sql.capture(), any(Object[].class)); + assertThat(sql.getValue()) + .startsWith("SELECT ") + .doesNotContain("FOR UPDATE", "INSERT ", "UPDATE ", "DELETE "); + verify(query).fetch(); + verifyNoMoreInteractions(dsl, query); + verifyNoInteractions(fence); + } + + @Test + void typedProjectionNormalizesParsedSpellingsWithoutReadingOrReplacingRawBinding() + throws InvalidProtocolBufferException { + UUID template = UUID.randomUUID(); + UUID revision = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + var mutation = + WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revision.toString()) + .setCommitId(commit.toString()) + .setAggregateId(template.toString()) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(template.toString()) + .setRegion(RegionDesignMutation.newBuilder().setName("region")) + .build(); + String original = + JsonFormat.printer() + .preservingProtoFieldNames() + .printingEnumsAsInts() + .omittingInsignificantWhitespace() + .print(mutation); + var parsed = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(original, parsed); + var graph = + new WorldDraftTopologyInputGraph( + UUID.randomUUID(), + UUID.randomUUID(), + List.of( + new WorldDraftTopologyInputGraph.Node( + "4", revision, template, template, parsed.build(), null))); + when(plan.graph()).thenReturn(graph); + var projection = repository.executionRevisions(plan); + assertThat(projection).hasSize(1); + var execution = projection.getFirst(); + assertThat(execution.revisionId()).isEqualTo(revision); + assertThat(execution.revisionOrder()).isEqualTo("4"); + assertThat(execution.owner()).isEqualTo(DraftCommitBinding.Owner.WORLD_MANAGEMENT); + assertThat(original).contains("\"aggregate_type\":"); + assertThat(execution.payload()) + .contains("\"aggregateType\":\"WORLD_DESIGN_AGGREGATE_TYPE_REGION\"") + .isNotEqualTo(original); + var decoded = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(execution.payload(), decoded); + assertThat(decoded.build()).isEqualTo(mutation); + assertThat(decoded.getRegion().getSpacingMultiplier()).isZero(); + verifyNoInteractions(dsl, fence, mapper); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitServiceTest.java new file mode 100644 index 0000000000..ce82ebe9c5 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitServiceTest.java @@ -0,0 +1,123 @@ +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldDraftTopologyCommitServiceTest { + private final WorldDraftTopologyCommitRepository repository = + mock(WorldDraftTopologyCommitRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final WorldDraftTopologyCommitService.PermissionVerifier verifier = + mock(WorldDraftTopologyCommitService.PermissionVerifier.class); + private final WorldDraftTopologyCommitPlan plan = mock(WorldDraftTopologyCommitPlan.class); + + @AfterEach + void clearTransactionFixture() { + TransactionSynchronizationManager.clear(); + } + + @Test + void defaultDenialCannotStartTransactionOrAccessOwnerStorage() { + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager); + assertThatThrownBy(() -> service.store(plan)).hasMessageContaining("permission is unavailable"); + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsCallerTransactionBeforeVerifierCouldMakeAnExternalCall() { + TransactionSynchronizationManager.setActualTransactionActive(true); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.store(plan)).hasMessageContaining("existing transaction"); + verifyNoInteractions(verifier, repository, manager); + } + + @Test + void syntheticVerifierPrecedesDedicatedWritableReadCommittedTransactionAndCommit() { + // This sequencing fixture is not authenticated Account ordering or fence release proof. + TransactionStatus status = mock(TransactionStatus.class); + WorldDraftTopologyCommitEvidence evidence = mock(WorldDraftTopologyCommitEvidence.class); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.store(plan)).thenReturn(evidence); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager, verifier); + assertThat(service.store(plan)).isSameAs(evidence); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + InOrder order = inOrder(verifier, manager, repository); + order.verify(verifier).verify(plan); + order.verify(manager).getTransaction(definition.capture()); + order.verify(repository).store(plan); + order.verify(manager).commit(status); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().isReadOnly()).isFalse(); + } + + @Test + void localFailureRollsBackWithoutReturningStorageEvidence() { + TransactionStatus status = mock(TransactionStatus.class); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.store(plan)).thenThrow(new IllegalStateException("late tuple conflict")); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.store(plan)).hasMessage("late tuple conflict"); + InOrder order = inOrder(manager, repository); + order.verify(manager).getTransaction(any()); + order.verify(repository).store(plan); + order.verify(manager).rollback(status); + } + + @Test + void committedReadbackReturnsOriginalEvidenceWithoutVerifierOrTransactionInteractions() { + WorldDraftTopologyCommitEvidence evidence = mock(WorldDraftTopologyCommitEvidence.class); + when(repository.readCommitted(plan)).thenReturn(Optional.of(evidence)); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager, verifier); + assertThat(service.readCommitted(plan)).containsSame(evidence); + verify(repository).readCommitted(plan); + verifyNoMoreInteractions(repository); + verifyNoInteractions(verifier, manager); + } + + @Test + void missingCommittedReadbackRemainsUnknownWithoutAttemptingDeniedWriter() { + when(repository.readCommitted(plan)).thenReturn(Optional.empty()); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager); + assertThat(service.readCommitted(plan)).isEmpty(); + verify(repository).readCommitted(plan); + verifyNoMoreInteractions(repository); + verifyNoInteractions(verifier, manager); + } + + @Test + void committedReadbackRejectsActiveCallerBeforeAnyCollaboratorInteraction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.readCommitted(plan)) + .hasMessageContaining("no active caller transaction"); + verifyNoInteractions(repository, verifier, manager, plan); + } +}