diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1cfc2541d4..ca86be8432 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: @@ -1208,6 +1207,64 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run Game Session canonical realm catalog PostgreSQL component proof + if: ${{ matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:integrationTest \ + --tests integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepositoryIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepositoryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepositoryIntegrationTest#persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumericEvidence()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepositoryIntegrationTest#requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenance()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepositoryIntegrationTest#isolatedCreationAllocatesDistinctRealmLocalNamespacesOutsideSharedRegistry()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepositoryIntegrationTest#concurrentExactCreationRecoversOneDurableRealmAndNamespace()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepositoryIntegrationTest#freshCatalogAndRetainedAssociationCannotBothAcquireTenantAuthorityInEitherOrder()' \ + game-session-service + + - name: Upload Game Session canonical realm catalog PostgreSQL proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-session-canonical-realm-catalog-postgresql-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/integrationTest/TEST-*GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run Game Session canonical CLOSED pointer PostgreSQL component proof + if: ${{ matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:integrationTest \ + --tests integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#commitsCatalogBackedClosedPointerWithoutNumericOrRuntimeAliases()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#canonicalClosedRowsRejectNumericRuntimeAndNamespaceAliasesWithoutGrowingEvidence()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#exactRetryAndLostResponseReadbackPreserveTheOriginalOutcomeAndEvent()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#changedAuditOrCatalogInputUnderTheSameRequestConflictsWithoutAddingRows()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#concurrentExactCreationLeavesOnePointerEventAndImmutableOutcome()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#rollingBackOwnerTransactionLeavesNoPointerEventOrOutcome()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#committedReadbackRequiresExactOwnerTransactionBoundaries()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#partialPointerCannotCommitWithoutItsAuditAndRequestOutcome()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#retainedNumericReadersRemainIsolatedAndCanonicalMutationGuardsHold()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#expectedClosedLocksAndReturnsOnlyTheExactNeverOpenOriginEvidence()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#expectedClosedRejectsMissingForgedAndWrongVersionOriginSelectors()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#expectedClosedLockRejectsDriftAndPartialOriginalEvidence()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest#expectedClosedRequiresCommittedPreflightAndWritableReadCommittedOwnerLock()' \ + game-session-service + + - name: Upload Game Session canonical CLOSED pointer PostgreSQL proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-session-canonical-closed-pointer-postgresql-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/integrationTest/TEST-*GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Account canonical membership identity PostgreSQL component proof if: ${{ matrix.module == 'account-service' }} run: | @@ -1229,6 +1286,172 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run Account canonical JOIN scope and intent PostgreSQL component proof + if: ${{ matrix.module == 'account-service' }} + run: | + ./gradlew :account-service:integrationTest \ + --tests integration.net.firedevops.firemud.accountservice.repository.AccountConnectScopeCanonicalIdentityIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountConnectScopeCanonicalIdentityIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectScopeCanonicalIdentityIntegrationTest#v2ScopesPreserveV1AndRequireExactUuidSourcesWithoutBearerOrNumericAliases()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectScopeCanonicalIdentityIntegrationTest#canonicalJoinJournalSharesRequestIdsAndRetainsPendingHashOnlyIntentEvidence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectScopeCanonicalIdentityIntegrationTest#concurrentCanonicalIntentAndPolicyRetriesRecoverOneImmutableRequestRow()' \ + account-service + + - name: Upload Account canonical JOIN scope and intent PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-canonical-join-scope-intent-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountConnectScopeCanonicalIdentityIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run Account canonical membership receipt PostgreSQL component proof + if: ${{ matrix.module == 'account-service' }} + run: | + ./gradlew :account-service:integrationTest \ + --tests integration.net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptCanonicalIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptCanonicalIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptCanonicalIntegrationTest#retainedV1HistoryBindsOnceAndCanonicalAppendContinuesItsSequence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptCanonicalIntegrationTest#freshCanonicalHeadHasNoNumericTenantAliasAndExactRetryDoesNotAdvanceIt()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptCanonicalIntegrationTest#freshKnownJoinHistoryWithMissingReceiptHeadCannotRestartForAnotherRequest()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptCanonicalIntegrationTest#retainedMembershipHistoryWithoutReceiptHeadCannotStartCanonicalSequence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptCanonicalIntegrationTest#concurrentMatchingRequestConvergesOnOneOriginalCanonicalReceipt()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptCanonicalIntegrationTest#rollbackAndUnprovedSourceLeaveNoCanonicalHeadOrReceipt()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptCanonicalIntegrationTest#canonicalAppendRequiresReadWriteOwnerTransactionAndHistoricalReadbackIsNotCurrent()' \ + account-service + + - name: Upload Account canonical membership receipt PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-canonical-membership-receipt-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountMembershipTransitionReceiptCanonicalIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run Account canonical audit storage PostgreSQL component proof + if: ${{ matrix.module == 'account-service' }} + run: | + ./gradlew :account-service:integrationTest \ + --tests integration.net.firedevops.firemud.accountservice.repository.AccountAuditCanonicalIdentityPostgresIntegrationTest \ + --tests net.firedevops.firemud.accountservice.repository.AccountRepositoryIntegrationTest.accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountAuditCanonicalIdentityPostgresIntegrationTest \ + --require-suite net.firedevops.firemud.accountservice.repository.AccountRepositoryIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuditCanonicalIdentityPostgresIntegrationTest#v49BackfillsRetainedV1AndReadsBackTheExactCanonicalEnvelope()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuditCanonicalIdentityPostgresIntegrationTest#canonicalAppendRollsBackAndRejectsReadOnlyOwnerTransactions()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuditCanonicalIdentityPostgresIntegrationTest#concurrentExactLockedReadbacksReturnTheSameOriginalEnvelope()' \ + --require-case 'net.firedevops.firemud.accountservice.repository.AccountRepositoryIntegrationTest#accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity()' \ + account-service + + - name: Upload Account canonical audit storage PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-canonical-audit-storage-postgresql-proof-${{ github.sha }} + path: | + services/account-service/build/test-results/integrationTest/TEST-*AccountAuditCanonicalIdentityPostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountRepositoryIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run Account canonical first-JOIN event PostgreSQL component proof + if: ${{ matrix.module == 'account-service' }} + run: | + ./gradlew :account-service:integrationTest \ + --tests integration.net.firedevops.firemud.accountservice.AccountCanonicalFirstJoinAuthorityEventIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountCanonicalFirstJoinAuthorityEventIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalFirstJoinAuthorityEventIntegrationTest#freshUuidFirstJoinCommitsClosedEventAndPairFromStoredMembershipAndPolicy()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalFirstJoinAuthorityEventIntegrationTest#approvedRetainedUuidAssociationPublishesWithoutInventingTenantIdentity()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalFirstJoinAuthorityEventIntegrationTest#absentRequestChangedScopeUnavailablePolicyAndChangedDigestAreDenied()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalFirstJoinAuthorityEventIntegrationTest#eventReadbackConflictRollsBackMembershipEventAndPairTogether()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalFirstJoinAuthorityEventIntegrationTest#failureAfterPairAdvanceRollsBackMembershipEventAndPairTogether()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalFirstJoinAuthorityEventIntegrationTest#retainedMembershipEventHistoryCannotBeResetOrReallocated()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCanonicalFirstJoinAuthorityEventIntegrationTest#concurrentSameScopePublishersCommitOnlyOneSequenceOneEvent()' \ + account-service + + - name: Upload Account canonical first-JOIN event PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-canonical-first-join-event-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountCanonicalFirstJoinAuthorityEventIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run Logging Account audit physical mTLS handler proof + if: ${{ matrix.module == 'logging-admin-service' }} + run: | + ./gradlew :logging-admin-service:test \ + --tests net.firedevops.firemud.loggingadmin.service.impl.AccountAuditCanonicalIdentityMtlsTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.loggingadmin.service.impl.AccountAuditCanonicalIdentityMtlsTest \ + --require-case 'net.firedevops.firemud.loggingadmin.service.impl.AccountAuditCanonicalIdentityMtlsTest#canonicalUuidCreateIsUnavailableAndReadEchoesExactIdentityOverSocketMtls()' \ + --require-case 'net.firedevops.firemud.loggingadmin.service.impl.AccountAuditCanonicalIdentityMtlsTest#retainedV1NumericCreateIsUnavailableAndReadEchoesIdentityOverSocketMtls()' \ + --require-case 'net.firedevops.firemud.loggingadmin.service.impl.AccountAuditCanonicalIdentityMtlsTest#retainedV1PlatformCreateIsUnavailableAndReadEchoesIdentityOverSocketMtls()' \ + --require-case 'net.firedevops.firemud.loggingadmin.service.impl.AccountAuditCanonicalIdentityMtlsTest#missingClientCertificateIsRejectedByTls()' \ + --require-case 'net.firedevops.firemud.loggingadmin.service.impl.AccountAuditCanonicalIdentityMtlsTest#wrongServiceValidCaCertificateCannotInvokeEitherAccountAuditMethod()' \ + --require-case 'net.firedevops.firemud.loggingadmin.service.impl.AccountAuditCanonicalIdentityMtlsTest#wrongNamespaceCertificateCannotInvokeEitherAccountAuditMethod()' \ + --require-case 'net.firedevops.firemud.loggingadmin.service.impl.AccountAuditCanonicalIdentityMtlsTest#sharedCertificateWithoutWorkloadUriCannotInvokeEitherAccountAuditMethod()' \ + --require-case 'net.firedevops.firemud.loggingadmin.service.impl.AccountAuditCanonicalIdentityMtlsTest#jwtOnlyCallerCannotBypassMissingClientCertificate()' \ + --require-case 'net.firedevops.firemud.loggingadmin.service.impl.AccountAuditCanonicalIdentityMtlsTest#createGatePrecedesIdentityValidationAndReadRejectsMalformedIdentity()' \ + logging-admin-service + + - name: Upload Logging Account audit physical mTLS proof results + if: ${{ always() && matrix.module == 'logging-admin-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: logging-account-audit-physical-mtls-proof-${{ github.sha }} + path: services/logging-admin-service/build/test-results/test/TEST-*AccountAuditCanonicalIdentityMtlsTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run Logging canonical Account audit PostgreSQL component proof + if: ${{ matrix.module == 'logging-admin-service' }} + run: | + ./gradlew :logging-admin-service:integrationTest \ + --tests net.firedevops.firemud.loggingadmin.LoggingAdminApplicationIntegrationTest \ + --tests net.firedevops.firemud.loggingadmin.CanonicalAuditIdentityMigrationIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.loggingadmin.LoggingAdminApplicationIntegrationTest \ + --require-suite net.firedevops.firemud.loggingadmin.CanonicalAuditIdentityMigrationIntegrationTest \ + --require-case 'net.firedevops.firemud.loggingadmin.LoggingAdminApplicationIntegrationTest#accountAuditReceiptAndProjectionShareStableIdentityAcrossRetryAndConflict()' \ + --require-case 'net.firedevops.firemud.loggingadmin.LoggingAdminApplicationIntegrationTest#canonicalUuidReceiptIsIsolatedFromRetainedNumericIdentityAndMinimizesSafely()' \ + --require-case 'net.firedevops.firemud.loggingadmin.LoggingAdminApplicationIntegrationTest#malformedPersistedIdentityCannotBypassDatabaseChecksOrGrowProjectionRows()' \ + --require-case 'net.firedevops.firemud.loggingadmin.LoggingAdminApplicationIntegrationTest#platformAuditProjectionHasNoTenantAndIsExcludedFromTenantQuery()' \ + --require-case 'net.firedevops.firemud.loggingadmin.LoggingAdminApplicationIntegrationTest#receiptFailureRollsBackTheAlreadyInsertedAuditProjection()' \ + --require-case 'net.firedevops.firemud.loggingadmin.LoggingAdminApplicationIntegrationTest#canonicalUuidReceiptFailureRollsBackItsProjection()' \ + --require-case 'net.firedevops.firemud.loggingadmin.LoggingAdminApplicationIntegrationTest#concurrentExactRetriesCreateOneProjectionAndReturnTheSameIdentifiers()' \ + --require-case 'net.firedevops.firemud.loggingadmin.CanonicalAuditIdentityMigrationIntegrationTest#versionThreePointOnePreservesRetainedVersionOneReceiptAndProjectionBytes()' \ + logging-admin-service + + - name: Upload Logging canonical Account audit PostgreSQL proof results + if: ${{ always() && matrix.module == 'logging-admin-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: logging-canonical-account-audit-postgresql-proof-${{ github.sha }} + path: | + services/logging-admin-service/build/test-results/integrationTest/TEST-*LoggingAdminApplicationIntegrationTest.xml + services/logging-admin-service/build/test-results/integrationTest/TEST-*CanonicalAuditIdentityMigrationIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Account persisted UUID authentication PostgreSQL component proof if: ${{ matrix.module == 'account-service' }} run: | @@ -1825,7 +2048,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 4e8d9f1e90..bbf9bbf54e 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -84,6 +84,20 @@ For version `2`, each preimage segment is strict UTF-8 prefixed by its canonical Only after authoritative available entitlement evaluation, the policy-request preimage additionally includes `AVAILABLE`, the exact lowercase boolean `allowPublicJoin`, and positive canonical-decimal `entitlementVersion`, in that order. Unavailable authority has no invented policy result/version or policy digest; retain a policy-independent pending intent and failure diagnostics. A typed scope value or digest is not an authentication capability: Account still verifies caller and persisted source, re-resolves the exact current Game Session target, and revalidates entitlement at commit. Complete UUID scope persistence, positive JOIN/event/audit/reconciliation, producer/consumer and negative proof remain required before activation; their status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md), not to the presence of these encoding rules. +Canonical scope retention widens the existing Account scope family rather than creating a second identity or retry authority. Store only the connect-scope token hash, the exact versioned target evidence and digest, and the full approved-retained or fresh Game Design-backed tenant association. The private Account primary key is resolved from the persisted Account UUID; fresh canonical tenant and instance evidence has no numeric alias. Retained v1 rows, preimages and owner history are not rewritten or interpreted as v2. Writes require the Account owner transaction and exact source readback; neither repository insertion nor construction of a typed scope establishes signed-token authenticity, caller authorization, current routing or entitlement. + +An incoming retry supplies the original connect-scope token, allowing its hash and complete v2 preimage to be checked against the immutable owner row. A hash-only recovery read does not reconstruct that bearer and cannot independently recompute a preimage containing it. Recovery instead proves the exact stored operation, scope hash, versioned digest, source association and dependent committed evidence under the existing JOIN recovery contract. Do not substitute the token hash as `connectScopeId`, persist the plaintext bearer, or describe structural/hash-only readback as fresh authorization or a recomputed bearer-bound digest. + +The same durable request-ID fence covers retained v1 and canonical v2 JOIN operations. Bind the v2 pending intent to its exact immutable scope and verified caller before retaining any policy result; changed caller, target or representation under that request ID conflicts. Under the Account and operation fences, one authoritative available result binds its exact boolean, positive entitlement version and policy-request digest immutably. An unavailable attempt records diagnostics without a fabricated policy result or digest and cannot overwrite already-bound available evidence. This journal evidence does not prove policy freshness: the eventual membership commit still revalidates the authority result. Legacy recovery must not interpret or terminalize a v2 operation, and a canonical pending intent cannot become a terminal success until the complete operation, membership, receipt, audit and event evidence is proved. + +Canonical provisional transition receipts widen the existing receipt/head family; they are transaction and recovery evidence, not an authority event, admission permission or outbox checkpoint. A head has one independent monotonically increasing provisional receipt sequence. Bind an approved retained head once to its exact persisted Account UUID, tenant UUID and immutable tenant-source tuple without changing its legacy storage key, existing receipt bytes or sequence. A fresh head uses the proved Game Design-backed UUID identity without a numeric tenant alias. Internal head and membership row keys remain private references. Mixed-version receipts share the same head counter and global request-ID uniqueness; historical readback dispatches from the receipt's own representation, never from the latest head state. Unsupported latest representations fail closed instead of being decoded as retained v1. + +Version-2 receipt evidence uses `account:membership-transition-receipt:v2:membership/{accountId}/{tenantId}` with exact canonical UUIDs. Its `membershipVersion` is the exact one-tenant map with a positive canonical decimal-string value, read from the same locked membership state. Receipt identity is `UUID.nameUUIDFromBytes` over strict UTF-8 `account-membership-transition-receipt/v2:` followed by the exact request ID; this identity is not its cryptographic payload digest. The SHA-256 preimage uses the byte-length framing above in this fixed order: `account-membership-transition-receipt/v2`, `2`, `PROVISIONAL_TRANSITION_RECEIPT`, canonical receipt stream key, receipt sequence, receipt UUID, transition type, request ID, Account UUID, tenant UUID, membership lifecycle state, lowercase gameplay-admission boolean, the map's sole tenant UUID key, its exact decimal version, membership-authority generation, authority provenance, tenant-provenance kind, tenant-source operation UUID and tenant-provenance digest. The private membership row ID and numeric aliases are excluded. JOIN/reactivation require `ACTIVE`, admitting state and `EXPLICIT_JOIN`; LEFT requires `INACTIVE`, nonadmitting state and that same provenance. Independent counters remain independent, with overflow denied before mutation rather than reset or wrap. + +Appending a canonical receipt requires an actual read-write Account owner transaction, the persisted Account fence and exact membership/tenant-source readback; constructing the evidence value is not authorization. Exact request replay returns the original immutable receipt, while changed input or cross-version request reuse conflicts. Current receipt readback additionally matches the current membership state; historical receipt readback remains historical after later transitions. The receipt does not by itself prove atomic JOIN completion: terminal operation, role snapshot, canonical authority event/checkpoint and tenant audit must still be committed and proved together by the JOIN owner. Detailed implementation and execution status remains in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). + +Account's canonical tenant audit uses the version-qualified UUID envelope of [Logging & Admin's ingress and receipt owner](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) through the existing outbox and RPCs. Account preserves exact retained numeric/platform envelope history and never invents a numeric alias for a fresh canonical tenant. The producer must compare the exact typed identity in delivery/readback before persisting terminal delivery evidence. A successful canonical JOIN must append that immutable outbox envelope in the same owner transaction as its membership, role snapshot, authority event, provisional receipt and operation outcome; implementing the audit carrier alone is not positive JOIN or admission proof. + ### Current vs Target Export Lifecycle The current `GET /accounts/{accountId}/export` route is a synchronous Account/profile-local read. Direct account-ID `ExportAccount` gRPC and the legacy account-targeted tenant-export REST/service and gRPC entries deny before data access. The local Account read has no cross-service required-owner fan-in and does not satisfy ADR 0050; none of these current surfaces may be described as a complete portable-data or tenant-admin export. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 5e6d1db920..f87e662dfd 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -58,6 +58,28 @@ The owner transaction atomically persists the local non-nil UUID operation, immu This source intake records no numeric tenant alias, instance, realm, pointer, lease, membership, authority generation or admission. It does not attach a retained Game Session runtime row: that requires the separately audited association and exact retained-row proof. The normal authorized creation workflow may invoke intake automatically after its Game Design commit; the primitive is not a public creator API and cannot bypass Account-owned creator/terms authorization. Source receipts and selector claims remain immutable survivor evidence; cleanup or release requires its owner retention proof rather than an invented TTL. Runtime catalog and credential activation stay denied until their complete producer, consumer and live proof gates pass. +### Initial canonical public-production realm catalog + +Game Session alone allocates and persists the runtime realm and playable namespace from its exact committed [authored-world source intake](#authored-world-source-intake-and-durable-readback). An initial public-production creation binds a stable non-nil UUID request ID, exact workload namespace and canonical tenant UUID, source-intake operation UUID, explicit realm selector/display name, visibility, public-production flag, `SHARED` or `ISOLATED` state scope, and character-creation policy. Both visibility and public-production are true for this initial operation; private/playtest lifecycle fields are absent. The policy is explicit owner data, not a default authorization result; a consumer must support its mode before acting on it. Creator authorization remains separately required before invoking this owner-local primitive. + +Read the committed source before the write transaction, then lock and compare that same immutable intake and tenant binding inside a read-write READ COMMITTED owner transaction. Reject missing, changed, contradictory or retained-associated fresh source; never derive a retained Game Session tenant key. Preserve `tenantSlug` separately from its tenant-scoped `worldSlug`; realm selectors are unique within the tenant, not just within one world. Allocate a non-nil realm UUID and initial catalog revision one. `SHARED` reuses the tenant's one persisted namespace from the existing shared-namespace family; new canonical rows have no numeric tenant alias. `ISOLATED` persists a distinct realm-local namespace in the catalog result, not the shared registry. Existing numeric rows and namespace bytes remain unchanged; attaching their authority requires a separate proved bridge. + +`game-session-canonical-realm-catalog-request/v1` uses these fixed-order values: domain, schema version `1`, creation request UUID, workload namespace, canonical tenant UUID, source-intake operation UUID, intake request UUID, intake request digest, intake receipt digest, source schema version, source registration request UUID, source operation UUID, source request digest, source canonical tenant UUID, source tenant selector, source world selector, source world display name, source Game Design row ID, source former tenant key, source provenance kind, source evidence digest, realm selector, realm display name, visibility, public-production, state scope, character-creation policy, playtest lifecycle and playtest generation. The two inapplicable playtest values are exactly `ABSENT`; they cannot be supplied to this operation. `game-session-canonical-realm-catalog-receipt/v1` binds, in order, domain, schema version `1`, workload namespace, canonical tenant UUID, creation request UUID, request digest, allocated realm UUID, allocated playable namespace UUID, catalog revision, source-intake operation UUID and intake receipt digest. Each value uses strict UTF-8 decimal byte-length framing with `:`; UUIDs are canonical non-nil strings, counters canonical decimal strings and booleans exactly `true` or `false`. No normalization or replacement encoding is permitted. SHA-256 results are lowercase `sha256:` plus 64 hexadecimal digits. Game Design's source digests remain owned by its contract rather than this local receipt. + +Commit the immutable catalog result and any new SHARED allocation atomically. Exact retry and lost-response readback return the original request, source evidence, realm UUID, namespace UUID, revision and digests; changed input under the same request conflicts without partial allocation. A read returns the unique visible public-production result or denies missing, multiple or conflicting evidence without a selector-order fallback. This initial catalog does not create an instance, open a pointer, prove World `ACTIVE`, commit membership or authorize admission. Runtime registration, authenticated producer/consumer composition, catalog changes/private modes and live activation remain separate tracked work. + +### Initial canonical CLOSED admission pointer + +[Multi-Tenancy](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) owns routing identity and `OPEN`/`CLOSED` semantics. Game Session's initial canonical pointer operation creates only explicit `CLOSED` authority for an exact committed fresh public-production catalog. It names no admissible instance and cannot prove World readiness, create membership, grant creator authorization or authorize admission. An authorized caller workflow is still required before invoking this unregistered owner-local primitive; audit principal text is not caller authentication. + +Bind a stable request UUID, workload namespace, canonical tenant and realm UUIDs, catalog creation request UUID and exact positive catalog revision, plus bounded actor/reason audit evidence. Prepare from committed catalog readback outside an ambient transaction, then lock and compare that complete catalog in a read-write READ COMMITTED owner transaction. Persist the canonical routing row in the existing pointer family, one append-only event in the existing event family, and its immutable request outcome atomically. Retain all numeric rows, audit values and history unchanged; legacy readers/writers cannot interpret canonical targetless rows. Initial canonical `pointerVersion` is one. Catalog/policy fields come from the referenced catalog, not a second policy snapshot copied into legacy pointer columns. Private/playtest lifecycle evidence is absent for this public-production operation. + +`game-session-canonical-closed-pointer-request/v1` hashes these fixed-order values: domain, schema version `1`, request UUID, workload namespace, canonical tenant UUID, realm UUID, catalog creation request UUID, catalog revision, exact catalog request digest, exact catalog receipt digest, actor principal, reason, `CLOSED`, `ABSENT`. `game-session-canonical-closed-pointer-receipt/v1` hashes, in order: domain, schema version `1`, request UUID, request digest, workload namespace, canonical tenant UUID, realm UUID, world selector, realm selector, pointer version, catalog revision, audit event ID, exact persisted UTC `Instant` timestamp, `CLOSED`, `ABSENT`. Every value uses strict UTF-8 decimal byte-length framing with `:`; UUIDs are canonical non-nil strings and counters/event IDs are positive canonical decimal strings. Hashes use lowercase `sha256:` SHA-256. These are local request/readback digests, not authentication or a new catalog/pointer authority. + +Exact retries and lost-response recovery read back the original routing tuple, timestamp, audit identity and outcome without another mutation; changed input conflicts. Committed readback proves that the pointer, audit, outcome and exact catalog agree before returning evidence. Partial, contradictory, aliased or changed evidence fails closed; neither an absent pointer nor an infrastructure failure is reported as deliberate closure. OPEN transitions, runtime exposure, authenticated transport, complete World/lifecycle proof and activation remain separate implementation gates. + +For the approved [first-OPEN transition](../../system-architecture-versioning-runtime.md#first-open-from-never-opened-authority), Game Session prepares the exact initial CLOSED origin from committed readback outside an ambient transaction and revalidates that same positive catalog/pointer/audit/request evidence under the catalog and pointer locks in a read-write READ COMMITTED owner transaction. A privately constructed local preparation or lock result is not authenticated World hold evidence or authorization. This check must preserve the original CLOSED outcome and cannot manufacture never-OPEN provenance from absent history. The World canonical launch binding, first-OPEN mutation and authenticated owner readback remain separate required composition; implementation and proof status belongs to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). + ### Retained tenant identity snapshot and local association Game Session owns the evidence behind `gameSessionEvidenceDigest` in [Game Design's audited association](../game-design-service/api-contracts.md#audited-retained-game-session-tenant-association). It captures an exact, declared identity projection of its retained rows, not a complete runtime backup or proof of historical lifecycle, effects or admission. The closed version-2 snapshot contains `schemaVersion=2`, the exact `targetNamespace`, canonical positive BIGINT decimal-string `legacyGameSessionTenantId`, and all six arrays below. Each array includes every row for that tenant, in ascending numeric primary-key order; the shared namespace uses its tenant primary key. Row objects contain exactly their listed SQL field names. SQL integer values are canonical decimal strings, UUIDs are canonical lowercase strings, booleans are JSON booleans, text is exact valid Unicode, and absent nullable fields are explicit JSON null. Each instance binds both its nullable retained numeric `owner_account_id` and nullable canonical `owner_account_uuid`; at least one must be present. Capturing those exact slots does not prove an association between them, authorize a guessed mapping, or make a retained numeric owner a canonical Account identity. No timestamp, display label, actor/reason or participant-result payload is reconstructed or asserted by this projection. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index e67b45b95d..b4cf845cf4 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -8,6 +8,8 @@ The service runtime model assumes replaceable workers, not authoritative in-proc ## Implementation Status +- The unregistered initial canonical realm-catalog candidate stores exact committed authored-world intake evidence and owner-allocated realm/namespace results under the [Game Session catalog contract](./api-contracts.md#initial-canonical-public-production-realm-catalog). V12.1 widens the existing SHARED allocation family without mapping or rewriting retained numeric rows; ISOLATED allocations remain realm-local. This is not a complete catalog lifecycle, creator authorization, instance/pointer producer or admission path. Execution evidence and remaining composition/activation gates belong to [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). + The sections below define the target-state runtime contract. Current implementation and proof status is: - The local V11 candidate adds nullable unique `game_instances.game_instance_uuid` without backfilling retained rows. Game Session's repository allocates a UUID on fresh insertion, reads back that exact persisted source and preserves it on update; unmapped retained identity denies strict canonical lookup. This is only the owner-local identity source: tenant storage, public DTO/proto/catalog/pointer migration, creation-request idempotency and authenticated selected-target composition remain separate gaps. It neither derives a UUID from a private numeric key nor enables admission. Validation and executed-versus-skipped proof belong to [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 9641b402fe..e10fcbdb3f 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -6,13 +6,19 @@ This document defines the Logging & Admin Service REST and gRPC surfaces, authen The canonical Account-to-Logging & Admin audit ingress is the existing `logging_admin.v1.LoggingAdminService/CreateLogEvent` RPC, converged in place rather than duplicated as a parallel ingress. It is a non-destructive internal service RPC, not an operator/admin mutation. Account is the producer and source authority for account state; Logging & Admin owns the receiver-side audit envelope, durable receipt/readback, deduplication, and audit projection. The audit ingress follows only shared envelope fundamentals (stable identity, event type/schema, producer occurrence time, and at-least-once/idempotent delivery) from [Session Behavior](../../system-architecture-session-behavior.md); it does **not** inherit that document's membership-specific field set or `eventDigest` grammar. Internal workload identity and method authorization follow [Authentication](../../system-architecture-authentication.md) and [gRPC](../../system-architecture-grpc.md#tls-requirements). -Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenantId` only for `tenant` scope and never for `platform` scope, stable `auditEventId` generated and persisted by Account, `producerService`, `eventType`, producer `occurredAt`, positive `schemaVersion`, exact UTF-8 `payload`, `payloadDigestVersion` exactly `1` until a later canonical digest-version registry is accepted, and `payloadDigest`. Global registration, `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity events use `platform` scope with no `tenantId`; tenant profile and JOIN events use `tenant` scope with the exact committed `tenantId`. Unsupported digest versions fail before deduplication or persistence. `producerService` is derived from the authenticated Account workload identity and a mismatching request value is rejected. An upstream producer domain-event digest, when present inside `payload`, remains opaque payload evidence and is distinct from the receiver's `payloadDigest`. `payloadDigest` is `sha256:` followed by 64 lowercase hexadecimal characters over the exact UTF-8 payload bytes under `payloadDigestVersion=1`; no JSON reserialization or alternate canonicalization is permitted. Receipt identity is the scope-qualified key `(scope, tenantId-or-zero, auditEventId)`. For a retry resolving to the same key, equivalence additionally requires the complete immutable `(producerService, eventType, occurredAt, schemaVersion, payloadDigestVersion, payloadDigest, exact payload bytes)` tuple: while exact payload bytes remain retained, an exact match returns the original receipt, while any changed tuple field or payload bytes fails closed as `IDEMPOTENCY_CONFLICT`. A different scope or tenant selects a different receipt identity; it does not retry, reconcile, or retarget the original event. Account must persist and reuse the original scope, tenant, and event ID for every retry or reconciliation and must never mint a replacement event after timeout, transport failure, or an ambiguous response. After the safe watermark permits payload minimization, the retained identity and metadata may still detect a changed non-payload tuple field, but the receiver must not claim exact payload equality or replay; a request matching the retained identity, metadata, and digest is a terminal non-replayable result. +Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), explicit `tenantIdentityVersion` and its sole applicable tenant value as defined below, stable `auditEventId` generated and persisted by Account, `producerService`, `eventType`, producer `occurredAt`, positive `schemaVersion`, exact UTF-8 `payload`, `payloadDigestVersion` exactly `1` until a later canonical digest-version registry is accepted, and `payloadDigest`. Global registration, `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity events use `platform` scope with no tenant; tenant profile and JOIN events use `tenant` scope with the exact committed tenant identity. Unsupported digest versions fail before deduplication or persistence. `producerService` is derived from the authenticated Account workload identity and a mismatching request value is rejected. An upstream producer domain-event digest, when present inside `payload`, remains opaque payload evidence and is distinct from the receiver's `payloadDigest`. `payloadDigest` is `sha256:` followed by 64 lowercase hexadecimal characters over the exact UTF-8 payload bytes under `payloadDigestVersion=1`; no JSON reserialization or alternate canonicalization is permitted. Retry equivalence is the complete immutable `(scope, tenantIdentityVersion, sole applicable tenant value, auditEventId, producerService, eventType, occurredAt, schemaVersion, payloadDigestVersion, payloadDigest, exact payload bytes)` tuple: while exact payload bytes remain retained, an exact match returns the original receipt, while any changed field or payload bytes fails closed as `IDEMPOTENCY_CONFLICT`. After the safe watermark permits payload minimization, the retained identity and metadata may still detect a changed non-payload field, but the receiver must not claim exact payload equality or replay; a matching late request is a terminal non-replayable result. Timeout, transport failure, or an ambiguous response is not success; the producer retries or reconciles with the same identity and digest and never mints a replacement event. -Each accepted Account audit request commits one `log_events` audit projection in the same PostgreSQL transaction as its durable receipt. `logEventId` is the projection's `log_events.id`, distinct from `receiptId` and the receipt row's database key. The projection is deliberately a bounded identity summary: `type` is the fixed value `ACCOUNT_AUDIT`, `message` is `Account audit event` followed by one ASCII space and `auditEventId`, and `timestamp`, `scope`, and `tenantId` come from the envelope. `account_id` remains unset because the envelope has no typed account-principal field. The exact payload and `eventType` remain in the receipt and are not copied into this projection, so payload minimization does not leave a second permanent payload copy. Platform projections retain `scope=platform` and `tenantId=NULL`; tenant projections retain `scope=tenant` and the exact positive `tenantId`. `QueryLogs` remains tenant-only and excludes platform rows; it can locate a projected audit event by its `auditEventId`, but this contract does not define or imply a platform query route. A scope-qualified `(scope, tenantId-or-zero, auditEventId)` uniqueness boundary ensures one receipt/projection per identity: an exact retry under that same key returns the original receipt and projection IDs, while a changed immutable tuple or payload bytes conflicts without another projection. The same `auditEventId` under another scope or tenant key is a separate identity, not permission to replay or retarget an Account event. +The existing RPCs distinguish tenant identity from payload schema through explicit `tenantIdentityVersion`. Version `1` retains original numeric tenant evidence: tenant scope carries the canonical positive BIGINT decimal string in `tenant_id` and no `tenant_uuid`; platform scope is version `1` with neither tenant field. Version `2` is tenant-only and carries the exact canonical lowercase non-nil UUID in `tenant_uuid`, with `tenant_id` absent. Neither receiver nor producer guesses a numeric alias or derives the identity version from `schemaVersion`. Missing, unsupported, mixed or contradictory identity evidence is rejected before persistence. New canonical tenant events use version `2`; retained version-1 rows, payload bytes, IDs, digests, timestamps and terminal delivery history remain unchanged and are decoded by their own explicit representation. -`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores the scope-qualified identity key and exact-compares its remaining immutable tuple and exact payload bytes while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same identity key and immutable tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. Because proto3 `bytes` has no presence bit, a default-empty `payload` is digest-only when `payloadDigest` is not the SHA-256 digest of empty bytes; with the empty-byte digest it is treated as an exact empty payload. A digest-only read is successful only for a stored minimized receipt; a retained-payload receipt requires the exact payload bytes and equality. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. **Current local implementation:** the Account audit request/response schema, Account workload check, exact payload digest validation, atomic scope-aware log projection and durable receipt insert/deduplication, bounded receipt readback with digest-only reads limited to minimized receipts and exact-byte reads for retained payloads, and accepted/duplicate/conflict/minimized outcomes are implemented locally. Account registration and JOIN now produce owner-local outbox entries; Account's delivery client checks returned receipt evidence before marking delivery complete. Focused local unit coverage exists, but PostgreSQL runtime proof and direct text-client-to-Logging end-to-end proof are not claimed. The target contract remains authoritative for full retention/readback horizons and any unresolved runtime edge cases. +The typed identity version and its sole applicable tenant value participate in the immutable envelope, scope-qualified uniqueness, exact duplicate comparison and both request/response readbacks. The receiver echoes and the Account producer verifies those fields together with the existing event, schema, digest and terminal receipt evidence. A canonical projection stores its tenant UUID separately and leaves numeric tenant fields unset; it never manufactures a legacy key. Retention and minimization preserve the explicit typed identity with the bounded receipt metadata. This audit carrier grants no membership or admission; Account's successful JOIN still commits its membership, authority event, provisional receipt, audit outbox and immutable outcome under the separate owner transaction. Canonical UUID projection querying requires its own exact-tenant authorization and implementation proof, not a guessed alias through the current numeric query. -Both typed receipt responses carry `auditProjectionVersion=1` only when the receiver has durably linked the exact scope-qualified receipt to a distinct `log_events` audit projection in the same transaction. `receiptId` names the durable receipt; `logEventId` names the linked projection, not the receipt row's surrogate. The projection retains bounded identity metadata rather than another payload copy, including after payload minimization. Missing (`0`) or unsupported versions are not evidence of this capability; Account rejects them before marking delivery verified. The version marker never substitutes for the complete envelope, receipt/projection identity, status, and outcome checks above. Enabling version 1 does not attest historical Account outbox IDs or rewrite their unknown projection provenance; recovery requires exact current readback and guarded Account-owned recording. See [Account Runtime and Data](../account-service/runtime-and-data.md#implementation-status). +Each accepted Account audit request commits one `log_events` audit projection in the same PostgreSQL transaction as its durable receipt. `logEventId` is the projection's `log_events.id`, distinct from `receiptId` and the receipt row's database key. The projection is deliberately a bounded identity summary: `type` is the fixed value `ACCOUNT_AUDIT`, `message` is `Account audit event` followed by one ASCII space and `auditEventId`, and `timestamp`, scope and version-qualified tenant identity come from the envelope. `account_id` remains unset because the envelope has no typed account-principal field. The exact payload and `eventType` remain in the receipt and are not copied into this projection, so payload minimization does not leave a second permanent payload copy. Platform projections retain `scope=platform` and no tenant; tenant projections retain `scope=tenant` and exactly one declared tenant representation. `QueryLogs` remains tenant-only and excludes platform rows; this contract does not define or imply a platform query route. Scope, tenant-identity version, typed tenant value and event identity qualify uniqueness so an exact retry returns the original receipt and projection IDs, while a changed immutable tuple under that identity conflicts without another projection. The private zero `tenant_key` used for version-1 platform identity is not a tenant UUID or a canonical tenant alias. + +Both `CreateLogEventRequest` and `ReadLogEventReceiptRequest` carry the complete immutable tuple, including the explicit tenant identity version and its sole applicable value. On a read, proto3's default-empty `payload` is digest-only when `payloadDigest` is not the SHA-256 digest of empty bytes; with the empty-byte digest it is treated as the exact empty payload. A digest-only read is successful only for a minimized receipt. While payload bytes are retained, a read must supply and match the exact bytes; after minimization, a matching identity and digest returns only bounded receipt metadata and never claims payload equality. + +`CreateLogEventResponse` and `ReadLogEventReceiptResponse` return the matching scope, `tenantIdentityVersion` and sole tenant value, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, schema and digest versions, `payloadDigest`, status, outcome, and `auditProjectionVersion`. The durable receipt exact-compares the complete immutable tuple and exact payload bytes while retained. Status/outcome is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. The projection version is `1` only when the receiver durably links the exact typed receipt to its distinct `log_events` projection in the same transaction. `receiptId` names the receipt; `logEventId` names the linked projection, never the receipt row's surrogate. The version marker does not replace complete envelope, identity, digest and terminal-outcome verification, and it does not attest historical Account outbox IDs or rewrite unknown historical projection provenance. Missing receipts return canonical non-OK gRPC `NOT_FOUND`; receiver or dependency unavailability returns canonical non-OK gRPC `UNAVAILABLE`. The Account delivery client rejects ErrorDetail responses, missing/unsupported projection versions, and any receipt that does not echo the full typed identity and event/schema/digest evidence it sent. + +The Account audit methods are workload-only: the receiver derives the exact `account-service` mTLS identity and applies the method-specific `CreateLogEvent` or `ReadLogEventReceipt` allowlist. Neither a bearer token nor `AdminRole` substitutes for that peer authorization. This carrier grants no membership or admission; Account's successful JOIN still commits its membership, authority event, provisional receipt, audit outbox and immutable outcome under its separate owner transaction. The local carrier does not establish canonical JOIN production, direct text-client-to-Logging delivery, complete retention/readback horizons or live deployment activation. Current implementation and executed-versus-unavailable proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The receipt retention class and cleanup owner are defined in [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index ec337a59cc..8323386859 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -12,7 +12,7 @@ Logging & Admin is the operator-facing policy, audit, and observability coordina ### Audit envelope and receipt retention -The Account audit envelope/receipt is a Logging & Admin-owned **retry and idempotency receipt** plus **purpose-bound audit evidence** family under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). The full retry-equivalence tuple and exact payload bytes remain durable through the longest applicable producer retry, receiver readback, duplicate-delivery, and reconciliation horizon, using existing canonical/configured horizons and the applicable legal-hold and erasure-owner links; this service does not invent a duplicate duration. After the producer safe watermark proves that horizon has ended and no legal hold or unresolved reconciliation reference remains, the payload may be minimized or removed, but the receipt retains `scope`, the applicable `tenantId`, `auditEventId`, `producerService`, `eventType`, `occurredAt`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `receiptId`, `logEventId`, terminal `status`/`outcome`, and the source/lineage identifiers needed for later exact proof. A late `CreateLogEvent` retry or `ReadLogEventReceipt` request after minimization is an explicit terminal non-replayable result, never an accepted duplicate or an exact successful readback; the retained digest and receipt metadata must not be presented as proof of exact payload equality. Garbage collection requires terminality, the safe watermark, no pending or ambiguous delivery/readback reference, and no legal hold; age alone is never sufficient. Missing, stale, conflicting, or unavailable evidence while any of those gates may still apply fails closed and cannot authorize deletion or a new event under the old identity. +The Account audit envelope/receipt is a Logging & Admin-owned **retry and idempotency receipt** plus **purpose-bound audit evidence** family under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). The full retry-equivalence tuple and exact payload bytes remain durable through the longest applicable producer retry, receiver readback, duplicate-delivery, and reconciliation horizon, using existing canonical/configured horizons and the applicable legal-hold and erasure-owner links; this service does not invent a duplicate duration. After the producer safe watermark proves that horizon has ended and no legal hold or unresolved reconciliation reference remains, the payload may be minimized or removed, but the receipt retains `scope`, `tenantIdentityVersion` and its sole applicable tenant value under the [API identity owner](./api-contracts.md#account-audit-ingress-and-receipt), `auditEventId`, `producerService`, `eventType`, `occurredAt`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `receiptId`, `logEventId`, terminal `status`/`outcome`, and the source/lineage identifiers needed for later exact proof. A late `CreateLogEvent` retry or `ReadLogEventReceipt` request after minimization is an explicit terminal non-replayable result, never an accepted duplicate or an exact successful readback; the retained digest and receipt metadata must not be presented as proof of exact payload equality. Garbage collection requires terminality, the safe watermark, no pending or ambiguous delivery/readback reference, and no legal hold; age alone is never sufficient. Missing, stale, conflicting, or unavailable evidence while any of those gates may still apply fails closed and cannot authorize deletion or a new event under the old identity. The target service preserves two independently degradable partitions: @@ -29,7 +29,8 @@ Target external session-lifecycle operator requests enter through Gateway and Lo The current shipped scope is narrower than this target contract: -- Forward V3 adds the Account audit projection and links retained V2 receipts without rewriting V2; forward V4 adds the canonical lowercase digest-format check as `NOT VALID`, and forward V5 adds a `NOT VALID` check requiring a positive tenant ID only for tenant-scoped audit projections. These checks apply to new or updated rows without attesting or rewriting retained rows. Exact audit projections use a scope-qualified tenant key matching `tenantId` (or zero for platform scope); older ordinary tenant `log_events` writers may omit that new key and leave its compatibility value at zero, while tenant queries continue to use `tenantId`. The migration fixture preserves a V2 row with an invalid digest and zero/negative tenant audit projections to prove V4/V5 do not rewrite retained evidence. Exact deployed-row inventory/readback and owner-approved constraint validation remain deployment gates; PostgreSQL migration/runtime proof has not executed locally and is not claimed. +- Forward V3 adds the Account audit projection and links retained V2 receipts without rewriting V2. The combined unapplied candidate places typed numeric-V1/canonical-UUID-V2 audit identity at V3.1 after that projection backfill, retaining existing identity uniqueness and ordinary non-audit tenant-key behavior. Its new-write checks are `NOT VALID`, as are the V4 canonical lowercase digest-format and V5 positive tenant-audit checks; retained malformed rows are neither attested nor rewritten. UUID-V2 audit identity has no numeric alias, while ordinary tenant queries still use their private `tenantId`. The fixture stages retained invalid-digest and zero/negative tenant-audit rows before these checks. Exact deployed Flyway history/checksums, retained-row readback and owner-approved constraint validation remain rollout gates; do not renumber applied V3 history or conceal a collision through repair or out-of-order execution. Local PostgreSQL migration/runtime execution is unavailable, not claimed. +- Live Account audit `CreateLogEvent` remains `UNAVAILABLE` after exact workload authentication and before conversion or storage, and Account's delivery job remains disabled. The typed UUID storage/service boundary is offline preparation; authenticated receipt readback remains available. Physical mTLS fixture receipt responses are mock-backed and do not prove live creation or an Account-to-Logging database transaction. Current capability and activation status belong to the linked implementation trackers. - This receiver has no automatic receipt-payload minimization or receipt garbage collector; `MINIMIZED/NON_REPLAYABLE` fixture states are not cleanup-execution proof. Current capability and activation gates are tracked in [Shared Runtime, Service Contracts, and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#audit-moderation-and-authority-boundaries). - The service exposes core admin investigation reads, saga inspection of Logging & Admin-local rows only, coordination-health reads, and a narrow log query whose current implementation reads only the service-owned PostgreSQL `log_events` table for an exact tenant plus case-insensitive message containment. Saga inspection does not aggregate adopter-local state; target cross-owner visibility requires owner read APIs plus a bounded aggregation/read model and must distinguish an unknown or unavailable adopter from an empty result. Moderation policy-input and report-persistence paths are only unsupported legacy transport/internal seams that hard fail closed or remain authorization-unproved; they are not exposed current capabilities. The service does not implement the target profile-aware indexed or console/journal query integrations, Kibana/Grafana clients, embedded dashboards, separate admin UI, or the complete target control-plane workflow for every recovery, regional, or aggregate operation. - The moderation policy-input and audit persistence mutation has present legacy transport stubs through `POST /moderation/actions` and the internal `ApplyModerationAction` gRPC ingress; after narrow tenant/admin checks they hard fail closed with HTTP `503 Service Unavailable` or an application-level gRPC `UNAVAILABLE` error, without dispatch or persistence. They are unsupported, nonconformant implementation drift and must not be wired or called as available mutations. They do not provide the target fixed-category policy-input/audit record or Account, Game Session, or Social & Groups enforcement state. Current execution performs no Account authorization-reference issuance or redemption, owner forwarding, or owner enforcement. Once its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and Logging & Admin receiving-boundary validation/redemption are complete, Logging & Admin redeems the separate intent-persistence reference exactly once at its receiving boundary; that reference is never forwarded or reused and the path does not require owner-side authorization-reference redemption or enforcement. Any future owner-enforcement command uses a separately issued reference redeemed once by its receiving owner. The separate `EvaluateModerationPolicy` compatibility read remains live at the owner enforcement boundaries and carries no mutation authorization reference. Public administrative report persistence at `POST /admin/reports` is unavailable: the HTTP controller and Gateway route were removed because canonical authorization and live reference validation are not implemented. The internal `CreateReport` gRPC ingress is not public; its interim receiver guard requires an internal-service JWT naming `social-groups-service`, which the Social & Groups client emits, while certificate-derived exact workload/method authorization remains unproved. The reserved player-bootstrap `POST /reports` submission route is separate and also unavailable until its caller-bound subject and live tenant-membership checks exist. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 340b01d865..2f4f9d2add 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -245,6 +245,14 @@ The current `worldSnapshotId` remains the deterministic same-scope marker descri The unresolved target work is tracked in [World Runtime and Movement](../../../project-management/implementation-tracking/world-runtime-and-movement.md#active-gaps): Game Session floor allocation from durable region commit authority and Game Logic propagation are target obligations, while World participant floor satisfaction and the opaque component-version plus scoped `servedThroughTickId` response remain unimplemented and unproved. The current proto/request and focused proof do not carry or demonstrate this contract; the exact coordinated wire shape and proof encoding remain implementation gaps. +## Initial Admission Hold Contract + +[Versioning and Runtime](../../system-architecture-versioning-runtime.md#first-open-from-never-opened-authority) owns the first-OPEN transition and its tagged prior-pointer preconditions. World owns the durable initial-admission hold and authoritative target lifecycle proof. The hold binds one stable initial-admission request/digest, the complete canonical namespace/tenant/realm/playable-namespace/scope, exact target instance/version/ACTIVE epoch, and the precondition tag with its applicable pointer/catalog versions. Private World storage selectors do not replace those identities: any association must come from exact persisted authenticated owner evidence, never numeric equality, slugs or Account's migration manifest. + +Acquire locks and verifies the exact ACTIVE lifecycle row and commits one immutable hold identity/fence; an exact retry reuses it, and changed bindings conflict without another hold. A nonterminal hold blocks every applicable target termination CAS. World finalizes only from authenticated Game Session readback of the exact hold-bound pointer/audit/outcome commit, or terminalizes an abort only from positive proof that this operation did not commit and its expected prior routing authority remains intact. Missing, contradictory or unavailable evidence remains reconciliation-required and termination-blocking. Expiry is diagnostic input, never automatic release or proof of abort. + +Targetless CLOSED catalog creation does not acquire this hold. The Game Session origin check, authenticated canonical launch association and complete lifecycle/hold/readback composition must be implemented and proved before this contract authorizes runtime activation; see [World Runtime and Movement](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). + ## Replacement Cutover Hold Contract World Management owns the durable one-shot hold that closes the race between proving the replacement target `ACTIVE` and Game Session committing the realm admission-pointer swap. This is a separate hold record/state, not a new `world_instance` lifecycle state and not a distributed transaction. The hold is acquired only after the target activation CAS and is finalized only after Game Session proves its local pointer transaction committed. diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index 48a3b5aa07..5ab2604368 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -527,7 +527,7 @@ Version cutover contract for a player-addressable realm: Realm pointer schema and authority are canonical in [Multi-Tenancy](./system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract). Versioning and runtime retains only the cutover lifecycle and its local consequences below. Game Session remains the sole routing owner; versioning workflows consume its API rather than direct table writes. -- A pointer swap to a different `gameInstanceId` is a cutover operation, not a generic edit. It must use the canonical `ExecutePreparedVersionCutover` operation, one durable `prepared_version_upgrade` record, and one World-owned one-shot cutover hold; `SetAdmissionPointer` is not an independent replacement commit path. The `COMPATIBLE` preparation binds the exact World `PREPARING` activation precondition plus the catalog-derived `{playableStateNamespaceId, playableStateScope}`, source and target instances/versions, frozen launch proof, exhaustive participant summary, owner-validated/applied mapping evidence, and freshness epochs required by [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). That namespace/scope tuple is carried unchanged through the prepared artifact, participant evidence, hold, pointer CAS/readback, and exact retry result; any catalog or tuple mismatch fails closed. World’s activation CAS produces the exact target `ACTIVE` proof; subsequent stable-order hold acquisition rereads and validates the exact source and target `ACTIVE` proofs, then produces its `cutoverHoldId`/`cutoverHoldFence`, which are stored with the durable execution/result. The Game Session owner-local pointer transaction validates both lifecycle proofs, the hold identity/fence, and expected pointer version. Final pointer CAS/readback and exact retries require all of those proofs rather than accepting a later lifecycle epoch or minting another hold. +- Replacing an OPEN pointer's target with a different `gameInstanceId` is a cutover operation, not a generic edit. It must use the canonical `ExecutePreparedVersionCutover` operation, one durable `prepared_version_upgrade` record, and one World-owned one-shot cutover hold; `SetAdmissionPointer` is not an independent replacement commit path. The `COMPATIBLE` preparation binds the exact World `PREPARING` activation precondition plus the catalog-derived `{playableStateNamespaceId, playableStateScope}`, source and target instances/versions, frozen launch proof, exhaustive participant summary, owner-validated/applied mapping evidence, and freshness epochs required by [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). That namespace/scope tuple is carried unchanged through the prepared artifact, participant evidence, hold, pointer CAS/readback, and exact retry result; any catalog or tuple mismatch fails closed. World’s activation CAS produces the exact target `ACTIVE` proof; subsequent stable-order hold acquisition rereads and validates the exact source and target `ACTIVE` proofs, then produces its `cutoverHoldId`/`cutoverHoldFence`, which are stored with the durable execution/result. The Game Session owner-local pointer transaction validates both lifecycle proofs, the hold identity/fence, and expected pointer version. Final pointer CAS/readback and exact retries require all of those proofs rather than accepting a later lifecycle epoch or minting another hold. - Pointer-audit history must preserve that same preparation identity. A successful cutover write records the `preparedVersionUpgradeId` on the resulting admission-pointer audit event so operators can prove which durable preparation authorized a given swap. - For private/playtest transitions, the applicable `playtestLifecycleId` is also part of the normalized `ExecutePreparedVersionCutover` request/digest and is carried unchanged through the prepared artifact, participant evidence/hold, pointer CAS/readback, durable execution/result, and exact replay; public-production transitions omit it. Any applicable lifecycle-ID mismatch fails closed. - Stopping a realm without a replacement uses the owner-defined `CLOSED` state before the old instance drains; the owner-defined unavailable and realm-unavailable outcomes remain distinct. @@ -537,6 +537,14 @@ Realm pointer schema and authority are canonical in [Multi-Tenancy](./system-arc - In that target contract, Game Session may complete a drain early after the source session index is empty. Deadline-based command rejection follows the persisted fence and authoritative clock independently of reconciliation. The durable reconciliation contract below records and reads back the fence/lifecycle effects; in particular, World Management's lifecycle fence and command-rejection readback precede the bounded notice and unconditional source-socket close. - **Local target consequence:** the source instance remains closed to new or reconnected bindings while existing sessions may continue only through `sourceDrainDeadlineAt`; after the deadline, terminal source cleanup follows the standard `InstanceTermination` workflow. +#### First OPEN From Never-Opened Authority + +The first admission-pointer OPEN is distinct from reopening or replacement. World supplies an initial-admission hold under its [owner contract](./microservices/world-management-service/api-contracts.md#initial-admission-hold-contract); Game Session accepts exactly one tagged precondition: `NO_PRIOR_POINTER`, or `EXPECT_CLOSED(pointerVersion, catalogRevision)`. The latter requires positive owner-local proof that the current targetless CLOSED pointer is the exact canonical catalog-created origin and has never been OPEN. Missing history, missing rows or a caller's assertion cannot establish that provenance. Previously OPEN pointers are excluded even when their current state is CLOSED. + +The stable operation identity binds that tag and its applicable expected versions, the complete canonical workload/tenant/realm/playable-namespace/scope tuple, and the exact target instance, version and World ACTIVE lifecycle epoch. Game Session validates the exact catalog and original pointer evidence under its owner transaction, then commits the pointer, append-only audit and immutable operation outcome atomically, advancing `pointerVersion`. Exact authenticated commit/abort readback and retry preserve that identity and the original result; neither owner infers success or non-commit from timeout or expiry. Normal source, hold and readback handoffs are automatic owner calls, not operator-supplied mappings. + +Creating a targetless canonical CLOSED origin requires no ACTIVE-instance hold: it grants no admission and selects no runtime target. Reopening a previously OPEN realm and replacing an OPEN target retain their separate compatibility, closure/drain and lifecycle-proof obligations; this initial path cannot substitute for them. The complete previously-OPEN reopen handoff remains an explicitly tracked owner obligation rather than an inferred permission. + #### Bounded Source-Drain Reconciliation Game Session owns the retryable reconciler and startup-recovery path for each durable source-drain item. A worker claims the item with a compare-and-set lease carrying a monotonically increasing `drainClaimFence`, bound to the exact `sourceDrainId` and source `gameInstanceId`. Only the current claim fence may persist effect state or completion. Lease expiry permits another worker to claim the item with a higher fence; a stale worker cannot commit after that handoff. diff --git a/design/developer-workflows/ai-delegation-and-review.md b/design/developer-workflows/ai-delegation-and-review.md index 31b2f53369..81981c3eea 100644 --- a/design/developer-workflows/ai-delegation-and-review.md +++ b/design/developer-workflows/ai-delegation-and-review.md @@ -26,9 +26,9 @@ Standing delegated stewardship may remove entries proven addressed, obsolete, or In this section, the `delegating orchestrator` is the task that issues a bounded assignment and owns its integration. Under an explicit Overseer arrangement, a lane orchestrator normally fills that role for operational work; the Overseer also fills it when directly delegating authorized operational work or evidence for an Overseer decision. This term does not transfer consequential product, architecture, priority, topology, or merge-readiness decisions away from the Overseer. -A bounded discovery reviewer may return a worthwhile, coherent batch early, or stop on a consequential finding that requires direction. The normal handoff retains findings, what was inspected, and remaining coverage or unresolved threads; it does not require a fixed finding quota, a new file, or a per-file ledger. +Every discovery or review assignment must finish its declared scope. Interim findings, including consequential findings that need direction, do not end the assignment; report them and continue the remaining safe, useful in-scope coverage. If a concrete blocker prevents completion, identify it and the remaining coverage, then continue any other safe, useful in-scope work while awaiting direction. Do not impose a finding quota or require a new file or per-file ledger. -The parent may resume the same reviewer within the same scope by supplying relevant changes since the prior checkpoint. The reviewer continues additional coverage and reports new findings or material revisions without duplicating the first batch. Follow important cross-service patterns far enough to support a sound recommendation rather than stopping at surface consolidation. The discovery workstream's eventual completion assessment after fixes converge uses a fresh independent reviewer under the existing independence rules. For that assessment, use a new execution context that has not received earlier findings, dispositions, or a desired conclusion before discovery; provide the governing authority, exact artifact and scope, and necessary factual constraints, and disclose unavoidable inherited context. An early batch is not complete coverage or domain closure. Fix audits are not required to use early-return mode. +If a concrete blocker is resolved and an assignment resumes, the parent may return the same reviewer to the same scope with relevant changes since the prior checkpoint. The reviewer completes remaining coverage and reports new findings or material revisions without duplicating findings already reported. Follow important cross-service patterns far enough to support a sound recommendation rather than stopping at surface consolidation. The discovery workstream's completion assessment after fixes converge uses a fresh independent reviewer under the existing independence rules. For that assessment, use a new execution context that has not received earlier findings, dispositions, or a desired conclusion before discovery; provide the governing authority, exact artifact and scope, and necessary factual constraints, and disclose unavoidable inherited context. Completing a declared scope does not claim domain-wide closure unless that breadth was assigned. Fix audits follow the same completion requirement. - Route subagents only to Luna and Sol. Resolve the latest available version of the selected family from actual tool model metadata at delegation time, even when older versions remain available; do not pin version identifiers or infer availability from marketing descriptions. An explicit human model choice takes precedence. Preserve user-selected model and reasoning settings for persistent tasks. - The allowed escalation order is Luna `high` -> Luna `xhigh` -> Sol `medium` -> Sol `high`. Choose the appropriate starting tier for the task rather than requiring an attempt at every earlier tier; any escalation follows that order. All four tiers may be chosen autonomously without separate model-tier approval. `max` is not an allowed tier for either family. Use Luna `high` for routine bounded investigation, mechanical patches, and straightforward test updates, and Luna `xhigh` for substantial delegated work and independent review. If a subagent launch fails specifically because the selected model is at capacity, wait 30–60 seconds and retry the same model and reasoning tier. If that delayed retry also fails, the lane orchestrator chooses an available fallback suitable for the assigned task within the allowed families and tiers, reports the model/tier substitution to the human when the fallback starts, and distinguishes capacity substitution from reasoning-driven escalation: it is not an automatic upgrade. If no permitted fallback is available, report a capacity blocker; do not invent a model chain or new approval path. Report the failed model/tier, wait duration or retry count, and any fallback in the end-of-round/status handoff. @@ -42,7 +42,7 @@ The parent may resume the same reviewer within the same scope by supplying relev - Delegation prompts and integration decisions must not use the current PR file cap as a file allowlist: identify every file needed for the correct canonical implementation and state why. If scope must expand, the lane orchestrator reports the correct files and reason and applies the [PR lifecycle](./pr-lifecycle.md#change-and-merge-policy) topology rules; execution helpers return to the parent rather than relocating fixes, dropping useful findings, packing unrelated helpers or tests, or changing semantics to fit a count. Main integration rejects count-driven compromises; if ownership or clean preservation is uncertain, pause that decision for Overseer adjudication while independent safe work continues. - For review-fix delegation, the delegating orchestrator must adjudicate the finding and state the smallest intended semantic change before assigning edits. A worker must not generalize a local finding into a new validator family, parallel schema mirror, broad document rewrite, or adjacent contract expansion. If the requested fix appears to require that wider mechanism, stop and report the proposed expansion for delegating-orchestrator integration instead of implementing it speculatively. - Subagent validation is a closed allowlist. During iteration, run only the focused affected formatting or tests explicitly named in the task; do not broaden checks merely because independent lanes coexist or a helper is handing off. At integration or merge checkpoints, the lane orchestrator owns consolidated proof and selects broader checks when the changed contract or runtime impact requires them. A subagent may run only the exact validation commands named in its task; prohibiting Gradle or another canonical command does not authorize standalone linters, approximations, ad hoc flags, or other substitute checks. If validation is `none`, report it as not applicable or deferred exactly as assigned. Proof selection and exact-head/scope CI evidence follow [Validation And Runtime Proof](./validation-and-runtime-proof.md). -- A delegated task ends when its assigned edits and explicitly named checks are complete; return immediately rather than adding self-selected wording passes, structural audits, cleanup, or substitute validation merely to appear thorough. If assigned work is unfinished, report the concrete blocker or wait to the parent and return; persistent-lane continuation follows [PR lifecycle](./pr-lifecycle.md#review-orchestration). An explicit task pause still binds until later explicit resumption. +- A delegated task ends when its assigned edits and explicitly named checks are complete; return immediately rather than adding self-selected wording passes, structural audits, cleanup, or substitute validation merely to appear thorough. If assigned work is unfinished, report the concrete blocker and remaining scope. For discovery and review assignments, continue safe, useful in-scope coverage while the blocker is pending and return only when no assigned coverage can continue. Persistent-lane continuation follows [PR lifecycle](./pr-lifecycle.md#review-orchestration). An explicit task pause still binds until later explicit resumption. - Reuse a completed subagent only for a direct continuation of the same bounded task or domain where its retained context remains an asset. Unrelated work uses a fresh thread with a descriptive task name: retained context can bias a new assignment, and a stale sidebar identity obscures what is actually running. End-of-round reporting identifies any intentional thread reuse as well as newly spawned workers. - Prefer a native blocking watcher or product wait primitive when the owning lane can remain blocked in that execution. When the main task continues safe work or yields and the available native wait cannot wake it, use one fresh read-only Luna sentinel tied to the exact Hosted, CI, or other external transition. The sentinel observes only: it stays alive until a terminal transition, meaningful timeout, or required adjudication, and never returns for ordinary pending or unchanged state. A detached background shell that requires parent polling is not wake-capable. The canonical wrapper or main owner alone triggers or retries the external operation; the sentinel does not. Its prompt must authorize the exact read-only PR, review, or CI inspection while retaining every write prohibition. Once a wake-capable read-only sentinel owns an external transition, the parent must not duplicate polling or recheck that same CI or Hosted state on ordinary mailbox timeouts; await its mailbox with a longer bounded interval that remains interruptible by user input, continue other useful work or yield, and respond only to a terminal transition or meaningful change. A watcher is a continuation mechanism, not a guarantee that the task will wake. - Every substantial round ending, handoff, or blocker report must include one short actual-delegation line naming model and tier, bounded roles, delegating-orchestrator verification, and any relevant reuse or constraint; if a substantial operational batch had no delegation or leaves execution capacity unused while substantial known work remains, briefly explain why, distinguishing dependencies or overlap from a missed dispatch opportunity. Do not require this in every commentary update, separate acknowledgement messages, agent-count targets, or forced model diversity. Every delegated handoff must also report changed files, explicitly named checks and their outcome or not-applicable/deferred state, reasoning-sensitive assumptions, and unresolved concerns. A terse completion claim without that evidence is not an integration handoff. @@ -52,8 +52,8 @@ The parent may resume the same reviewer within the same scope by supplying relev ## Independent Review Evidence -- For an exhaustive audit, require a per-item coverage ledger, named source and design documents read, and an incomplete-review gate. An unsupported "No findings" statement is not exhaustive evidence. +- For an exhaustive audit, require per-item coverage, named source and design documents read, and an incomplete-review gate. An unsupported "No findings" statement is not exhaustive evidence. - Use the unified `dev-tools/pr-review` Hosted or CLI commands as the default iterative PR defect-discovery and fix-verification path. During normal PR polishing, do not spawn subagents to review or re-review fix batches. The delegating orchestrator inspects the integrated diff, runs appropriate validation, and uses subsequent complete controller cycles for independent review. Additional model-based fix review requires an explicit assignment from the Overseer or human. - Outside routine fix review, keep model-backed independent review for a consequential initial check before the controller is available, a risk the controller cannot cover, a fresh whole-domain corpus assessment, a deliberately commissioned audit, or another explicitly assigned independent review. When it is justified, use a fresh-context reviewer at the required delegation tier and the independence boundary defined above. The delegating orchestrator remains responsible for checking the evidence and deciding whether the review is complete within its assigned authority. -- For an explicitly assigned multi-pass model review of a PR, maintain one shared private per-PR review note across passes. Use `FireMUD-project-direction/tmp/review-ledgers/pr-.md` in this workspace; if it is unavailable, establish another shared private path before the first pass. Record each complete pass's reviewed head and scope, found/accepted/routed counts, concise finding dispositions and remaining gaps, and label narrow investigations separately. Report the note's path in the handoff. This does not add a ledger to routine controller cycles or focused fix validation. Record each commissioned pass in controller history using [PR-review SQLite operations](../../dev-tools/pr_review/README.md); restrictions on provider requests, live promotion, or queue changes do not exclude that recording. If the store is unavailable, preserve exact evidence in the private note and report the recording gap and recovery action promptly; safe review work may continue. +- Record commissioned subagent review passes, findings, decisions, routes, fixed commits, and proof in controller history using [PR-review SQLite operations](../../dev-tools/pr_review/README.md). The controller is the sole normal durable review record, including explicitly assigned multi-pass programmes; do not maintain parallel private per-PR ledgers, persistent checkpoint receipts, status snapshots, or duplicate handoff files. Retain reviewed head and scope, exact finding severity and dispositions, counts, remaining gaps, and the distinction between broad passes and narrow investigations in the controller. Restrictions on provider requests, live promotion, or queue changes do not exclude that recording. Only when the controller is unavailable, preserve exact evidence temporarily and promptly report the recording gap and recovery action; safe review work may continue. Temporary command inputs and outputs remain allowed, and existing captures, backups, site outputs, active briefs, and unpublished work remain subject to their owning retention and cleanup rules. - Bounded implementation helpers, initial discovery, and normal focused tests remain allowed without becoming routine fix-review agents. End-of-run reporting must summarize how many subagents were used, their bounded roles, and whether they changed files or only supplied evidence. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index b2b0834bfd..1fee97851a 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -380,3 +380,8 @@ Entry format: - Context: two bounded CI sentinels inspected a shortened or mistyped run identifier instead of the supplied full identifier and reported HTTP 404. That was not evidence that the authorized run was inaccessible or nonexistent. - Outcome: direct same-task corrections restored observation of the intended runs. The current run37030807027 is visible; its earlier lookup of37007080727 supplied no validation evidence. No repository or CI mutation was needed. - Expected pattern: copy the complete identifier from the assigned run URL, verify the returned run identifier and head SHA before attribution, and include the actually inspected identifier in a lookup-failure report. Do not escalate a mistyped-ID lookup as a platform-access failure or silently substitute a different run. + +- `2026-10-03`: Use the installed shared controller after SQLite cutover + - Context: an older stacked worktree's repo-local controller refused status with `SQLite cutover marker does not match database metadata`. This was a reader/version mismatch, not evidence about the PR's review or CI state. + - Outcome: the human-designated `/home/ben/.local/bin/firemud-pr-review` reports writer build 8 and is used for the readback instead. No private database, marker or review evidence was edited to bypass the refusal. + - Expected pattern: select the installed shared entrypoint named by the active brief, verify its version and preserve fail-closed cutover records; do not repair private metadata from an outdated checkout. diff --git a/design/project-management/ai-task-prompt-library/system-review-prompts/00-shared-review-contract.md b/design/project-management/ai-task-prompt-library/system-review-prompts/00-shared-review-contract.md index f5e8fdbed6..8d4a66809b 100644 --- a/design/project-management/ai-task-prompt-library/system-review-prompts/00-shared-review-contract.md +++ b/design/project-management/ai-task-prompt-library/system-review-prompts/00-shared-review-contract.md @@ -56,7 +56,7 @@ For an exhaustive review, maintain a response-local coverage table containing: A focused commissioned review may use a smaller table matching its declared boundary. Working coverage tables remain ephemeral unless the human explicitly requests a retained artifact. -Intentionally bounded representative discovery may complete its declared assessment with evidence proportional to that objective, without claiming whole-repository exhaustiveness or domain closure. Early-return and same-scope resumption are defined in the [AI Delegation And Review](../../../developer-workflows/ai-delegation-and-review.md) guide. +Intentionally bounded representative discovery may complete its declared assessment with evidence proportional to that objective, without claiming whole-repository exhaustiveness or domain closure. It must cover the full declared assessment. Findings that need human direction do not end the review; continue other safe, useful in-scope coverage and report any concrete blocker with the remaining coverage. ## Findings @@ -80,8 +80,8 @@ Within a coordinated review, identify duplicates using the canonical owner, affe End with exactly one review state: - `complete` – every item in the declared assessment boundary was covered or explicitly excluded with an acceptable rationale; -- `incomplete` – the review was an early batch, used undeclared sampling, skipped a required area, or necessary proof or live evidence was unavailable; or -- `blocked` – a missing authority, competing target state, unavailable required source, or human decision prevents the review from continuing. +- `incomplete` – the review left a declared item uncovered, used undeclared sampling, skipped a required area, or necessary proof or live evidence was unavailable; or +- `blocked` – a missing authority, competing target state, unavailable required source, or human decision prevents any remaining in-scope review from continuing. `No findings` does not imply `complete`. A static review may be complete within its declared static boundary while live evidence remains unavailable, but it must not make an unqualified readiness claim. @@ -89,4 +89,4 @@ End with exactly one review state: Reread current sources from disk. Prior findings are evidence to reconcile, not authority. Classify them as still present, resolved, changed, superseded, or not reproducible, and do not silently drop them. -Stop and request human direction rather than choosing between competing product outcomes, target architectures, security or privacy risk acceptance, release scope, or traffic-opening decisions. +Request human direction rather than choosing between competing product outcomes, target architectures, security or privacy risk acceptance, release scope, or traffic-opening decisions. Record the decision needed and the coverage it blocks, then continue all other safe in-scope assessment; stop only when no remaining scope can proceed. 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 48aa650ec8..a8ddc39e6d 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,55 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The same exact run's Game Session/TCP startup evidence exposes V13 duplicating the V7 `realm_id` audit column; `catalog_revision` was also already present. The retained-safe correction reuses both columns, preserves legitimate legacy realm/namespace/catalog values and their pair invariant, and applies canonical CLOSED's no-runtime/namespace-alias shape only to representation two. The existing retained-row fixture now captures the actual V7 values before upgrade and compares them afterward; a new mandatory PostgreSQL case rejects numeric and namespace aliases without pointer/audit/outcome growth. Corrected runner execution is required. The earlier Game Session authored-source failures do not have separately uploaded raw XML, so their shared migration root cause is an inference from startup evidence rather than five independently verified executions. + +Exact #2949 `d557bd49c0fa6e162af2006be326bd89e5b6f156` [CI37209247075](https://github.com/benhook1013/FireMUD/actions/runs/37209247075) completed with aggregate failure. Raw XML establishes three canonical scope cases, one canonical membership-identity case, six of seven canonical receipt cases and all nine physical Logging mTLS cases passed without skips. The retained receipt upgrade failed in V48 because its migration-owned `receipt_head_id` backfill invoked V41's runtime append-only trigger. The bounded correction suspends only that named trigger around the transactional backfill and immediately restores it; the retained-upgrade fixture proves unchanged original receipt fields and sequence plus subsequent UPDATE/DELETE rejection. The Logging strict gate also demanded four obsolete successful-Create method names; their replacements require the actual current denied-Create/allowed-readback cases, retaining all nine mandatory physical mTLS cases. Corrected-head PostgreSQL execution remains required. Missing first-JOIN, typed Logging migration and catalog/CLOSED raw XML is unavailable proof, not a pass. Shared Ruff and Python websocket dependency failures remain separately routed. No runtime activation, deployed migration repair or fresh-image success is claimed. + +The normal source-to-canonical-JOIN reconciliation now passes the consolidated Account, Logging, Game Session, Common Platform and Common Security checks, three service boot JARs, formatting, analyzers, coverage and documentation gate (1m43s; 313 tasks, 32 executed and 281 up-to-date). Game Session executes 2,398 unit, 18 integration and 26 cross-service cases cleanly; Account's 865, Logging's 234, Common Platform's 177 and Common Security's 126 clean unit results are reused from the unchanged preceding runs. Local skips remain explicit: Account 288 and Logging 23 integration cases, plus Game Session 17 unit, 189 integration and 56 cross-service cases. Docker is unavailable, so this is not execution of the newly composed PostgreSQL migration/receipt proof. Incoming initial-admission fixtures now carry the retained representation discriminator without weakening runtime isolation; the canonical CLOSED fixture uses the parent's ID-ordered reader. Exact composed-head CI, fresh-image and authenticated end-to-end proof remain gates, not implied by this local success. + +The composed canonical-JOIN candidate preserves Logging's V2 receipt → V3 projection backfill → V3.1 typed audit identity → V4/V5 retained-safe checks → V6 moderation identity order. V3.1 retains existing numeric identity uniqueness, separates UUID-V2 without aliases and enforces new-write constraints without attesting malformed retained rows. This is an unapplied candidate only; exact environment history/checksums and retained readback remain gates. Live authenticated `CreateLogEvent` and scheduled Account delivery remain denied. The updated physical-mTLS fixture proves denial before service invocation and typed identity on allowed mock-backed receipt readback, not positive audit creation. Historical successful-Create evidence below applies only to its earlier stated head. + +Exact source #2933 `85e1b104c3087b72f73e5bd8018a5ddf79e7fbbb` [CI37202688779](https://github.com/benhook1013/FireMUD/actions/runs/37202688779) completed with aggregate failure. Raw XML proves all four required Game Design PostgreSQL suites executed with no skips, failures or errors: association10, EntityDigest baseline9, fresh tenant creation8 and authored-world source10; the corrected selector now provides37 actual executions, not merely discovery. Game Session retained association17 and Account authority15/mTLS3+6 also passed, and Account JOIN/reconciliation/storage, Social and Logging strict gates succeeded. Root independently parsed and hashed the four Game Design files. The later broad Game Session Gradle check was canceled; Ruff B023, ten missing-websocket-dependency errors and13/17 TCP denied-PLAY failures remain actual aggregate failures. The Python defects are routed to #2853; denied-PLAY and complete runtime producer proof remain open. This is source-head component evidence, not execution of the newly composed #2949 tree, live deployment or activation. + +The source-to-canonical-JOIN reconciliation preserves Game Session's audit lookup index at V12 and mechanically places the initial canonical realm catalog at V12.1, before the canonical CLOSED migration at V13. The catalog SQL bytes are unchanged; the incoming cardinality and index guards remain present. This prepares only a collision-free unapplied candidate. Exact environment Flyway history/checksums and retained-row readback remain rollout gates; a previously applied conflicting V12 cannot be silently renumbered, repaired or hidden with out-of-order execution. Historical execution below remains evidence for its stated head, not PostgreSQL proof of this newly composed sequence. + +Exact #2949 `996d99ca11c99c685fdef0dd35a859a25ce3fc8b` [CI37097862965](https://github.com/benhook1013/FireMUD/actions/runs/37097862965) completed with aggregate failure; its sole observer finished. Independently parsed and rehashed raw XML proves all 56 captured methods executed cleanly without skips: three Account audit, one retained-row migration, fifteen Logging receiver, one Logging migration, nine physical mTLS, and the prior 27 scope/receipt/catalog/CLOSED methods. The corrected malformed-row case rejects every invalid write at the exact constraint and proves no projection growth. Physical mTLS uses production peer extraction and handler code with ephemeral fixture PKI and a mocked receiver service; it does not prove an Account-to-Logging database workflow or deployment. Concrete tooling, Automation formatting and Game Design duplicate-tenant fixture failures remain separately owned; no aggregate success, activation or ring mount is claimed. + +Canonical first-JOIN event publication is a separate owner-local prerequisite in preparation. It reads persisted UUID membership/roles, exact V2 pending intent and stored AVAILABLE policy after the Account fence, then commits the closed event/checkpoint and positive pair transition together without advancing caller authority or issuance fence. Its fixtures deliberately seed policy and source evidence; they do not prove authenticated entitlement, public JOIN, terminal outcome or recovery. Runtime paths remain denied until that complete composition is implemented and proved. + +Exact #2949 `51bfdafda78ff1448ac753de867a5b3c73afd2e2` [CI37092681148](https://github.com/benhook1013/FireMUD/actions/runs/37092681148) finished with aggregate failure. All four required raw XML suites prove three canonical Account scope/intent, seven receipt, five catalog and twelve CLOSED-pointer methods actually executed cleanly, with zero skips, failures or errors. Independently parsed method lists and hashes prove the corrected receipt setup and all four new locked-origin cases on this composed tree. Account's broader integration check executed 265 cases with one failure: the retained-row migration fixture compared pre-V48 receipt metadata with a widened row. The correction compares every original field separately from the new unbridged metadata and still needs corrected-head PostgreSQL execution. Game Session's component proof and Gradle checks passed before coverage upload was cancelled; separately owned Python lint, Automation formatting, Game Design duplicate-tenant and dev-demo summary failures remain explicit. No watcher remains for this terminal run. This is not aggregate success, complete canonical JOIN, authenticated World handoff, live readiness or activation; local Docker skips below remain accurate local limits. + +The next Account/Logging audit batch widens the existing outbox and receiver receipt/projection families with explicit numeric-V1 versus canonical-UUID-V2 tenant identity. Retained bytes and terminal history remain unchanged; UUID rows have no numeric alias. Exact receipt evidence, ambiguous-delivery readback, minimization metadata and workload-only ingress validation are included. Consolidated Account, Logging and Game Session full checks, all three boot JARs, formatting, static analysis, coverage and documentation passed locally in 2m23s (190 tasks; 64 executed, 126 up-to-date). Same-code XML records 707 Account, 201 Logging and 1,915 Game Session clean unit executions, plus 18 Game Session integration and 26 cross-service executions; unchanged results were reused where Gradle reported up-to-date. Account's 264 and Logging's 16 integration cases all skipped without Docker, including the three new Account audit methods and Logging migration/receiver methods. Game Session also skipped 17 unit, 169 integration and 54 cross-service cases. Corrected-head PostgreSQL execution and physical peer proof remain required. This batch does not wire the UUID carrier into the positive JOIN transaction or enable canonical UUID log querying, runtime admission or a ring mount. + +The approved first-OPEN boundary now has local Game Session preparation of the exact committed canonical CLOSED origin and atomic catalog/pointer-locked revalidation in a writable READ COMMITTED transaction. Privately constructed local evidence is not World authorization or an OPEN transition. Four unit cases passed; all twelve CLOSED-pointer PostgreSQL methods compiled but skipped locally without Docker. The full Account/Game Session checks, both boot JARs, formatting, static analysis, coverage and documentation passed in 1m55s/158 tasks (41 executed, 117 up-to-date). Same-code XML records 695 Account and 1,915 Game Session clean unit executions, 18 Game Session non-Docker integration and 26 cross-service executions; unchanged Account unit results were reused. Account's 261 integration cases and Game Session's 17 unit, 169 integration and 54 cross-service cases skipped. Canonical World launch association, tagged hold, ACTIVE epoch, termination blocking, authenticated readback and actual first OPEN remain required; no runtime path or ring mount is enabled. + +Exact #2949 `1a36c2bbe6892642d8c85e18b7067008f8b8beb3` [CI37090835818](https://github.com/benhook1013/FireMUD/actions/runs/37090835818) finished with aggregate failure. Independently parsed raw XML proves all three canonical JOIN scope/intent, five catalog and eight CLOSED-pointer PostgreSQL cases executed cleanly without skips. All seven receipt cases executed but failed in fixture source-evidence construction before receipt assertions: fresh and retained synthetic keys exceeded the unchanged 36-code-point owner bound. The bounded correction uses independently random keys within that bound, not tenant-derived aliases; corrected receipt execution and the four new locked-origin methods remain required. Game Session's component proofs, checks, LOGIN fixture-isolation proof and runtime JAR build succeeded before its job was cancelled during Gradle post-setup. Account's later missing-suite checks are unavailable dependent evidence, not further executed failures. Python lint, Automation formatting, Game Design duplicate-tenant and dev-demo summary failures remain separately owned; none is assumed flaky or resolved merely because this focused batch passes. + +The corrected canonical receipt/CLOSED batch passed the full Account and Game Session checks, both boot JARs, formatting, Checkstyle, SpotBugs, coverage and documentation checks locally (18s; 156 tasks, 16 executed and 140 up-to-date). All 695 Account unit cases executed cleanly, including five new receipt/vector cases. Game Session's unchanged 1,914 unit, 18 non-Docker integration and 26 cross-service executions were reused. Account's 261 integration cases and Game Session's 17 unit, 165 integration and 54 cross-service cases skipped locally; this includes all seven new receipt PostgreSQL cases and the eight corrected CLOSED-pointer cases. Docker is absent in this environment. Exact corrected-head PostgreSQL execution, fresh-image composition and live proof remain required. The CLOSED timestamp correction uses an explicit TIMESTAMPTZ cast, not weaker request, timestamp or atomic-readback checks. The approved first-OPEN contract still requires its complete World identity/lifecycle handoff and positive never-OPEN provenance proof; it is not implemented or activated by this receipt batch. + +The canonical provisional-receipt preparation widens the existing V28/V40 family in V48. Approved retained heads keep their original storage key, immutable V1 receipt bytes and sequence; fresh UUID-qualified heads have no numeric tenant alias. Both representations share one private head counter and the global request-ID fence. Canonical evidence carries the exact one-tenant membership-version map and source provenance, but is not an authority-event checkpoint or admission grant. A missing receipt head cannot reset known JOIN/LEFT history; the first fresh receipt requires the exact pending JOIN and same-request first positive pair/event evidence. Focused PostgreSQL fixtures compose existing owner repository and codec primitives to establish that prerequisite in one transaction. This is storage and readback proof, not a canonical UUID JOIN service producer or authenticated caller proof. Complete positive JOIN, canonical audit delivery and terminal-operation reconciliation remain open; the runtime paths and ring mount remain denied/unpublished. This preparation is not covered by the preceding published catalog-only checkpoint's CI. + +Exact #2949 `211cbe4421c615e833279542d4a8158c8d9a62cc` [CI37079397170](https://github.com/benhook1013/FireMUD/actions/runs/37079397170) finished with aggregate failure. Account passed; independently parsed raw XML proves its three canonical scope/journal and six retained outbox methods executed cleanly, with no skips. Game Session's catalog suite executed all five methods: four passed, including concurrent exact recovery and fresh-versus-retained isolation; the retained-preservation case failed at its plain catalog-TRUNCATE error-message assertion. V13's pointer foreign key rejects that statement before its expected immutable trigger. The focused fixture correction separately checks that FK rejection and disposable-schema CASCADE immutable-trigger rejection, retaining original result/state readback. The eight CLOSED-pointer cases were skipped after that failure and have no matching XML artifact; they remain unproved. Missing LOGIN XML is unavailable dependent proof, not an executed LOGIN regression. Game Design's authored-world verifier passed its required cases but has no uploaded raw XML, while its broader duplicate-tenant fixture and shared tooling failures remain separately owned. Corrected exact-head database, fresh-image and live proof remain gates. + +The bounded catalog fixture correction passed the full local Game Session check, boot JAR, formatting, static analysis, coverage and documentation in41s/134tasks (20executed/114up-to-date). Unchanged unit/cross-service results were reused; PostgreSQL methods still skipped without Docker. This is proof of the correction's compilation/static boundary, not corrected PostgreSQL execution or proof of the independently prepared Account receipt extension. + +The owner-local Game Session CLOSED batch creates initial canonical `CLOSED` routing in the existing pointer and event families, tied to the exact committed V12 catalog. V13 preserves retained numeric rows as representation one and partitions legacy selectors from canonical targetless rows. The pointer, append-only audit and immutable request outcome must commit atomically; separate committed readback verifies the complete catalog and original request/result digests. This batch supplies no `OPEN` transition, admissible instance, World readiness, authenticated workflow or admission. Three unit cases and eight PostgreSQL methods cover actual producer digest vectors, exact retry, both concurrent commits, rollback, owner transaction/isolation, partial-triple denial and complete pre-V13 pointer/event JSON preservation. All eight PostgreSQL methods skipped locally without Docker; corrected exact-head runner execution remains required. + +The corrected combined Account/Game Session checks, both boot JARs, formatting, static analysis, coverage, links and Markdown passed58s/157tasks (20executed/137up-to-date). Same-code XML has690 Account and1,914 Game Session clean unit executions,18 non-Docker integration and26 cross-service executions; unchanged unit/cross-service results were reused in the final gate. Account254integration and Game Session17unit/165integration/54cross-service cases skipped locally. Root independently reproduced both Unicode request/receipt vectors. The existing H2 fixture now includes the retained representation-one default; five nullable fixture readbacks require actual rows before dereference. A constructor-local suppression documents CLOSED's intentionally absent instance; no production guard or general analyzer filter is weakened. Actionlint,25 CI-scope contracts and Flyway12sets/138files passed. Fresh-image/live proof and runtime activation remain open. + +Exact preceding #2949 `3400ad31a62bc0231729a119450458733550dd54` [CI37075247821](https://github.com/benhook1013/FireMUD/actions/runs/37075247821) passed Account and executed all three new scope/journal cases once without skips, failures or errors. Root parsed20 raw component XMLs proving160 unique clean executions. Game Session's authored-world source fixture failed its plain-TRUNCATE immutable-message assertion after V12 added referring foreign keys; the catalog step then skipped with no matching XML. Its local correction proves plain FK denial and disposable-schema CASCADE immutable-trigger denial separately, preserving original receipt/row-count readback. Catalog/CLOSED proof selectors now use their actual integration package. All five catalog methods and the eight CLOSED methods still require corrected runner execution; missing LOGIN XML is unavailable dependent proof, not an executed LOGIN failure. + +The next OPEN boundary needs implementation convergence with General's World bootstrap contract: the approved initial-admission hold now has explicit `NO_PRIOR_POINTER` and `EXPECT_CLOSED(pointerVersion, catalogRevision)` modes, but the separately published numeric hold is not a canonical UUID launch association. Existing numeric fixture identities cannot be guessed into canonical UUIDs. The CLOSED storage primitive and local locked-origin check do not resolve or bypass the remaining World hold and authenticated commit/abort readback gates. The contract extension is approved; implementation and executed composition proof remain open. + +The canonical JOIN producer preparation now widens the existing Account scope and operation families in V46/V47, rather than creating parallel journals. Incoming retries require the original bearer and exact persisted Account/tenant source; hash-only readback cannot reconstruct that bearer or authorize admission. V1 scope bytes, intent digests, request-ID reservations and retained history stay unchanged. V2 intents remain `PENDING`; only one exact available entitlement result may bind its policy digest, while unavailable authority records diagnostics without a policy result/version. Legacy writers and reconciliation cannot interpret or terminalize V2 rows. Complete UUID entitlement/current-target revalidation, positive membership/role/event/receipt/audit commit and canonical reconciliation remain unimplemented gates. + +Game Session's V12 owner-local initial catalog allocates and atomically persists the realm and its SHARED or ISOLATED playable namespace from exact committed fresh authored-world intake. It preserves retained numeric namespace bytes and tenant-selector uniqueness in the existing SHARED family; canonical fresh rows create no numeric alias, and ISOLATED allocations do not enter that registry. Stable-request recovery, changed-input denial, transaction isolation and fresh-versus-retained source fences have focused fixtures. The PostgreSQL-only SHARED-family identity reshape is deliberately excluded from H2/jOOQ schema emulation because its implicit primary-key name differs; production migrations and real PostgreSQL proof remain authoritative, and the explicit SQL repository does not depend on generated canonical SHARED columns. This primitive neither opens a pointer nor proves World lifecycle, creator authorization, admission or a completed catalog transport. + +The prepared scope/journal fixture has three PostgreSQL methods, and the catalog fixture has five. CI requires every exact method and captures raw XML. Their compilation/static proof and executed runner results must be recorded separately; authored tests and Docker-disabled skips are not PostgreSQL execution. Runtime RPC, credential/context/catalog activation remain denied and the Account-ring mount remains unpublished. + +The corrected composed Account/Game Session full checks, both boot JARs, formatting, Checkstyle, SpotBugs, coverage, links and Markdown passed in1m50s/158tasks (34executed/124up-to-date). Same-code XML contains690 Account and1,911 Game Session clean unit executions,18 Game Session non-Docker integration and26 cross-service executions; unchanged Game Session unit/integration results were reused in the final gate. Account254integration and Game Session17unit/157integration/54cross-service cases skipped locally, including all eight new database methods. Initial gates exposed six ambiguous generic transaction assertions and an obsolete suppression; their bounded fixes retain all guards and no-mutation/history assertions. Actionlint,25CI-scope contracts,Flyway12sets/137files and diff hygiene passed. Exact composed runner execution and fresh-image/live proof remain open. + +Exact parent #2945 `e9595b4daae3131aba182a57517ede2d0f05b1ec` [CI37071975351](https://github.com/benhook1013/FireMUD/actions/runs/37071975351) passed Account and Game Session while aggregate validation remained red on concrete Python/dev-demo/Common Platform/Automation/Game Design failures. Root verified24 raw component XMLs with191 unique clean executions, zero skips. Account's final integration task passed but the retained-row assertion has no separately uploaded case XML. This parent evidence does not cover the later V46/V47/V12 batch above or enable admission. The source-to-cutoff reconciliation preserves Account's LEFT receipt migration at V42 and mechanically places the child logout-all receipt migration at V42.1, before the already-preserved downstream V43–V55 lineage. The logout SQL bytes and immutable receipt/event guards are unchanged; both behaviors remain present rather than selecting one duplicate version. This prepares a collision-free unapplied candidate, not permission to renumber an applied migration or repair retained Flyway history. Deployment still requires exact owning-environment migration inventory and retained-data readback; a conflicting applied history must remain a fail-closed rollout gate. Historical component executions below do not prove this newly composed migration sequence or enable any runtime path. Exact #2945 checkpoint `91a001128df72ce83e8c9784e50457e267b7b582` [CI37061673261](https://github.com/benhook1013/FireMUD/actions/runs/37061673261) executed all67 targeted cases with zero skips, failures or errors: canonical Account membership1, Game Session owner migration1/instance identity1, membership PostgreSQL/socket2, issuer PostgreSQL/socket22, issuer mTLS14/Redis8, acknowledgment8, capture9 and mock-backed LOGIN1. Root independently parsed and hashed the raw XML. Both corrected UUID fixtures are runner-proved. Game Session passed; Account's later aggregate check exposed a stale retained-row test projection: V45 adds four explicitly unbridged membership metadata fields while all preexisting values match. The scoped correction compares every original field unchanged and separately proves the new null/source provenance slots. Corrected aggregate execution remains required; other jobs retain their concrete failures. This is not complete positive fresh JOIN, live readiness or activation proof; the ring mount remains unpublished and runtime paths denied. Earlier exact-head failures below preserve their historical attribution. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 8fe028a652..e4d3e9485a 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -23,7 +23,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | [Authentication](../../architecture/system-architecture-authentication.md) owns target tenant-scoped selector rules; [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) records local handling. Current exact browse ordinals are snapshot-bound, but the pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` selectors are unavailable. Unique bare `worldSlug` resolution is current implementation drift; target behavior prohibits it. V2 enforces tenant-local selector uniqueness and V6 persists generated realm/namespace IDs for retained supported rows, but canonical `{tenantId, realmId}` repository addressing, retained catalog-to-realm mapping, and PostgreSQL cross-tenant proof remain open. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production discovery and scope issuance are implemented locally; positive admission and namespace-qualified roster proof remain unavailable. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target receives retryable `AUTH_UNAVAILABLE`, while unbound private selectors retain the generic hidden projection. The legacy Account grant reader is slug-only and does not prove private gameplay admission; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | -| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V11__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V12__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, V11 child cardinality guard, V11.1 canonical instance UUID, then V12 child tenant lookup index. The V11/V12 files preserve the child SQL bytes. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup) stays activation-blocked pending exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail migration rather than selecting or deleting a survivor. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | +| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V11__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V12__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, V11 child cardinality guard, V11.1 canonical instance UUID, then V12 child tenant lookup index, V12.1 canonical realm catalog and V13 canonical CLOSED pointer. The V11/V12 files preserve the child SQL bytes. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup) stays activation-blocked pending exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail migration rather than selecting or deleting a survivor. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Authenticated registration/transport for explicit `CLOSED` and canonical `{tenantId, realmId}` addressing, retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources 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 a3e6d38957..c586713792 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,12 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The canonical launch correction must also supply genuinely fresh instance creation, not merely attach a UUID carrier to the legacy prepare call: Game Session's `game_instances.tenant_id` and World's lifecycle/topology tenant selectors remain required numeric fields on this tree. A fresh canonical catalog provides no numeric tenant alias. Widen the actual owner instance/lifecycle representation and source-qualified creation/readback together; adding a binding table while inventing a numeric tenant selector would not close this gate. Exact retained instance associations remain separately source-proved and cannot be inferred from the Game Session row number or an Account mapping. + +The [Game Design authored-world source](../../architecture/microservices/game-design-service/api-contracts.md#authored-world-source-registration-and-game-session-readback) proves selector provenance, not a release or a World template lookup. Its private source game key cannot be reused as a World tenant association. Overseer approved the binding correction at Game Design's existing immutable launch-descriptor owner, with Game Session retaining orchestration and World requiring authenticated durable binding/readback before `PREPARING`. Downstream owner contracts and producer implementation are in preparation, not published or proved canonical materialization or activation. The Game Design version-state and World lifecycle epochs remain distinct. + +The canonical Unit 1B tree does not yet contain a persisted authenticated launch association from Game Session's canonical catalog/instance identities to World's lifecycle row. Existing start/prepare paths still carry numeric tenant/instance/template/version selectors and drop the persisted Game Session instance UUID; the fresh canonical catalog deliberately supplies no numeric tenant alias. The separately prepared #2939 numeric `NO_PRIOR_POINTER` hold is therefore not a compatible canonical first-OPEN handoff. Required work is an explicit persisted owner launch binding and authenticated exact readback, both tagged initial-hold modes, an ACTIVE epoch fence, termination blocking while unresolved, and atomic Game Session pointer/audit/outcome proof. Retained associations require authoritative source evidence rather than guessed mapping. See the [initial hold owner contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-hold-contract). No canonical World hold, OPEN runtime composition or activation is claimed by the current receipt/CLOSED checkpoint. + This tracker is the permanent reader-facing implementation record for world runtime, room reads, movement, lifecycle orchestration, and Draft topology mutation. Canonical target-state design remains under [design/architecture](../../architecture/README.md). The initial-admission implementation now includes the typed Game Session workload-only acquire RPC, a durable World hold, lifecycle-row termination serialization, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The opt-in run-owned local Compose coordinator now drives the hold from Game Session’s durable initial-bind intent and resolves it only through exact authenticated owner proof. Raw Game Session `RUNNING` and World `ACTIVE` runtime seeds have been removed; local World metadata seeding retains versioned template rooms `1021` and `2045` for the current transitional movement contract. The focused unit-test anchors in the capability table cover service-local seams; PostgreSQL race/restart and live Compose proof remain unclaimed. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract) and the [Game Session implementation status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind). diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { diff --git a/protos/logging-admin/v1/README.md b/protos/logging-admin/v1/README.md index 74aa089125..4874a132e0 100644 --- a/protos/logging-admin/v1/README.md +++ b/protos/logging-admin/v1/README.md @@ -5,3 +5,7 @@ They describe the gRPC API exposed by the service. Generate Java stubs with `./gradlew generateProto` from the repository root. For details see the [design docs](../../../design/architecture/microservices/logging-admin-service/README.md). + +The existing Account audit create and receipt-read messages carry the explicit tenant identity +version and UUID fields at tags 11 and 12; see the [audit ingress contract](../../../design/architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) +for their versioned scope rules. diff --git a/protos/logging-admin/v1/logging_admin_service.proto b/protos/logging-admin/v1/logging_admin_service.proto index 6871831122..29045e4466 100644 --- a/protos/logging-admin/v1/logging_admin_service.proto +++ b/protos/logging-admin/v1/logging_admin_service.proto @@ -50,6 +50,9 @@ message CreateLogEventRequest { bytes payload = 11; int32 payload_digest_version = 12; string payload_digest = 13; + // Version 1 carries the retained numeric tenant identity; version 2 carries tenant_uuid. + int32 tenant_identity_version = 14; + string tenant_uuid = 15; } message CreateLogEventResponse { @@ -67,6 +70,8 @@ message CreateLogEventResponse { // Version 1 attests an exact receipt linked atomically to a distinct audit log projection. // Zero or unsupported versions cannot verify delivery or historical producer provenance. int32 audit_projection_version = 12; + int32 tenant_identity_version = 13; + string tenant_uuid = 14; } message ReadLogEventReceiptRequest { @@ -80,6 +85,8 @@ message ReadLogEventReceiptRequest { bytes payload = 8; int32 payload_digest_version = 9; string payload_digest = 10; + int32 tenant_identity_version = 11; + string tenant_uuid = 12; } message ReadLogEventReceiptResponse { @@ -97,6 +104,8 @@ message ReadLogEventReceiptResponse { // Same receipt/projection attestation as CreateLogEventResponse; never payload replay proof. // Zero or unsupported versions cannot verify delivery or historical producer provenance. int32 audit_projection_version = 12; + int32 tenant_identity_version = 13; + string tenant_uuid = 14; } enum AccountAuditScope { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java index 2565777ef2..65ff949b59 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java @@ -2,6 +2,8 @@ import com.google.protobuf.ByteString; import com.google.protobuf.Timestamp; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import jakarta.annotation.PostConstruct; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -11,6 +13,7 @@ import javax.net.ssl.SSLException; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; @@ -22,6 +25,8 @@ import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -65,24 +70,56 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( /** Send one unchanged owner-local outbox envelope and verify the exact receiver receipt. */ public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { - AccountAuditScope scope; - if ("platform".equals(envelope.scope())) { - if (envelope.tenantId() != null) { - throw new IllegalArgumentException("Platform audit events must not carry a tenant ID"); - } - scope = AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM; - } else if ("tenant".equals(envelope.scope())) { - if (envelope.tenantId() == null || envelope.tenantId() <= 0) { - throw new IllegalArgumentException("Tenant audit events require a positive tenant ID"); + CreateLogEventRequest request = toCreateRequest(envelope); + try { + CreateLogEventResponse response = + stub().withDeadlineAfter(5, TimeUnit.SECONDS).createLogEvent(request); + requireSupportedReceiptProjection( + response.hasError(), response.getError().getCode(), response.getAuditProjectionVersion()); + return verifyReceipt( + envelope, + response.getScope(), + response.getTenantId(), + response.getTenantIdentityVersion(), + response.getTenantUuid(), + response.getAuditEventId(), + response.getSchemaVersion(), + response.getPayloadDigestVersion(), + response.getPayloadDigest(), + response.getStatus(), + response.getOutcome(), + response.getReceiptId(), + response.getLogEventId()); + } catch (StatusRuntimeException ex) { + if (!mayHaveCommitted(ex.getStatus().getCode())) { + throw ex; } - scope = AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT; - } else { - throw new IllegalArgumentException("Account audit scope must be platform or tenant"); + ReadLogEventReceiptResponse response = + stub().withDeadlineAfter(5, TimeUnit.SECONDS).readLogEventReceipt(toReadRequest(request)); + requireSupportedReceiptProjection( + response.hasError(), response.getError().getCode(), response.getAuditProjectionVersion()); + return verifyReceipt( + envelope, + response.getScope(), + response.getTenantId(), + response.getTenantIdentityVersion(), + response.getTenantUuid(), + response.getAuditEventId(), + response.getSchemaVersion(), + response.getPayloadDigestVersion(), + response.getPayloadDigest(), + response.getStatus(), + response.getOutcome(), + response.getReceiptId(), + response.getLogEventId()); } + } + private static CreateLogEventRequest toCreateRequest(AccountAuditEnvelope envelope) { CreateLogEventRequest.Builder builder = CreateLogEventRequest.newBuilder() - .setScope(scope) + .setScope(scopeFor(envelope)) + .setTenantIdentityVersion(envelope.tenantIdentityVersion()) .setAuditEventId(envelope.auditEventId().toString()) .setProducerService(envelope.producerService()) .setEventType(envelope.eventType()) @@ -98,44 +135,99 @@ public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { if (envelope.tenantId() != null) { builder.setTenantId(envelope.tenantId().toString()); } - CreateLogEventResponse response = - stub().withDeadlineAfter(5, TimeUnit.SECONDS).createLogEvent(builder.build()); - if (response.hasError()) { - String errorCode = response.getError().getCode(); + if (envelope.tenantUuid() != null) { + builder.setTenantUuid(envelope.tenantUuid().toString()); + } + return builder.build(); + } + + private static ReadLogEventReceiptRequest toReadRequest(CreateLogEventRequest request) { + return ReadLogEventReceiptRequest.newBuilder() + .setScope(request.getScope()) + .setTenantId(request.getTenantId()) + .setTenantIdentityVersion(request.getTenantIdentityVersion()) + .setTenantUuid(request.getTenantUuid()) + .setAuditEventId(request.getAuditEventId()) + .setProducerService(request.getProducerService()) + .setEventType(request.getEventType()) + .setOccurredAt(request.getOccurredAt()) + .setSchemaVersion(request.getSchemaVersion()) + .setPayload(request.getPayload()) + .setPayloadDigestVersion(request.getPayloadDigestVersion()) + .setPayloadDigest(request.getPayloadDigest()) + .build(); + } + + private static AccountAuditScope scopeFor(AccountAuditEnvelope envelope) { + return switch (envelope.scope()) { + case "platform" -> AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM; + case "tenant" -> AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT; + default -> + throw new IllegalArgumentException("Account audit scope must be platform or tenant"); + }; + } + + private static void requireSupportedReceiptProjection( + boolean hasError, String errorCode, int auditProjectionVersion) { + if (hasError) { if (errorCode == null || !errorCode.matches("[A-Z][A-Z0-9_]{0,63}")) { errorCode = "UNKNOWN"; } throw new IllegalStateException("Account audit receiver returned error code " + errorCode); } - if (response.getAuditProjectionVersion() != 1) { + if (auditProjectionVersion != 1) { throw new IllegalStateException( "Account audit receiver did not prove a supported audit projection version"); } - if (!response.getAuditEventId().equals(envelope.auditEventId().toString()) - || !response.getPayloadDigest().equals(envelope.payloadDigest()) - || response.getSchemaVersion() != envelope.schemaVersion() - || response.getPayloadDigestVersion() != envelope.payloadDigestVersion() - || response.getScope() != builder.getScope() - || !response.getTenantId().equals(builder.getTenantId())) { + } + + private static boolean mayHaveCommitted(Status.Code code) { + return code == Status.Code.CANCELLED + || code == Status.Code.DEADLINE_EXCEEDED + || code == Status.Code.INTERNAL + || code == Status.Code.UNKNOWN + || code == Status.Code.UNAVAILABLE; + } + + private static AuditDeliveryResult verifyReceipt( + AccountAuditEnvelope envelope, + AccountAuditScope scope, + String tenantId, + int tenantIdentityVersion, + String tenantUuid, + String auditEventId, + int schemaVersion, + int payloadDigestVersion, + String payloadDigest, + AccountAuditReceiptStatus status, + AccountAuditReceiptOutcome outcome, + String receiptId, + String logEventId) { + String expectedTenantId = envelope.tenantId() == null ? "" : envelope.tenantId().toString(); + String expectedTenantUuid = + envelope.tenantUuid() == null ? "" : envelope.tenantUuid().toString(); + if (!auditEventId.equals(envelope.auditEventId().toString()) + || !payloadDigest.equals(envelope.payloadDigest()) + || schemaVersion != envelope.schemaVersion() + || payloadDigestVersion != envelope.payloadDigestVersion() + || scope != scopeFor(envelope) + || !tenantId.equals(expectedTenantId) + || tenantIdentityVersion != envelope.tenantIdentityVersion() + || !tenantUuid.equals(expectedTenantUuid)) { throw new IllegalStateException( "Account audit receiver returned mismatched receipt evidence"); } boolean minimized = - response.getStatus() == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED - && response.getOutcome() - == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE; + status == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED + && outcome == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE; boolean committed = - response.getStatus() == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED - && (response.getOutcome() - == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED - || response.getOutcome() - == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE); - if ((!committed && !minimized) - || response.getReceiptId().isBlank() - || response.getLogEventId().isBlank()) { + status == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED + && (outcome == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED + || outcome == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE); + if ((!committed && !minimized) || receiptId.isBlank() || logEventId.isBlank()) { throw new IllegalStateException("Account audit receiver did not prove a terminal receipt"); } - return new AuditDeliveryResult(response.getReceiptId(), response.getLogEventId(), minimized); + return new AuditDeliveryResult(receiptId, logEventId, minimized); } /** Existing deferred-commerce path remains best effort until its own outbox convergence. */ @@ -146,7 +238,7 @@ public void logPayment(long tenantId, long accountId, long transactionId) { new AccountAuditEnvelope( UUID.randomUUID(), "tenant", - tenantId, + AccountAuditTenantIdentity.retainedTenantV1(tenantId), "account-service", "PAYMENT_TXN", Instant.now(), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java index ff5e2700d3..345678e282 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditDigest.java @@ -1,23 +1,51 @@ package net.firedevops.firemud.accountservice.dto; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HexFormat; +import java.util.regex.Pattern; /** Receiver-version-1 digest over exact persisted UTF-8 payload bytes. */ public final class AccountAuditDigest { + private static final Pattern CANONICAL_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private AccountAuditDigest() {} public static String ofPayload(String payload) { + if (payload == null) { + throw new IllegalArgumentException("Account audit payload is required"); + } try { return "sha256:" + HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest(payload.getBytes(StandardCharsets.UTF_8))); + .formatHex(MessageDigest.getInstance("SHA-256").digest(strictUtf8(payload))); } catch (NoSuchAlgorithmException ex) { throw new IllegalStateException("SHA-256 is unavailable", ex); } } + + private static byte[] strictUtf8(String payload) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(payload)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException("Account audit payload is not valid Unicode", ex); + } + } + + public static boolean isValid(String digest) { + return digest != null && CANONICAL_DIGEST.matcher(digest).matches(); + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java index a99ebc70cb..ac534ecb6b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditEnvelope.java @@ -7,11 +7,45 @@ public record AccountAuditEnvelope( UUID auditEventId, String scope, - Long tenantId, + AccountAuditTenantIdentity tenantIdentity, String producerService, String eventType, Instant occurredAt, int schemaVersion, int payloadDigestVersion, String payloadDigest, - String payload) {} + String payload) { + public AccountAuditEnvelope { + if (auditEventId == null + || producerService == null + || eventType == null + || occurredAt == null + || schemaVersion <= 0 + || payloadDigestVersion != 1 + || payloadDigest == null) { + throw new IllegalArgumentException( + "Account audit envelope fields are incomplete or unsupported"); + } + if (tenantIdentity == null) { + throw new IllegalArgumentException("Account audit tenant identity is required"); + } + tenantIdentity.requireScope(scope); + if (!AccountAuditDigest.isValid(payloadDigest) + || (payload != null && !payloadDigest.equals(AccountAuditDigest.ofPayload(payload)))) { + throw new IllegalArgumentException( + "Account audit payload digest does not match exact UTF-8 bytes"); + } + } + + public Long tenantId() { + return tenantIdentity.tenantId(); + } + + public int tenantIdentityVersion() { + return tenantIdentity.version(); + } + + public UUID tenantUuid() { + return tenantIdentity.tenantUuid(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditTenantIdentity.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditTenantIdentity.java new file mode 100644 index 0000000000..bd82eb30f4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuditTenantIdentity.java @@ -0,0 +1,77 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; + +/** Explicit representation of the tenant identity carried by an Account audit envelope. */ +public record AccountAuditTenantIdentity(int version, Long tenantId, UUID tenantUuid) { + public static final int VERSION_1 = 1; + public static final int VERSION_2 = 2; + + public AccountAuditTenantIdentity { + if (version == VERSION_1) { + if (tenantUuid != null || (tenantId != null && tenantId <= 0)) { + throw new IllegalArgumentException( + "Version-1 audit identity must use a positive numeric ID"); + } + } else if (version == VERSION_2) { + if (tenantId != null || tenantUuid == null || isNil(tenantUuid)) { + throw new IllegalArgumentException( + "Version-2 audit identity must use a non-nil tenant UUID"); + } + } else { + throw new IllegalArgumentException("Unsupported Account audit tenant identity version"); + } + } + + public static AccountAuditTenantIdentity platformV1() { + return new AccountAuditTenantIdentity(VERSION_1, null, null); + } + + public static AccountAuditTenantIdentity retainedTenantV1(long tenantId) { + return new AccountAuditTenantIdentity(VERSION_1, tenantId, null); + } + + /** Strict wire/storage constructor; construction does not prove tenant ownership or authority. */ + public static AccountAuditTenantIdentity canonicalTenantV2(String tenantUuid) { + if (tenantUuid == null) { + throw new IllegalArgumentException("Canonical tenant UUID is required"); + } + final UUID parsed; + try { + parsed = UUID.fromString(tenantUuid); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Canonical tenant UUID is malformed", ex); + } + if (!tenantUuid.equals(parsed.toString())) { + throw new IllegalArgumentException("Canonical tenant UUID must use lowercase canonical form"); + } + return new AccountAuditTenantIdentity(VERSION_2, null, parsed); + } + + public void requireScope(String scope) { + Objects.requireNonNull(scope, "scope"); + boolean platformV1 = + "platform".equals(scope) && version == VERSION_1 && tenantId == null && tenantUuid == null; + boolean tenantV1 = + "tenant".equals(scope) + && version == VERSION_1 + && tenantId != null + && tenantId > 0 + && tenantUuid == null; + boolean tenantV2 = + "tenant".equals(scope) + && version == VERSION_2 + && tenantId == null + && tenantUuid != null + && !isNil(tenantUuid); + if (!platformV1 && !tenantV1 && !tenantV2) { + throw new IllegalArgumentException( + "Account audit scope and typed tenant identity must match"); + } + } + + private static boolean isNil(UUID value) { + return value.getMostSignificantBits() == 0L && value.getLeastSignificantBits() == 0L; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalMembershipTransitionReceipt.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalMembershipTransitionReceipt.java new file mode 100644 index 0000000000..c7268e9f23 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalMembershipTransitionReceipt.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +/** Canonical UUID evidence for a provisional membership transition, not an authority checkpoint. */ +public record CanonicalMembershipTransitionReceipt( + String receiptStreamKey, + long receiptSequence, + UUID receiptId, + String receiptDigest, + String evidenceStatus, + String transitionType, + String requestId, + UUID accountId, + UUID tenantId, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + Map membershipVersion, + long membershipAuthorityGeneration, + String authorityProvenance, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest) { + + public CanonicalMembershipTransitionReceipt { + requestId = MembershipTransitionReceiptDigest.requireRequestIdV2(requestId); + accountId = MembershipTransitionReceiptDigest.requireCanonicalUuid(accountId, "accountId"); + tenantId = MembershipTransitionReceiptDigest.requireCanonicalUuid(tenantId, "tenantId"); + receiptStreamKey = Objects.requireNonNull(receiptStreamKey, "receiptStreamKey"); + receiptId = Objects.requireNonNull(receiptId, "receiptId"); + receiptDigest = + MembershipTransitionReceiptDigest.requireSha256Digest(receiptDigest, "receiptDigest"); + evidenceStatus = Objects.requireNonNull(evidenceStatus, "evidenceStatus"); + transitionType = Objects.requireNonNull(transitionType, "transitionType"); + membershipLifecycleState = + Objects.requireNonNull(membershipLifecycleState, "membershipLifecycleState"); + authorityProvenance = Objects.requireNonNull(authorityProvenance, "authorityProvenance"); + tenantProvenanceKind = Objects.requireNonNull(tenantProvenanceKind, "tenantProvenanceKind"); + tenantSourceOperationId = + MembershipTransitionReceiptDigest.requireCanonicalUuid( + tenantSourceOperationId, "tenantSourceOperationId"); + tenantProvenanceDigest = + MembershipTransitionReceiptDigest.requireSha256Digest( + tenantProvenanceDigest, "tenantProvenanceDigest"); + if (receiptSequence <= 0L || membershipAuthorityGeneration <= 0L) { + throw new IllegalArgumentException("Canonical membership receipt counters must be positive"); + } + if (!MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(evidenceStatus)) { + throw new IllegalArgumentException("Canonical membership receipt evidence status is invalid"); + } + if (!MembershipTransitionReceiptDigest.receiptIdForRequestV2(requestId).equals(receiptId)) { + throw new IllegalArgumentException( + "Canonical membership receipt ID does not match request ID"); + } + if (membershipVersion == null + || membershipVersion.size() != 1 + || !membershipVersion.containsKey(tenantId.toString())) { + throw new IllegalArgumentException( + "Canonical membership version must contain exactly its tenant UUID"); + } + String version = membershipVersion.get(tenantId.toString()); + MembershipTransitionReceiptDigest.requirePositiveDecimal(version, "membershipVersion"); + membershipVersion = Map.of(tenantId.toString(), version); + + if (!"APPROVED_RETAINED".equals(tenantProvenanceKind) + && !"FRESH_GAME_DESIGN".equals(tenantProvenanceKind)) { + throw new IllegalArgumentException("Canonical membership tenant provenance is unsupported"); + } + boolean activeTransition = + "MEMBERSHIP_JOINED".equals(transitionType) + || "MEMBERSHIP_REACTIVATED".equals(transitionType); + boolean leaveTransition = "MEMBERSHIP_LEFT".equals(transitionType); + if ((!activeTransition && !leaveTransition) + || (activeTransition + && (!"ACTIVE".equals(membershipLifecycleState) || !gameplayAdmissionAllowed)) + || (leaveTransition + && (!"INACTIVE".equals(membershipLifecycleState) || gameplayAdmissionAllowed)) + || !"EXPLICIT_JOIN".equals(authorityProvenance)) { + throw new IllegalArgumentException( + "Canonical membership receipt transition does not match its state and provenance"); + } + if (!MembershipTransitionReceiptDigest.receiptStreamKeyV2(accountId, tenantId) + .equals(receiptStreamKey)) { + throw new IllegalArgumentException("Canonical membership receipt stream key is inconsistent"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java index 79cf3fd5e6..a74d39a682 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/MembershipTransitionReceiptDigest.java @@ -1,9 +1,15 @@ package net.firedevops.firemud.accountservice.dto; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HexFormat; +import java.util.Map; import java.util.UUID; /** Deterministic SHA-256 digest for a provisional Account membership transition receipt only. */ @@ -12,6 +18,11 @@ public final class MembershipTransitionReceiptDigest { private static final String VERSIONED_RECEIPT_ID_PREFIX = "account-membership-transition-receipt/v1:"; + private static final String VERSIONED_RECEIPT_ID_V2_PREFIX = + "account-membership-transition-receipt/v2:"; + private static final String RECEIPT_STREAM_KEY_V2_PREFIX = + "account:membership-transition-receipt:v2:membership/"; + private static final String RECEIPT_DIGEST_V2_DOMAIN = "account-membership-transition-receipt/v2"; private MembershipTransitionReceiptDigest() {} @@ -98,6 +109,168 @@ public static String transitionDigest( } } + public static String receiptStreamKeyV2(UUID accountUuid, UUID tenantUuid) { + return RECEIPT_STREAM_KEY_V2_PREFIX + + requireCanonicalUuid(accountUuid, "accountUuid") + + "/" + + requireCanonicalUuid(tenantUuid, "tenantUuid"); + } + + public static UUID receiptIdForRequestV2(String requestId) { + String request = requireRequestIdV2(requestId); + return UUID.nameUUIDFromBytes( + strictUtf8(VERSIONED_RECEIPT_ID_V2_PREFIX + request, "requestId")); + } + + /** Computes the canonical V2 provisional receipt digest, excluding the digest field itself. */ + public static String transitionDigestV2(CanonicalMembershipTransitionReceipt receipt) { + if (receipt == null) { + throw new IllegalArgumentException("canonical membership receipt is required"); + } + String request = requireRequestIdV2(receipt.requestId()); + UUID accountUuid = requireCanonicalUuid(receipt.accountId(), "accountId"); + UUID tenantUuid = requireCanonicalUuid(receipt.tenantId(), "tenantId"); + UUID receiptId = receipt.receiptId(); + if (receiptId == null || !receiptId.equals(receiptIdForRequestV2(request))) { + throw new IllegalArgumentException("receiptId does not match the canonical request ID"); + } + requirePositive(receipt.receiptSequence(), "receiptSequence"); + requirePositive(receipt.membershipAuthorityGeneration(), "membershipAuthorityGeneration"); + String streamKey = requiredV2Field("receiptStreamKey", receipt.receiptStreamKey()); + if (!receiptStreamKeyV2(accountUuid, tenantUuid).equals(streamKey)) { + throw new IllegalArgumentException("receiptStreamKey does not match the canonical scope"); + } + String transition = requiredV2Field("transitionType", receipt.transitionType()); + String lifecycle = + requiredV2Field("membershipLifecycleState", receipt.membershipLifecycleState()); + String authority = requiredV2Field("authorityProvenance", receipt.authorityProvenance()); + String tenantKind = requiredV2Field("tenantProvenanceKind", receipt.tenantProvenanceKind()); + if (!EVIDENCE_STATUS.equals(receipt.evidenceStatus())) { + throw new IllegalArgumentException("evidenceStatus is not provisional transition evidence"); + } + boolean activeTransition = + "MEMBERSHIP_JOINED".equals(transition) || "MEMBERSHIP_REACTIVATED".equals(transition); + boolean leaveTransition = "MEMBERSHIP_LEFT".equals(transition); + if ((!activeTransition && !leaveTransition) + || (activeTransition + && (!"ACTIVE".equals(lifecycle) || !receipt.gameplayAdmissionAllowed())) + || (leaveTransition + && (!"INACTIVE".equals(lifecycle) || receipt.gameplayAdmissionAllowed())) + || !"EXPLICIT_JOIN".equals(authority)) { + throw new IllegalArgumentException( + "transitionType does not match canonical membership state"); + } + if (!"APPROVED_RETAINED".equals(tenantKind) && !"FRESH_GAME_DESIGN".equals(tenantKind)) { + throw new IllegalArgumentException("tenantProvenanceKind is unsupported"); + } + UUID sourceOperation = + requireCanonicalUuid(receipt.tenantSourceOperationId(), "tenantSourceOperationId"); + String sourceDigest = + requireSha256Digest(receipt.tenantProvenanceDigest(), "tenantProvenanceDigest"); + Map membershipVersion = receipt.membershipVersion(); + if (membershipVersion == null + || membershipVersion.size() != 1 + || !membershipVersion.containsKey(tenantUuid.toString())) { + throw new IllegalArgumentException("membershipVersion must contain exactly the tenant UUID"); + } + String version = + requirePositiveDecimal(membershipVersion.get(tenantUuid.toString()), "membershipVersion"); + + MessageDigest digest = sha256(); + frame(digest, RECEIPT_DIGEST_V2_DOMAIN); + frame(digest, "2"); + frame(digest, EVIDENCE_STATUS); + frame(digest, streamKey); + frame(digest, Long.toString(receipt.receiptSequence())); + frame(digest, receiptId.toString()); + frame(digest, transition); + frame(digest, request); + frame(digest, accountUuid.toString()); + frame(digest, tenantUuid.toString()); + frame(digest, lifecycle); + frame(digest, receipt.gameplayAdmissionAllowed() ? "true" : "false"); + frame(digest, tenantUuid.toString()); + frame(digest, version); + frame(digest, Long.toString(receipt.membershipAuthorityGeneration())); + frame(digest, authority); + frame(digest, tenantKind); + frame(digest, sourceOperation.toString()); + frame(digest, sourceDigest); + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } + + public static String requireRequestIdV2(String requestId) { + if (requestId == null || requestId.isBlank() || requestId.length() > 128) { + throw new IllegalArgumentException("requestId must contain 1 to 128 characters"); + } + strictUtf8(requestId, "requestId"); + return requestId; + } + + public static UUID requireCanonicalUuid(UUID value, String name) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + return value; + } + + public static String requirePositiveDecimal(String value, String name) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(name + " must be a canonical positive decimal"); + } + BigInteger parsed = new BigInteger(value); + if (parsed.signum() <= 0 || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(name + " must be a canonical positive decimal"); + } + return value; + } + + public static String requireSha256Digest(String value, String name) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be a lowercase SHA-256 digest"); + } + return value; + } + + private static String requiredV2Field(String name, String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + strictUtf8(value, name); + return value; + } + + private static void frame(MessageDigest digest, String value) { + byte[] bytes = strictUtf8(value, "receipt preimage segment"); + digest.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + digest.update((byte) ':'); + digest.update(bytes); + } + + private static byte[] strictUtf8(String value, String name) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] result = new byte[encoded.remaining()]; + encoded.get(result); + return result; + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException(name + " is not strict UTF-8", ex); + } + } + + private static MessageDigest sha256() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + private static String field(String name, Object value) { String wireValue = value.toString(); requiredField(name, wireValue); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java index c850e5469f..ce48c3cd9d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -13,12 +13,14 @@ import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; import net.firedevops.firemud.accountservice.jooq.tables.records.AccountAuditOutboxRecord; import org.jooq.DSLContext; import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Owner-local audit identity, immutable envelope, and durable delivery state. */ @Repository @@ -32,18 +34,74 @@ public AccountAuditOutboxRepository(DSLContext dsl) { this.dsl = dsl; } + /** Source-only retained identity writer; every row it writes uses explicit tenant version 1. */ public AccountAuditEnvelope append( UUID auditEventId, String scope, Long tenantId, String eventType, String payload) { - if (!("platform".equals(scope) && tenantId == null) - && !("tenant".equals(scope) && tenantId != null && tenantId > 0)) { - throw new IllegalArgumentException("Audit scope and tenant ID must match"); + AccountAuditTenantIdentity identity = retainedIdentity(scope, tenantId); + return append(auditEventId, scope, identity, eventType, payload, false); + } + + /** + * Appends version-2 canonical tenant identity in the active Account owner write transaction. This + * storage boundary does not establish source authenticity, membership, or admission. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountAuditEnvelope appendCanonicalTenant( + UUID auditEventId, String canonicalTenantUuid, String eventType, String payload) { + requireReadWriteOwnerTransaction(); + return append( + auditEventId, + "tenant", + AccountAuditTenantIdentity.canonicalTenantV2(canonicalTenantUuid), + eventType, + payload, + true); + } + + /** + * Locks and returns only the exact original canonical envelope in the current owner transaction. + * A missing row returns empty; changed identity or immutable bytes fail closed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findExactCanonicalTenantEnvelopeForUpdate( + AccountAuditEnvelope expected) { + requireReadWriteOwnerTransaction(); + if (expected == null + || expected.tenantIdentityVersion() != AccountAuditTenantIdentity.VERSION_2 + || expected.payload() == null) { + throw new IllegalArgumentException("Exact canonical tenant audit envelope is required"); } + var found = + dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX) + .where(ACCOUNT_AUDIT_OUTBOX.AUDIT_EVENT_ID.eq(expected.auditEventId())) + .forUpdate() + .fetchOptional(this::toEnvelope); + found.ifPresent( + actual -> { + if (!actual.equals(expected)) { + throw new IllegalStateException( + "Canonical Account audit identity conflicts with its immutable original envelope"); + } + }); + return found; + } + + private AccountAuditEnvelope append( + UUID auditEventId, + String scope, + AccountAuditTenantIdentity identity, + String eventType, + String payload, + boolean canonicalWrite) { + identity.requireScope(scope); Instant occurredAt = Instant.now(); String digest = AccountAuditDigest.ofPayload(payload); AccountAuditOutboxRecord row = dsl.newRecord(ACCOUNT_AUDIT_OUTBOX); row.setAuditEventId(auditEventId); row.setScope(scope); - row.setTenantId(tenantId); + row.setTenantId(identity.tenantId()); + row.setTenantIdentityVersion(identity.version()); + row.setTenantUuid(identity.tenantUuid()); row.setProducerService("account-service"); row.setEventType(eventType); row.setOccurredAt(toLocalDateTime(occurredAt)); @@ -55,7 +113,23 @@ public AccountAuditEnvelope append( row.setDeliveryStatus("PENDING"); row.store(); row.refresh(); - return toEnvelope(row); + AccountAuditEnvelope stored = toEnvelope(row); + if (!stored.auditEventId().equals(auditEventId) + || !stored.scope().equals(scope) + || !stored.tenantIdentity().equals(identity) + || !stored.producerService().equals("account-service") + || !stored.eventType().equals(eventType) + || stored.schemaVersion() != 1 + || stored.payloadDigestVersion() != 1 + || !stored.payloadDigest().equals(digest) + || !payload.equals(stored.payload())) { + throw new IllegalStateException("Account audit outbox did not preserve its exact envelope"); + } + if (canonicalWrite && stored.tenantIdentityVersion() != AccountAuditTenantIdentity.VERSION_2) { + throw new IllegalStateException( + "Account audit outbox did not preserve canonical identity version"); + } + return stored; } public List pending(int limit, Instant dueBeforeOrAt) { @@ -154,6 +228,7 @@ public void markDelivered( String expectedStatus = minimized ? "MINIMIZED" : "COMMITTED"; if (durableRow != null && expectedStatus.equals(durableRow.getDeliveryStatus()) + && Integer.valueOf(1).equals(durableRow.getReceiverAuditProjectionVersion()) && Objects.equals(receiptId, durableRow.getReceiverReceiptId()) && Objects.equals(logEventId, durableRow.getReceiverLogEventId())) { return; @@ -187,7 +262,8 @@ private AccountAuditEnvelope toEnvelope(AccountAuditOutboxRecord row) { return new AccountAuditEnvelope( row.getAuditEventId(), row.getScope(), - row.getTenantId(), + new AccountAuditTenantIdentity( + row.getTenantIdentityVersion(), row.getTenantId(), row.getTenantUuid()), row.getProducerService(), row.getEventType(), toInstant(row.getOccurredAt()), @@ -197,6 +273,24 @@ private AccountAuditEnvelope toEnvelope(AccountAuditOutboxRecord row) { row.getPayload()); } + private static void requireReadWriteOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical Account audit identity requires an active read-write owner transaction"); + } + } + + private static AccountAuditTenantIdentity retainedIdentity(String scope, Long tenantId) { + if ("platform".equals(scope) && tenantId == null) { + return AccountAuditTenantIdentity.platformV1(); + } + if ("tenant".equals(scope) && tenantId != null && tenantId > 0) { + return AccountAuditTenantIdentity.retainedTenantV1(tenantId); + } + throw new IllegalArgumentException("Audit scope and retained tenant identity must match"); + } + public record JoinAuditEvidence( AccountAuditEnvelope envelope, String deliveryStatus, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java index 4a2470fc62..3dfcd09332 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java @@ -3,23 +3,39 @@ import static net.firedevops.firemud.accountservice.jooq.Tables.ACCOUNT_CONNECT_SCOPE_RECORDS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigDecimal; import java.time.Instant; +import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Durable, exact-byte scope evidence; its token hash is only a lookup key, never authority. */ @Repository -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected DSLContext is an internal Spring collaborator.") public class AccountConnectScopeRepository { + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern UTC_RFC3339 = + Pattern.compile( + "([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.([0-9]+))?Z"); + private static final String DELETE_EXPIRED_UNREFERENCED_SQL = "DELETE FROM account_connect_scope_records scope " + "WHERE scope.ctid IN (" @@ -33,6 +49,7 @@ public class AccountConnectScopeRepository { + " THEN candidate.connect_scope_expires_at::timestamptz <= CAST(? AS timestamptz) " + " ELSE FALSE " + " END " + + " AND candidate.scope_digest_version = 1 " + " AND NOT EXISTS (" + " SELECT 1 FROM account_join_operations operation " + " WHERE operation.scope_token_hash = candidate.scope_token_hash" @@ -43,11 +60,30 @@ public class AccountConnectScopeRepository { + ")"; private final DSLContext dsl; + private final AccountRepository accounts; + private final AccountTenantIdentityResolver retainedTenantIdentities; + private final FreshTenantIdentityAssociationRepository freshTenantIdentities; - public AccountConnectScopeRepository(DSLContext dsl) { - this.dsl = dsl; + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor validates injected internal collaborators; it neither publishes this " + + "nor invokes overridable methods.") + public AccountConnectScopeRepository( + DSLContext dsl, + AccountRepository accounts, + AccountTenantIdentityResolver retainedTenantIdentities, + FreshTenantIdentityAssociationRepository freshTenantIdentities) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.accounts = Objects.requireNonNull(accounts, "AccountRepository is required"); + this.retainedTenantIdentities = + Objects.requireNonNull( + retainedTenantIdentities, "Retained tenant identity reader is required"); + this.freshTenantIdentities = + Objects.requireNonNull(freshTenantIdentities, "Fresh tenant identity reader is required"); } + /** Retains the exact legacy numeric representation without rewriting its v1 digest. */ public void insert(VerifiedJoinScope scope) { dsl.insertInto(ACCOUNT_CONNECT_SCOPE_RECORDS) .set( @@ -90,7 +126,364 @@ public Optional findEvidenceByTokenHash(String scopeTokenH } return dsl.selectFrom(ACCOUNT_CONNECT_SCOPE_RECORDS) .where(ACCOUNT_CONNECT_SCOPE_RECORDS.SCOPE_TOKEN_HASH.eq(scopeTokenHash)) - .fetchOptional(AccountConnectScopeRepository::toEvidence); + .fetchOptional( + record -> { + requireRetainedV1(record); + return toEvidence(record); + }); + } + + /** + * Persists canonical UUID scope evidence beside retained v1 scope rows in the shared table. + * Caller identity, current target routing, and entitlement authorization remain owner-service + * responsibilities; this method proves only the supplied persisted Account and tenant sources. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void insertCanonical( + long privateAccountId, + CanonicalJoinScopeV2 scope, + VerifiedTenantProvenance tenantProvenance) { + requireOwnerTransaction(); + Objects.requireNonNull(scope, "Canonical JOIN scope is required"); + Objects.requireNonNull(tenantProvenance, "Verified tenant provenance is required"); + if (privateAccountId <= 0L) { + throw new IllegalArgumentException("A positive private Account row key is required"); + } + requireStoredScopeLengths(scope); + requireOrderedScopeTimes(scope); + verifyAccountIdentity(privateAccountId, scope.accountId()); + verifyTenantIdentity(scope.tenantId(), tenantProvenance); + + String tokenHash = AccountJoinDigest.tokenHash(scope.connectScopeId()); + String scopeDigest = AccountJoinDigest.scopeV2(scope); + CanonicalConnectScopeEvidence expected = + new CanonicalConnectScopeEvidence( + tokenHash, + privateAccountId, + "PUBLIC_PRODUCTION", + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + 2, + scopeDigest, + tenantProvenance); + + int inserted = + dsl.execute( + "INSERT INTO account_connect_scope_records " + + "(scope_token_hash, account_id, target_class, tenant_id, realm_id, world_slug, " + + "realm_slug, playable_state_namespace_id, playable_state_scope, game_instance_id, " + + "catalog_revision, pointer_version, evaluated_at, connect_scope_expires_at, " + + "snapshot_digest, scope_digest_version, account_uuid, tenant_uuid, tenant_slug, " + + "playable_state_namespace_uuid, game_instance_uuid, tenant_provenance_kind, " + + "tenant_provenance_legacy_tenant_id, tenant_source_operation_id, " + + "tenant_provenance_digest) " + + "VALUES (?, ?, ?, NULL, ?, ?, ?, NULL, ?, NULL, ?, ?, ?, ?, ?, 2, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (scope_token_hash) DO NOTHING", + expected.scopeTokenHash(), + expected.privateAccountId(), + expected.targetClass(), + expected.realmId(), + expected.worldSlug(), + expected.realmSlug(), + expected.playableStateScope(), + expected.catalogRevision(), + expected.pointerVersion(), + expected.evaluatedAt(), + expected.connectScopeExpiresAt(), + expected.scopeDigest(), + expected.accountUuid(), + expected.tenantUuid(), + expected.tenantSlug(), + expected.playableStateNamespaceUuid(), + expected.gameInstanceUuid(), + expected.tenantProvenance().kind().name(), + expected.tenantProvenance().legacyTenantId(), + expected.tenantProvenance().sourceOperationId(), + expected.tenantProvenance().digest()); + if (inserted < 0 || inserted > 1) { + throw new IllegalStateException("Canonical Account connect scope insert was ambiguous"); + } + + CanonicalConnectScopeEvidence committed = + readCanonicalEvidenceByTokenHash(tokenHash) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical Account connect scope insert readback is absent")); + if (!committed.equals(expected)) { + throw new CanonicalScopeConflictException( + "Canonical Account connect scope conflicts with immutable token-hash evidence"); + } + } + + /** + * Resolves a V2 scope only from the caller-supplied bearer and exact persisted owner evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCanonical(String connectScopeId) { + requireOwnerTransaction(); + Objects.requireNonNull(connectScopeId, "Connect scope bearer is required"); + if (connectScopeId.isBlank()) { + throw new IllegalArgumentException("Connect scope bearer is required"); + } + String tokenHash = AccountJoinDigest.tokenHash(connectScopeId); + return readCanonicalEvidenceByTokenHash(tokenHash) + .map( + evidence -> { + CanonicalJoinScopeV2 scope = toCanonicalScope(evidence, connectScopeId); + requireStoredScopeLengths(scope); + requireOrderedScopeTimes(scope); + if (!evidence.scopeDigest().equals(AccountJoinDigest.scopeV2(scope))) { + throw new IllegalStateException("Canonical JOIN scope digest mismatch"); + } + return scope; + }); + } + + /** + * Reads canonical V2 recovery evidence by its one-way hash. It does not reconstruct the bearer or + * recompute the token-dependent scope digest; callers must use owner operation evidence and exact + * immutable cross-readback for recovery. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCanonicalEvidenceByTokenHash( + String scopeTokenHash) { + requireOwnerTransaction(); + requireSha256(scopeTokenHash, "JOIN scope token hash"); + return readCanonicalEvidenceByTokenHash(scopeTokenHash); + } + + private Optional readCanonicalEvidenceByTokenHash( + String scopeTokenHash) { + Record record = + dsl.fetchOne( + "SELECT scope_token_hash, account_id, target_class, tenant_id, realm_id, world_slug, " + + "realm_slug, playable_state_namespace_id, playable_state_scope, game_instance_id, " + + "catalog_revision, pointer_version, evaluated_at, connect_scope_expires_at, " + + "snapshot_digest, scope_digest_version, account_uuid, tenant_uuid, tenant_slug, " + + "playable_state_namespace_uuid, game_instance_uuid, tenant_provenance_kind, " + + "tenant_provenance_legacy_tenant_id, tenant_source_operation_id, " + + "tenant_provenance_digest FROM account_connect_scope_records " + + "WHERE scope_token_hash = ?", + scopeTokenHash); + if (record == null) { + return Optional.empty(); + } + + CanonicalConnectScopeEvidence evidence = toCanonicalEvidence(record); + verifyAccountIdentity(evidence.privateAccountId(), evidence.accountUuid()); + verifyTenantIdentity(evidence.tenantUuid(), evidence.tenantProvenance()); + return Optional.of(evidence); + } + + private void verifyAccountIdentity(long privateAccountId, UUID expectedAccountUuid) { + Account account = + accounts + .findByIdForUpdate(privateAccountId) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical JOIN scope Account storage source is absent")); + if (account.getId() == null + || account.getId() != privateAccountId + || !expectedAccountUuid.equals(account.getAccountUuid()) + || !Objects.equals(account.getAccountUuidSourceNumericId(), privateAccountId) + || account.getAccountUuidProvenance() == null) { + throw new IllegalStateException( + "Canonical JOIN scope does not match the locked persisted Account identity"); + } + } + + private void verifyTenantIdentity( + UUID expectedTenantUuid, VerifiedTenantProvenance expectedProvenance) { + if (expectedProvenance.kind() == TenantProvenanceKind.APPROVED_RETAINED) { + ApprovedAssociation association = retainedTenantIdentities.resolve(expectedTenantUuid); + if (!expectedTenantUuid.equals(association.canonicalTenantId()) + || !Objects.equals(expectedProvenance.legacyTenantId(), association.legacyTenantId()) + || !expectedProvenance.sourceOperationId().equals(association.operationId()) + || !expectedProvenance.digest().equals(association.manifestDigest())) { + throw new IllegalStateException( + "Canonical JOIN scope retained tenant provenance differs from owner readback"); + } + return; + } + if (expectedProvenance.kind() == TenantProvenanceKind.FRESH_GAME_DESIGN) { + FreshTenantCreationEvidence association = + freshTenantIdentities + .read(expectedTenantUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical JOIN scope fresh tenant source is absent")); + if (!expectedTenantUuid.equals(association.canonicalTenantId()) + || expectedProvenance.legacyTenantId() != null + || !expectedProvenance.sourceOperationId().equals(association.operationId()) + || !expectedProvenance.digest().equals(association.evidenceDigest())) { + throw new IllegalStateException( + "Canonical JOIN scope fresh tenant provenance differs from owner readback"); + } + return; + } + throw new IllegalStateException("Canonical JOIN scope tenant provenance kind is unsupported"); + } + + private static CanonicalJoinScopeV2 toCanonicalScope( + CanonicalConnectScopeEvidence evidence, String connectScopeId) { + return new CanonicalJoinScopeV2( + connectScopeId, + evidence.accountUuid(), + evidence.tenantUuid(), + evidence.realmId(), + evidence.tenantSlug(), + evidence.worldSlug(), + evidence.realmSlug(), + evidence.playableStateNamespaceUuid(), + evidence.playableStateScope(), + evidence.gameInstanceUuid(), + evidence.catalogRevision(), + evidence.pointerVersion(), + evidence.evaluatedAt(), + evidence.connectScopeExpiresAt()); + } + + private static CanonicalConnectScopeEvidence toCanonicalEvidence(Record record) { + Integer digestVersion = record.get("scope_digest_version", Integer.class); + if (!Integer.valueOf(2).equals(digestVersion)) { + throw new IllegalStateException("JOIN scope is not canonical digest version 2"); + } + if (record.get("tenant_id", Long.class) != null + || record.get("game_instance_id", Long.class) != null + || record.get("playable_state_namespace_id", String.class) != null) { + throw new IllegalStateException("Canonical JOIN scope contains a numeric identity alias"); + } + + String sourceKind = required(record.get("tenant_provenance_kind", String.class), "tenant kind"); + TenantProvenanceKind tenantKind; + try { + tenantKind = TenantProvenanceKind.valueOf(sourceKind); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Canonical JOIN scope tenant provenance is invalid", exception); + } + VerifiedTenantProvenance tenantProvenance = + new VerifiedTenantProvenance( + record.get("tenant_provenance_legacy_tenant_id", Long.class), + tenantKind, + required( + record.get("tenant_source_operation_id", UUID.class), "tenant source operation"), + required(record.get("tenant_provenance_digest", String.class), "tenant source digest")); + return new CanonicalConnectScopeEvidence( + required(record.get("scope_token_hash", String.class), "scope token hash"), + required(record.get("account_id", Long.class), "private Account row key"), + required(record.get("target_class", String.class), "scope target"), + required(record.get("account_uuid", UUID.class), "Account UUID"), + required(record.get("tenant_uuid", UUID.class), "tenant UUID"), + required(record.get("realm_id", UUID.class), "realm UUID"), + required(record.get("tenant_slug", String.class), "tenant slug"), + required(record.get("world_slug", String.class), "world slug"), + required(record.get("realm_slug", String.class), "realm slug"), + required( + record.get("playable_state_namespace_uuid", UUID.class), "playable namespace UUID"), + required(record.get("playable_state_scope", String.class), "playable state scope"), + required(record.get("game_instance_uuid", UUID.class), "game instance UUID"), + required(record.get("catalog_revision", Long.class), "catalog revision"), + required(record.get("pointer_version", Long.class), "pointer version"), + required(record.get("evaluated_at", String.class), "scope evaluation time"), + required(record.get("connect_scope_expires_at", String.class), "scope expiry time"), + digestVersion, + required(record.get("snapshot_digest", String.class), "scope digest"), + tenantProvenance); + } + + private static T required(T value, String field) { + if (value == null) { + throw new IllegalStateException("Canonical JOIN scope is missing " + field); + } + return value; + } + + private static void requireSha256(String value, String field) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical Account connect scope access requires an active owner transaction"); + } + } + + private static void requireOrderedScopeTimes(CanonicalJoinScopeV2 scope) { + requireOrderedScopeTimes(scope.evaluatedAt(), scope.connectScopeExpiresAt()); + } + + private static void requireOrderedScopeTimes(String evaluatedAtText, String expiresAtText) { + BigDecimal evaluatedAt = epochSeconds(evaluatedAtText); + BigDecimal expiresAt = epochSeconds(expiresAtText); + if (expiresAt.compareTo(evaluatedAt) <= 0) { + throw new IllegalArgumentException( + "Canonical JOIN scope expiry must be after its exact evaluation time"); + } + } + + private static void requireStoredScopeLengths(CanonicalJoinScopeV2 scope) { + requireDatabaseCharacterLimit("tenantSlug", scope.tenantSlug(), 128); + requireDatabaseCharacterLimit("worldSlug", scope.worldSlug(), 128); + requireDatabaseCharacterLimit("realmSlug", scope.realmSlug(), 128); + requireDatabaseCharacterLimit("evaluatedAt", scope.evaluatedAt(), 40); + requireDatabaseCharacterLimit("connectScopeExpiresAt", scope.connectScopeExpiresAt(), 40); + } + + private static void requireDatabaseCharacterLimit(String field, String value, int limit) { + if (value.codePointCount(0, value.length()) > limit) { + throw new IllegalArgumentException( + "Canonical JOIN scope " + field + " exceeds its durable storage limit"); + } + } + + /** Compares exact RFC3339 seconds without changing or truncating their digest bytes. */ + private static BigDecimal epochSeconds(String timestamp) { + Matcher matcher = UTC_RFC3339.matcher(timestamp); + if (!matcher.matches()) { + throw new IllegalArgumentException("Canonical JOIN scope time is not exact UTC RFC3339"); + } + LocalDate date = + LocalDate.of( + Integer.parseInt(matcher.group(1)), + Integer.parseInt(matcher.group(2)), + Integer.parseInt(matcher.group(3))); + int hour = Integer.parseInt(matcher.group(4)); + int minute = Integer.parseInt(matcher.group(5)); + int second = Integer.parseInt(matcher.group(6)); + if (hour > 23 || minute > 59 || second > 60) { + throw new IllegalArgumentException("Canonical JOIN scope time is not valid UTC RFC3339"); + } + long wholeSeconds = + date.atStartOfDay().toEpochSecond(ZoneOffset.UTC) + + (hour * 60L + minute) * 60L + + Math.min(second, 59); + if (second == 60) { + wholeSeconds++; + } + BigDecimal exactTime = BigDecimal.valueOf(wholeSeconds); + String fraction = matcher.group(7); + if (fraction != null) { + exactTime = exactTime.add(new BigDecimal("0." + fraction)); + } + return exactTime; } private static ConnectScopeEvidence toEvidence(Record record) { @@ -131,6 +524,7 @@ public int deleteExpiredUnreferenced(Instant capturedNow, int batchSize) { } private VerifiedJoinScope toScope(Record record, String connectScopeId) { + requireRetainedV1(record); if (!"PUBLIC_PRODUCTION".equals(record.get(ACCOUNT_CONNECT_SCOPE_RECORDS.TARGET_CLASS))) { throw new IllegalStateException("JOIN scope is not public production"); } @@ -156,6 +550,81 @@ private VerifiedJoinScope toScope(Record record, String connectScopeId) { return scope; } + private static void requireRetainedV1(Record record) { + Integer version = record.get("scope_digest_version", Integer.class); + if (!Integer.valueOf(1).equals(version)) { + throw new IllegalStateException("JOIN scope is not retained digest version 1"); + } + } + + /** Hash-only V2 recovery evidence; intentionally contains no connectScopeId bearer. */ + public record CanonicalConnectScopeEvidence( + String scopeTokenHash, + long privateAccountId, + String targetClass, + UUID accountUuid, + UUID tenantUuid, + UUID realmId, + String tenantSlug, + String worldSlug, + String realmSlug, + UUID playableStateNamespaceUuid, + String playableStateScope, + UUID gameInstanceUuid, + long catalogRevision, + long pointerVersion, + String evaluatedAt, + String connectScopeExpiresAt, + int scopeDigestVersion, + String scopeDigest, + VerifiedTenantProvenance tenantProvenance) { + public CanonicalConnectScopeEvidence { + requireSha256(scopeTokenHash, "JOIN scope token hash"); + if (privateAccountId <= 0L + || !"PUBLIC_PRODUCTION".equals(targetClass) + || accountUuid == null + || accountUuid.equals(new UUID(0L, 0L)) + || tenantUuid == null + || tenantUuid.equals(new UUID(0L, 0L)) + || realmId == null + || realmId.equals(new UUID(0L, 0L)) + || tenantSlug == null + || tenantSlug.isEmpty() + || worldSlug == null + || worldSlug.isEmpty() + || realmSlug == null + || realmSlug.isEmpty() + || playableStateNamespaceUuid == null + || playableStateNamespaceUuid.equals(new UUID(0L, 0L)) + || playableStateScope == null + || (!"SHARED".equals(playableStateScope) && !"ISOLATED".equals(playableStateScope)) + || gameInstanceUuid == null + || gameInstanceUuid.equals(new UUID(0L, 0L)) + || catalogRevision <= 0L + || pointerVersion <= 0L + || evaluatedAt == null + || connectScopeExpiresAt == null + || scopeDigestVersion != 2 + || tenantProvenance == null) { + throw new IllegalArgumentException("Canonical JOIN scope evidence is incomplete"); + } + requireDatabaseCharacterLimit("tenantSlug", tenantSlug, 128); + requireDatabaseCharacterLimit("worldSlug", worldSlug, 128); + requireDatabaseCharacterLimit("realmSlug", realmSlug, 128); + requireDatabaseCharacterLimit("evaluatedAt", evaluatedAt, 40); + requireDatabaseCharacterLimit("connectScopeExpiresAt", connectScopeExpiresAt, 40); + requireOrderedScopeTimes(evaluatedAt, connectScopeExpiresAt); + requireSha256(scopeDigest, "Canonical JOIN scope digest"); + } + } + + /** Conflicting reuse of one scope-token hash cannot replace the original scope evidence. */ + public static final class CanonicalScopeConflictException extends IllegalStateException { + public CanonicalScopeConflictException(String message) { + super(message); + } + } + public record ConnectScopeEvidence( String scopeTokenHash, long accountId, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index b5daad6efb..85780d50aa 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -8,24 +8,51 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; import org.jooq.DSLContext; +import org.jooq.Record; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Serializes explicit JOIN on the global account row and retains exact operation outcomes. */ @Repository -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected DSLContext is an internal Spring collaborator.") public class AccountJoinOperationRepository { private static final int MAX_RECONCILIATION_PAGE_SIZE = 100; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final String CANONICAL_SELECT_COLUMNS = + "SELECT request_id, account_id, tenant_id, verified_caller_binding, scope_token_hash, " + + "connect_scope_digest, intent_digest_version, intent_digest, " + + "entitlement_authority_availability, allow_public_join, entitlement_version, " + + "request_digest_version, request_digest, last_attempt_failure_code, " + + "last_attempt_authority_availability, caller_bound_authority_invalidated, status, " + + "operation_representation_version, scope_digest_version, target_class, account_uuid, " + + "tenant_uuid, tenant_slug, realm_id, world_slug, realm_slug, " + + "playable_state_namespace_id, playable_state_namespace_uuid, playable_state_scope, " + + "game_instance_id, game_instance_uuid, catalog_revision, pointer_version " + + "FROM account_join_operations"; private final DSLContext dsl; + private final AccountConnectScopeRepository connectScopes; - public AccountJoinOperationRepository(DSLContext dsl) { - this.dsl = dsl; + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor validates injected internal collaborators; it neither publishes this " + + "nor invokes overridable methods.") + public AccountJoinOperationRepository( + DSLContext dsl, AccountConnectScopeRepository connectScopes) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.connectScopes = Objects.requireNonNull(connectScopes, "Connect scope reader is required"); } public void lockAccount(long accountId) { @@ -42,13 +69,13 @@ public void lockAccount(long accountId) { public Optional find(String requestId) { return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) - .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId)) + .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId).and(retainedV1Representation())) .fetchOptional(AccountJoinOperationRepository::toJoinOperation); } public Optional findForUpdate(String requestId) { return dsl.selectFrom(ACCOUNT_JOIN_OPERATIONS) - .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId)) + .where(ACCOUNT_JOIN_OPERATIONS.REQUEST_ID.eq(requestId).and(retainedV1Representation())) .forUpdate() .fetchOptional(AccountJoinOperationRepository::toJoinOperation); } @@ -66,6 +93,7 @@ public List findDuePendingReconciliation(Instant now, int limit) ACCOUNT_JOIN_OPERATIONS .STATUS .eq("PENDING") + .and(retainedV1Representation()) .and( ACCOUNT_JOIN_OPERATIONS.NEXT_RECONCILIATION_ATTEMPT_AT.le( toLocalDateTime(now)))) @@ -126,6 +154,7 @@ public boolean recordReconciliationAttempt( ACCOUNT_JOIN_OPERATIONS .REQUEST_ID .eq(requestId) + .and(retainedV1Representation()) .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING")) .and( ACCOUNT_JOIN_OPERATIONS.RECONCILIATION_ATTEMPT_COUNT.eq( @@ -177,6 +206,191 @@ public boolean insertIntent( return inserted == 1; } + /** + * Persists a policy-independent V2 intent in the shared global request-id journal. The exact + * bearer is required here so the immutable V46 scope and V2 intent preimages can be recomputed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public boolean insertCanonicalIntent( + String requestId, CanonicalJoinScopeV2 scope, String callerBinding) { + requireOwnerTransaction(); + requireCanonicalOperationInput(requestId, callerBinding); + Objects.requireNonNull(scope, "Canonical JOIN scope is required"); + CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); + String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); + + int inserted = + dsl.execute( + "INSERT INTO account_join_operations " + + "(request_id, account_id, tenant_id, verified_caller_binding, " + + "scope_token_hash, connect_scope_digest, world_slug, realm_slug, realm_id, " + + "playable_state_namespace_id, playable_state_scope, game_instance_id, " + + "catalog_revision, pointer_version, intent_digest_version, intent_digest, " + + "entitlement_authority_availability, caller_bound_authority_invalidated, " + + "last_attempt_authority_availability, status, operation_representation_version, " + + "scope_digest_version, target_class, account_uuid, tenant_uuid, tenant_slug, " + + "playable_state_namespace_uuid, game_instance_uuid) " + + "VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, NULL, ?, NULL, ?, ?, 2, ?, " + + "'NOT_EVALUATED', FALSE, 'NOT_EVALUATED', 'PENDING', 2, 2, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (request_id) DO NOTHING", + requestId, + scopeEvidence.privateAccountId(), + callerBinding, + scopeEvidence.scopeTokenHash(), + scopeEvidence.scopeDigest(), + scope.worldSlug(), + scope.realmSlug(), + scope.realmId(), + scope.playableStateScope(), + scope.catalogRevision(), + scope.pointerVersion(), + intentDigest, + scopeEvidence.targetClass(), + scopeEvidence.accountUuid(), + scopeEvidence.tenantUuid(), + scopeEvidence.tenantSlug(), + scopeEvidence.playableStateNamespaceUuid(), + scopeEvidence.gameInstanceUuid()); + if (inserted < 0 || inserted > 1) { + throw new IllegalStateException("Canonical JOIN intent insert was ambiguous"); + } + + CanonicalJoinOperationEvidence committed = + readCanonicalEvidenceByRequestId(requestId, false) + .orElseThrow( + () -> new IllegalStateException("Canonical JOIN intent insert readback is absent")); + requireCanonicalIntentMatch(committed, requestId, callerBinding, intentDigest, scopeEvidence); + return inserted == 1; + } + + /** + * Reads immutable V2 operation and scope facts by request ID without reconstructing a bearer or + * recomputing a token-dependent digest. This is structural recovery evidence, not authorization. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCanonicalEvidenceByRequestId( + String requestId) { + requireOwnerTransaction(); + requireRequestId(requestId); + return readCanonicalEvidenceByRequestId(requestId, false); + } + + /** Binds or exactly replays available V2 policy evidence under the Account and journal fences. */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinOperationEvidence bindCanonicalPolicyEvidence( + String requestId, + CanonicalJoinScopeV2 scope, + String callerBinding, + boolean allowPublicJoin, + long entitlementVersion) { + requireOwnerTransaction(); + requireCanonicalOperationInput(requestId, callerBinding); + Objects.requireNonNull(scope, "Canonical JOIN scope is required"); + CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); + String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); + String requestDigest = + AccountJoinDigest.requestV2( + scope, + callerBinding, + EntitlementAvailabilityV2.AVAILABLE, + allowPublicJoin, + entitlementVersion); + CanonicalJoinOperationEvidence operation = + lockCanonicalEvidenceByRequestId(requestId) + .orElseThrow( + () -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); + + if (operation.requestDigest() != null) { + requireCanonicalPolicyMatch(operation, requestDigest, allowPublicJoin, entitlementVersion); + return operation; + } + + int updated = + dsl.execute( + "UPDATE account_join_operations SET entitlement_authority_availability = 'AVAILABLE', " + + "entitlement_version = ?, allow_public_join = ?, request_digest_version = 2, " + + "request_digest = ?, last_attempt_authority_availability = 'AVAILABLE', " + + "last_attempt_failure_code = NULL, updated_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND operation_representation_version = 2 " + + "AND status = 'PENDING' AND request_digest IS NULL", + entitlementVersion, + allowPublicJoin, + requestDigest, + requestId); + if (updated != 1) { + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN operation changed before policy binding"); + } + + CanonicalJoinOperationEvidence committed = + readCanonicalEvidenceByRequestId(requestId, false) + .orElseThrow( + () -> + new IllegalStateException("Canonical JOIN policy binding readback is absent")); + requireCanonicalIntentMatch(committed, requestId, callerBinding, intentDigest, scopeEvidence); + requireCanonicalPolicyMatch(committed, requestDigest, allowPublicJoin, entitlementVersion); + return committed; + } + + /** Records unavailable policy without creating a policy result, entitlement version or digest. */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalJoinOperationEvidence recordCanonicalPolicyUnavailable( + String requestId, CanonicalJoinScopeV2 scope, String callerBinding, String failureCode) { + requireOwnerTransaction(); + requireCanonicalOperationInput(requestId, callerBinding); + Objects.requireNonNull(scope, "Canonical JOIN scope is required"); + if (failureCode == null || failureCode.isBlank() || failureCode.length() > 64) { + throw new IllegalArgumentException( + "JOIN attempt failure code must contain 1 to 64 characters"); + } + CanonicalConnectScopeEvidence scopeEvidence = requireIncomingScope(scope); + String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); + CanonicalJoinOperationEvidence operation = + lockCanonicalEvidenceByRequestId(requestId) + .orElseThrow( + () -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); + if (operation.requestDigest() != null) { + throw new CanonicalJoinOperationConflictException( + "Available canonical JOIN policy evidence cannot be downgraded"); + } + + int updated = + dsl.execute( + "UPDATE account_join_operations SET entitlement_authority_availability = 'UNAVAILABLE', " + + "last_attempt_authority_availability = 'UNAVAILABLE', " + + "last_attempt_failure_code = ?, updated_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND operation_representation_version = 2 " + + "AND status = 'PENDING' AND request_digest IS NULL", + failureCode, + requestId); + if (updated != 1) { + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN operation changed while recording policy unavailability"); + } + + CanonicalJoinOperationEvidence committed = + readCanonicalEvidenceByRequestId(requestId, false) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical JOIN unavailable-attempt readback is absent")); + requireCanonicalIntentMatch(committed, requestId, callerBinding, intentDigest, scopeEvidence); + if (!"UNAVAILABLE".equals(committed.entitlementAuthorityAvailability()) + || committed.entitlementVersion() != null + || committed.allowPublicJoin() != null + || committed.requestDigestVersion() != null + || committed.requestDigest() != null + || !failureCode.equals(committed.lastAttemptFailureCode())) { + throw new IllegalStateException( + "Canonical JOIN unavailable attempt readback contains policy evidence"); + } + return committed; + } + public void bindPolicyEvidence( String requestId, String requestDigest, Long entitlementVersion, Boolean allowPublicJoin) { int updated = @@ -193,6 +407,7 @@ public void bindPolicyEvidence( ACCOUNT_JOIN_OPERATIONS .REQUEST_ID .eq(requestId) + .and(retainedV1Representation()) .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING")) .and(ACCOUNT_JOIN_OPERATIONS.REQUEST_DIGEST.isNull())) .execute(); @@ -227,6 +442,7 @@ public void recordAttemptFailure( ACCOUNT_JOIN_OPERATIONS .REQUEST_ID .eq(requestId) + .and(retainedV1Representation()) .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) .execute(); if (updated != 1) { @@ -276,6 +492,7 @@ public void finish( ACCOUNT_JOIN_OPERATIONS .REQUEST_ID .eq(requestId) + .and(retainedV1Representation()) .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) .execute(); if (updated != 1) { @@ -291,6 +508,7 @@ public void recordCallerBoundAuthorityInvalidation(String requestId) { ACCOUNT_JOIN_OPERATIONS .REQUEST_ID .eq(requestId) + .and(retainedV1Representation()) .and(ACCOUNT_JOIN_OPERATIONS.STATUS.eq("PENDING"))) .execute(); if (updated != 1) { @@ -298,6 +516,273 @@ public void recordCallerBoundAuthorityInvalidation(String requestId) { } } + private Optional readCanonicalEvidenceByRequestId( + String requestId, boolean forUpdate) { + Record row = + dsl.fetchOne( + CANONICAL_SELECT_COLUMNS + " WHERE request_id = ?" + (forUpdate ? " FOR UPDATE" : ""), + requestId); + if (row == null) { + return Optional.empty(); + } + if (!Integer.valueOf(2).equals(row.get("operation_representation_version", Integer.class))) { + throw new CanonicalJoinOperationConflictException( + "JOIN request ID is retained in a different operation representation"); + } + String scopeTokenHash = required(row, "scope_token_hash", String.class); + CanonicalConnectScopeEvidence scopeEvidence = + connectScopes + .findCanonicalEvidenceByTokenHash(scopeTokenHash) + .orElseThrow( + () -> + new IllegalStateException("Canonical JOIN operation scope evidence is absent")); + return Optional.of(toCanonicalOperationEvidence(row, scopeEvidence)); + } + + private Optional lockCanonicalEvidenceByRequestId( + String requestId) { + // The source read locks the owning Account row before this operation-row lock, preserving the + // Account -> operation ordering used by JOIN and preventing an inversion during retries. + if (readCanonicalEvidenceByRequestId(requestId, false).isEmpty()) { + return Optional.empty(); + } + return readCanonicalEvidenceByRequestId(requestId, true); + } + + private CanonicalConnectScopeEvidence requireIncomingScope(CanonicalJoinScopeV2 scope) { + CanonicalJoinScopeV2 persisted = + connectScopes + .findCanonical(scope.connectScopeId()) + .orElseThrow( + () -> + new CanonicalJoinOperationConflictException( + "Canonical JOIN scope evidence is absent")); + if (!persisted.equals(scope)) { + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN scope differs from immutable token evidence"); + } + return connectScopes + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(scope.connectScopeId())) + .orElseThrow( + () -> new IllegalStateException("Canonical JOIN scope source readback is absent")); + } + + private static CanonicalJoinOperationEvidence toCanonicalOperationEvidence( + Record row, CanonicalConnectScopeEvidence scopeEvidence) { + Long accountId = required(row, "account_id", Long.class); + if (accountId.longValue() != scopeEvidence.privateAccountId() + || row.get("tenant_id", Long.class) != null + || row.get("game_instance_id", Long.class) != null + || row.get("playable_state_namespace_id", String.class) != null + || !Objects.equals(row.get("target_class", String.class), scopeEvidence.targetClass()) + || !Objects.equals(row.get("account_uuid", UUID.class), scopeEvidence.accountUuid()) + || !Objects.equals(row.get("tenant_uuid", UUID.class), scopeEvidence.tenantUuid()) + || !Objects.equals(row.get("tenant_slug", String.class), scopeEvidence.tenantSlug()) + || !Objects.equals(row.get("realm_id", UUID.class), scopeEvidence.realmId()) + || !Objects.equals(row.get("world_slug", String.class), scopeEvidence.worldSlug()) + || !Objects.equals(row.get("realm_slug", String.class), scopeEvidence.realmSlug()) + || !Objects.equals( + row.get("playable_state_namespace_uuid", UUID.class), + scopeEvidence.playableStateNamespaceUuid()) + || !Objects.equals( + row.get("playable_state_scope", String.class), scopeEvidence.playableStateScope()) + || !Objects.equals( + row.get("game_instance_uuid", UUID.class), scopeEvidence.gameInstanceUuid()) + || !Objects.equals(row.get("catalog_revision", Long.class), scopeEvidence.catalogRevision()) + || !Objects.equals(row.get("pointer_version", Long.class), scopeEvidence.pointerVersion()) + || !Objects.equals( + required(row, "scope_digest_version", Integer.class), + scopeEvidence.scopeDigestVersion()) + || !Objects.equals( + required(row, "connect_scope_digest", String.class), scopeEvidence.scopeDigest())) { + throw new IllegalStateException( + "Canonical JOIN operation contradicts its immutable scope source"); + } + + String status = required(row, "status", String.class); + if (!"PENDING".equals(status)) { + throw new IllegalStateException("Canonical JOIN operation has unsupported terminal evidence"); + } + return new CanonicalJoinOperationEvidence( + required(row, "request_id", String.class), + accountId, + required(row, "verified_caller_binding", String.class), + required(row, "scope_token_hash", String.class), + required(row, "connect_scope_digest", String.class), + required(row, "operation_representation_version", Integer.class), + required(row, "scope_digest_version", Integer.class), + required(row, "intent_digest_version", Integer.class), + required(row, "intent_digest", String.class), + required(row, "entitlement_authority_availability", String.class), + row.get("allow_public_join", Boolean.class), + row.get("entitlement_version", Long.class), + row.get("request_digest_version", Integer.class), + row.get("request_digest", String.class), + required(row, "last_attempt_authority_availability", String.class), + row.get("last_attempt_failure_code", String.class), + required(row, "caller_bound_authority_invalidated", Boolean.class), + status, + scopeEvidence); + } + + private static T required(Record row, String column, Class type) { + T value = row.get(column, type); + if (value == null) { + throw new IllegalStateException("Canonical JOIN operation is missing " + column); + } + return value; + } + + private static void requireCanonicalIntentMatch( + CanonicalJoinOperationEvidence operation, + String requestId, + String callerBinding, + String intentDigest, + CanonicalConnectScopeEvidence scopeEvidence) { + if (!requestId.equals(operation.requestId()) + || !callerBinding.equals(operation.callerBinding()) + || !intentDigest.equals(operation.intentDigest()) + || !scopeEvidence.equals(operation.scopeEvidence())) { + throw new CanonicalJoinOperationConflictException( + "JOIN request ID conflicts with canonical caller or scope intent"); + } + } + + private static void requireCanonicalPolicyMatch( + CanonicalJoinOperationEvidence operation, + String requestDigest, + boolean allowPublicJoin, + long entitlementVersion) { + if (!"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) + || !Objects.equals(operation.allowPublicJoin(), allowPublicJoin) + || !Objects.equals(operation.entitlementVersion(), entitlementVersion) + || !Integer.valueOf(2).equals(operation.requestDigestVersion()) + || !requestDigest.equals(operation.requestDigest())) { + throw new CanonicalJoinOperationConflictException( + "Canonical JOIN request ID conflicts with immutable available policy evidence"); + } + } + + private static void requireCanonicalOperationInput(String requestId, String callerBinding) { + requireRequestId(requestId); + if (callerBinding == null + || callerBinding.isBlank() + || callerBinding.codePointCount(0, callerBinding.length()) > 128) { + throw new IllegalArgumentException( + "Verified canonical JOIN caller binding must contain 1 to 128 characters"); + } + } + + private static void requireRequestId(String requestId) { + if (requestId == null + || requestId.isBlank() + || requestId.codePointCount(0, requestId.length()) > 128) { + throw new IllegalArgumentException("JOIN request ID must contain 1 to 128 characters"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical Account JOIN operation access requires an active owner transaction"); + } + } + + private static void requireSha256(String value, String field) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a lowercase SHA-256 digest"); + } + } + + private static org.jooq.Condition retainedV1Representation() { + return org.jooq.impl.DSL.field("operation_representation_version", Integer.class).eq(1); + } + + /** Hash-only V2 operation plus exact owner scope evidence; it exposes no bearer. */ + public record CanonicalJoinOperationEvidence( + String requestId, + long privateAccountId, + String callerBinding, + String scopeTokenHash, + String connectScopeDigest, + int operationRepresentationVersion, + int scopeDigestVersion, + int intentDigestVersion, + String intentDigest, + String entitlementAuthorityAvailability, + Boolean allowPublicJoin, + Long entitlementVersion, + Integer requestDigestVersion, + String requestDigest, + String lastAttemptAuthorityAvailability, + String lastAttemptFailureCode, + boolean callerBoundAuthorityInvalidated, + String status, + CanonicalConnectScopeEvidence scopeEvidence) { + public CanonicalJoinOperationEvidence { + if (requestId == null + || requestId.isBlank() + || privateAccountId <= 0L + || callerBinding == null + || callerBinding.isBlank() + || scopeTokenHash == null + || connectScopeDigest == null + || operationRepresentationVersion != 2 + || scopeDigestVersion != 2 + || intentDigestVersion != 2 + || intentDigest == null + || entitlementAuthorityAvailability == null + || lastAttemptAuthorityAvailability == null + || !"PENDING".equals(status) + || callerBoundAuthorityInvalidated + || scopeEvidence == null + || scopeEvidence.privateAccountId() != privateAccountId + || !scopeTokenHash.equals(scopeEvidence.scopeTokenHash()) + || !connectScopeDigest.equals(scopeEvidence.scopeDigest())) { + throw new IllegalArgumentException("Canonical JOIN operation evidence is incomplete"); + } + requireSha256(scopeTokenHash, "Canonical JOIN scope token hash"); + requireSha256(connectScopeDigest, "Canonical JOIN scope digest"); + requireSha256(intentDigest, "Canonical JOIN intent digest"); + if ("AVAILABLE".equals(entitlementAuthorityAvailability)) { + if (allowPublicJoin == null + || entitlementVersion == null + || entitlementVersion <= 0L + || !Integer.valueOf(2).equals(requestDigestVersion) + || requestDigest == null + || lastAttemptFailureCode != null + || !"AVAILABLE".equals(lastAttemptAuthorityAvailability)) { + throw new IllegalArgumentException( + "Canonical JOIN available policy evidence is incomplete"); + } + requireSha256(requestDigest, "Canonical JOIN request digest"); + } else if (("UNAVAILABLE".equals(entitlementAuthorityAvailability) + || "NOT_EVALUATED".equals(entitlementAuthorityAvailability)) + && allowPublicJoin == null + && entitlementVersion == null + && requestDigestVersion == null + && requestDigest == null + && (("UNAVAILABLE".equals(entitlementAuthorityAvailability) + && "UNAVAILABLE".equals(lastAttemptAuthorityAvailability) + && lastAttemptFailureCode != null + && !lastAttemptFailureCode.isBlank()) + || ("NOT_EVALUATED".equals(entitlementAuthorityAvailability) + && "NOT_EVALUATED".equals(lastAttemptAuthorityAvailability) + && lastAttemptFailureCode == null))) { + // An unavailable authority attempt has no synthetic result or digest. + } else { + throw new IllegalArgumentException("Canonical JOIN policy evidence is contradictory"); + } + } + } + + /** Cross-version or changed-input reuse of the shared request ID is a deterministic conflict. */ + public static final class CanonicalJoinOperationConflictException extends IllegalStateException { + public CanonicalJoinOperationConflictException(String message) { + super(message); + } + } + public record JoinOperation( String requestId, long accountId, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java index 09259c8977..b7fa1409df 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptRepository.java @@ -1,11 +1,20 @@ package net.firedevops.firemud.accountservice.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.CanonicalMembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; @@ -25,6 +34,8 @@ public class AccountMembershipTransitionReceiptRepository { private static final String MEMBERSHIP_JOINED = "MEMBERSHIP_JOINED"; private static final String MEMBERSHIP_REACTIVATED = "MEMBERSHIP_REACTIVATED"; private static final String MEMBERSHIP_LEFT = "MEMBERSHIP_LEFT"; + private static final String ZERO_SHA256_DIGEST = + "sha256:0000000000000000000000000000000000000000000000000000000000000000"; private final DSLContext dsl; @@ -32,11 +43,1089 @@ public AccountMembershipTransitionReceiptRepository(DSLContext dsl) { this.dsl = dsl; } + /** Appends a UUID-qualified provisional transition receipt on the shared receipt-head counter. */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalMembershipTransitionReceipt appendCanonicalTransition( + UUID accountUuid, UUID tenantUuid, String transitionType, String requestId) { + requireOwnerWriteTransaction(); + UUID canonicalAccountUuid = + MembershipTransitionReceiptDigest.requireCanonicalUuid(accountUuid, "accountUuid"); + UUID canonicalTenantUuid = + MembershipTransitionReceiptDigest.requireCanonicalUuid(tenantUuid, "tenantUuid"); + String canonicalRequestId = MembershipTransitionReceiptDigest.requireRequestIdV2(requestId); + lockReceiptRequestFence(canonicalRequestId); + CanonicalMembershipState membership = + lockCanonicalMembership(canonicalAccountUuid, canonicalTenantUuid); + if (membership == null) { + throw new IllegalStateException("Canonical Account membership does not exist"); + } + requireTransitionState(membership, transitionType); + + CanonicalReceiptHead head = lockReceiptHead(membership); + Record requestRow = readReceiptRequest(canonicalRequestId); + if (requestRow != null) { + Short version = requestRow.get("receipt_version", Short.class); + if (version == null || version != 2) { + throw new IllegalStateException( + "Account membership request ID is already retained in another receipt version"); + } + if (head == null + || !Objects.equals(requestRow.get("receipt_head_id", Long.class), head.receiptHeadId())) { + throw new IllegalStateException( + "Canonical Account membership request ID belongs to another receipt scope"); + } + CanonicalMembershipTransitionReceipt original = + decodeCanonicalReceipt(requestRow, membership, head); + if (!sameCanonicalTransition(original, membership, transitionType, canonicalRequestId)) { + throw new IllegalStateException( + "Account membership request ID is already bound to different transition evidence"); + } + return original; + } + + long nextSequence; + if (head == null) { + if (("APPROVED_RETAINED".equals(membership.tenantProvenanceKind()) + && hasPriorMembershipHistory(membership.accountId(), membership.tenantId())) + || hasPriorCanonicalOperationOrAudit(membership, canonicalRequestId) + || hasPriorCanonicalMembershipEventHistory(membership, canonicalRequestId)) { + throw new IllegalStateException( + "Account membership history exists without its original receipt head"); + } + requireFirstCanonicalJoinEvidence(membership, canonicalRequestId, transitionType); + nextSequence = 1L; + } else { + requireHeadMatchesMembership(head, membership); + if (head.lastReceiptSequence() <= 0L) { + throw new IllegalStateException("Account membership receipt head counter is malformed"); + } + Record latest = readHeadReceipt(head.receiptHeadId(), head.lastReceiptSequence()); + if (latest == null) { + throw new IllegalStateException( + "Account membership receipt head lacks its exact latest receipt"); + } + validateReceiptForAppend(latest, membership, head); + if (head.lastReceiptSequence() == Long.MAX_VALUE) { + throw new IllegalStateException("Account membership receipt sequence is exhausted"); + } + nextSequence = head.lastReceiptSequence() + 1L; + } + + CanonicalMembershipTransitionReceipt receipt = + createCanonicalReceipt(membership, nextSequence, transitionType, canonicalRequestId); + if (head == null) { + String storageKey = + "APPROVED_RETAINED".equals(membership.tenantProvenanceKind()) + ? MembershipTransitionReceiptDigest.receiptStreamKey( + membership.accountId(), membership.tenantId()) + : receipt.receiptStreamKey(); + insertCanonicalHead(membership, storageKey, nextSequence); + } else if (head.accountUuid() == null) { + bindCanonicalHeadAndAdvance(head, membership, nextSequence); + } else { + advanceCanonicalHead(head, nextSequence); + } + insertCanonicalReceipt(membership, receipt); + return receipt; + } + + /** Reads one immutable canonical receipt by request ID, preserving historical receipt state. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCanonicalByRequestId(String requestId) { + requireOwnerWriteTransaction(); + String canonicalRequestId = MembershipTransitionReceiptDigest.requireRequestIdV2(requestId); + Record row = readReceiptRequest(canonicalRequestId); + if (row == null) { + return Optional.empty(); + } + Short version = row.get("receipt_version", Short.class); + if (version == null || version == 1) { + return Optional.empty(); + } + if (version != 2) { + throw new IllegalStateException("Account membership receipt representation is unsupported"); + } + UUID accountUuid = row.get("account_uuid", UUID.class); + UUID tenantUuid = row.get("tenant_uuid", UUID.class); + CanonicalMembershipState membership = lockCanonicalMembership(accountUuid, tenantUuid); + if (membership == null) { + throw new IllegalStateException( + "Canonical Account membership receipt has no persisted membership source"); + } + Long headId = row.get("receipt_head_id", Long.class); + CanonicalReceiptHead head = lockReceiptHeadById(headId); + if (head == null) { + throw new IllegalStateException("Canonical Account membership receipt head is absent"); + } + return Optional.of(decodeCanonicalReceipt(row, membership, head)); + } + + /** Reads and validates the current latest canonical receipt without treating it as authority. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findLatestCanonicalReceipt( + UUID accountUuid, UUID tenantUuid) { + requireOwnerWriteTransaction(); + UUID canonicalAccountUuid = + MembershipTransitionReceiptDigest.requireCanonicalUuid(accountUuid, "accountUuid"); + UUID canonicalTenantUuid = + MembershipTransitionReceiptDigest.requireCanonicalUuid(tenantUuid, "tenantUuid"); + CanonicalMembershipState membership = + lockCanonicalMembership(canonicalAccountUuid, canonicalTenantUuid); + if (membership == null) { + return Optional.empty(); + } + CanonicalReceiptHead head = lockReceiptHead(membership); + if (head == null) { + throw new IllegalStateException( + "Canonical Account membership exists without retained transition receipt history"); + } + requireHeadMatchesMembership(head, membership); + if (head.lastReceiptSequence() <= 0L) { + throw new IllegalStateException("Account membership receipt head counter is malformed"); + } + Record row = readHeadReceipt(head.receiptHeadId(), head.lastReceiptSequence()); + if (row == null) { + throw new IllegalStateException( + "Account membership receipt head lacks its exact latest receipt"); + } + Short version = row.get("receipt_version", Short.class); + if (version == null) { + throw new IllegalStateException("Account membership receipt version is malformed"); + } + if (version == 1) { + validateVersion1Receipt(row, membership, head); + if (!Objects.equals( + row.get("membership_lifecycle_state", String.class), membership.lifecycleState()) + || !Objects.equals( + row.get("gameplay_admission_allowed", Boolean.class), + membership.gameplayAdmissionAllowed()) + || !Objects.equals( + row.get("membership_version", Long.class), membership.membershipVersion()) + || !Objects.equals( + row.get("membership_authority_generation", Long.class), + membership.membershipAuthorityGeneration()) + || !Objects.equals( + row.get("authority_provenance", String.class), membership.authorityProvenance())) { + throw new IllegalStateException( + "Canonical Account membership row does not match its latest V1 provisional receipt"); + } + return Optional.empty(); + } + if (version != 2) { + throw new IllegalStateException("Account membership receipt representation is unsupported"); + } + CanonicalMembershipTransitionReceipt receipt = decodeCanonicalReceipt(row, membership, head); + if (!sameCanonicalCurrentState(receipt, membership)) { + throw new IllegalStateException( + "Canonical Account membership row does not match its latest provisional receipt"); + } + return Optional.of(receipt); + } + + private CanonicalMembershipState lockCanonicalMembership(UUID accountUuid, UUID tenantUuid) { + Record account = + dsl.fetchOne( + "SELECT id, account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", accountUuid); + if (account == null + || account.get("id", Long.class) == null + || account.get("id", Long.class) <= 0L + || !accountUuid.equals(account.get("account_uuid", UUID.class))) { + throw new IllegalStateException("Canonical Account UUID is not an exact persisted Account"); + } + long accountId = account.get("id", Long.class); + Record row = + dsl.fetchOne( + "SELECT id, account_id, tenant_id, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, lifecycle_state, " + + "gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance " + + "FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_uuid = ? FOR UPDATE", + accountId, + tenantUuid); + if (row == null) { + return null; + } + Long membershipId = row.get("id", Long.class); + Long storedAccountId = row.get("account_id", Long.class); + Long tenantId = row.get("tenant_id", Long.class); + UUID storedTenantUuid = row.get("tenant_uuid", UUID.class); + String tenantKind = row.get("tenant_provenance_kind", String.class); + UUID sourceOperationId = row.get("tenant_source_operation_id", UUID.class); + String sourceDigest = row.get("tenant_provenance_digest", String.class); + String lifecycleState = row.get("lifecycle_state", String.class); + Boolean admissionAllowed = row.get("gameplay_admission_allowed", Boolean.class); + Long membershipVersion = row.get("membership_version", Long.class); + Long authorityGeneration = row.get("membership_authority_generation", Long.class); + String authorityProvenance = row.get("authority_provenance", String.class); + if (membershipId == null + || membershipId <= 0L + || !Long.valueOf(accountId).equals(storedAccountId) + || !tenantUuid.equals(storedTenantUuid) + || lifecycleState == null + || admissionAllowed == null + || membershipVersion == null + || membershipVersion <= 0L + || authorityGeneration == null + || authorityGeneration <= 0L + || authorityProvenance == null) { + throw new IllegalStateException("Persisted canonical Account membership is malformed"); + } + CanonicalMembershipState membership = + new CanonicalMembershipState( + accountId, + membershipId, + accountUuid, + tenantUuid, + tenantId, + tenantKind, + sourceOperationId, + sourceDigest, + lifecycleState, + admissionAllowed, + membershipVersion, + authorityGeneration, + authorityProvenance); + requireExactTenantSource(membership); + return membership; + } + + private void requireExactTenantSource(CanonicalMembershipState membership) { + MembershipTransitionReceiptDigest.requireCanonicalUuid( + membership.tenantSourceOperationId(), "tenantSourceOperationId"); + MembershipTransitionReceiptDigest.requireSha256Digest( + membership.tenantProvenanceDigest(), "tenantProvenanceDigest"); + Boolean matches; + if ("APPROVED_RETAINED".equals(membership.tenantProvenanceKind())) { + if (membership.tenantId() == null || membership.tenantId() <= 0L) { + throw new IllegalStateException( + "Approved retained canonical membership has no positive legacy tenant key"); + } + matches = + (Boolean) + dsl.fetchValue( + "SELECT EXISTS (" + + "SELECT 1 FROM account_approved_legacy_tenant_associations retained " + + "JOIN account_canonical_tenant_identity_claims claim " + + "ON claim.canonical_tenant_id = retained.canonical_tenant_id " + + "AND claim.identity_kind = retained.identity_kind " + + "AND claim.source_operation_id = retained.operation_id " + + "AND claim.source_account_legacy_tenant_id = retained.legacy_tenant_id " + + "AND claim.source_target_namespace = retained.target_namespace " + + "AND claim.source_creation_request_id IS NULL " + + "AND claim.source_request_digest IS NULL " + + "AND claim.source_game_row_id = retained.source_game_row_id " + + "AND claim.source_game_tenant_key = retained.source_legacy_game_tenant_id " + + "AND claim.source_provenance_kind IS NULL " + + "AND claim.source_evidence_digest = retained.account_evidence_digest " + + "AND claim.source_manifest_digest = retained.manifest_digest " + + "WHERE retained.legacy_tenant_id = ? " + + "AND retained.canonical_tenant_id = ? " + + "AND retained.operation_id = ? " + + "AND retained.manifest_digest = ?)", + membership.tenantId(), + membership.tenantUuid(), + membership.tenantSourceOperationId(), + membership.tenantProvenanceDigest()); + } else if ("FRESH_GAME_DESIGN".equals(membership.tenantProvenanceKind())) { + if (membership.tenantId() != null) { + throw new IllegalStateException( + "Fresh Game Design canonical membership must not carry a legacy tenant key"); + } + matches = + (Boolean) + dsl.fetchValue( + "SELECT EXISTS (" + + "SELECT 1 FROM account_fresh_tenant_identity_associations fresh " + + "JOIN account_canonical_tenant_identity_claims claim " + + "ON claim.canonical_tenant_id = fresh.canonical_tenant_id " + + "AND claim.identity_kind = fresh.identity_kind " + + "AND claim.source_operation_id = fresh.operation_id " + + "AND claim.source_target_namespace = fresh.target_namespace " + + "AND claim.source_creation_request_id = fresh.creation_request_id " + + "AND claim.source_request_digest = fresh.request_digest " + + "AND claim.source_game_row_id = fresh.source_game_row_id " + + "AND claim.source_game_tenant_key = fresh.source_game_tenant_key " + + "AND claim.source_provenance_kind = fresh.provenance_kind " + + "AND claim.source_evidence_digest = fresh.evidence_digest " + + "AND claim.source_account_legacy_tenant_id IS NULL " + + "AND claim.source_manifest_digest IS NULL " + + "WHERE fresh.canonical_tenant_id = ? " + + "AND fresh.operation_id = ? " + + "AND fresh.evidence_digest = ?)", + membership.tenantUuid(), + membership.tenantSourceOperationId(), + membership.tenantProvenanceDigest()); + } else { + throw new IllegalStateException("Canonical membership tenant provenance is unsupported"); + } + if (!Boolean.TRUE.equals(matches)) { + throw new IllegalStateException( + "Canonical Account membership has no exact immutable tenant-source evidence"); + } + } + + private CanonicalReceiptHead lockReceiptHead(CanonicalMembershipState membership) { + Record row = + dsl.fetchOne( + "SELECT receipt_head_id, account_id, tenant_id, receipt_stream_key, " + + "last_receipt_sequence, account_uuid, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_uuid = ? FOR UPDATE", + membership.accountId(), + membership.tenantUuid()); + if (row == null && "APPROVED_RETAINED".equals(membership.tenantProvenanceKind())) { + row = + dsl.fetchOne( + "SELECT receipt_head_id, account_id, tenant_id, receipt_stream_key, " + + "last_receipt_sequence, account_uuid, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ? FOR UPDATE", + membership.accountId(), + membership.tenantId()); + } + return row == null ? null : mapHead(row); + } + + private CanonicalReceiptHead lockReceiptHeadById(Long receiptHeadId) { + if (receiptHeadId == null || receiptHeadId <= 0L) { + throw new IllegalStateException("Canonical Account membership receipt head ID is malformed"); + } + Record row = + dsl.fetchOne( + "SELECT receipt_head_id, account_id, tenant_id, receipt_stream_key, " + + "last_receipt_sequence, account_uuid, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE receipt_head_id = ? FOR UPDATE", + receiptHeadId); + return row == null ? null : mapHead(row); + } + + private static CanonicalReceiptHead mapHead(Record row) { + Long id = row.get("receipt_head_id", Long.class); + Long accountId = row.get("account_id", Long.class); + Long tenantId = row.get("tenant_id", Long.class); + String streamKey = row.get("receipt_stream_key", String.class); + Long sequence = row.get("last_receipt_sequence", Long.class); + if (id == null + || id <= 0L + || accountId == null + || accountId <= 0L + || streamKey == null + || sequence == null + || sequence <= 0L) { + throw new IllegalStateException("Account membership receipt head is malformed"); + } + return new CanonicalReceiptHead( + id, + accountId, + tenantId, + streamKey, + sequence, + row.get("account_uuid", UUID.class), + row.get("tenant_uuid", UUID.class), + row.get("tenant_provenance_kind", String.class), + row.get("tenant_source_operation_id", UUID.class), + row.get("tenant_provenance_digest", String.class)); + } + + private static void requireHeadMatchesMembership( + CanonicalReceiptHead head, CanonicalMembershipState membership) { + if (head.accountId() != membership.accountId() + || !Objects.equals(head.tenantId(), membership.tenantId())) { + throw new IllegalStateException( + "Account membership receipt head storage scope is inconsistent"); + } + if (head.accountUuid() == null) { + if (!"APPROVED_RETAINED".equals(membership.tenantProvenanceKind()) + || head.tenantUuid() != null + || head.tenantProvenanceKind() != null + || head.tenantSourceOperationId() != null + || head.tenantProvenanceDigest() != null + || !MembershipTransitionReceiptDigest.receiptStreamKey( + membership.accountId(), membership.tenantId()) + .equals(head.receiptStreamKey())) { + throw new IllegalStateException( + "Unbound Account membership receipt head is not an exact retained V1 head"); + } + return; + } + if (!membership.accountUuid().equals(head.accountUuid()) + || !membership.tenantUuid().equals(head.tenantUuid()) + || !membership.tenantProvenanceKind().equals(head.tenantProvenanceKind()) + || !membership.tenantSourceOperationId().equals(head.tenantSourceOperationId()) + || !membership.tenantProvenanceDigest().equals(head.tenantProvenanceDigest())) { + throw new IllegalStateException( + "Canonical Account membership receipt head differs from immutable tenant identity"); + } + String expectedStorageKey = + "APPROVED_RETAINED".equals(membership.tenantProvenanceKind()) + ? MembershipTransitionReceiptDigest.receiptStreamKey( + membership.accountId(), membership.tenantId()) + : MembershipTransitionReceiptDigest.receiptStreamKeyV2( + membership.accountUuid(), membership.tenantUuid()); + if (!expectedStorageKey.equals(head.receiptStreamKey())) { + throw new IllegalStateException( + "Canonical Account membership receipt head changed its retained storage key"); + } + } + + private Record readReceiptRequest(String requestId) { + return dsl.fetchOne( + "SELECT receipt_stream_key, receipt_sequence, account_id, tenant_id, receipt_head_id, " + + "receipt_version, account_uuid, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, evidence_status, " + + "transition_type, request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance, receipt_id, receipt_digest " + + "FROM account_membership_transition_receipts WHERE request_id = ?", + requestId); + } + + private Record readHeadReceipt(long receiptHeadId, long sequence) { + return dsl.fetchOne( + "SELECT receipt_stream_key, receipt_sequence, account_id, tenant_id, receipt_head_id, " + + "receipt_version, account_uuid, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, evidence_status, " + + "transition_type, request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance, receipt_id, receipt_digest " + + "FROM account_membership_transition_receipts " + + "WHERE receipt_head_id = ? AND receipt_sequence = ?", + receiptHeadId, + sequence); + } + + private CanonicalMembershipTransitionReceipt decodeCanonicalReceipt( + Record row, CanonicalMembershipState membership, CanonicalReceiptHead head) { + Short version = row.get("receipt_version", Short.class); + Long receiptHeadId = row.get("receipt_head_id", Long.class); + Long sequence = row.get("receipt_sequence", Long.class); + Long accountId = row.get("account_id", Long.class); + Long tenantId = row.get("tenant_id", Long.class); + Long membershipId = row.get("membership_id", Long.class); + Long membershipVersion = row.get("membership_version", Long.class); + Long authorityGeneration = row.get("membership_authority_generation", Long.class); + UUID accountUuid = row.get("account_uuid", UUID.class); + UUID tenantUuid = row.get("tenant_uuid", UUID.class); + String streamKey = row.get("receipt_stream_key", String.class); + String evidenceStatus = row.get("evidence_status", String.class); + String transitionType = row.get("transition_type", String.class); + String requestId = row.get("request_id", String.class); + String lifecycleState = row.get("membership_lifecycle_state", String.class); + Boolean admissionAllowed = row.get("gameplay_admission_allowed", Boolean.class); + String authorityProvenance = row.get("authority_provenance", String.class); + String tenantKind = row.get("tenant_provenance_kind", String.class); + UUID sourceOperationId = row.get("tenant_source_operation_id", UUID.class); + String sourceDigest = row.get("tenant_provenance_digest", String.class); + UUID receiptId = row.get("receipt_id", UUID.class); + String receiptDigest = row.get("receipt_digest", String.class); + if (version == null + || version != 2 + || receiptHeadId == null + || receiptHeadId != head.receiptHeadId() + || sequence == null + || sequence <= 0L + || sequence > head.lastReceiptSequence() + || accountId == null + || accountId != membership.accountId() + || !Objects.equals(tenantId, membership.tenantId()) + || membershipId == null + || membershipId != membership.membershipId() + || !membership.accountUuid().equals(accountUuid) + || !membership.tenantUuid().equals(tenantUuid) + || membershipVersion == null + || membershipVersion <= 0L + || authorityGeneration == null + || authorityGeneration <= 0L + || lifecycleState == null + || admissionAllowed == null + || authorityProvenance == null + || !MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(evidenceStatus) + || !requestIdMatchesReceipt(requestId) + || !Objects.equals(tenantKind, membership.tenantProvenanceKind()) + || !Objects.equals(sourceOperationId, membership.tenantSourceOperationId()) + || !Objects.equals(sourceDigest, membership.tenantProvenanceDigest()) + || receiptId == null + || receiptDigest == null) { + throw new IllegalStateException("Canonical Account membership receipt scope is inconsistent"); + } + requireHeadMatchesMembership(head, membership); + if (!MembershipTransitionReceiptDigest.receiptStreamKeyV2(accountUuid, tenantUuid) + .equals(streamKey)) { + throw new IllegalStateException("Canonical Account membership receipt key is inconsistent"); + } + CanonicalMembershipTransitionReceipt receipt; + try { + receipt = + new CanonicalMembershipTransitionReceipt( + streamKey, + sequence, + receiptId, + receiptDigest, + evidenceStatus, + transitionType, + requestId, + accountUuid, + tenantUuid, + lifecycleState, + admissionAllowed, + Map.of(tenantUuid.toString(), Long.toString(membershipVersion)), + authorityGeneration, + authorityProvenance, + tenantKind, + sourceOperationId, + sourceDigest); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Canonical Account membership receipt is malformed", malformed); + } + if (!MembershipTransitionReceiptDigest.transitionDigestV2(receipt).equals(receiptDigest)) { + throw new IllegalStateException( + "Canonical Account membership receipt digest is inconsistent"); + } + return receipt; + } + + private static boolean requestIdMatchesReceipt(String requestId) { + try { + MembershipTransitionReceiptDigest.requireRequestIdV2(requestId); + return true; + } catch (IllegalArgumentException malformed) { + return false; + } + } + + private void validateReceiptForAppend( + Record row, CanonicalMembershipState membership, CanonicalReceiptHead head) { + Short version = row.get("receipt_version", Short.class); + if (version == null) { + throw new IllegalStateException("Account membership receipt version is malformed"); + } + if (version == 1) { + validateVersion1Receipt(row, membership, head); + } else if (version == 2) { + decodeCanonicalReceipt(row, membership, head); + } else { + throw new IllegalStateException("Account membership receipt representation is unsupported"); + } + } + + private void validateVersion1Receipt( + Record row, CanonicalMembershipState membership, CanonicalReceiptHead head) { + Long sequence = row.get("receipt_sequence", Long.class); + Long accountId = row.get("account_id", Long.class); + Long tenantId = row.get("tenant_id", Long.class); + Long receiptHeadId = row.get("receipt_head_id", Long.class); + Long membershipId = row.get("membership_id", Long.class); + Long version = row.get("membership_version", Long.class); + Long authorityGeneration = row.get("membership_authority_generation", Long.class); + String streamKey = row.get("receipt_stream_key", String.class); + String transitionType = row.get("transition_type", String.class); + String requestId = row.get("request_id", String.class); + String lifecycleState = row.get("membership_lifecycle_state", String.class); + Boolean admissionAllowed = row.get("gameplay_admission_allowed", Boolean.class); + String authorityProvenance = row.get("authority_provenance", String.class); + String evidenceStatus = row.get("evidence_status", String.class); + UUID receiptId = row.get("receipt_id", UUID.class); + String digest = row.get("receipt_digest", String.class); + if (sequence == null + || sequence <= 0L + || accountId == null + || accountId != membership.accountId() + || membership.tenantId() == null + || !membership.tenantId().equals(tenantId) + || receiptHeadId == null + || receiptHeadId != head.receiptHeadId() + || membershipId == null + || membershipId != membership.membershipId() + || version == null + || version <= 0L + || authorityGeneration == null + || authorityGeneration <= 0L + || !Objects.equals(streamKey, head.receiptStreamKey()) + || !MembershipTransitionReceiptDigest.EVIDENCE_STATUS.equals(evidenceStatus) + || !requestIdMatchesReceiptV1(requestId) + || lifecycleState == null + || admissionAllowed == null + || authorityProvenance == null + || receiptId == null + || digest == null + || !receiptId.equals(MembershipTransitionReceiptDigest.receiptIdForRequest(requestId))) { + throw new IllegalStateException("Retained V1 Account membership receipt is inconsistent"); + } + String expected = + MembershipTransitionReceiptDigest.transitionDigest( + streamKey, + sequence, + receiptId, + transitionType, + requestId, + accountId, + tenantId, + membershipId, + lifecycleState, + admissionAllowed, + version, + authorityGeneration, + authorityProvenance); + if (!expected.equals(digest)) { + throw new IllegalStateException( + "Retained V1 Account membership receipt digest is inconsistent"); + } + } + + private static boolean requestIdMatchesReceiptV1(String requestId) { + return requestId != null && !requestId.isBlank() && requestId.length() <= 128; + } + + private boolean hasPriorCanonicalMembershipEventHistory( + CanonicalMembershipState membership, String currentRequestId) { + String streamKey = canonicalMembershipEventStreamKey(membership); + Boolean found = + (Boolean) + dsl.fetchValue( + "SELECT EXISTS (" + + "SELECT 1 FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ? " + + "AND last_event_sequence > 1 " + + "UNION ALL SELECT 1 FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ? AND last_sequence > 1 " + + "UNION ALL SELECT 1 FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? " + + "AND (outbox_sequence <> 1 OR request_id <> ?))", + membership.accountUuid(), + membership.tenantUuid(), + streamKey, + streamKey, + currentRequestId); + return Boolean.TRUE.equals(found); + } + + private boolean hasPriorCanonicalOperationOrAudit( + CanonicalMembershipState membership, String currentRequestId) { + Boolean found = + (Boolean) + dsl.fetchValue( + "SELECT EXISTS (" + + "SELECT 1 FROM account_join_operations operation " + + "WHERE operation.operation_representation_version = 2 " + + "AND operation.account_uuid = ? AND operation.tenant_uuid = ? " + + "AND (operation.request_id <> ? OR operation.status <> 'PENDING' " + + "OR operation.outcome IS NOT NULL OR operation.membership_id IS NOT NULL) " + + "UNION ALL SELECT 1 FROM account_audit_outbox audit " + + "WHERE audit.producer_service = 'account-service' " + + "AND audit.event_type IN ('ACCOUNT_JOINED_PUBLIC_PRODUCTION', 'ACCOUNT_MEMBERSHIP_LEFT') " + + "AND audit.payload IS NOT NULL " + + "AND audit.payload::jsonb ->> 'accountId' = ? " + + "AND audit.payload::jsonb ->> 'tenantId' = ? " + + "AND (audit.payload::jsonb ->> 'requestId') IS DISTINCT FROM ?)", + membership.accountUuid(), + membership.tenantUuid(), + currentRequestId, + membership.accountUuid().toString(), + membership.tenantUuid().toString(), + currentRequestId); + return Boolean.TRUE.equals(found); + } + + private void requireFirstCanonicalJoinEvidence( + CanonicalMembershipState membership, String requestId, String transitionType) { + if (!MEMBERSHIP_JOINED.equals(transitionType) + || !"ACTIVE".equals(membership.lifecycleState()) + || !membership.gameplayAdmissionAllowed()) { + throw new IllegalStateException( + "A missing canonical receipt head cannot restart retained transition history"); + } + String eventStreamKey = canonicalMembershipEventStreamKey(membership); + Record operation = + dsl.fetchOne( + "SELECT operation.operation_representation_version, operation.account_id, " + + "operation.account_uuid, operation.tenant_uuid, operation.status, " + + "operation.outcome, operation.membership_id " + + "FROM account_join_operations operation " + + "WHERE operation.request_id = ? " + + "AND operation.operation_representation_version = 2 " + + "AND operation.scope_digest_version = 2 " + + "AND operation.account_id = ? AND operation.account_uuid = ? " + + "AND operation.tenant_uuid = ? AND operation.target_class = 'PUBLIC_PRODUCTION' " + + "AND operation.status = 'PENDING' AND operation.outcome IS NULL " + + "AND operation.membership_id IS NULL " + + "AND operation.entitlement_authority_availability = 'AVAILABLE' " + + "AND operation.allow_public_join IS TRUE " + + "AND operation.entitlement_version IS NOT NULL AND operation.entitlement_version > 0 " + + "AND operation.request_digest_version = 2 " + + "AND operation.request_digest IS NOT NULL " + + "AND operation.request_digest ~ '^sha256:[0-9a-f]{64}$' " + + "AND EXISTS (SELECT 1 FROM account_connect_scope_records scope " + + "WHERE scope.scope_token_hash = operation.scope_token_hash " + + "AND scope.scope_digest_version = 2 " + + "AND scope.snapshot_digest = operation.connect_scope_digest " + + "AND scope.account_id = operation.account_id " + + "AND scope.account_uuid = operation.account_uuid " + + "AND scope.target_class = operation.target_class " + + "AND scope.tenant_id IS NULL AND scope.tenant_uuid = operation.tenant_uuid " + + "AND scope.tenant_provenance_kind = ? " + + "AND scope.tenant_provenance_legacy_tenant_id IS NOT DISTINCT FROM ? " + + "AND scope.tenant_source_operation_id = ? " + + "AND scope.tenant_provenance_digest = ? " + + "AND scope.tenant_slug = operation.tenant_slug " + + "AND scope.realm_id = operation.realm_id " + + "AND scope.world_slug = operation.world_slug " + + "AND scope.realm_slug = operation.realm_slug " + + "AND scope.playable_state_namespace_uuid = operation.playable_state_namespace_uuid " + + "AND scope.playable_state_scope = operation.playable_state_scope " + + "AND scope.game_instance_uuid = operation.game_instance_uuid " + + "AND scope.catalog_revision = operation.catalog_revision " + + "AND scope.pointer_version = operation.pointer_version)", + requestId, + membership.accountId(), + membership.accountUuid(), + membership.tenantUuid(), + membership.tenantProvenanceKind(), + membership.tenantId(), + membership.tenantSourceOperationId(), + membership.tenantProvenanceDigest()); + if (operation == null + || !Integer.valueOf(2) + .equals(operation.get("operation_representation_version", Integer.class)) + || !Long.valueOf(membership.accountId()).equals(operation.get("account_id", Long.class)) + || !membership.accountUuid().equals(operation.get("account_uuid", UUID.class)) + || !membership.tenantUuid().equals(operation.get("tenant_uuid", UUID.class)) + || !"PENDING".equals(operation.get("status", String.class)) + || operation.get("outcome", String.class) != null + || operation.get("membership_id", Long.class) != null) { + throw new IllegalStateException( + "First canonical membership receipt lacks its exact pending JOIN operation"); + } + Record pair = + dsl.fetchOne( + "SELECT legacy_tenant_id, tenant_provenance_kind, tenant_source_operation_id, " + + "tenant_provenance_digest, membership_exists, membership_version, " + + "membership_authority_generation, last_event_sequence, last_event_id, " + + "last_event_digest, last_transition_invalidated " + + "FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ? FOR UPDATE", + membership.accountUuid(), + membership.tenantUuid()); + Record event = + dsl.fetchOne( + "SELECT event.outbox_sequence, event.request_id, event.event_id, event.event_digest, " + + "event.payload, stream.last_sequence FROM account_authority_outbox_events event " + + "JOIN account_authority_outbox_streams stream " + + "ON stream.outbox_stream_key = event.outbox_stream_key " + + "WHERE event.outbox_stream_key = ? AND event.outbox_sequence = 1 " + + "AND event.request_id = ?", + eventStreamKey, + requestId); + if (pair == null + || event == null + || !Objects.equals(pair.get("legacy_tenant_id", Long.class), membership.tenantId()) + || !Objects.equals( + pair.get("tenant_provenance_kind", String.class), membership.tenantProvenanceKind()) + || !Objects.equals( + pair.get("tenant_source_operation_id", UUID.class), + membership.tenantSourceOperationId()) + || !Objects.equals( + pair.get("tenant_provenance_digest", String.class), membership.tenantProvenanceDigest()) + || !Boolean.TRUE.equals(pair.get("membership_exists", Boolean.class)) + || !Objects.equals( + pair.get("membership_version", Long.class), membership.membershipVersion()) + || !Objects.equals( + pair.get("membership_authority_generation", Long.class), + membership.membershipAuthorityGeneration()) + || !Long.valueOf(1L).equals(pair.get("last_event_sequence", Long.class)) + || !Objects.equals( + pair.get("last_event_id", String.class), event.get("event_id", String.class)) + || !Objects.equals( + pair.get("last_event_digest", String.class), event.get("event_digest", String.class)) + || !Boolean.FALSE.equals(pair.get("last_transition_invalidated", Boolean.class)) + || !Long.valueOf(1L).equals(event.get("outbox_sequence", Long.class)) + || !Long.valueOf(1L).equals(event.get("last_sequence", Long.class))) { + throw new IllegalStateException( + "First canonical membership receipt lacks exact sequence-one Account event evidence"); + } + MembershipEvent decodedEvent; + try { + decodedEvent = + MembershipAuthorityEventV1Codec.verify( + strictEventText(event.get("payload", byte[].class))); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "First canonical membership receipt Account event payload is invalid", malformed); + } + if (!MembershipAuthorityEventV1Codec.SCHEMA_VERSION.equals(decodedEvent.schemaVersion()) + || !MembershipAuthorityEventV1Codec.EVENT_TYPE.equals(decodedEvent.eventType()) + || !requestId.equals(decodedEvent.requestId()) + || !eventStreamKey.equals(decodedEvent.outboxStreamKey()) + || !"1".equals(decodedEvent.outboxSequence()) + || !membership.accountUuid().toString().equals(decodedEvent.accountId()) + || !membership.tenantUuid().toString().equals(decodedEvent.tenantId()) + || !"ACTIVE".equals(decodedEvent.membershipLifecycleState()) + || !Map.of( + membership.tenantUuid().toString(), Long.toString(membership.membershipVersion())) + .equals(decodedEvent.membershipVersion()) + || !Long.toString(membership.membershipAuthorityGeneration()) + .equals(decodedEvent.membershipAuthorityGeneration()) + || !decodedEvent.gameplayAdmissionAllowed() + || decodedEvent.callerBoundAuthorityInvalidated() + || !Objects.equals(event.get("event_id", String.class), decodedEvent.eventId()) + || !Objects.equals(event.get("event_digest", String.class), decodedEvent.eventDigest())) { + throw new IllegalStateException( + "First canonical membership receipt Account event differs from exact JOIN state"); + } + } + + private static String strictEventText(byte[] payload) { + if (payload == null || payload.length == 0) { + throw new IllegalArgumentException("Account membership event payload is empty"); + } + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(payload)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException( + "Account membership event payload is not strict UTF-8", malformed); + } + } + + private static String canonicalMembershipEventStreamKey(CanonicalMembershipState membership) { + return "account:auth-authority:v1:membership/" + + membership.accountUuid() + + "/" + + membership.tenantUuid(); + } + + private CanonicalMembershipTransitionReceipt createCanonicalReceipt( + CanonicalMembershipState membership, long sequence, String transitionType, String requestId) { + String streamKey = + MembershipTransitionReceiptDigest.receiptStreamKeyV2( + membership.accountUuid(), membership.tenantUuid()); + UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequestV2(requestId); + Map membershipVersion = + Map.of(membership.tenantUuid().toString(), Long.toString(membership.membershipVersion())); + CanonicalMembershipTransitionReceipt draft = + new CanonicalMembershipTransitionReceipt( + streamKey, + sequence, + receiptId, + ZERO_SHA256_DIGEST, + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + transitionType, + requestId, + membership.accountUuid(), + membership.tenantUuid(), + membership.lifecycleState(), + membership.gameplayAdmissionAllowed(), + membershipVersion, + membership.membershipAuthorityGeneration(), + membership.authorityProvenance(), + membership.tenantProvenanceKind(), + membership.tenantSourceOperationId(), + membership.tenantProvenanceDigest()); + return new CanonicalMembershipTransitionReceipt( + streamKey, + sequence, + receiptId, + MembershipTransitionReceiptDigest.transitionDigestV2(draft), + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + transitionType, + requestId, + membership.accountUuid(), + membership.tenantUuid(), + membership.lifecycleState(), + membership.gameplayAdmissionAllowed(), + membershipVersion, + membership.membershipAuthorityGeneration(), + membership.authorityProvenance(), + membership.tenantProvenanceKind(), + membership.tenantSourceOperationId(), + membership.tenantProvenanceDigest()); + } + + private void insertCanonicalHead( + CanonicalMembershipState membership, String streamKey, long sequence) { + Long receiptHeadId = + dsl.resultQuery( + "INSERT INTO account_membership_transition_receipt_stream_heads " + + "(account_id, tenant_id, receipt_stream_key, last_receipt_sequence, " + + "account_uuid, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, updated_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP) " + + "RETURNING receipt_head_id", + membership.accountId(), + membership.tenantId(), + streamKey, + sequence, + membership.accountUuid(), + membership.tenantUuid(), + membership.tenantProvenanceKind(), + membership.tenantSourceOperationId(), + membership.tenantProvenanceDigest()) + .fetchOne(0, Long.class); + if (receiptHeadId == null || receiptHeadId <= 0L) { + throw new IllegalStateException("Canonical Account membership receipt head was not inserted"); + } + } + + private void bindCanonicalHeadAndAdvance( + CanonicalReceiptHead head, CanonicalMembershipState membership, long sequence) { + int changed = + dsl.execute( + "UPDATE account_membership_transition_receipt_stream_heads " + + "SET last_receipt_sequence = ?, account_uuid = ?, tenant_uuid = ?, " + + "tenant_provenance_kind = ?, tenant_source_operation_id = ?, " + + "tenant_provenance_digest = ?, updated_at = CURRENT_TIMESTAMP " + + "WHERE receipt_head_id = ? AND account_id = ? AND tenant_id = ? " + + "AND account_uuid IS NULL AND last_receipt_sequence = ?", + sequence, + membership.accountUuid(), + membership.tenantUuid(), + membership.tenantProvenanceKind(), + membership.tenantSourceOperationId(), + membership.tenantProvenanceDigest(), + head.receiptHeadId(), + membership.accountId(), + membership.tenantId(), + head.lastReceiptSequence()); + if (changed != 1) { + throw new IllegalStateException( + "Approved retained Account membership receipt head changed before canonical binding"); + } + } + + private void advanceCanonicalHead(CanonicalReceiptHead head, long sequence) { + int changed = + dsl.execute( + "UPDATE account_membership_transition_receipt_stream_heads " + + "SET last_receipt_sequence = ?, updated_at = CURRENT_TIMESTAMP " + + "WHERE receipt_head_id = ? AND last_receipt_sequence = ? " + + "AND account_uuid = ? AND tenant_uuid = ? " + + "AND tenant_source_operation_id = ? AND tenant_provenance_digest = ?", + sequence, + head.receiptHeadId(), + head.lastReceiptSequence(), + head.accountUuid(), + head.tenantUuid(), + head.tenantSourceOperationId(), + head.tenantProvenanceDigest()); + if (changed != 1) { + throw new IllegalStateException("Canonical Account membership receipt head is stale"); + } + } + + private void insertCanonicalReceipt( + CanonicalMembershipState membership, CanonicalMembershipTransitionReceipt receipt) { + int inserted = + dsl.execute( + "INSERT INTO account_membership_transition_receipts " + + "(receipt_stream_key, receipt_sequence, account_id, tenant_id, receipt_head_id, " + + "receipt_version, account_uuid, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, evidence_status, " + + "transition_type, request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance, receipt_id, receipt_digest) " + + "VALUES (?, ?, ?, ?, (SELECT receipt_head_id " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_uuid = ?), 2, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.receiptStreamKey(), + receipt.receiptSequence(), + membership.accountId(), + membership.tenantId(), + membership.accountId(), + membership.tenantUuid(), + receipt.accountId(), + receipt.tenantId(), + receipt.tenantProvenanceKind(), + receipt.tenantSourceOperationId(), + receipt.tenantProvenanceDigest(), + receipt.evidenceStatus(), + receipt.transitionType(), + receipt.requestId(), + membership.membershipId(), + receipt.membershipLifecycleState(), + receipt.gameplayAdmissionAllowed(), + Long.parseLong(receipt.membershipVersion().get(receipt.tenantId().toString())), + receipt.membershipAuthorityGeneration(), + receipt.authorityProvenance(), + receipt.receiptId(), + receipt.receiptDigest()); + if (inserted != 1) { + throw new IllegalStateException("Canonical Account membership receipt was not inserted"); + } + } + + private static boolean sameCanonicalTransition( + CanonicalMembershipTransitionReceipt receipt, + CanonicalMembershipState membership, + String transitionType, + String requestId) { + return receipt.requestId().equals(requestId) + && receipt.accountId().equals(membership.accountUuid()) + && receipt.tenantId().equals(membership.tenantUuid()) + && receipt.transitionType().equals(transitionType) + && sameCanonicalCurrentState(receipt, membership); + } + + private static boolean sameCanonicalCurrentState( + CanonicalMembershipTransitionReceipt receipt, CanonicalMembershipState membership) { + return receipt.membershipLifecycleState().equals(membership.lifecycleState()) + && receipt.gameplayAdmissionAllowed() == membership.gameplayAdmissionAllowed() + && receipt + .membershipVersion() + .equals( + Map.of( + membership.tenantUuid().toString(), + Long.toString(membership.membershipVersion()))) + && receipt.membershipAuthorityGeneration() == membership.membershipAuthorityGeneration() + && receipt.authorityProvenance().equals(membership.authorityProvenance()) + && receipt.tenantProvenanceKind().equals(membership.tenantProvenanceKind()) + && receipt.tenantSourceOperationId().equals(membership.tenantSourceOperationId()) + && receipt.tenantProvenanceDigest().equals(membership.tenantProvenanceDigest()); + } + + private static void requireTransitionState( + CanonicalMembershipState membership, String transitionType) { + if (MEMBERSHIP_JOINED.equals(transitionType) || MEMBERSHIP_REACTIVATED.equals(transitionType)) { + if (!"ACTIVE".equals(membership.lifecycleState()) + || !membership.gameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.authorityProvenance())) { + throw new IllegalArgumentException("JOIN receipt requires its committed active state"); + } + return; + } + if (MEMBERSHIP_LEFT.equals(transitionType)) { + if (!"INACTIVE".equals(membership.lifecycleState()) + || membership.gameplayAdmissionAllowed() + || !"EXPLICIT_JOIN".equals(membership.authorityProvenance())) { + throw new IllegalArgumentException( + "LEAVE receipt requires its committed inactive non-admitting state"); + } + return; + } + throw new IllegalArgumentException("Membership transition type is unsupported"); + } + + private void requireOwnerWriteTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical Account membership receipt access requires an active owner transaction with read-write access"); + } + } + /** Appends one provisional receipt inside the surrounding Account membership transaction. */ @Transactional(propagation = Propagation.MANDATORY) public MembershipTransitionReceipt appendTransition( AccountTenantMembership membership, String transitionType, String requestId) { - requireOwnerTransaction(); + requireOwnerWriteTransaction(); if (membership == null || membership.getAccount() == null || membership.getAccount().getId() == null @@ -44,13 +1133,34 @@ public MembershipTransitionReceipt appendTransition( throw new IllegalArgumentException("A persisted Account membership is required"); } long accountId = membership.getAccount().getId(); + if (membership.getTenantId() == null || membership.getTenantId() <= 0L) { + throw new IllegalArgumentException("A legacy Account membership tenant key is required"); + } long tenantId = membership.getTenantId(); long membershipId = membership.getId(); requireTransitionState(membership, transitionType); + lockReceiptRequestFence(requestId); + requireRequestIdAvailableV1(requestId); + requireLatestReceiptRepresentation(accountId, tenantId); String streamKey = MembershipTransitionReceiptDigest.receiptStreamKey(accountId, tenantId); UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest(requestId); - Long sequence = + // Validate every caller-controlled V1 digest segment before allocating the shared counter. + MembershipTransitionReceiptDigest.transitionDigest( + streamKey, + 1L, + receiptId, + transitionType, + requestId, + accountId, + tenantId, + membershipId, + membership.getLifecycleState(), + membership.isGameplayAdmissionAllowed(), + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + membership.getAuthorityProvenance()); + Record headRecord = dsl.resultQuery( "INSERT INTO account_membership_transition_receipt_stream_heads " + "(account_id, tenant_id, receipt_stream_key, last_receipt_sequence, updated_at) " @@ -59,12 +1169,14 @@ public MembershipTransitionReceipt appendTransition( + "last_receipt_sequence = " + "account_membership_transition_receipt_stream_heads.last_receipt_sequence + 1, " + "updated_at = CURRENT_TIMESTAMP " - + "RETURNING last_receipt_sequence", + + "RETURNING receipt_head_id, last_receipt_sequence", accountId, tenantId, streamKey) - .fetchOne(0, Long.class); - if (sequence == null || sequence <= 0L) { + .fetchOne(); + Long headId = headRecord == null ? null : headRecord.get("receipt_head_id", Long.class); + Long sequence = headRecord == null ? null : headRecord.get("last_receipt_sequence", Long.class); + if (headId == null || headId <= 0L || sequence == null || sequence <= 0L) { throw new IllegalStateException("Account membership receipt sequence was not allocated"); } String digest = @@ -85,15 +1197,17 @@ public MembershipTransitionReceipt appendTransition( int inserted = dsl.execute( "INSERT INTO account_membership_transition_receipts " - + "(receipt_stream_key, receipt_sequence, account_id, tenant_id, evidence_status, " + + "(receipt_stream_key, receipt_sequence, account_id, tenant_id, receipt_head_id, " + + "evidence_status, " + "transition_type, request_id, membership_id, membership_lifecycle_state, " + "gameplay_admission_allowed, membership_version, " + "membership_authority_generation, authority_provenance, receipt_id, receipt_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", streamKey, sequence, accountId, tenantId, + headId, MembershipTransitionReceiptDigest.EVIDENCE_STATUS, transitionType, requestId, @@ -166,7 +1280,8 @@ public Optional findByRequestId(String requestId) { dsl.fetchOne( "SELECT r.receipt_stream_key, r.receipt_sequence, r.account_id, r.tenant_id, " + "h.receipt_stream_key AS head_stream_key, " - + "h.last_receipt_sequence AS head_receipt_sequence, r.evidence_status, " + + "h.last_receipt_sequence AS head_receipt_sequence, r.receipt_version, " + + "r.evidence_status, " + "r.transition_type, r.request_id, r.membership_id, r.membership_lifecycle_state, " + "r.gameplay_admission_allowed, r.membership_version, " + "r.membership_authority_generation, r.authority_provenance, r.receipt_id, r.receipt_digest " @@ -178,6 +1293,11 @@ public Optional findByRequestId(String requestId) { if (row == null) { return Optional.empty(); } + Short receiptVersion = row.get("receipt_version", Short.class); + if (receiptVersion == null || receiptVersion != 1) { + throw new IllegalStateException( + "Account membership receipt request uses an unsupported canonical representation"); + } String streamKey = row.get("receipt_stream_key", String.class); Long sequence = row.get("receipt_sequence", Long.class); Long headSequence = row.get("head_receipt_sequence", Long.class); @@ -323,14 +1443,15 @@ private ReceiptSnapshot readLatestReceiptSnapshot(long accountId, long tenantId) } Record row = dsl.fetchOne( - "SELECT h.receipt_stream_key, h.last_receipt_sequence, " + "SELECT h.receipt_head_id, h.receipt_stream_key, h.last_receipt_sequence, " + "m.id AS current_membership_id, " + "m.lifecycle_state AS current_lifecycle_state, " + "m.gameplay_admission_allowed AS current_admission_allowed, " + "m.membership_version AS current_membership_version, " + "m.membership_authority_generation AS current_authority_generation, " + "m.authority_provenance AS current_authority_provenance, " - + "r.receipt_sequence AS row_receipt_sequence, r.account_id AS receipt_account_id, " + + "r.receipt_version, r.receipt_sequence AS row_receipt_sequence, " + + "r.account_id AS receipt_account_id, " + "r.tenant_id AS receipt_tenant_id, r.evidence_status, r.transition_type, " + "r.request_id, r.membership_id AS receipt_membership_id, " + "r.membership_lifecycle_state AS receipt_lifecycle_state, " @@ -345,7 +1466,7 @@ private ReceiptSnapshot readLatestReceiptSnapshot(long accountId, long tenantId) + "LEFT JOIN account_tenant_membership m " + "ON m.account_id = ? AND m.tenant_id = ? " + "LEFT JOIN account_membership_transition_receipts r " - + "ON r.receipt_stream_key = h.receipt_stream_key " + + "ON r.receipt_head_id = h.receipt_head_id " + "AND r.receipt_sequence = h.last_receipt_sequence ", accountId, tenantId, @@ -354,6 +1475,11 @@ private ReceiptSnapshot readLatestReceiptSnapshot(long accountId, long tenantId) if (row == null) { return null; } + Short receiptVersion = row.get("receipt_version", Short.class); + if (receiptVersion != null && receiptVersion != 1) { + throw new IllegalStateException( + "Latest Account membership receipt uses an unsupported canonical representation"); + } Long sequence = row.get("last_receipt_sequence", Long.class); Long currentMembershipId = row.get("current_membership_id", Long.class); if (sequence == null) { @@ -457,7 +1583,7 @@ private boolean hasPriorMembershipHistory(long accountId, long tenantId) { + "UNION ALL SELECT 1 FROM account_audit_outbox " + "WHERE scope = 'tenant' AND tenant_id = ? " + "AND producer_service = 'account-service' " - + "AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' " + + "AND event_type IN ('ACCOUNT_JOINED_PUBLIC_PRODUCTION', 'ACCOUNT_MEMBERSHIP_LEFT') " + "AND (payload IS NULL OR payload::jsonb ->> 'accountId' = CAST(? AS TEXT))" + ")", accountId, @@ -509,6 +1635,53 @@ private void requireOwnerTransaction() { } } + private void requireLatestReceiptRepresentation(long accountId, long tenantId) { + Record row = + dsl.fetchOne( + "SELECT head.last_receipt_sequence, receipt.receipt_version " + + "FROM account_membership_transition_receipt_stream_heads head " + + "LEFT JOIN account_membership_transition_receipts receipt " + + "ON receipt.receipt_head_id = head.receipt_head_id " + + "AND receipt.receipt_sequence = head.last_receipt_sequence " + + "WHERE head.account_id = ? AND head.tenant_id = ? FOR UPDATE OF head", + accountId, + tenantId); + if (row == null) { + return; + } + Short version = row.get("receipt_version", Short.class); + if (version == null) { + throw new IllegalStateException( + "Account membership receipt head lacks its exact latest receipt"); + } + if (version != 1) { + throw new IllegalStateException( + "Latest Account membership receipt uses an unsupported canonical representation"); + } + Long sequence = row.get("last_receipt_sequence", Long.class); + if (sequence == null || sequence <= 0L) { + throw new IllegalStateException("Account membership receipt head counter is malformed"); + } + if (sequence == Long.MAX_VALUE) { + throw new IllegalStateException("Account membership receipt sequence is exhausted"); + } + } + + private void lockReceiptRequestFence(String requestId) { + if (requestId == null) { + throw new IllegalArgumentException("Account membership request ID is required"); + } + dsl.fetch("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", requestId); + } + + private void requireRequestIdAvailableV1(String requestId) { + Record row = readReceiptRequest(requestId); + if (row != null) { + throw new IllegalStateException( + "Account membership request ID is already retained in another transition receipt"); + } + } + private record ReceiptSnapshot( MembershipTransitionReceipt receipt, Long currentMembershipId, @@ -520,6 +1693,33 @@ private record ReceiptSnapshot( long receiptMembershipVersion, long receiptAuthorityGeneration) {} + private record CanonicalMembershipState( + long accountId, + long membershipId, + UUID accountUuid, + UUID tenantUuid, + Long tenantId, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest, + String lifecycleState, + boolean gameplayAdmissionAllowed, + long membershipVersion, + long membershipAuthorityGeneration, + String authorityProvenance) {} + + private record CanonicalReceiptHead( + long receiptHeadId, + long accountId, + Long tenantId, + String receiptStreamKey, + long lastReceiptSequence, + UUID accountUuid, + UUID tenantUuid, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest) {} + /** Immutable receipt bytes plus the state needed to bind it to its original event. */ public record TransitionReceiptEvidence( MembershipTransitionReceipt receipt, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 8fd88fd96d..af22769ec4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -12,6 +12,10 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; @@ -1326,6 +1330,114 @@ public Checkpoint publishNewMembershipChange( return checkpoint; } + /** + * Publishes the first canonical UUID membership event from its committed Account sources. + * + *

The UUIDs and request ID select storage lookups only. A caller-supplied membership, + * provenance object, scope digest, or policy assertion cannot authorize publication. Account, + * tenant association, pending V2 operation/policy, membership, and role evidence are each read + * back from their owner stores after acquiring the Account-first transaction fence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Checkpoint publishCanonicalFirstJoinMembershipChange( + CanonicalJoinScopeV2 scope, String requestId, String callerBinding) { + requireWritableOwnerTransaction(); + Objects.requireNonNull(scope, "canonical JOIN scope is required"); + UUID accountUuid = scope.accountId(); + UUID tenantUuid = scope.tenantId(); + requireCanonicalUuidInput(accountUuid, "Account UUID"); + requireCanonicalUuidInput(tenantUuid, "tenant UUID"); + requirePositive(requestId, "canonical JOIN request ID"); + + Identity identity = resolveCanonicalIdentity(accountUuid, tenantUuid); + AccountTenantMembership membership = + membershipRepository + .findCanonicalMembershipForUpdate(accountUuid, tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Canonical first-JOIN membership row is absent")); + requireCanonicalMembershipIdentity(identity, membership); + if (membership.getMembershipVersion() != 2L + || membership.getMembershipAuthorityGeneration() != 1L) { + throw new IllegalStateException( + "Canonical first JOIN must advance membership version one to two without advancing generation"); + } + + AccountJoinOperationRepository.CanonicalJoinOperationEvidence operation = + joinOperationRepository + .findCanonicalEvidenceByRequestId(requestId) + .orElseThrow( + () -> new IllegalStateException("Canonical first-JOIN V2 operation is absent")); + requireCanonicalFirstJoinOperation(identity, scope, requestId, callerBinding, operation); + + RoleSnapshot roles = + roleSnapshotRepository + .findForCanonicalUpdate( + accountUuid, + tenantUuid, + identity.provenance(), + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow( + () -> new IllegalStateException("Canonical first-JOIN role snapshot is absent")); + requireCanonicalFirstJoinRoles(identity, membership, roles); + + PairAuthority absenceBaseline = + pairAuthorityRepository + .readForUpdate(accountUuid, tenantUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical first JOIN has no committed never-joined pair baseline")); + if (!identity.provenance().equals(absenceBaseline.provenance()) + || absenceBaseline.membershipExists() + || absenceBaseline.membershipVersion() != 1L + || absenceBaseline.membershipAuthorityGeneration() != 1L + || absenceBaseline.lastEventSequence() != 0L + || absenceBaseline.lastEventId() != null + || absenceBaseline.lastEventDigest() != null + || absenceBaseline.lastTransitionInvalidated()) { + throw new IllegalStateException( + "Canonical first JOIN differs from its exact positive absence baseline"); + } + + CompositeSnapshot snapshot = readSnapshot(identity); + ScopeState membershipState = only(snapshot.memberships(), "membership"); + requireMatchingFence(snapshot, membershipState, accountUuid); + if (membershipState.generation() != 1L) { + throw new IllegalStateException( + "Canonical first-JOIN membership authority generation is not its initial value"); + } + String streamKey = membershipStreamKey(identity); + if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { + throw new IllegalStateException( + "Canonical first JOIN cannot publish over retained membership-event history"); + } + + Checkpoint checkpoint = + appendAndReadBack( + identity, requestId, membership, () -> roles, snapshot, false, true, false); + PairAuthority committed = + pairAuthorityRepository.commitTransition( + absenceBaseline, + new PairTransition( + true, + checkpoint.outboxSequence(), + checkpoint.sourceEventId(), + checkpoint.sourceEventDigest(), + false)); + if (checkpoint.outboxSequence() != 1L + || committed.membershipVersion() != 2L + || committed.membershipAuthorityGeneration() != 1L + || committed.lastEventSequence() != 1L + || !Objects.equals(committed.lastEventId(), checkpoint.sourceEventId()) + || !Objects.equals(committed.lastEventDigest(), checkpoint.sourceEventDigest()) + || committed.lastTransitionInvalidated()) { + throw new IllegalStateException( + "Canonical first-JOIN pair authority readback differs from its exact event"); + } + return checkpoint; + } + /** Compare-and-advances an inactive member's existing canonical generation before publication. */ @Transactional(propagation = Propagation.MANDATORY) public Checkpoint publishReactivatedMembershipChange( @@ -1514,6 +1626,26 @@ private Checkpoint appendAndReadBack( boolean callerBoundAuthorityInvalidated, boolean newMembership, boolean inactiveMembership) { + return appendAndReadBack( + identity, + requestId, + membership, + () -> requireRoleSnapshot(identity, membership, inactiveMembership), + snapshot, + callerBoundAuthorityInvalidated, + newMembership, + inactiveMembership); + } + + private Checkpoint appendAndReadBack( + Identity identity, + String requestId, + AccountTenantMembership membership, + Supplier roleSnapshotSupplier, + CompositeSnapshot snapshot, + boolean callerBoundAuthorityInvalidated, + boolean newMembership, + boolean inactiveMembership) { requirePositive(requestId, "membership transition request ID"); if (inactiveMembership) { requireInactiveMembership(membership); @@ -1539,7 +1671,8 @@ private Checkpoint appendAndReadBack( ScopeState issuer = snapshot.issuer(); ScopeState account = snapshot.account(); ScopeState tenant = only(snapshot.tenants(), "tenant"); - RoleSnapshot roles = requireRoleSnapshot(identity, membership, inactiveMembership); + RoleSnapshot roles = roleSnapshotSupplier.get(); + requireRoleSnapshotIdentity(identity, membership, roles, inactiveMembership); String streamKey = membershipStreamKey(identity); String expectedEventId = eventIdForRequest(requestId); MembershipEvent[] candidate = new MembershipEvent[1]; @@ -1626,7 +1759,7 @@ private Checkpoint requireCurrentMembershipEvent( || !"EXPLICIT_JOIN".equals(authorityProvenance) || roleSnapshot == null || roleSnapshot.accountId() != identity.accountId() - || roleSnapshot.tenantId() != identity.legacyTenantId() + || !Objects.equals(roleSnapshot.tenantId(), identity.legacyTenantId()) || roleSnapshot.membershipId() != membershipId || roleSnapshot.snapshotVersion() != membershipVersion) { throw new IllegalStateException("Current Account membership and role evidence is incomplete"); @@ -2154,7 +2287,7 @@ private RoleSnapshot requireRoleSnapshot( "Account membership role snapshot is not canonical", exception); } if (snapshot.accountId() != identity.accountId() - || snapshot.tenantId() != identity.legacyTenantId() + || !Objects.equals(snapshot.tenantId(), identity.legacyTenantId()) || snapshot.membershipId() != membership.getId() || snapshot.snapshotVersion() != membership.getMembershipVersion() || (!inactiveMembership && !exactRoles.contains("player"))) { @@ -2219,12 +2352,182 @@ private Identity resolveIdentity(long accountId, long legacyTenantId) { throw new IllegalStateException( "JOIN retained tenant has no exact approved UUID association"); } + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + legacyTenantId, + TenantProvenanceKind.APPROVED_RETAINED, + association.operationId(), + association.manifestDigest()); return new Identity( accountId, legacyTenantId, account.getAccountUuid(), association.canonicalTenantId(), - association); + provenance); + } + + private Identity resolveCanonicalIdentity(UUID accountUuid, UUID tenantUuid) { + Account initialAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Canonical JOIN Account row is absent")); + requirePersistedAccountIdentity(initialAccount, accountUuid); + long accountId = initialAccount.getId(); + + // Serialize every first-JOIN publisher on the Account row before tenant/provenance reads. + joinOperationRepository.lockAccount(accountId); + Account fencedAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow( + () -> new IllegalStateException("Canonical JOIN Account row disappeared at fence")); + requirePersistedAccountIdentity(fencedAccount, accountUuid); + if (!Objects.equals(initialAccount.getId(), fencedAccount.getId()) + || initialAccount.getAccountUuidProvenance() != fencedAccount.getAccountUuidProvenance() + || !Objects.equals( + initialAccount.getAccountUuidSourceNumericId(), + fencedAccount.getAccountUuidSourceNumericId())) { + throw new IllegalStateException("Canonical JOIN Account identity changed at its row fence"); + } + + VerifiedTenantProvenance provenance = + freshTenantIdentityAssociationRepository + .read(tenantUuid) + .map( + evidence -> { + if (!tenantUuid.equals(evidence.canonicalTenantId())) { + throw new IllegalStateException( + "Fresh Game Design tenant association differs from its UUID scope"); + } + return new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + evidence.operationId(), + evidence.evidenceDigest()); + }) + .orElseGet( + () -> { + ApprovedAssociation association = tenantIdentityResolver.resolve(tenantUuid); + if (association.legacyTenantId() <= 0L + || !tenantUuid.equals(association.canonicalTenantId())) { + throw new IllegalStateException( + "Retained Account tenant association differs from its UUID scope"); + } + return new VerifiedTenantProvenance( + association.legacyTenantId(), + TenantProvenanceKind.APPROVED_RETAINED, + association.operationId(), + association.manifestDigest()); + }); + return new Identity( + accountId, provenance.legacyTenantId(), accountUuid, tenantUuid, provenance); + } + + private void requireCanonicalMembershipIdentity( + Identity identity, AccountTenantMembership membership) { + VerifiedTenantProvenance provenance = identity.provenance(); + if (membership == null + || membership.getId() == null + || membership.getId() <= 0L + || membership.getAccount() == null) { + throw new IllegalStateException("Canonical JOIN membership row is incomplete"); + } + requirePersistedAccountIdentity(membership.getAccount(), identity.accountUuid()); + if (membership.getAccount().getId() != identity.accountId() + || !identity.tenantUuid().equals(membership.getTenantUuid()) + || !Objects.equals(membership.getTenantId(), provenance.legacyTenantId()) + || !provenance.kind().name().equals(membership.getTenantProvenanceKind()) + || !Objects.equals(membership.getTenantSourceOperationId(), provenance.sourceOperationId()) + || !Objects.equals(membership.getTenantProvenanceDigest(), provenance.digest())) { + throw new IllegalStateException( + "Canonical JOIN membership differs from its Account or tenant source association"); + } + requireActiveMembership(membership); + } + + private void requireCanonicalFirstJoinOperation( + Identity identity, + CanonicalJoinScopeV2 requestedScope, + String requestId, + String callerBinding, + AccountJoinOperationRepository.CanonicalJoinOperationEvidence operation) { + var scope = operation.scopeEvidence(); + boolean exactScope = + scope.scopeTokenHash().equals(AccountJoinDigest.tokenHash(requestedScope.connectScopeId())) + && scope.privateAccountId() == identity.accountId() + && scope.targetClass().equals("PUBLIC_PRODUCTION") + && scope.accountUuid().equals(requestedScope.accountId()) + && scope.tenantUuid().equals(requestedScope.tenantId()) + && scope.realmId().equals(requestedScope.realmId()) + && scope.tenantSlug().equals(requestedScope.tenantSlug()) + && scope.worldSlug().equals(requestedScope.worldSlug()) + && scope.realmSlug().equals(requestedScope.realmSlug()) + && scope.playableStateNamespaceUuid().equals(requestedScope.playableStateNamespaceId()) + && scope.playableStateScope().equals(requestedScope.playableStateScope()) + && scope.gameInstanceUuid().equals(requestedScope.gameInstanceId()) + && scope.catalogRevision() == requestedScope.catalogRevision() + && scope.pointerVersion() == requestedScope.pointerVersion() + && scope.evaluatedAt().equals(requestedScope.evaluatedAt()) + && scope.connectScopeExpiresAt().equals(requestedScope.connectScopeExpiresAt()) + && scope.scopeDigest().equals(AccountJoinDigest.scopeV2(requestedScope)); + if (!exactScope + || callerBinding == null + || !callerBinding.equals(operation.callerBinding()) + || !AccountJoinDigest.intentV2(requestId, requestedScope, callerBinding) + .equals(operation.intentDigest())) { + throw new IllegalStateException( + "Canonical JOIN request or scope differs from its exact pending V2 operation"); + } + String expectedPolicyDigest = + AccountJoinDigest.requestV2( + requestedScope, + callerBinding, + EntitlementAvailabilityV2.AVAILABLE, + operation.allowPublicJoin(), + operation.entitlementVersion()); + if (!requestId.equals(operation.requestId()) + || operation.privateAccountId() != identity.accountId() + || operation.operationRepresentationVersion() != 2 + || operation.intentDigestVersion() != 2 + || operation.scopeDigestVersion() != 2 + || !"PENDING".equals(operation.status()) + || !"AVAILABLE".equals(operation.entitlementAuthorityAvailability()) + || !Boolean.TRUE.equals(operation.allowPublicJoin()) + || operation.entitlementVersion() == null + || operation.entitlementVersion() <= 0L + || !Integer.valueOf(2).equals(operation.requestDigestVersion()) + || !expectedPolicyDigest.equals(operation.requestDigest()) + || operation.lastAttemptFailureCode() != null + || !"AVAILABLE".equals(operation.lastAttemptAuthorityAvailability()) + || !"PUBLIC_PRODUCTION".equals(scope.targetClass()) + || !identity.accountUuid().equals(scope.accountUuid()) + || !identity.tenantUuid().equals(scope.tenantUuid()) + || !identity.provenance().equals(scope.tenantProvenance())) { + throw new IllegalStateException( + "Canonical JOIN operation, target, or available public-join policy differs from its Account sources"); + } + } + + private void requireCanonicalFirstJoinRoles( + Identity identity, AccountTenantMembership membership, RoleSnapshot roles) { + List exactRoles; + try { + exactRoles = + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet(roles.roles()); + } catch (RuntimeException exception) { + throw new IllegalStateException("Canonical JOIN role snapshot is not canonical", exception); + } + if (roles.accountId() != identity.accountId() + || !Objects.equals(roles.tenantId(), identity.provenance().legacyTenantId()) + || roles.membershipId() != membership.getId() + || roles.snapshotVersion() != membership.getMembershipVersion() + || !identity.accountUuid().equals(roles.accountUuid()) + || !identity.tenantUuid().equals(roles.tenantUuid()) + || !identity.provenance().equals(roles.tenantProvenance()) + || !exactRoles.contains("player")) { + throw new IllegalStateException( + "Canonical JOIN role snapshot differs from its exact membership or tenant association"); + } } private void requirePersistedAccountIdentity(Account account, UUID expectedAccountUuid) { @@ -2252,13 +2555,42 @@ private void requireActiveOwnerTransaction() { } } + private void requireWritableOwnerTransaction() { + requireActiveOwnerTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical Account membership event publication requires a writable owner transaction"); + } + } + private VerifiedTenantProvenance verifiedProvenance(Identity identity) { - ApprovedAssociation association = identity.association(); - return new VerifiedTenantProvenance( - identity.legacyTenantId(), - TenantProvenanceKind.APPROVED_RETAINED, - association.operationId(), - association.manifestDigest()); + return identity.provenance(); + } + + private void requireRoleSnapshotIdentity( + Identity identity, + AccountTenantMembership membership, + RoleSnapshot roles, + boolean inactiveMembership) { + List exactRoles; + try { + exactRoles = + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet(roles.roles()); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "Account membership role snapshot is not canonical", exception); + } + if (roles.accountId() != identity.accountId() + || roles.membershipId() != membership.getId() + || roles.snapshotVersion() != membership.getMembershipVersion() + || (identity.legacyTenantId() == null + ? (!identity.accountUuid().equals(roles.accountUuid()) + || !identity.tenantUuid().equals(roles.tenantUuid()) + || !identity.provenance().equals(roles.tenantProvenance())) + : !Objects.equals(identity.legacyTenantId(), roles.tenantId())) + || (!inactiveMembership && !exactRoles.contains("player"))) { + throw new IllegalStateException("Account role snapshot differs from its exact membership"); + } } private void requireMembershipIdentity( @@ -2701,10 +3033,10 @@ private static String canonicalIssuerStreamKey() { private record Identity( long accountId, - long legacyTenantId, + Long legacyTenantId, UUID accountUuid, UUID tenantUuid, - ApprovedAssociation association) {} + VerifiedTenantProvenance provenance) {} private enum MembershipSnapshotReadMode { ENROLL_IF_NEEDED, diff --git a/services/account-service/src/main/resources/db/migration/V46__canonical_uuid_connect_scope_evidence.sql b/services/account-service/src/main/resources/db/migration/V46__canonical_uuid_connect_scope_evidence.sql new file mode 100644 index 0000000000..1c9830cb24 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V46__canonical_uuid_connect_scope_evidence.sql @@ -0,0 +1,209 @@ +-- Keep retained v1 scope evidence byte-for-byte readable while storing new UUID scopes in the +-- same token-hash keyed family. V2 rows deliberately have no numeric tenant or game-instance key. +ALTER TABLE account_connect_scope_records + ADD COLUMN scope_digest_version INTEGER NOT NULL DEFAULT 1, + ADD COLUMN account_uuid UUID, + ADD COLUMN tenant_uuid UUID, + ADD COLUMN tenant_slug VARCHAR(128), + ADD COLUMN playable_state_namespace_uuid UUID, + ADD COLUMN game_instance_uuid UUID, + ADD COLUMN tenant_provenance_kind VARCHAR(32), + ADD COLUMN tenant_provenance_legacy_tenant_id BIGINT, + ADD COLUMN tenant_source_operation_id UUID, + ADD COLUMN tenant_provenance_digest VARCHAR(71); + +ALTER TABLE account_connect_scope_records + ALTER COLUMN tenant_id DROP NOT NULL; + +ALTER TABLE account_connect_scope_records + ALTER COLUMN playable_state_namespace_id DROP NOT NULL; + +ALTER TABLE account_connect_scope_records + ALTER COLUMN game_instance_id DROP NOT NULL; + +ALTER TABLE account_connect_scope_records + DROP CONSTRAINT account_connect_scope_positive_check; + +ALTER TABLE account_connect_scope_records + ADD CONSTRAINT account_connect_scope_positive_check + CHECK ( + (scope_digest_version = 1 + AND tenant_id IS NOT NULL AND tenant_id > 0 + AND game_instance_id IS NOT NULL AND game_instance_id > 0 + AND playable_state_namespace_id IS NOT NULL + AND catalog_revision > 0 AND pointer_version > 0) + OR + (scope_digest_version = 2 + AND tenant_id IS NULL + AND game_instance_id IS NULL + AND playable_state_namespace_id IS NULL + AND catalog_revision > 0 AND pointer_version > 0) + ); + +ALTER TABLE account_connect_scope_records + ADD CONSTRAINT account_connect_scope_digest_version_check + CHECK (scope_digest_version IN (1, 2)); + +ALTER TABLE account_connect_scope_records + ADD CONSTRAINT account_connect_scope_identity_version_check + CHECK ( + (scope_digest_version = 1 + AND account_uuid IS NULL + AND tenant_uuid IS NULL + AND tenant_slug IS NULL + AND playable_state_namespace_uuid IS NULL + AND game_instance_uuid IS NULL + AND tenant_provenance_kind IS NULL + AND tenant_provenance_legacy_tenant_id IS NULL + AND tenant_source_operation_id IS NULL + AND tenant_provenance_digest IS NULL) + OR + (scope_digest_version = 2 + AND target_class = 'PUBLIC_PRODUCTION' + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + AND account_uuid IS NOT NULL + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_slug IS NOT NULL AND tenant_slug <> '' + AND realm_id IS NOT NULL + AND realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug IS NOT NULL AND world_slug <> '' + AND realm_slug IS NOT NULL AND realm_slug <> '' + AND playable_state_namespace_uuid IS NOT NULL + AND playable_state_namespace_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_scope IS NOT NULL + AND playable_state_scope IN ('SHARED', 'ISOLATED') + AND game_instance_uuid IS NOT NULL + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND evaluated_at IS NOT NULL AND evaluated_at <> '' + AND connect_scope_expires_at IS NOT NULL AND connect_scope_expires_at <> '' + AND snapshot_digest IS NOT NULL + AND snapshot_digest ~ '^sha256:[0-9a-f]{64}$' + AND tenant_provenance_kind IS NOT NULL + AND tenant_source_operation_id IS NOT NULL + AND tenant_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_provenance_digest IS NOT NULL + AND tenant_provenance_digest ~ '^sha256:[0-9a-f]{64}$' + AND ( + (tenant_provenance_kind = 'APPROVED_RETAINED' + AND tenant_provenance_legacy_tenant_id IS NOT NULL + AND tenant_provenance_legacy_tenant_id > 0) + OR + (tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND tenant_provenance_legacy_tenant_id IS NULL) + )) + ); + +-- V1 inserts and existing V1 rows keep their original shape and historical mutation behavior. +-- New V2 source identity and digest evidence is immutable and must point at exact owner rows. +-- [jooq ignore start] +CREATE FUNCTION validate_account_connect_scope_identity() RETURNS trigger AS $$ +DECLARE + account_matches BOOLEAN := FALSE; + tenant_source_matches BOOLEAN := FALSE; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.scope_digest_version = 2 THEN + RAISE EXCEPTION 'Canonical Account connect scope evidence cannot be deleted without cleanup proof' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF OLD.scope_digest_version = 2 THEN + RAISE EXCEPTION 'Canonical Account connect scope evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.scope_digest_version = 2 THEN + RAISE EXCEPTION 'Retained Account connect scope evidence cannot be upgraded in place' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.scope_digest_version = 1 THEN + RETURN NEW; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM accounts account_row + WHERE account_row.id = NEW.account_id + AND account_row.account_uuid = NEW.account_uuid + AND account_row.account_uuid_source_numeric_id = account_row.id + AND account_row.account_uuid_provenance IS NOT NULL + ) INTO account_matches; + IF NOT account_matches THEN + RAISE EXCEPTION 'Canonical Account connect scope has no exact persisted Account identity' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.tenant_provenance_kind = 'APPROVED_RETAINED' THEN + SELECT EXISTS ( + SELECT 1 + FROM account_approved_legacy_tenant_associations retained + WHERE retained.identity_kind = 'APPROVED_RETAINED' + AND retained.legacy_tenant_id = NEW.tenant_provenance_legacy_tenant_id + AND retained.canonical_tenant_id = NEW.tenant_uuid + AND retained.operation_id = NEW.tenant_source_operation_id + AND retained.manifest_digest = NEW.tenant_provenance_digest + ) INTO tenant_source_matches; + ELSIF NEW.tenant_provenance_kind = 'FRESH_GAME_DESIGN' THEN + SELECT EXISTS ( + SELECT 1 + FROM account_fresh_tenant_identity_associations fresh + WHERE fresh.canonical_tenant_id = NEW.tenant_uuid + AND fresh.operation_id = NEW.tenant_source_operation_id + AND fresh.evidence_digest = NEW.tenant_provenance_digest + AND EXISTS ( + SELECT 1 + FROM account_canonical_tenant_identity_claims claim + WHERE claim.canonical_tenant_id = fresh.canonical_tenant_id + AND claim.identity_kind = 'FRESH_GAME_DESIGN' + AND claim.source_operation_id = fresh.operation_id + AND claim.source_target_namespace = fresh.target_namespace + AND claim.source_creation_request_id = fresh.creation_request_id + AND claim.source_request_digest = fresh.request_digest + AND claim.source_game_row_id = fresh.source_game_row_id + AND claim.source_game_tenant_key = fresh.source_game_tenant_key + AND claim.source_provenance_kind = fresh.provenance_kind + AND claim.source_evidence_digest = fresh.evidence_digest + AND claim.source_account_legacy_tenant_id IS NULL + AND claim.source_manifest_digest IS NULL + ) + ) INTO tenant_source_matches; + END IF; + + IF NOT tenant_source_matches THEN + RAISE EXCEPTION 'Canonical Account connect scope has no exact immutable tenant source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_connect_scope_identity_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_connect_scope_records + FOR EACH ROW EXECUTE FUNCTION validate_account_connect_scope_identity(); + +CREATE FUNCTION guard_account_connect_scope_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM account_connect_scope_records + WHERE scope_digest_version = 2 + ) THEN + RAISE EXCEPTION 'Canonical Account connect scope evidence cannot be truncated without cleanup proof' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_connect_scope_truncate_guard + BEFORE TRUNCATE ON account_connect_scope_records + FOR EACH STATEMENT EXECUTE FUNCTION guard_account_connect_scope_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V47__canonical_uuid_join_operation_intents.sql b/services/account-service/src/main/resources/db/migration/V47__canonical_uuid_join_operation_intents.sql new file mode 100644 index 0000000000..342aae7feb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V47__canonical_uuid_join_operation_intents.sql @@ -0,0 +1,337 @@ +-- Retained V1 operation rows keep the shared request-id fence and their exact bytes. New V2 +-- intents use the same journal, but store canonical target identifiers and no numeric aliases. +ALTER TABLE account_join_operations + ADD COLUMN operation_representation_version INTEGER NOT NULL DEFAULT 1, + ADD COLUMN scope_digest_version INTEGER NOT NULL DEFAULT 1, + ADD COLUMN target_class VARCHAR(20), + ADD COLUMN account_uuid UUID, + ADD COLUMN tenant_uuid UUID, + ADD COLUMN tenant_slug VARCHAR(128), + ADD COLUMN playable_state_namespace_uuid UUID, + ADD COLUMN game_instance_uuid UUID; + +ALTER TABLE account_join_operations + ALTER COLUMN tenant_id DROP NOT NULL; + +ALTER TABLE account_join_operations + ALTER COLUMN playable_state_namespace_id DROP NOT NULL; + +ALTER TABLE account_join_operations + ALTER COLUMN game_instance_id DROP NOT NULL; + +ALTER TABLE account_join_operations + DROP CONSTRAINT account_join_operation_positive_versions_check; + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_operation_positive_versions_check + CHECK ( + (operation_representation_version = 1 + AND tenant_id IS NOT NULL AND tenant_id > 0 + AND game_instance_id IS NOT NULL AND game_instance_id > 0 + AND playable_state_namespace_id IS NOT NULL + AND catalog_revision > 0 AND pointer_version > 0 + AND (entitlement_version IS NULL OR entitlement_version > 0)) + OR + (operation_representation_version = 2 + AND tenant_id IS NULL + AND game_instance_id IS NULL + AND playable_state_namespace_id IS NULL + AND catalog_revision > 0 AND pointer_version > 0 + AND (entitlement_version IS NULL OR entitlement_version > 0)) + ); + +ALTER TABLE account_join_operations + DROP CONSTRAINT account_join_intent_digest_version_check; + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_intent_digest_version_check + CHECK ( + (operation_representation_version = 1 + AND intent_digest_version = 1 + AND length(intent_digest) = 71 + AND intent_digest LIKE 'sha256:%') + OR + (operation_representation_version = 2 + AND intent_digest_version = 2 + AND intent_digest_version IS NOT NULL + AND intent_digest IS NOT NULL + AND intent_digest ~ '^sha256:[0-9a-f]{64}$') + ); + +ALTER TABLE account_join_operations + DROP CONSTRAINT account_join_policy_digest_check; + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_policy_digest_check + CHECK ( + (operation_representation_version = 1 + AND ( + (request_digest_version IS NULL + AND request_digest IS NULL + AND entitlement_authority_availability <> 'AVAILABLE' + AND entitlement_version IS NULL + AND allow_public_join IS NULL) + OR + (request_digest_version = 1 + AND request_digest IS NOT NULL + AND length(request_digest) = 71 + AND request_digest LIKE 'sha256:%' + AND entitlement_authority_availability = 'AVAILABLE' + AND entitlement_version IS NOT NULL + AND allow_public_join IS NOT NULL) + )) + OR + (operation_representation_version = 2 + AND ( + (request_digest_version IS NULL + AND request_digest IS NULL + AND entitlement_authority_availability IN ('UNAVAILABLE', 'NOT_EVALUATED') + AND entitlement_version IS NULL + AND allow_public_join IS NULL) + OR + (request_digest_version = 2 + AND request_digest_version IS NOT NULL + AND request_digest IS NOT NULL + AND request_digest ~ '^sha256:[0-9a-f]{64}$' + AND entitlement_authority_availability = 'AVAILABLE' + AND entitlement_version IS NOT NULL + AND entitlement_version > 0 + AND allow_public_join IS NOT NULL) + )) + ); + +ALTER TABLE account_join_operations + ADD CONSTRAINT account_join_operation_representation_check + CHECK ( + (operation_representation_version = 1 + AND scope_digest_version = 1 + AND target_class IS NULL + AND account_uuid IS NULL + AND tenant_uuid IS NULL + AND tenant_slug IS NULL + AND playable_state_namespace_uuid IS NULL + AND game_instance_uuid IS NULL) + OR + (operation_representation_version = 2 + AND scope_digest_version = 2 + AND scope_digest_version IS NOT NULL + AND request_id IS NOT NULL + AND account_id IS NOT NULL + AND verified_caller_binding IS NOT NULL + AND scope_token_hash IS NOT NULL + AND connect_scope_digest IS NOT NULL + AND realm_id IS NOT NULL + AND world_slug IS NOT NULL + AND realm_slug IS NOT NULL + AND playable_state_scope IS NOT NULL + AND catalog_revision IS NOT NULL + AND pointer_version IS NOT NULL + AND intent_digest_version IS NOT NULL + AND intent_digest IS NOT NULL + AND entitlement_authority_availability IS NOT NULL + AND last_attempt_authority_availability IS NOT NULL + AND caller_bound_authority_invalidated IS FALSE + AND status IS NOT NULL + AND btrim(request_id) <> '' + AND verified_caller_binding <> '' + AND scope_token_hash ~ '^sha256:[0-9a-f]{64}$' + AND target_class IS NOT NULL + AND target_class = 'PUBLIC_PRODUCTION' + AND tenant_id IS NULL + AND game_instance_id IS NULL + AND playable_state_namespace_id IS NULL + AND account_uuid IS NOT NULL + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_slug IS NOT NULL AND tenant_slug <> '' + AND realm_id IS NOT NULL + AND realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug IS NOT NULL AND world_slug <> '' + AND realm_slug IS NOT NULL AND realm_slug <> '' + AND playable_state_namespace_uuid IS NOT NULL + AND playable_state_namespace_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_scope IS NOT NULL + AND playable_state_scope IN ('SHARED', 'ISOLATED') + AND game_instance_uuid IS NOT NULL + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND connect_scope_digest ~ '^sha256:[0-9a-f]{64}$' + AND intent_digest IS NOT NULL + AND intent_digest_version = 2 + AND intent_digest ~ '^sha256:[0-9a-f]{64}$' + AND status = 'PENDING' + AND outcome IS NULL + AND membership_id IS NULL + AND outcome_membership_version IS NULL + AND outcome_membership_authority_generation IS NULL) + ); + +-- V2 rows may only bind one available policy after their pending intent. V1 keeps its historical +-- update behavior; legacy readers and writers must not interpret or mutate V2 rows. +-- [jooq ignore start] +CREATE FUNCTION guard_account_join_operation_identity() RETURNS trigger AS $$ +DECLARE + scope_source_matches BOOLEAN := FALSE; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.operation_representation_version = 2 THEN + RAISE EXCEPTION 'Canonical JOIN operation evidence cannot be deleted' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.operation_representation_version = 1 THEN + RETURN NEW; + END IF; + + IF NEW.operation_representation_version IS DISTINCT FROM 2 + OR NEW.scope_digest_version IS DISTINCT FROM 2 + OR NEW.intent_digest_version IS DISTINCT FROM 2 + OR NEW.status IS DISTINCT FROM 'PENDING' + OR NEW.outcome IS NOT NULL + OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM FALSE + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.entitlement_version IS NOT NULL + OR NEW.allow_public_join IS NOT NULL + OR NEW.request_digest_version IS NOT NULL + OR NEW.request_digest IS NOT NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'NOT_EVALUATED' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN operation must start as an exact pending intent' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM account_connect_scope_records scope_row + WHERE scope_row.scope_token_hash = NEW.scope_token_hash + AND scope_row.scope_digest_version = 2 + AND scope_row.snapshot_digest = NEW.connect_scope_digest + AND scope_row.account_id = NEW.account_id + AND scope_row.account_uuid = NEW.account_uuid + AND scope_row.target_class = NEW.target_class + AND scope_row.tenant_id IS NULL + AND scope_row.tenant_uuid = NEW.tenant_uuid + AND scope_row.tenant_slug = NEW.tenant_slug + AND scope_row.realm_id = NEW.realm_id + AND scope_row.world_slug = NEW.world_slug + AND scope_row.realm_slug = NEW.realm_slug + AND scope_row.playable_state_namespace_id IS NULL + AND scope_row.playable_state_namespace_uuid = NEW.playable_state_namespace_uuid + AND scope_row.playable_state_scope = NEW.playable_state_scope + AND scope_row.game_instance_id IS NULL + AND scope_row.game_instance_uuid = NEW.game_instance_uuid + AND scope_row.catalog_revision = NEW.catalog_revision + AND scope_row.pointer_version = NEW.pointer_version + ) INTO scope_source_matches; + IF NOT scope_source_matches THEN + RAISE EXCEPTION 'Canonical JOIN operation has no exact persisted scope source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version = 1 THEN + IF NEW.operation_representation_version <> 1 THEN + RAISE EXCEPTION 'Retained JOIN operation evidence cannot change representation' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_representation_version <> 2 + OR NEW.operation_representation_version <> 2 + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.verified_caller_binding IS DISTINCT FROM OLD.verified_caller_binding + OR NEW.scope_token_hash IS DISTINCT FROM OLD.scope_token_hash + OR NEW.connect_scope_digest IS DISTINCT FROM OLD.connect_scope_digest + OR NEW.world_slug IS DISTINCT FROM OLD.world_slug + OR NEW.realm_slug IS DISTINCT FROM OLD.realm_slug + OR NEW.realm_id IS DISTINCT FROM OLD.realm_id + OR NEW.playable_state_namespace_id IS DISTINCT FROM OLD.playable_state_namespace_id + OR NEW.playable_state_scope IS DISTINCT FROM OLD.playable_state_scope + OR NEW.game_instance_id IS DISTINCT FROM OLD.game_instance_id + OR NEW.catalog_revision IS DISTINCT FROM OLD.catalog_revision + OR NEW.pointer_version IS DISTINCT FROM OLD.pointer_version + OR NEW.intent_digest_version IS DISTINCT FROM OLD.intent_digest_version + OR NEW.intent_digest IS DISTINCT FROM OLD.intent_digest + OR NEW.scope_digest_version IS DISTINCT FROM OLD.scope_digest_version + OR NEW.target_class IS DISTINCT FROM OLD.target_class + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.tenant_slug IS DISTINCT FROM OLD.tenant_slug + OR NEW.playable_state_namespace_uuid IS DISTINCT FROM OLD.playable_state_namespace_uuid + OR NEW.game_instance_uuid IS DISTINCT FROM OLD.game_instance_uuid + OR NEW.status IS DISTINCT FROM 'PENDING' + OR NEW.outcome IS NOT NULL + OR NEW.membership_id IS NOT NULL + OR NEW.outcome_membership_version IS NOT NULL + OR NEW.outcome_membership_authority_generation IS NOT NULL + OR NEW.caller_bound_authority_invalidated IS DISTINCT FROM OLD.caller_bound_authority_invalidated + OR NEW.reconciliation_attempt_count IS DISTINCT FROM OLD.reconciliation_attempt_count + OR NEW.last_reconciliation_attempt_at IS DISTINCT FROM OLD.last_reconciliation_attempt_at + OR NEW.last_reconciliation_attempt_reason IS DISTINCT FROM OLD.last_reconciliation_attempt_reason + OR NEW.next_reconciliation_attempt_at IS DISTINCT FROM OLD.next_reconciliation_attempt_at + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Canonical JOIN operation intent evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.request_digest IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN available policy evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.request_digest IS NOT NULL THEN + IF NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.entitlement_version IS NULL + OR NEW.allow_public_join IS NULL + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'AVAILABLE' + OR NEW.last_attempt_failure_code IS NOT NULL THEN + RAISE EXCEPTION 'Canonical JOIN policy binding is incomplete' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.request_digest_version IS NOT NULL + OR NEW.entitlement_version IS NOT NULL + OR NEW.allow_public_join IS NOT NULL + OR NEW.entitlement_authority_availability IS DISTINCT FROM 'UNAVAILABLE' + OR NEW.last_attempt_authority_availability IS DISTINCT FROM 'UNAVAILABLE' + OR NEW.last_attempt_failure_code IS NULL + OR btrim(NEW.last_attempt_failure_code) = '' THEN + RAISE EXCEPTION 'Canonical JOIN unavailable attempt cannot invent policy evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_join_operation_identity_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_join_operations + FOR EACH ROW EXECUTE FUNCTION guard_account_join_operation_identity(); + +CREATE FUNCTION guard_account_join_operation_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM account_join_operations + WHERE operation_representation_version = 2 + ) THEN + RAISE EXCEPTION 'Canonical JOIN operation evidence cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_join_operation_truncate_guard + BEFORE TRUNCATE ON account_join_operations + FOR EACH STATEMENT EXECUTE FUNCTION guard_account_join_operation_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V48__canonical_uuid_membership_transition_receipts.sql b/services/account-service/src/main/resources/db/migration/V48__canonical_uuid_membership_transition_receipts.sql new file mode 100644 index 0000000000..f8c28ba992 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V48__canonical_uuid_membership_transition_receipts.sql @@ -0,0 +1,367 @@ +-- Widen the existing provisional receipt family. V1 head keys and receipt bytes remain intact; +-- canonical receipts consume the same per-head sequence and global request-ID fence. +ALTER TABLE account_membership_transition_receipts + DROP CONSTRAINT account_membership_transition_receipts_stream_fk; + +ALTER TABLE account_membership_transition_receipt_stream_heads + DROP CONSTRAINT account_membership_transition_receipt_stream_heads_pk; + +ALTER TABLE account_membership_transition_receipt_stream_heads + ADD COLUMN receipt_head_id BIGINT GENERATED ALWAYS AS IDENTITY; + +ALTER TABLE account_membership_transition_receipt_stream_heads + ADD COLUMN account_uuid UUID; + +ALTER TABLE account_membership_transition_receipt_stream_heads + ADD COLUMN tenant_uuid UUID; + +ALTER TABLE account_membership_transition_receipt_stream_heads + ADD COLUMN tenant_provenance_kind VARCHAR(32); + +ALTER TABLE account_membership_transition_receipt_stream_heads + ADD COLUMN tenant_source_operation_id UUID; + +ALTER TABLE account_membership_transition_receipt_stream_heads + ADD COLUMN tenant_provenance_digest VARCHAR(71); + +ALTER TABLE account_membership_transition_receipt_stream_heads + ALTER COLUMN tenant_id DROP NOT NULL; + +ALTER TABLE account_membership_transition_receipt_stream_heads + ADD CONSTRAINT account_membership_transition_receipt_stream_heads_pk + PRIMARY KEY (receipt_head_id); + +ALTER TABLE account_membership_transition_receipt_stream_heads + DROP CONSTRAINT account_membership_transition_receipt_stream_heads_key_check; + +ALTER TABLE account_membership_transition_receipt_stream_heads + ADD CONSTRAINT account_membership_transition_receipt_stream_heads_numeric_pair_unique + UNIQUE (account_id, tenant_id); + +ALTER TABLE account_membership_transition_receipt_stream_heads + ADD CONSTRAINT account_membership_transition_receipt_stream_heads_canonical_pair_unique + UNIQUE (account_uuid, tenant_uuid); + +ALTER TABLE account_membership_transition_receipt_stream_heads + ADD CONSTRAINT account_membership_transition_receipt_stream_heads_identity_check + CHECK ( + (account_uuid IS NULL + AND tenant_uuid IS NULL + AND tenant_provenance_kind IS NULL + AND tenant_source_operation_id IS NULL + AND tenant_provenance_digest IS NULL + AND tenant_id IS NOT NULL + AND tenant_id > 0 + AND receipt_stream_key = + 'account:membership-transition-receipt:v1:membership/' + || account_id::TEXT || '/' || tenant_id::TEXT) + OR + (account_uuid IS NOT NULL + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_provenance_kind IS NOT NULL + AND tenant_source_operation_id IS NOT NULL + AND tenant_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_provenance_digest IS NOT NULL + AND tenant_provenance_digest ~ '^sha256:[0-9a-f]{64}$' + AND ( + (tenant_provenance_kind = 'APPROVED_RETAINED' + AND tenant_id IS NOT NULL + AND tenant_id > 0 + AND receipt_stream_key = + 'account:membership-transition-receipt:v1:membership/' + || account_id::TEXT || '/' || tenant_id::TEXT) + OR + (tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND tenant_id IS NULL + AND receipt_stream_key = + 'account:membership-transition-receipt:v2:membership/' + || account_uuid::TEXT || '/' || tenant_uuid::TEXT) + )) + ); + +ALTER TABLE account_membership_transition_receipts + ADD CONSTRAINT account_membership_transition_receipts_stream_fk + FOREIGN KEY (account_id, tenant_id) + REFERENCES account_membership_transition_receipt_stream_heads (account_id, tenant_id) + ON DELETE RESTRICT; + +ALTER TABLE account_membership_transition_receipts + ADD COLUMN receipt_head_id BIGINT; + +ALTER TABLE account_membership_transition_receipts + ADD COLUMN receipt_version SMALLINT NOT NULL DEFAULT 1; + +ALTER TABLE account_membership_transition_receipts + ADD COLUMN account_uuid UUID; + +ALTER TABLE account_membership_transition_receipts + ADD COLUMN tenant_uuid UUID; + +ALTER TABLE account_membership_transition_receipts + ADD COLUMN tenant_provenance_kind VARCHAR(32); + +ALTER TABLE account_membership_transition_receipts + ADD COLUMN tenant_source_operation_id UUID; + +ALTER TABLE account_membership_transition_receipts + ADD COLUMN tenant_provenance_digest VARCHAR(71); + +ALTER TABLE account_membership_transition_receipts + ALTER COLUMN tenant_id DROP NOT NULL; + +-- V41 protects retained receipt bytes from runtime mutation. Disable only that row guard for +-- this migration-owned key backfill, then restore it before the migration continues. +-- [jooq ignore start] +ALTER TABLE account_membership_transition_receipts + DISABLE TRIGGER account_membership_transition_receipts_append_only; +-- [jooq ignore stop] + +UPDATE account_membership_transition_receipts receipt +SET receipt_head_id = ( + SELECT head.receipt_head_id + FROM account_membership_transition_receipt_stream_heads head + WHERE receipt.account_id = head.account_id + AND receipt.tenant_id = head.tenant_id +) +WHERE EXISTS ( + SELECT 1 + FROM account_membership_transition_receipt_stream_heads head + WHERE receipt.account_id = head.account_id + AND receipt.tenant_id = head.tenant_id +); + +-- [jooq ignore start] +ALTER TABLE account_membership_transition_receipts + ENABLE TRIGGER account_membership_transition_receipts_append_only; +-- [jooq ignore stop] + +ALTER TABLE account_membership_transition_receipts + ALTER COLUMN receipt_head_id SET NOT NULL; + +ALTER TABLE account_membership_transition_receipts + DROP CONSTRAINT account_membership_transition_receipts_key_check; + +ALTER TABLE account_membership_transition_receipts + ADD CONSTRAINT account_membership_transition_receipts_head_sequence_unique + UNIQUE (receipt_head_id, receipt_sequence); + +ALTER TABLE account_membership_transition_receipts + ADD CONSTRAINT account_membership_transition_receipts_head_fk + FOREIGN KEY (receipt_head_id) + REFERENCES account_membership_transition_receipt_stream_heads (receipt_head_id) + ON DELETE RESTRICT; + +ALTER TABLE account_membership_transition_receipts + ADD CONSTRAINT account_membership_transition_receipts_version_check + CHECK (receipt_version IN (1, 2)); + +ALTER TABLE account_membership_transition_receipts + ADD CONSTRAINT account_membership_transition_receipts_key_check + CHECK ( + (receipt_version = 1 + AND account_uuid IS NULL + AND tenant_uuid IS NULL + AND tenant_provenance_kind IS NULL + AND tenant_source_operation_id IS NULL + AND tenant_provenance_digest IS NULL + AND tenant_id IS NOT NULL + AND receipt_stream_key = + 'account:membership-transition-receipt:v1:membership/' + || account_id::TEXT || '/' || tenant_id::TEXT) + OR + (receipt_version = 2 + AND account_uuid IS NOT NULL + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_provenance_kind IS NOT NULL + AND tenant_source_operation_id IS NOT NULL + AND tenant_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_provenance_digest IS NOT NULL + AND tenant_provenance_digest ~ '^sha256:[0-9a-f]{64}$' + AND ( + (tenant_provenance_kind = 'APPROVED_RETAINED' + AND tenant_id IS NOT NULL + AND tenant_id > 0) + OR + (tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND tenant_id IS NULL) + ) + AND receipt_stream_key = + 'account:membership-transition-receipt:v2:membership/' + || account_uuid::TEXT || '/' || tenant_uuid::TEXT) + ); + +CREATE INDEX idx_account_membership_transition_receipts_canonical_latest + ON account_membership_transition_receipts + (account_uuid, tenant_uuid, receipt_sequence DESC) + WHERE receipt_version = 2; + +-- [jooq ignore start] +CREATE FUNCTION validate_account_membership_receipt_head_identity() RETURNS trigger AS $$ +DECLARE + persisted_account_uuid UUID; + source_matches BOOLEAN := FALSE; +BEGIN + IF TG_OP = 'UPDATE' THEN + IF NEW.receipt_head_id IS DISTINCT FROM OLD.receipt_head_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.receipt_stream_key IS DISTINCT FROM OLD.receipt_stream_key THEN + RAISE EXCEPTION 'Account membership receipt head storage identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.last_receipt_sequence < OLD.last_receipt_sequence + OR (NEW.last_receipt_sequence <> OLD.last_receipt_sequence + AND (OLD.last_receipt_sequence = 9223372036854775807 + OR NEW.last_receipt_sequence <> OLD.last_receipt_sequence + 1)) THEN + RAISE EXCEPTION 'Account membership receipt sequence cannot reset, skip, or wrap' + USING ERRCODE = 'check_violation'; + END IF; + IF OLD.account_uuid IS NOT NULL AND ( + NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.tenant_provenance_kind IS DISTINCT FROM OLD.tenant_provenance_kind + OR NEW.tenant_source_operation_id IS DISTINCT FROM OLD.tenant_source_operation_id + OR NEW.tenant_provenance_digest IS DISTINCT FROM OLD.tenant_provenance_digest) THEN + RAISE EXCEPTION 'Canonical Account membership receipt head identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF OLD.account_uuid IS NULL AND NEW.account_uuid IS NOT NULL + AND NEW.tenant_provenance_kind <> 'APPROVED_RETAINED' THEN + RAISE EXCEPTION 'Only an approved retained receipt head may be bound in place' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + + IF NEW.account_uuid IS NULL THEN + RETURN NEW; + END IF; + + SELECT account.account_uuid + INTO persisted_account_uuid + FROM accounts account + WHERE account.id = NEW.account_id; + IF persisted_account_uuid IS DISTINCT FROM NEW.account_uuid THEN + RAISE EXCEPTION 'Account membership receipt head Account UUID is not persisted' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.tenant_provenance_kind = 'APPROVED_RETAINED' THEN + SELECT EXISTS ( + SELECT 1 + FROM account_approved_legacy_tenant_associations retained + JOIN account_canonical_tenant_identity_claims claim + ON claim.canonical_tenant_id = retained.canonical_tenant_id + AND claim.identity_kind = retained.identity_kind + AND claim.source_operation_id = retained.operation_id + AND claim.source_account_legacy_tenant_id = retained.legacy_tenant_id + AND claim.source_target_namespace = retained.target_namespace + AND claim.source_creation_request_id IS NULL + AND claim.source_request_digest IS NULL + AND claim.source_game_row_id = retained.source_game_row_id + AND claim.source_game_tenant_key = retained.source_legacy_game_tenant_id + AND claim.source_provenance_kind IS NULL + AND claim.source_evidence_digest = retained.account_evidence_digest + AND claim.source_manifest_digest = retained.manifest_digest + WHERE retained.legacy_tenant_id = NEW.tenant_id + AND retained.canonical_tenant_id = NEW.tenant_uuid + AND retained.operation_id = NEW.tenant_source_operation_id + AND retained.manifest_digest = NEW.tenant_provenance_digest + ) INTO source_matches; + ELSIF NEW.tenant_provenance_kind = 'FRESH_GAME_DESIGN' THEN + SELECT EXISTS ( + SELECT 1 + FROM account_fresh_tenant_identity_associations fresh + JOIN account_canonical_tenant_identity_claims claim + ON claim.canonical_tenant_id = fresh.canonical_tenant_id + AND claim.identity_kind = fresh.identity_kind + AND claim.source_operation_id = fresh.operation_id + AND claim.source_target_namespace = fresh.target_namespace + AND claim.source_creation_request_id = fresh.creation_request_id + AND claim.source_request_digest = fresh.request_digest + AND claim.source_game_row_id = fresh.source_game_row_id + AND claim.source_game_tenant_key = fresh.source_game_tenant_key + AND claim.source_provenance_kind = fresh.provenance_kind + AND claim.source_evidence_digest = fresh.evidence_digest + AND claim.source_account_legacy_tenant_id IS NULL + AND claim.source_manifest_digest IS NULL + WHERE fresh.canonical_tenant_id = NEW.tenant_uuid + AND fresh.operation_id = NEW.tenant_source_operation_id + AND fresh.evidence_digest = NEW.tenant_provenance_digest + ) INTO source_matches; + END IF; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Account membership receipt head has no exact immutable tenant source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION validate_account_membership_transition_receipt_head() RETURNS trigger AS $$ +DECLARE + head_row account_membership_transition_receipt_stream_heads%ROWTYPE; +BEGIN + SELECT * INTO head_row + FROM account_membership_transition_receipt_stream_heads head + WHERE head.receipt_head_id = NEW.receipt_head_id; + IF NOT FOUND + OR head_row.account_id IS DISTINCT FROM NEW.account_id + OR head_row.tenant_id IS DISTINCT FROM NEW.tenant_id + OR NEW.receipt_sequence > head_row.last_receipt_sequence THEN + RAISE EXCEPTION 'Account membership transition receipt does not match its shared head' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.receipt_version = 1 THEN + IF head_row.account_uuid IS NOT NULL + AND head_row.tenant_provenance_kind <> 'APPROVED_RETAINED' THEN + RAISE EXCEPTION 'V1 receipt cannot use a canonical-only Account membership head' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.receipt_stream_key IS DISTINCT FROM head_row.receipt_stream_key THEN + RAISE EXCEPTION 'V1 Account membership receipt changed its retained stream key' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF head_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR head_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR head_row.tenant_provenance_kind IS DISTINCT FROM NEW.tenant_provenance_kind + OR head_row.tenant_source_operation_id IS DISTINCT FROM NEW.tenant_source_operation_id + OR head_row.tenant_provenance_digest IS DISTINCT FROM NEW.tenant_provenance_digest THEN + RAISE EXCEPTION 'Canonical Account membership receipt source differs from its head' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION reject_account_membership_transition_receipt_v2_update() RETURNS trigger AS $$ +BEGIN + IF OLD.receipt_version = 2 OR NEW.receipt_version = 2 + OR OLD.receipt_version IS DISTINCT FROM NEW.receipt_version THEN + RAISE EXCEPTION 'Canonical Account membership transition receipts are immutable' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_membership_receipt_head_identity_guard + BEFORE INSERT OR UPDATE ON account_membership_transition_receipt_stream_heads + FOR EACH ROW EXECUTE FUNCTION validate_account_membership_receipt_head_identity(); + +CREATE TRIGGER account_membership_transition_receipt_head_guard + BEFORE INSERT ON account_membership_transition_receipts + FOR EACH ROW EXECUTE FUNCTION validate_account_membership_transition_receipt_head(); + +CREATE TRIGGER account_membership_transition_receipt_v2_immutable + BEFORE UPDATE ON account_membership_transition_receipts + FOR EACH ROW EXECUTE FUNCTION reject_account_membership_transition_receipt_v2_update(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V49__canonical_uuid_audit_identity.sql b/services/account-service/src/main/resources/db/migration/V49__canonical_uuid_audit_identity.sql new file mode 100644 index 0000000000..a37a7586bf --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V49__canonical_uuid_audit_identity.sql @@ -0,0 +1,34 @@ +ALTER TABLE account_audit_outbox + ADD COLUMN tenant_identity_version INTEGER; + +ALTER TABLE account_audit_outbox + ADD COLUMN tenant_uuid UUID; + +-- Retained rows are representation one exactly as stored; the new UUID field stays absent. +UPDATE account_audit_outbox +SET tenant_identity_version = 1; + +ALTER TABLE account_audit_outbox + ALTER COLUMN tenant_identity_version SET NOT NULL; + +ALTER TABLE account_audit_outbox + DROP CONSTRAINT account_audit_outbox_scope_check; + +ALTER TABLE account_audit_outbox + ADD CONSTRAINT account_audit_outbox_scope_identity_check + CHECK ( + (scope = 'platform' + AND tenant_identity_version = 1 + AND tenant_id IS NULL + AND tenant_uuid IS NULL) + OR (scope = 'tenant' + AND tenant_identity_version = 1 + AND tenant_id IS NOT NULL + AND tenant_id > 0 + AND tenant_uuid IS NULL) + OR (scope = 'tenant' + AND tenant_identity_version = 2 + AND tenant_id IS NULL + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::uuid) + ); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalFirstJoinAuthorityEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalFirstJoinAuthorityEventIntegrationTest.java new file mode 100644 index 0000000000..103f2fee86 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCanonicalFirstJoinAuthorityEventIntegrationTest.java @@ -0,0 +1,886 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +import java.util.Objects; +import java.util.Optional; +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.accountservice.AccountServiceApplication; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +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.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.util.AopTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL storage/publisher proof for Account's canonical first-JOIN authority event. + * + *

Policy inputs and source associations are locally seeded owner fixtures. These cases prove + * Account persistence composition only; they do not claim authenticated entitlement, caller, or + * public JOIN flow proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = AccountServiceApplication.class, + properties = { + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, + GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.grpc.workload-namespace=firemud-unit1b" + }) +class AccountCanonicalFirstJoinAuthorityEventIntegrationTest { + private static final String TEST_NAMESPACE = "firemud-unit1b"; + + @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, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private AccountMembershipAuthorityEventProducer producer; + @Autowired private AccountAuthorityGenerationRepository generations; + @Autowired private AccountAuthorityOutboxRepository authorityOutbox; + @Autowired private AccountConnectScopeRepository connectScopes; + @Autowired private AccountJoinOperationRepository joinOperations; + @Autowired private AccountMembershipPairAuthorityRepository pairAuthority; + @Autowired private AccountRepository accounts; + @Autowired private AccountTenantMembershipRepository memberships; + @Autowired private AccountTenantMembershipRoleSnapshotRepository roleSnapshots; + @Autowired private FreshTenantIdentityAssociationRepository freshAssociations; + @Autowired private ApprovedLegacyTenantAssociationRepository approvedAssociations; + @Autowired private LegacyTenantSourceEvidence retainedSourceEvidence; + + @MockitoSpyBean private AccountAuthorityOutboxRepository authorityOutboxSpy; + @MockitoSpyBean private AccountMembershipPairAuthorityRepository pairAuthoritySpy; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @Test + void freshUuidFirstJoinCommitsClosedEventAndPairFromStoredMembershipAndPolicy() { + JoinFixture fixture = freshFixture(true, 9L); + long issuanceFenceBefore = issuanceFence(fixture.account().accountUuid()); + var baseline = fixture.baseline(); + + var checkpoint = publishWithMembershipWrite(fixture); + String streamKey = membershipStreamKey(fixture.account().accountUuid(), fixture.tenantUuid()); + Event persisted = + inTransaction( + () -> authorityOutbox.findEvent(streamKey, fixture.requestId()).orElseThrow()); + var event = + MembershipAuthorityEventV1Codec.verify( + new String(persisted.payload(), StandardCharsets.UTF_8)); + var pair = + inTransaction( + () -> + pairAuthority + .readForUpdate(fixture.account().accountUuid(), fixture.tenantUuid()) + .orElseThrow()); + + assertThat(baseline.membershipVersion()) + .isEqualTo(java.util.Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(checkpoint.outboxSequence()).isEqualTo(1L); + assertThat(persisted.outboxSequence()).isEqualTo(1L); + assertThat(persisted.outboxStreamKey()).isEqualTo(streamKey); + assertThat(event.accountId()).isEqualTo(fixture.account().accountUuid().toString()); + assertThat(event.tenantId()).isEqualTo(fixture.tenantUuid().toString()); + assertThat(event.sourceScope()) + .isEqualTo("membership/" + fixture.account().accountUuid() + "/" + fixture.tenantUuid()); + assertThat(event.membershipVersion()) + .isEqualTo(java.util.Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(event.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(event.authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(event.authorityTuple().accountAuthorityGeneration()).isEqualTo("1"); + assertThat(event.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(java.util.Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(event.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(java.util.Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(event.authorityTuple().privateRealmGrantVersions()).isEmpty(); + assertThat(event.authorityTuple().accountSecurityCutoff()).isEmpty(); + assertThat(event.authorityTuple().tenantBillingCutoff()).isEmpty(); + assertThat(event.roles()).containsExactly("player"); + assertThat(event.gameplayAdmissionAllowed()).isTrue(); + assertThat(event.callerBoundAuthorityInvalidated()).isFalse(); + assertThat(event.issuanceFence()).isEqualTo(Long.toString(issuanceFenceBefore)); + assertThat(checkpoint.sourceEventId()).isEqualTo(event.eventId()); + assertThat(checkpoint.sourceEventDigest()).isEqualTo(event.eventDigest()); + assertThat(pair.membershipExists()).isTrue(); + assertThat(pair.membershipVersion()).isEqualTo(2L); + assertThat(pair.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(pair.lastEventSequence()).isEqualTo(1L); + assertThat(pair.lastEventId()).isEqualTo(event.eventId()); + assertThat(pair.lastEventDigest()).isEqualTo(event.eventDigest()); + assertThat(pair.lastTransitionInvalidated()).isFalse(); + assertThat(issuanceFence(fixture.account().accountUuid())).isEqualTo(issuanceFenceBefore); + assertThat(countReceipts(fixture)).isZero(); + assertThat(generation("MEMBERSHIP", fixture.account().accountUuid(), fixture.tenantUuid())) + .isEqualTo(1L); + + Record membershipRow = + dsl.fetchOne( + "SELECT tenant_id, tenant_uuid, tenant_provenance_kind, tenant_source_operation_id, " + + "tenant_provenance_digest FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_uuid = ?", + fixture.account().accountId(), + fixture.tenantUuid()); + assertThat(membershipRow).isNotNull(); + assertThat(membershipRow.get("tenant_id", Long.class)).isNull(); + assertThat(membershipRow.get("tenant_uuid", UUID.class)).isEqualTo(fixture.tenantUuid()); + assertThat(membershipRow.get("tenant_provenance_kind", String.class)) + .isEqualTo("FRESH_GAME_DESIGN"); + assertThat(membershipRow.get("tenant_source_operation_id", UUID.class)) + .isEqualTo(fixture.provenance().sourceOperationId()); + assertThat(membershipRow.get("tenant_provenance_digest", String.class)) + .isEqualTo(fixture.provenance().digest()); + + Record operation = + dsl.fetchOne( + "SELECT tenant_id, game_instance_id, playable_state_namespace_id, " + + "tenant_uuid, game_instance_uuid, playable_state_namespace_uuid, " + + "status, entitlement_authority_availability, allow_public_join, request_digest " + + "FROM account_join_operations WHERE request_id = ?", + fixture.requestId()); + assertThat(operation).isNotNull(); + assertThat(operation.get("tenant_id", Long.class)).isNull(); + assertThat(operation.get("game_instance_id", Long.class)).isNull(); + assertThat(operation.get("playable_state_namespace_id", String.class)).isNull(); + assertThat(operation.get("tenant_uuid", UUID.class)).isEqualTo(fixture.tenantUuid()); + assertThat(operation.get("game_instance_uuid", UUID.class)) + .isEqualTo(fixture.scope().gameInstanceId()); + assertThat(operation.get("playable_state_namespace_uuid", UUID.class)) + .isEqualTo(fixture.scope().playableStateNamespaceId()); + assertThat(operation.get("status", String.class)).isEqualTo("PENDING"); + assertThat(operation.get("entitlement_authority_availability", String.class)) + .isEqualTo("AVAILABLE"); + assertThat(operation.get("allow_public_join", Boolean.class)).isTrue(); + assertThat(operation.get("request_digest", String.class)) + .isEqualTo( + AccountJoinDigest.requestV2( + fixture.scope(), + fixture.callerBinding(), + AccountJoinDigest.EntitlementAvailabilityV2.AVAILABLE, + true, + 9L)); + } + + @Test + void approvedRetainedUuidAssociationPublishesWithoutInventingTenantIdentity() { + JoinFixture fixture = retainedFixture(true, 7L); + var checkpoint = publishWithMembershipWrite(fixture); + String streamKey = membershipStreamKey(fixture.account().accountUuid(), fixture.tenantUuid()); + Event persisted = + inTransaction( + () -> authorityOutbox.findEvent(streamKey, fixture.requestId()).orElseThrow()); + var event = + MembershipAuthorityEventV1Codec.verify( + new String(persisted.payload(), StandardCharsets.UTF_8)); + var pair = + inTransaction( + () -> + pairAuthority + .readForUpdate(fixture.account().accountUuid(), fixture.tenantUuid()) + .orElseThrow()); + + assertThat(fixture.provenance().kind()).isEqualTo(TenantProvenanceKind.APPROVED_RETAINED); + assertThat(checkpoint.outboxSequence()).isEqualTo(1L); + assertThat(event.membershipVersion()) + .isEqualTo(java.util.Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(event.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(pair.provenance()).isEqualTo(fixture.provenance()); + assertThat(pair.membershipVersion()).isEqualTo(2L); + assertThat(pair.lastEventSequence()).isEqualTo(1L); + assertThat(event.tenantId()).isEqualTo(fixture.tenantUuid().toString()); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_uuid = ? AND tenant_id = ?", + fixture.account().accountId(), + fixture.tenantUuid(), + fixture.provenance().legacyTenantId()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void absentRequestChangedScopeUnavailablePolicyAndChangedDigestAreDenied() { + JoinFixture notEvaluated = freshFixture(null, null); + CanonicalJoinScopeV2 alteredScope = + copyScope(notEvaluated.scope(), "different-world", notEvaluated.scope().tenantId()); + assertDeniedWithoutCommittedMembership( + notEvaluated, alteredScope, notEvaluated.requestId(), "caller-bound-bootstrap"); + assertDeniedWithoutCommittedMembership( + notEvaluated, + copyScope(notEvaluated.scope(), notEvaluated.scope().worldSlug(), UUID.randomUUID()), + notEvaluated.requestId(), + notEvaluated.callerBinding()); + assertDeniedWithoutCommittedMembership( + notEvaluated, + notEvaluated.scope(), + UUID.randomUUID().toString(), + notEvaluated.callerBinding()); + assertDeniedWithoutCommittedMembership( + notEvaluated, notEvaluated.scope(), notEvaluated.requestId(), notEvaluated.callerBinding()); + + JoinFixture deniedPolicy = freshFixture(false, 12L); + assertDeniedWithoutCommittedMembership( + deniedPolicy, deniedPolicy.scope(), deniedPolicy.requestId(), deniedPolicy.callerBinding()); + + JoinFixture changedDigest = freshFixture(true, 14L); + MapSnapshot beforeChangedDigest = pairSnapshot(changedDigest); + String changedDigestStreamKey = + membershipStreamKey(changedDigest.account().accountUuid(), changedDigest.tenantUuid()); + String originalDigest = + AccountJoinDigest.requestV2( + changedDigest.scope(), + changedDigest.callerBinding(), + AccountJoinDigest.EntitlementAvailabilityV2.AVAILABLE, + true, + 14L); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_join_operations SET request_digest = ? WHERE request_id = ?", + "sha256:" + "d".repeat(64), + changedDigest.requestId())) + .hasMessageContaining("Canonical JOIN available policy evidence is immutable"); + assertThat( + dsl.resultQuery( + "SELECT request_digest FROM account_join_operations WHERE request_id = ?", + changedDigest.requestId()) + .fetchOne(0, String.class)) + .isEqualTo(originalDigest); + assertThat(pairSnapshot(changedDigest)).isEqualTo(beforeChangedDigest); + assertThat(countMemberships(changedDigest)).isZero(); + assertThat(countEvents(changedDigestStreamKey)).isZero(); + assertThat(countStreams(changedDigestStreamKey)).isZero(); + } + + @Test + void eventReadbackConflictRollsBackMembershipEventAndPairTogether() { + JoinFixture fixture = freshFixture(true, 9L); + MapSnapshot before = pairSnapshot(fixture); + String streamKey = membershipStreamKey(fixture.account().accountUuid(), fixture.tenantUuid()); + AccountAuthorityOutboxRepository authorityOutboxTarget = + AopTestUtils.getUltimateTargetObject(authorityOutboxSpy); + doAnswer( + invocation -> { + Optional exact = (Optional) invocation.callRealMethod(); + return exact.map( + value -> { + Event event = (Event) value; + return new Event( + event.outboxStreamKey(), + event.requestId(), + event.outboxSequence(), + event.eventId(), + "sha256:" + "e".repeat(64), + event.payload()); + }); + }) + .when(authorityOutboxTarget) + .findEvent(eq(streamKey), eq(fixture.requestId())); + + assertThatThrownBy(() -> publishWithMembershipWrite(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs"); + + assertThat(pairSnapshot(fixture)).isEqualTo(before); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countEvents(streamKey)).isZero(); + assertThat(countStreams(streamKey)).isZero(); + } + + @Test + void failureAfterPairAdvanceRollsBackMembershipEventAndPairTogether() { + JoinFixture fixture = freshFixture(true, 9L); + MapSnapshot before = pairSnapshot(fixture); + String streamKey = membershipStreamKey(fixture.account().accountUuid(), fixture.tenantUuid()); + AccountMembershipPairAuthorityRepository pairAuthorityTarget = + AopTestUtils.getUltimateTargetObject(pairAuthoritySpy); + doAnswer( + invocation -> { + invocation.callRealMethod(); + throw new IllegalStateException("simulated failure after pair advance"); + }) + .when(pairAuthorityTarget) + .commitTransition(any(PairAuthority.class), any(PairTransition.class)); + + assertThatThrownBy(() -> publishWithMembershipWrite(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulated failure after pair advance"); + + assertThat(pairSnapshot(fixture)).isEqualTo(before); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countEvents(streamKey)).isZero(); + assertThat(countStreams(streamKey)).isZero(); + } + + @Test + void retainedMembershipEventHistoryCannotBeResetOrReallocated() { + JoinFixture fixture = freshFixture(true, 9L); + String streamKey = membershipStreamKey(fixture.account().accountUuid(), fixture.tenantUuid()); + inTransaction( + () -> { + authorityOutbox.append( + streamKey, + "retained-history-" + UUID.randomUUID(), + UUID.randomUUID().toString(), + "sha256:" + "a".repeat(64), + "{}".getBytes(StandardCharsets.UTF_8)); + return null; + }); + MapSnapshot before = pairSnapshot(fixture); + + assertThatThrownBy(() -> publishWithMembershipWrite(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("retained membership-event history"); + + assertThat(pairSnapshot(fixture)).isEqualTo(before); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countEvents(streamKey)).isEqualTo(1L); + assertThat(countStreams(streamKey)).isEqualTo(1L); + } + + @Test + void concurrentSameScopePublishersCommitOnlyOneSequenceOneEvent() throws Exception { + JoinFixture fixture = freshFixture(true, 9L); + inTransactionWithoutResult(() -> writeCanonicalMembershipAndRoles(fixture)); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + AtomicInteger successes = new AtomicInteger(); + AtomicInteger rejected = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> publishConcurrently(fixture, ready, start, successes, rejected)); + Future second = + executor.submit(() -> publishConcurrently(fixture, ready, start, successes, rejected)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + first.get(30, TimeUnit.SECONDS); + second.get(30, TimeUnit.SECONDS); + } finally { + start.countDown(); + executor.shutdownNow(); + } + + String streamKey = membershipStreamKey(fixture.account().accountUuid(), fixture.tenantUuid()); + assertThat(successes.get()).isEqualTo(1); + assertThat(rejected.get()).isEqualTo(1); + assertThat(countEvents(streamKey)).isEqualTo(1L); + var pair = + inTransaction( + () -> + pairAuthority + .readForUpdate(fixture.account().accountUuid(), fixture.tenantUuid()) + .orElseThrow()); + assertThat(pair.membershipVersion()).isEqualTo(2L); + assertThat(pair.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(pair.lastEventSequence()).isEqualTo(1L); + } + + private JoinFixture freshFixture(Boolean allowPublicJoin, Long entitlementVersion) { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence evidence = freshEvidence(tenantUuid); + inTransaction( + () -> { + freshAssociations.importVerified(evidence); + generations.initializeTenantIfAbsent(tenantUuid); + generations.initializeIssuerIfAbsent(AccountServiceImpl.ACCOUNT_JWT_ISSUER); + return null; + }); + AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot baseline = + inTransaction( + () -> + producer.readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + evidence.operationId(), + evidence.evidenceDigest()); + return prepareOperation( + account, tenantUuid, provenance, baseline, allowPublicJoin, entitlementVersion); + } + + private JoinFixture retainedFixture(Boolean allowPublicJoin, Long entitlementVersion) { + AccountFixture account = accountFixture(); + long legacyTenantId = positiveRandomLong(); + UUID tenantUuid = UUID.randomUUID(); + seedRetainedTenantSource(legacyTenantId); + String sourceDigest = retainedSourceEvidence.digest(legacyTenantId); + UUID associationOperation = UUID.randomUUID(); + ResolveLegacyAccountTenantAssociationResponse response = + ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(legacyTenantId) + .setCanonicalTenantId(tenantUuid.toString()) + .setSourceLegacyGameTenantId("r-" + UUID.randomUUID().toString().replace("-", "")) + .setSourceGameRowId(positiveRandomLong()) + .setAccountEvidenceDigest(sourceDigest) + .setOperationId(associationOperation.toString()) + .setManifestDigest("sha256:" + "b".repeat(64)) + .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace(TEST_NAMESPACE) + .setSignerKeyId("publisher-fixture") + .setApprovedBy("fixture@example.test") + .setApprovalReference("canonical-first-join-fixture") + .setSignedAt(Instant.parse("2026-10-03T00:00:00Z").toString()) + .setOperationEntryCount(1) + .setManifestSchemaVersion(1) + .build(); + inTransaction( + () -> { + approvedAssociations.importApproved(legacyTenantId, response); + generations.initializeIssuerIfAbsent(AccountServiceImpl.ACCOUNT_JWT_ISSUER); + return null; + }); + inTransactionWithoutResult( + () -> producer.preparePairAuthorityForJoin(account.accountId(), legacyTenantId)); + var baseline = + inTransaction( + () -> pairAuthority.readForUpdate(account.accountUuid(), tenantUuid).orElseThrow()); + assertThat(baseline.membershipExists()).isFalse(); + assertThat(baseline.membershipVersion()).isEqualTo(1L); + assertThat(baseline.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(baseline.lastEventSequence()).isZero(); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + legacyTenantId, + TenantProvenanceKind.APPROVED_RETAINED, + associationOperation, + response.getManifestDigest()); + return prepareOperation( + account, tenantUuid, provenance, null, allowPublicJoin, entitlementVersion); + } + + private JoinFixture prepareOperation( + AccountFixture account, + UUID tenantUuid, + VerifiedTenantProvenance provenance, + AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot baseline, + Boolean allowPublicJoin, + Long entitlementVersion) { + CanonicalJoinScopeV2 scope = canonicalScope(account.accountUuid(), tenantUuid); + String requestId = UUID.randomUUID().toString(); + String callerBinding = "fixture-bootstrap-" + UUID.randomUUID(); + inTransaction( + () -> { + connectScopes.insertCanonical(account.accountId(), scope, provenance); + joinOperations.insertCanonicalIntent(requestId, scope, callerBinding); + if (allowPublicJoin != null) { + joinOperations.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, allowPublicJoin, entitlementVersion); + } + return null; + }); + return new JoinFixture( + account, tenantUuid, provenance, scope, requestId, callerBinding, baseline); + } + + private AccountAuthorityOutboxRepository.Checkpoint publishWithMembershipWrite( + JoinFixture fixture) { + return inTransaction( + () -> { + writeCanonicalMembershipAndRoles(fixture); + return producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope(), fixture.requestId(), fixture.callerBinding()); + }); + } + + private void writeCanonicalMembershipAndRoles(JoinFixture fixture) { + Account account = accounts.findByAccountUuid(fixture.account().accountUuid()).orElseThrow(); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setAccount(account); + membership.setTenantId(fixture.provenance().legacyTenantId()); + membership.setTenantUuid(fixture.tenantUuid()); + membership.setTenantProvenanceKind(fixture.provenance().kind().name()); + membership.setTenantSourceOperationId(fixture.provenance().sourceOperationId()); + membership.setTenantProvenanceDigest(fixture.provenance().digest()); + membership.setGameplayAdmissionAllowed(true); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(2L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + memberships.saveCanonical( + membership, fixture.account().accountUuid(), fixture.tenantUuid(), fixture.provenance()); + roleSnapshots.replaceCanonical( + membership, + fixture.account().accountUuid(), + fixture.tenantUuid(), + fixture.provenance(), + 2L, + java.util.List.of("player")); + } + + private void assertDeniedWithoutCommittedMembership( + JoinFixture fixture, + CanonicalJoinScopeV2 requestScope, + String requestId, + String callerBinding) { + String streamKey = membershipStreamKey(fixture.account().accountUuid(), fixture.tenantUuid()); + MapSnapshot before = pairSnapshot(fixture); + assertThatThrownBy( + () -> + inTransaction( + () -> { + writeCanonicalMembershipAndRoles(fixture); + return producer.publishCanonicalFirstJoinMembershipChange( + requestScope, requestId, callerBinding); + })) + .isInstanceOf(RuntimeException.class); + assertThat(pairSnapshot(fixture)).isEqualTo(before); + assertThat(countMemberships(fixture)).isZero(); + assertThat(countEvents(streamKey)).isZero(); + assertThat(countStreams(streamKey)).isZero(); + } + + private void publishConcurrently( + JoinFixture fixture, + CountDownLatch ready, + CountDownLatch start, + AtomicInteger successes, + AtomicInteger rejected) { + ready.countDown(); + await(start); + try { + inTransaction( + () -> + producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope(), fixture.requestId(), fixture.callerBinding())); + successes.incrementAndGet(); + } catch (RuntimeException conflict) { + rejected.incrementAndGet(); + } + } + + private AccountFixture accountFixture() { + String suffix = UUID.randomUUID().toString().replace("-", ""); + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "first-join-" + suffix, + "canonical-first-join-" + suffix + "@example.test", + "fixture-hash") + .fetchOne(0, Long.class), + "Account fixture insert returned no row ID"); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class), + "Account fixture row has no canonical UUID"); + dsl.execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) VALUES ('ACCOUNT', ?, 1, 1)", + accountUuid); + dsl.execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", + accountUuid); + inTransactionWithoutResult( + () -> generations.initializeIssuerIfAbsent(AccountServiceImpl.ACCOUNT_JWT_ISSUER)); + return new AccountFixture(accountId, accountUuid); + } + + private FreshTenantCreationEvidence freshEvidence(UUID tenantUuid) { + UUID creationRequestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceTenantKey = "f-" + UUID.randomUUID().toString().replace("-", ""); + String requestDigest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, creationRequestId, sourceTenantKey, "First join fixture", null); + long sourceGameRowId = positiveRandomLong(); + String provenanceKind = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind)); + } + + private CanonicalJoinScopeV2 canonicalScope(UUID accountUuid, UUID tenantUuid) { + return new CanonicalJoinScopeV2( + "first-join-scope-" + UUID.randomUUID(), + accountUuid, + tenantUuid, + UUID.randomUUID(), + "join-tenant-" + UUID.randomUUID().toString().substring(0, 8), + "join-world-" + UUID.randomUUID().toString().substring(0, 8), + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 3L, + 2L, + "2026-10-03T00:00:00Z", + "2026-10-03T01:00:00Z"); + } + + private CanonicalJoinScopeV2 copyScope( + CanonicalJoinScopeV2 source, String worldSlug, UUID tenantUuid) { + return new CanonicalJoinScopeV2( + source.connectScopeId(), + source.accountId(), + tenantUuid, + source.realmId(), + source.tenantSlug(), + worldSlug, + source.realmSlug(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.gameInstanceId(), + source.catalogRevision(), + source.pointerVersion(), + source.evaluatedAt(), + source.connectScopeExpiresAt()); + } + + private void seedRetainedTenantSource(long tenantId) { + String suffix = UUID.randomUUID().toString().replace("-", ""); + Record donor = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, ?, ?) RETURNING id", + "retained-source-" + suffix, + "retained-source-" + suffix + "@example.test", + "fixture-hash", + tenantId), + "Retained-tenant donor insert returned no row"); + long donorId = + Objects.requireNonNull( + donor.get("id", Long.class), "Retained-tenant donor row has no numeric ID"); + long membershipId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED') " + + "RETURNING id", + donorId, + tenantId) + .fetchOne(0, Long.class), + "Retained-tenant donor membership insert returned no row ID"); + dsl.execute( + "INSERT INTO account_legacy_tenant_sources " + + "(account_id, legacy_tenant_id, matching_membership_id, " + + "matching_membership_admission_allowed, profile_tenant_count, matching_profile_count, " + + "disposition) VALUES (?, ?, ?, FALSE, 0, 0, 'UNVERIFIED')", + donorId, + tenantId, + membershipId); + dsl.execute( + "INSERT INTO account_legacy_membership_sources " + + "(membership_id, account_id, tenant_id, original_gameplay_admission_allowed, " + + "matches_account_legacy_tenant, disposition) " + + "VALUES (?, ?, ?, FALSE, TRUE, 'UNVERIFIED')", + membershipId, + donorId, + tenantId); + } + + private MapSnapshot pairSnapshot(JoinFixture fixture) { + Record row = + dsl.fetchOne( + "SELECT membership_exists, membership_version, membership_authority_generation, " + + "last_event_sequence, last_event_id, last_event_digest, " + + "last_transition_invalidated FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + fixture.account().accountUuid(), + fixture.tenantUuid()); + assertThat(row).isNotNull(); + return new MapSnapshot(row.intoMap()); + } + + private long countMemberships(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_uuid = ?", + fixture.account().accountId(), + fixture.tenantUuid()) + .fetchOne(0, Long.class), + "Account membership count query returned no value"); + } + + private long countEvents(String streamKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class), + "Account authority event count query returned no value"); + } + + private long countStreams(String streamKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_streams WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class), + "Account authority stream count query returned no value"); + } + + private long countReceipts(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_transition_receipts " + + "WHERE account_uuid = ? AND tenant_uuid = ? AND receipt_version = 2", + fixture.account().accountUuid(), + fixture.tenantUuid()) + .fetchOne(0, Long.class), + "Account transition receipt count query returned no value"); + } + + private long issuanceFence(UUID accountUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class), + "Account issuance fence row has no value"); + } + + private long generation(String kind, UUID accountUuid, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT generation FROM account_authority_generations WHERE scope_kind = ? " + + "AND account_uuid IS NOT DISTINCT FROM ? AND tenant_uuid IS NOT DISTINCT FROM ?", + kind, + accountUuid, + tenantUuid) + .fetchOne(0, Long.class), + "Account authority generation row has no value"); + } + + private String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid; + } + + private T inTransaction(java.util.function.Supplier callback) { + return new TransactionTemplate(transactionManager).execute(status -> callback.get()); + } + + private void inTransactionWithoutResult(Runnable callback) { + new TransactionTemplate(transactionManager).executeWithoutResult(status -> callback.run()); + } + + private long positiveRandomLong() { + long candidate = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return candidate == 0L ? 1L : candidate; + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent publisher barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent publisher was interrupted", exception); + } + } + + private record AccountFixture(long accountId, UUID accountUuid) {} + + private record JoinFixture( + AccountFixture account, + UUID tenantUuid, + VerifiedTenantProvenance provenance, + CanonicalJoinScopeV2 scope, + String requestId, + String callerBinding, + AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot baseline) {} + + private record MapSnapshot(java.util.Map values) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java index 1bfe40f8f3..bf7e2e00fb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java @@ -38,6 +38,7 @@ import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeRepository; import net.firedevops.firemud.accountservice.repository.AccountBareLoginResponseEnvelope; import net.firedevops.firemud.accountservice.repository.AccountCommittedConnectSource; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation.Lifecycle; import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; @@ -1390,7 +1391,11 @@ private PreparedAccount newPreparedAccount() throws Exception { AccountRepository accountRepository = new AccountRepository(dsl); AccountTenantIdentityResolver tenantResolver = new AccountTenantIdentityResolver(associations, sourceEvidence, WORKLOAD_NAMESPACE); - AccountJoinOperationRepository joinRepository = new AccountJoinOperationRepository(dsl); + AccountConnectScopeRepository connectScopeRepository = + new AccountConnectScopeRepository( + dsl, accountRepository, tenantResolver, freshTenantIdentityRepository); + AccountJoinOperationRepository joinRepository = + new AccountJoinOperationRepository(dsl, connectScopeRepository); AccountCommittedConnectSourceReader reader = new AccountCommittedConnectSourceReader( issuanceRepository, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuditCanonicalIdentityPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuditCanonicalIdentityPostgresIntegrationTest.java new file mode 100644 index 0000000000..cf8b53262f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuditCanonicalIdentityPostgresIntegrationTest.java @@ -0,0 +1,377 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof of the typed Account audit storage and V49 retained-row boundary only. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountAuditCanonicalIdentityPostgresIntegrationTest { + private static final long RETAINED_TENANT_ID = 73L; + private static final String CANONICAL_TENANT_UUID = "33333333-3333-4333-8333-333333333333"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void v49BackfillsRetainedV1AndReadsBackTheExactCanonicalEnvelope() { + TestContext context = testContext("48"); + UUID retainedEventId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + String retainedPayload = "{\"retained\":\"exact V1 bytes\"}"; + insertPreV49TenantEnvelope(context.setupDsl(), retainedEventId, retainedPayload); + Map retainedBefore = auditEnvelopeSnapshot(context.setupDsl(), retainedEventId); + + flyway(context.dataSource(), context.schema(), "49").migrate(); + + assertThat(auditEnvelopeSnapshot(context.setupDsl(), retainedEventId)) + .containsExactlyEntriesOf(retainedBefore); + assertThat(identityVersion(context.setupDsl(), retainedEventId)).isEqualTo(1); + assertThat(tenantUuid(context.setupDsl(), retainedEventId)).isNull(); + + AccountAuditOutboxRepository repository = new AccountAuditOutboxRepository(context.dsl()); + String canonicalPayload = "{\"join\":\"immutable UTF-8 payload\"}"; + UUID canonicalEventId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + AccountAuditEnvelope appended = + inTransaction( + context, + () -> + repository.appendCanonicalTenant( + canonicalEventId, + CANONICAL_TENANT_UUID, + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + canonicalPayload)); + + assertThat(appended.tenantIdentityVersion()).isEqualTo(2); + assertThat(appended.tenantId()).isNull(); + assertThat(appended.tenantUuid()).isEqualTo(UUID.fromString(CANONICAL_TENANT_UUID)); + assertThat(identityVersion(context.setupDsl(), canonicalEventId)).isEqualTo(2); + assertThat(tenantId(context.setupDsl(), canonicalEventId)).isNull(); + assertThat(tenantUuid(context.setupDsl(), canonicalEventId)) + .isEqualTo(UUID.fromString(CANONICAL_TENANT_UUID)); + + Optional exactReadback = + inTransaction( + context, () -> repository.findExactCanonicalTenantEnvelopeForUpdate(appended)); + assertThat(exactReadback).contains(appended); + + String changedPayload = canonicalPayload + " "; + AccountAuditEnvelope changedEnvelope = + new AccountAuditEnvelope( + appended.auditEventId(), + appended.scope(), + appended.tenantIdentity(), + appended.producerService(), + appended.eventType(), + appended.occurredAt(), + appended.schemaVersion(), + appended.payloadDigestVersion(), + AccountAuditDigest.ofPayload(changedPayload), + changedPayload); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> repository.findExactCanonicalTenantEnvelopeForUpdate(changedEnvelope))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("immutable original envelope"); + assertThat(auditCount(context.setupDsl())).isEqualTo(2L); + + UUID retainedAppendId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + AccountAuditEnvelope retainedAppend = + inTransaction( + context, + () -> + repository.append( + retainedAppendId, + "tenant", + RETAINED_TENANT_ID, + "ACCOUNT_AUDIT_V1_FIXTURE", + "{\"retained\":true}")); + assertThat(retainedAppend.tenantIdentityVersion()).isEqualTo(1); + assertThat(tenantId(context.setupDsl(), retainedAppendId)).isEqualTo(RETAINED_TENANT_ID); + assertThat(tenantUuid(context.setupDsl(), retainedAppendId)).isNull(); + + long countBeforeInvalidWrites = auditCount(context.setupDsl()); + assertMissingIdentityVersionRejected(context, UUID.randomUUID()); + assertInvalidInsert(context, UUID.randomUUID(), "tenant", null, 1, null); + assertInvalidInsert( + context, UUID.randomUUID(), "tenant", RETAINED_TENANT_ID, 2, CANONICAL_TENANT_UUID); + assertInvalidInsert(context, UUID.randomUUID(), "tenant", null, 2, null); + assertInvalidInsert( + context, UUID.randomUUID(), "tenant", null, 2, "00000000-0000-0000-0000-000000000000"); + assertInvalidInsert(context, UUID.randomUUID(), "tenant", null, 3, CANONICAL_TENANT_UUID); + assertInvalidInsert(context, UUID.randomUUID(), "platform", null, 2, null); + assertThat(auditCount(context.setupDsl())).isEqualTo(countBeforeInvalidWrites); + } + + @Test + void canonicalAppendRollsBackAndRejectsReadOnlyOwnerTransactions() { + TestContext context = testContext("49"); + AccountAuditOutboxRepository repository = new AccountAuditOutboxRepository(context.dsl()); + UUID rolledBackEventId = UUID.randomUUID(); + + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> { + repository.appendCanonicalTenant( + rolledBackEventId, + CANONICAL_TENANT_UUID, + "ACCOUNT_AUDIT_ROLLBACK_TEST", + "{}"); + throw new IllegalStateException("simulate owner transaction rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("simulate owner transaction rollback"); + assertThat(auditCount(context.setupDsl())).isZero(); + + TransactionTemplate readOnly = + new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute( + status -> + repository.appendCanonicalTenant( + UUID.randomUUID(), + CANONICAL_TENANT_UUID, + "ACCOUNT_AUDIT_READ_ONLY_TEST", + "{}"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active read-write owner transaction"); + assertThat(auditCount(context.setupDsl())).isZero(); + } + + @Test + void concurrentExactLockedReadbacksReturnTheSameOriginalEnvelope() throws Exception { + TestContext context = testContext("49"); + AccountAuditOutboxRepository repository = new AccountAuditOutboxRepository(context.dsl()); + String payload = "{\"request\":\"stable\"}"; + AccountAuditEnvelope appended = + inTransaction( + context, + () -> + repository.appendCanonicalTenant( + UUID.randomUUID(), + CANONICAL_TENANT_UUID, + "ACCOUNT_AUDIT_CONCURRENT_READBACK_TEST", + payload)); + + ExecutorService executor = Executors.newFixedThreadPool(2); + CyclicBarrier bothTransactionsStarted = new CyclicBarrier(2); + try { + Future> first = + executor.submit( + () -> + inTransaction( + context, + () -> { + await(bothTransactionsStarted); + return repository.findExactCanonicalTenantEnvelopeForUpdate(appended); + })); + Future> second = + executor.submit( + () -> + inTransaction( + context, + () -> { + await(bothTransactionsStarted); + return repository.findExactCanonicalTenantEnvelopeForUpdate(appended); + })); + + assertThat(first.get(10, TimeUnit.SECONDS)).contains(appended); + assertThat(second.get(10, TimeUnit.SECONDS)).contains(appended); + assertThat(auditCount(context.setupDsl())).isEqualTo(1L); + } finally { + executor.shutdownNow(); + } + } + + private static void insertPreV49TenantEnvelope( + DSLContext dsl, UUID auditEventId, String payload) { + dsl.execute( + "INSERT INTO account_audit_outbox " + + "(audit_event_id, scope, tenant_id, producer_service, event_type, occurred_at, " + + "schema_version, payload_digest_version, payload_digest, payload, delivery_status) " + + "VALUES (?, 'tenant', ?, 'account-service', 'ACCOUNT_AUDIT_RETAINED_TEST', " + + "TIMESTAMP '2026-10-01 12:34:56.123456', 1, 1, ?, ?, 'PENDING')", + auditEventId, + RETAINED_TENANT_ID, + AccountAuditDigest.ofPayload(payload), + payload); + } + + private static Map auditEnvelopeSnapshot(DSLContext dsl, UUID auditEventId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT audit_event_id, scope, tenant_id, producer_service, event_type, " + + "occurred_at, schema_version, payload_digest_version, payload_digest, " + + "payload, receiver_receipt_id, receiver_log_event_id, delivery_status, " + + "last_attempt_at, created_at FROM account_audit_outbox " + + "WHERE audit_event_id = ?", + auditEventId)) + .intoMap(); + } + + private static int identityVersion(DSLContext dsl, UUID auditEventId) { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_identity_version FROM account_audit_outbox WHERE audit_event_id = ?", + auditEventId)); + return Objects.requireNonNull(row.getValue(0, Integer.class)); + } + + private static Long tenantId(DSLContext dsl, UUID auditEventId) { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_id FROM account_audit_outbox WHERE audit_event_id = ?", + auditEventId)); + return row.getValue(0, Long.class); + } + + private static UUID tenantUuid(DSLContext dsl, UUID auditEventId) { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_uuid FROM account_audit_outbox WHERE audit_event_id = ?", + auditEventId)); + return row.getValue(0, UUID.class); + } + + private static long auditCount(DSLContext dsl) { + var row = Objects.requireNonNull(dsl.fetchOne("SELECT COUNT(*) FROM account_audit_outbox")); + return Objects.requireNonNull(row.getValue(0, Long.class)); + } + + private static void assertInvalidInsert( + TestContext context, + UUID auditEventId, + String scope, + Long tenantId, + int identityVersion, + String tenantUuid) { + String payload = "{}"; + assertThatThrownBy( + () -> + context + .setupDsl() + .execute( + "INSERT INTO account_audit_outbox " + + "(audit_event_id, scope, tenant_id, tenant_identity_version, " + + "tenant_uuid, producer_service, event_type, occurred_at, " + + "schema_version, payload_digest_version, payload_digest, payload, " + + "delivery_status) " + + "VALUES (?, ?, ?, ?, CAST(? AS UUID), 'account-service', " + + "'ACCOUNT_AUDIT_INVALID_TEST', TIMESTAMP '2026-10-01 12:34:56', " + + "1, 1, ?, ?, 'PENDING')", + auditEventId, + scope, + tenantId, + identityVersion, + tenantUuid, + AccountAuditDigest.ofPayload(payload), + payload)) + .isInstanceOf(DataAccessException.class); + } + + private static void assertMissingIdentityVersionRejected(TestContext context, UUID auditEventId) { + String payload = "{}"; + assertThatThrownBy( + () -> + context + .setupDsl() + .execute( + "INSERT INTO account_audit_outbox " + + "(audit_event_id, scope, tenant_id, tenant_uuid, producer_service, " + + "event_type, occurred_at, schema_version, payload_digest_version, " + + "payload_digest, payload, delivery_status) " + + "VALUES (?, 'tenant', ?, NULL, 'account-service', " + + "'ACCOUNT_AUDIT_MISSING_VERSION_TEST', " + + "TIMESTAMP '2026-10-01 12:34:56', 1, 1, ?, ?, 'PENDING')", + auditEventId, + RETAINED_TENANT_ID, + AccountAuditDigest.ofPayload(payload), + payload)) + .isInstanceOf(DataAccessException.class); + } + + private static TestContext testContext(String targetVersion) { + String schema = "account_audit_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + flyway(dataSource, schema, targetVersion).migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + return new TestContext(schema, dataSource, setupDsl, transactionDsl, transaction); + } + + private static Flyway flyway( + DriverManagerDataSource dataSource, String schema, String targetVersion) { + return Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target(targetVersion) + .load(); + } + + private static T inTransaction(TestContext context, Supplier operation) { + return Objects.requireNonNull(context.transaction().execute(status -> operation.get())); + } + + private static void await(CyclicBarrier barrier) { + try { + barrier.await(5, TimeUnit.SECONDS); + } catch (Exception ex) { + throw new IllegalStateException("Concurrent audit readback did not synchronize", ex); + } + } + + private record TestContext( + String schema, + DriverManagerDataSource dataSource, + DSLContext setupDsl, + DSLContext dsl, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java new file mode 100644 index 0000000000..60107ea2a9 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountConnectScopeCanonicalIdentityIntegrationTest.java @@ -0,0 +1,1437 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.Callable; +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.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.CanonicalConnectScopeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.CanonicalJoinOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof of the shared V1/V2 scope evidence storage boundary. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountConnectScopeCanonicalIdentityIntegrationTest { + private static final String TEST_NAMESPACE = "account-service"; + private static final long RETAINED_TENANT_ID = 700L; + private static final String RETAINED_MANIFEST_DIGEST = "sha256:" + "b".repeat(64); + private static final String V1_TOKEN = "retained-numeric-scope-token"; + private static final String V1_SCOPE_SELECT = + "SELECT scope_token_hash, account_id, target_class, tenant_id, realm_id, world_slug, " + + "realm_slug, playable_state_namespace_id, playable_state_scope, game_instance_id, " + + "catalog_revision, pointer_version, evaluated_at, connect_scope_expires_at, " + + "playtest_lifecycle_id, playtest_state_generation, snapshot_digest, created_at " + + "FROM account_connect_scope_records WHERE scope_token_hash = ?"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void v2ScopesPreserveV1AndRequireExactUuidSourcesWithoutBearerOrNumericAliases() { + Fixture fixture = fixture(); + SeededRetainedIdentity retained = seedRetainedIdentity(fixture.setupDsl()); + AccountConnectScopeRepository scopes = scopeRepository(fixture).scopes(); + VerifiedJoinScope v1Scope = retainedV1Scope(retained.accountId()); + scopes.insert(v1Scope); + Record v1Before = + fixture.setupDsl().fetchOne(V1_SCOPE_SELECT, AccountJoinDigest.tokenHash(V1_TOKEN)); + assertThat(v1Before).isNotNull(); + + String retainedSourceDigest = + new LegacyTenantSourceEvidence(fixture.setupDsl()).digest(RETAINED_TENANT_ID); + UUID retainedTenantUuid = UUID.randomUUID(); + UUID retainedOperationId = UUID.randomUUID(); + insertApprovedRetainedAssociation( + fixture.setupDsl(), retainedTenantUuid, retainedOperationId, retainedSourceDigest); + + UUID freshTenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence freshAssociation = freshTenantEvidence(freshTenantUuid); + fixture + .transaction() + .executeWithoutResult( + status -> + scopeRepository(fixture).freshTenantIdentities().importVerified(freshAssociation)); + + flyway(fixture.dataSource(), fixture.schema(), "46").migrate(); + + Record v1After = + fixture.setupDsl().fetchOne(V1_SCOPE_SELECT, AccountJoinDigest.tokenHash(V1_TOKEN)); + assertThat(v1After.intoMap()).containsExactlyEntriesOf(v1Before.intoMap()); + Integer v1ScopeDigestVersion = + Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT scope_digest_version FROM account_connect_scope_records " + + "WHERE scope_token_hash = ?", + AccountJoinDigest.tokenHash(V1_TOKEN)) + .fetchOne(0, Integer.class), + "Retained scope digest version must be persisted"); + assertThat(v1ScopeDigestVersion).isEqualTo(1); + + CanonicalConnectScopeRepositoryFixture canonical = scopeRepository(fixture); + VerifiedTenantProvenance retainedProvenance = + new VerifiedTenantProvenance( + RETAINED_TENANT_ID, + TenantProvenanceKind.APPROVED_RETAINED, + retainedOperationId, + RETAINED_MANIFEST_DIGEST); + CanonicalJoinScopeV2 retainedScope = + v2Scope( + "retained-uuid-scope-token", + retained.accountUuid(), + retainedTenantUuid, + "retained-tenant"); + fixture + .transaction() + .executeWithoutResult( + status -> { + canonical + .scopes() + .insertCanonical(retained.accountId(), retainedScope, retainedProvenance); + canonical + .scopes() + .insertCanonical(retained.accountId(), retainedScope, retainedProvenance); + }); + + CanonicalConnectScopeEvidence retainedEvidence = + fixture + .transaction() + .execute( + status -> + canonical + .scopes() + .findCanonicalEvidenceByTokenHash( + AccountJoinDigest.tokenHash(retainedScope.connectScopeId())) + .orElseThrow()); + Optional retainedBearerReadback = + fixture + .transaction() + .execute(status -> canonical.scopes().findCanonical(retainedScope.connectScopeId())); + assertThat(retainedBearerReadback).contains(retainedScope); + assertThat(retainedEvidence.scopeTokenHash()) + .isEqualTo(AccountJoinDigest.tokenHash(retainedScope.connectScopeId())); + assertThat(retainedEvidence.privateAccountId()).isEqualTo(retained.accountId()); + assertThat(retainedEvidence.accountUuid()).isEqualTo(retained.accountUuid()); + assertThat(retainedEvidence.tenantUuid()).isEqualTo(retainedTenantUuid); + assertThat(retainedEvidence.tenantProvenance()).isEqualTo(retainedProvenance); + assertThat(retainedEvidence.scopeDigestVersion()).isEqualTo(2); + assertThat(retainedEvidence.scopeDigest()).isEqualTo(AccountJoinDigest.scopeV2(retainedScope)); + assertThat(retainedEvidence.evaluatedAt()).isEqualTo(retainedScope.evaluatedAt()); + assertThat(retainedEvidence.connectScopeExpiresAt()) + .isEqualTo(retainedScope.connectScopeExpiresAt()); + assertThat(retainedEvidence.scopeDigest()).contains("sha256:"); + Record retainedNumericAliases = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT tenant_id, game_instance_id, playable_state_namespace_id " + + "FROM account_connect_scope_records WHERE scope_token_hash = ?", + retainedEvidence.scopeTokenHash()), + "Canonical scope row must be persisted for alias inspection"); + assertThat(retainedNumericAliases.intoMap()) + .containsEntry("tenant_id", null) + .containsEntry("game_instance_id", null) + .containsEntry("playable_state_namespace_id", null); + Long plaintextBearerColumnCount = + Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM information_schema.columns " + + "WHERE table_schema = ? AND table_name = 'account_connect_scope_records' " + + "AND column_name = 'connect_scope_id'", + fixture.schema()) + .fetchOne(0, Long.class), + "Information-schema column count must be returned"); + assertThat(plaintextBearerColumnCount).isZero(); + + VerifiedTenantProvenance freshProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + freshAssociation.operationId(), + freshAssociation.evidenceDigest()); + CanonicalJoinScopeV2 freshScope = + v2Scope("fresh-uuid-scope-token", retained.accountUuid(), freshTenantUuid, "fresh-tenant"); + fixture + .transaction() + .executeWithoutResult( + status -> + canonical + .scopes() + .insertCanonical(retained.accountId(), freshScope, freshProvenance)); + Optional freshReadback = + fixture + .transaction() + .execute(status -> canonical.scopes().findCanonical(freshScope.connectScopeId())); + assertThat(freshReadback).contains(freshScope); + + CanonicalJoinScopeV2 conflictingRetry = + new CanonicalJoinScopeV2( + retainedScope.connectScopeId(), + retainedScope.accountId(), + retainedScope.tenantId(), + retainedScope.realmId(), + retainedScope.tenantSlug(), + "changed-world", + retainedScope.realmSlug(), + retainedScope.playableStateNamespaceId(), + retainedScope.playableStateScope(), + retainedScope.gameInstanceId(), + retainedScope.catalogRevision(), + retainedScope.pointerVersion(), + retainedScope.evaluatedAt(), + retainedScope.connectScopeExpiresAt()); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + canonical + .scopes() + .insertCanonical( + retained.accountId(), conflictingRetry, retainedProvenance))) + .isInstanceOf(AccountConnectScopeRepository.CanonicalScopeConflictException.class); + + UUID otherAccountUuid = insertAccount(fixture.setupDsl(), "scope-other"); + long otherAccountId = + Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery("SELECT id FROM accounts WHERE account_uuid = ?", otherAccountUuid) + .fetchOne(0, Long.class), + "Secondary Account insert must retain its private row key"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + canonical + .scopes() + .insertCanonical( + otherAccountId, retainedScope, retainedProvenance))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical JOIN scope does not match the locked persisted Account identity"); + + CanonicalJoinScopeV2 wrongTenant = + v2Scope( + "wrong-tenant-scope-token", retained.accountUuid(), UUID.randomUUID(), "wrong-tenant"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + canonical + .scopes() + .insertCanonical( + retained.accountId(), wrongTenant, retainedProvenance))) + .isInstanceOf(IllegalStateException.class); + + VerifiedTenantProvenance wrongSource = + new VerifiedTenantProvenance( + RETAINED_TENANT_ID, + TenantProvenanceKind.APPROVED_RETAINED, + UUID.randomUUID(), + RETAINED_MANIFEST_DIGEST); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + canonical + .scopes() + .insertCanonical(retained.accountId(), retainedScope, wrongSource))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical JOIN scope retained tenant provenance differs from owner readback"); + + CanonicalJoinScopeV2 badOrdering = + new CanonicalJoinScopeV2( + "bad-ordering-scope-token", + retained.accountUuid(), + retainedTenantUuid, + retainedScope.realmId(), + retainedScope.tenantSlug(), + retainedScope.worldSlug(), + retainedScope.realmSlug(), + retainedScope.playableStateNamespaceId(), + retainedScope.playableStateScope(), + retainedScope.gameInstanceId(), + retainedScope.catalogRevision(), + retainedScope.pointerVersion(), + "2026-10-03T00:00:00.1234567891Z", + "2026-10-03T00:00:00.1234567890Z"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + canonical + .scopes() + .insertCanonical( + retained.accountId(), badOrdering, retainedProvenance))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Canonical JOIN scope expiry must be after its exact evaluation time"); + + CanonicalJoinScopeV2 badDigestScope = + v2Scope( + "wrong-digest-scope-token", + retained.accountUuid(), + retainedTenantUuid, + "retained-tenant"); + String incorrectDigest = "sha256:" + "0".repeat(64); + fixture + .transaction() + .executeWithoutResult( + status -> + insertRawCanonicalScope( + fixture.transactionDsl(), + retained.accountId(), + badDigestScope, + retainedProvenance, + incorrectDigest)); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + canonical.scopes().findCanonical(badDigestScope.connectScopeId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical JOIN scope digest mismatch"); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .transactionDsl() + .execute( + "UPDATE account_connect_scope_records SET snapshot_digest = ? " + + "WHERE scope_token_hash = ?", + "sha256:" + "c".repeat(64), + retainedEvidence.scopeTokenHash()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .transactionDsl() + .execute( + "UPDATE account_connect_scope_records SET scope_digest_version = 1 " + + "WHERE scope_token_hash = ?", + retainedEvidence.scopeTokenHash()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .transactionDsl() + .execute( + "DELETE FROM account_connect_scope_records " + + "WHERE scope_token_hash = ?", + retainedEvidence.scopeTokenHash()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .transactionDsl() + .execute("TRUNCATE account_connect_scope_records"))) + .isInstanceOf(DataAccessException.class); + + assertAliasInsertRejected( + fixture.setupDsl(), + retainedEvidence.scopeTokenHash(), + AccountJoinDigest.tokenHash("numeric-tenant-alias-candidate"), + RETAINED_TENANT_ID); + assertThatThrownBy( + () -> + fixture.transaction().execute(status -> canonical.scopes().findCanonical(V1_TOKEN))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("JOIN scope is not canonical digest version 2"); + assertThatThrownBy(() -> canonical.scopes().find(V2_TOKEN_FOR_RETAINED_SCOPE)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("JOIN scope is not retained digest version 1"); + assertThatThrownBy( + () -> canonical.scopes().findEvidenceByTokenHash(retainedEvidence.scopeTokenHash())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("JOIN scope is not retained digest version 1"); + + Optional originalRetainedReadback = + fixture + .transaction() + .execute(status -> canonical.scopes().findCanonical(retainedScope.connectScopeId())); + assertThat(originalRetainedReadback).contains(retainedScope); + Long retainedScopeRowCount = + Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_connect_scope_records " + + "WHERE scope_token_hash = ?", + retainedEvidence.scopeTokenHash()) + .fetchOne(0, Long.class), + "Retained scope row count must be returned"); + assertThat(retainedScopeRowCount).isEqualTo(1L); + } + + @Test + void canonicalJoinJournalSharesRequestIdsAndRetainsPendingHashOnlyIntentEvidence() { + Fixture fixture = fixture(); + SeededRetainedIdentity account = seedRetainedIdentity(fixture.setupDsl()); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence tenantEvidence = freshTenantEvidence(tenantUuid); + fixture + .transaction() + .executeWithoutResult( + status -> + scopeRepository(fixture).freshTenantIdentities().importVerified(tenantEvidence)); + flyway(fixture.dataSource(), fixture.schema(), "46").migrate(); + flyway(fixture.dataSource(), fixture.schema(), "47").migrate(); + + AccountConnectScopeRepository scopes = scopeRepository(fixture).scopes(); + VerifiedTenantProvenance tenantProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantEvidence.operationId(), + tenantEvidence.evidenceDigest()); + CanonicalJoinScopeV2 scope = + v2Scope("canonical-join-scope-token", account.accountUuid(), tenantUuid, "join-tenant"); + fixture + .transaction() + .executeWithoutResult( + status -> scopes.insertCanonical(account.accountId(), scope, tenantProvenance)); + AccountJoinOperationRepository operations = + new AccountJoinOperationRepository(fixture.transactionDsl(), scopes); + + String requestId = "canonical-join-lost-ack"; + String callerBinding = "verified-bootstrap-caller"; + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> { + operations.insertCanonicalIntent(requestId, scope, callerBinding); + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCommit() { + throw new IllegalStateException( + "simulated lost canonical JOIN intent acknowledgement"); + } + }); + })) + .hasMessage("simulated lost canonical JOIN intent acknowledgement"); + Boolean lostAcknowledgementRetryInserted = + fixture + .transaction() + .execute(status -> operations.insertCanonicalIntent(requestId, scope, callerBinding)); + assertThat(lostAcknowledgementRetryInserted).isFalse(); + + CanonicalJoinOperationEvidence pending = + fixture + .transaction() + .execute(status -> operations.findCanonicalEvidenceByRequestId(requestId)) + .orElseThrow(); + assertThat(pending.status()).isEqualTo("PENDING"); + assertThat(pending.operationRepresentationVersion()).isEqualTo(2); + assertThat(pending.scopeDigestVersion()).isEqualTo(2); + assertThat(pending.intentDigestVersion()).isEqualTo(2); + assertThat(pending.intentDigest()) + .isEqualTo(AccountJoinDigest.intentV2(requestId, scope, callerBinding)); + assertThat(pending.entitlementAuthorityAvailability()).isEqualTo("NOT_EVALUATED"); + assertThat(pending.allowPublicJoin()).isNull(); + assertThat(pending.entitlementVersion()).isNull(); + assertThat(pending.requestDigestVersion()).isNull(); + assertThat(pending.requestDigest()).isNull(); + assertThat(pending.toString()).doesNotContain(scope.connectScopeId()); + Record aliases = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT tenant_id, game_instance_id, playable_state_namespace_id, " + + "tenant_uuid, game_instance_uuid, playable_state_namespace_uuid " + + "FROM account_join_operations WHERE request_id = ?", + requestId), + "Canonical JOIN operation must be persisted for alias inspection"); + assertThat(aliases.get("tenant_id", Long.class)).isNull(); + assertThat(aliases.get("game_instance_id", Long.class)).isNull(); + assertThat(aliases.get("playable_state_namespace_id", String.class)).isNull(); + assertThat(aliases.get("tenant_uuid", UUID.class)).isEqualTo(tenantUuid); + assertThat(aliases.get("game_instance_uuid", UUID.class)).isEqualTo(scope.gameInstanceId()); + assertThat(aliases.get("playable_state_namespace_uuid", UUID.class)) + .isEqualTo(scope.playableStateNamespaceId()); + + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.insertCanonicalIntent(requestId, scope, "other-caller"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + CanonicalJoinScopeV2 changedTarget = + new CanonicalJoinScopeV2( + "canonical-join-other-scope-token", + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + "other-world", + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()); + fixture + .transaction() + .executeWithoutResult( + status -> scopes.insertCanonical(account.accountId(), changedTarget, tenantProvenance)); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.insertCanonicalIntent( + requestId, changedTarget, callerBinding))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + + String rollbackRequestId = "canonical-join-rollback"; + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> { + operations.insertCanonicalIntent(rollbackRequestId, scope, callerBinding); + throw new IllegalStateException("simulated canonical JOIN rollback"); + })) + .hasMessage("simulated canonical JOIN rollback"); + Optional rolledBackEvidence = + fixture + .transaction() + .execute(status -> operations.findCanonicalEvidenceByRequestId(rollbackRequestId)); + assertThat(rolledBackEvidence).isEmpty(); + Boolean rollbackRetryInserted = + fixture + .transaction() + .execute( + status -> + operations.insertCanonicalIntent(rollbackRequestId, scope, callerBinding)); + assertThat(rollbackRetryInserted).isTrue(); + + CanonicalJoinOperationEvidence policyBound = + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, true, 9L)); + String expectedPolicyDigest = + AccountJoinDigest.requestV2( + scope, callerBinding, AccountJoinDigest.EntitlementAvailabilityV2.AVAILABLE, true, 9L); + assertThat(policyBound.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(policyBound.allowPublicJoin()).isTrue(); + assertThat(policyBound.entitlementVersion()).isEqualTo(9L); + assertThat(policyBound.requestDigestVersion()).isEqualTo(2); + assertThat(policyBound.requestDigest()).isEqualTo(expectedPolicyDigest); + CanonicalJoinOperationEvidence policyReplay = + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, true, 9L)); + assertThat(policyReplay).isEqualTo(policyBound); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, false, 9L))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, true, 10L))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.recordCanonicalPolicyUnavailable( + requestId, scope, callerBinding, "ENTITLEMENT_UNAVAILABLE"))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + + String unavailableRequestId = "canonical-join-policy-unavailable"; + fixture + .transaction() + .executeWithoutResult( + status -> operations.insertCanonicalIntent(unavailableRequestId, scope, callerBinding)); + CanonicalJoinOperationEvidence unavailable = + fixture + .transaction() + .execute( + status -> + operations.recordCanonicalPolicyUnavailable( + unavailableRequestId, scope, callerBinding, "ENTITLEMENT_UNAVAILABLE")); + assertThat(unavailable.status()).isEqualTo("PENDING"); + assertThat(unavailable.entitlementAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(unavailable.lastAttemptAuthorityAvailability()).isEqualTo("UNAVAILABLE"); + assertThat(unavailable.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(unavailable.allowPublicJoin()).isNull(); + assertThat(unavailable.entitlementVersion()).isNull(); + assertThat(unavailable.requestDigestVersion()).isNull(); + assertThat(unavailable.requestDigest()).isNull(); + + String policyRollbackRequestId = "canonical-join-policy-rollback"; + fixture + .transaction() + .executeWithoutResult( + status -> + operations.insertCanonicalIntent(policyRollbackRequestId, scope, callerBinding)); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> { + operations.bindCanonicalPolicyEvidence( + policyRollbackRequestId, scope, callerBinding, true, 11L); + throw new IllegalStateException("simulated policy binding rollback"); + })) + .hasMessage("simulated policy binding rollback"); + CanonicalJoinOperationEvidence afterPolicyRollback = + fixture + .transaction() + .execute(status -> operations.findCanonicalEvidenceByRequestId(policyRollbackRequestId)) + .orElseThrow(); + assertThat(afterPolicyRollback.entitlementAuthorityAvailability()).isEqualTo("NOT_EVALUATED"); + assertThat(afterPolicyRollback.entitlementVersion()).isNull(); + assertThat(afterPolicyRollback.requestDigest()).isNull(); + + String rawGuardSourceId = "canonical-join-raw-guard-source"; + fixture + .transaction() + .executeWithoutResult( + status -> operations.insertCanonicalIntent(rawGuardSourceId, scope, callerBinding)); + assertRawCanonicalInsertRejected( + fixture.setupDsl(), + rawGuardSourceId, + "canonical-join-raw-invalidated", + true, + "PENDING", + null); + assertRawCanonicalInsertRejected( + fixture.setupDsl(), + rawGuardSourceId, + "canonical-join-raw-terminal", + false, + "FAILED", + "DENIED"); + assertRawCanonicalRequiredSlotRejected( + fixture.setupDsl(), rawGuardSourceId, "canonical-join-raw-missing-target", "target_class"); + assertRawCanonicalRequiredSlotRejected( + fixture.setupDsl(), rawGuardSourceId, "canonical-join-raw-missing-account", "account_uuid"); + assertRawCanonicalRequiredSlotRejected( + fixture.setupDsl(), rawGuardSourceId, "canonical-join-raw-missing-tenant", "tenant_uuid"); + assertRawCanonicalRequiredSlotRejected( + fixture.setupDsl(), + rawGuardSourceId, + "canonical-join-raw-missing-tenant-slug", + "tenant_slug"); + assertRawCanonicalRequiredSlotRejected( + fixture.setupDsl(), + rawGuardSourceId, + "canonical-join-raw-missing-namespace", + "playable_state_namespace_uuid"); + assertRawCanonicalRequiredSlotRejected( + fixture.setupDsl(), + rawGuardSourceId, + "canonical-join-raw-missing-instance", + "game_instance_uuid"); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_join_operations SET operation_representation_version = 3 " + + "WHERE request_id = ?", + requestId)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute("DELETE FROM account_join_operations WHERE request_id = ?", requestId)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> fixture.setupDsl().execute("TRUNCATE TABLE account_join_operations")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_join_operations SET verified_caller_binding = ? " + + "WHERE request_id = ?", + "raw-changed-caller", + requestId)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_join_operations SET allow_public_join = FALSE " + + "WHERE request_id = ?", + requestId)) + .isInstanceOf(DataAccessException.class); + + VerifiedJoinScope v1Scope = retainedV1Scope(account.accountId()); + scopes.insert(v1Scope); + String v1CollisionRequestId = "shared-request-id-v1-first"; + fixture + .transaction() + .executeWithoutResult( + status -> + operations.insertIntent( + v1CollisionRequestId, + v1Scope, + "legacy-caller", + AccountJoinDigest.intent(v1CollisionRequestId, v1Scope, "legacy-caller"))); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.insertCanonicalIntent( + v1CollisionRequestId, scope, callerBinding))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + String v2CollisionRequestId = "shared-request-id-v2-first"; + fixture + .transaction() + .executeWithoutResult( + status -> operations.insertCanonicalIntent(v2CollisionRequestId, scope, callerBinding)); + Boolean v1RetryAgainstV2Inserted = + fixture + .transaction() + .execute( + status -> + operations.insertIntent( + v2CollisionRequestId, + v1Scope, + "legacy-caller", + AccountJoinDigest.intent(v2CollisionRequestId, v1Scope, "legacy-caller"))); + assertThat(v1RetryAgainstV2Inserted).isFalse(); + assertThat(operations.find(v2CollisionRequestId)).isEmpty(); + Optional v2CollisionEvidence = + fixture + .transaction() + .execute(status -> operations.findCanonicalEvidenceByRequestId(v2CollisionRequestId)); + assertThat(v2CollisionEvidence).isPresent(); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + operations.findCanonicalEvidenceByRequestId(v1CollisionRequestId))) + .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_join_operations SET operation_representation_version = 2 " + + "WHERE request_id = ?", + v1CollisionRequestId)) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + operations.bindPolicyEvidence( + requestId, "sha256:" + "a".repeat(64), 1L, true))) + .hasMessage("JOIN operation changed before policy binding"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + operations.recordAttemptFailure( + requestId, "UNAVAILABLE", "LEGACY_FAILURE"))) + .hasMessage("JOIN operation changed while recording attempt failure"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> operations.finish(requestId, "COMMITTED", "JOINED", 1L, 1L, 1L))) + .hasMessage("JOIN operation changed concurrently"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> operations.recordCallerBoundAuthorityInvalidation(requestId))) + .hasMessage("JOIN operation changed concurrently"); + Record v2OperationBefore = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne("SELECT * FROM account_join_operations WHERE request_id = ?", requestId), + "Canonical JOIN operation row must remain readable"); + int expectedAttemptCount = + Objects.requireNonNull( + v2OperationBefore.get("reconciliation_attempt_count", Integer.class), + "Canonical JOIN operation attempt count must be persisted"); + Instant expectedNextAttemptAt = + JooqPersistenceSupport.toInstant( + Objects.requireNonNull( + v2OperationBefore.get("next_reconciliation_attempt_at", LocalDateTime.class), + "Canonical JOIN operation due time must be persisted")); + Instant attemptedAt = Instant.now(); + assertThat( + operations.recordReconciliationAttempt( + requestId, + expectedAttemptCount, + 1, + expectedNextAttemptAt, + attemptedAt, + "legacy selector guard", + attemptedAt.plusSeconds(1))) + .isFalse(); + assertThat(operations.find(requestId)).isEmpty(); + assertThat(operations.findForUpdate(requestId)).isEmpty(); + assertThat(operations.findDuePendingReconciliation(expectedNextAttemptAt, 100)) + .noneMatch(operation -> operation.requestId().equals(requestId)); + Record v2OperationAfter = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne("SELECT * FROM account_join_operations WHERE request_id = ?", requestId), + "Canonical JOIN operation row must remain readable after rejected V1 mutations"); + assertThat(v2OperationAfter.intoMap()).containsExactlyEntriesOf(v2OperationBefore.intoMap()); + } + + @Test + void concurrentCanonicalIntentAndPolicyRetriesRecoverOneImmutableRequestRow() throws Exception { + Fixture fixture = fixture(); + SeededRetainedIdentity account = seedRetainedIdentity(fixture.setupDsl()); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence tenantEvidence = freshTenantEvidence(tenantUuid); + fixture + .transaction() + .executeWithoutResult( + status -> + scopeRepository(fixture).freshTenantIdentities().importVerified(tenantEvidence)); + flyway(fixture.dataSource(), fixture.schema(), "46").migrate(); + flyway(fixture.dataSource(), fixture.schema(), "47").migrate(); + + AccountConnectScopeRepository scopes = scopeRepository(fixture).scopes(); + VerifiedTenantProvenance tenantProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantEvidence.operationId(), + tenantEvidence.evidenceDigest()); + CanonicalJoinScopeV2 scope = + v2Scope( + "concurrent-canonical-join-scope", account.accountUuid(), tenantUuid, "join-tenant"); + fixture + .transaction() + .executeWithoutResult( + status -> scopes.insertCanonical(account.accountId(), scope, tenantProvenance)); + AccountJoinOperationRepository operations = + new AccountJoinOperationRepository(fixture.transactionDsl(), scopes); + + String requestId = "canonical-join-concurrent-exact-retry"; + String callerBinding = "verified-bootstrap-concurrent-caller"; + long membershipsBefore = + Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ?", + account.accountId()) + .fetchOne(0, Long.class)); + long outboxBefore = + Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery("SELECT COUNT(*) FROM account_audit_outbox") + .fetchOne(0, Long.class)); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + CountDownLatch intentReady = new CountDownLatch(2); + CountDownLatch releaseIntents = new CountDownLatch(1); + Future firstInsert = + submitAtBarrier( + executor, + intentReady, + releaseIntents, + () -> + fixture + .transaction() + .execute( + status -> + operations.insertCanonicalIntent(requestId, scope, callerBinding))); + Future secondInsert = + submitAtBarrier( + executor, + intentReady, + releaseIntents, + () -> + fixture + .transaction() + .execute( + status -> + operations.insertCanonicalIntent(requestId, scope, callerBinding))); + assertThat(intentReady.await(15, TimeUnit.SECONDS)).isTrue(); + releaseIntents.countDown(); + boolean firstWasInserted = firstInsert.get(30, TimeUnit.SECONDS); + boolean secondWasInserted = secondInsert.get(30, TimeUnit.SECONDS); + assertThat(firstWasInserted).isNotEqualTo(secondWasInserted); + + CountDownLatch policyReady = new CountDownLatch(2); + CountDownLatch releasePolicy = new CountDownLatch(1); + Future firstPolicy = + submitAtBarrier( + executor, + policyReady, + releasePolicy, + () -> + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, true, 17L))); + Future secondPolicy = + submitAtBarrier( + executor, + policyReady, + releasePolicy, + () -> + fixture + .transaction() + .execute( + status -> + operations.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, true, 17L))); + assertThat(policyReady.await(15, TimeUnit.SECONDS)).isTrue(); + releasePolicy.countDown(); + CanonicalJoinOperationEvidence firstPolicyResult = firstPolicy.get(30, TimeUnit.SECONDS); + CanonicalJoinOperationEvidence secondPolicyResult = secondPolicy.get(30, TimeUnit.SECONDS); + assertThat(secondPolicyResult).isEqualTo(firstPolicyResult); + assertThat(firstPolicyResult.requestId()).isEqualTo(requestId); + assertThat(firstPolicyResult.status()).isEqualTo("PENDING"); + assertThat(firstPolicyResult.intentDigest()) + .isEqualTo(AccountJoinDigest.intentV2(requestId, scope, callerBinding)); + assertThat(firstPolicyResult.requestDigest()) + .isEqualTo( + AccountJoinDigest.requestV2( + scope, + callerBinding, + AccountJoinDigest.EntitlementAvailabilityV2.AVAILABLE, + true, + 17L)); + assertThat(firstPolicyResult.entitlementVersion()).isEqualTo(17L); + assertThat(firstPolicyResult.allowPublicJoin()).isTrue(); + assertThat( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_join_operations WHERE request_id = ?", + requestId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ?", + account.accountId()) + .fetchOne(0, Long.class)) + .isEqualTo(membershipsBefore); + assertThat( + fixture + .setupDsl() + .resultQuery("SELECT COUNT(*) FROM account_audit_outbox") + .fetchOne(0, Long.class)) + .isEqualTo(outboxBefore); + } finally { + executor.shutdownNow(); + } + } + + private static Future submitAtBarrier( + ExecutorService executor, CountDownLatch ready, CountDownLatch release, Callable action) { + return executor.submit( + () -> { + ready.countDown(); + if (!release.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent PostgreSQL fixture barrier timed out"); + } + return action.call(); + }); + } + + private static void assertRawCanonicalInsertRejected( + DSLContext dsl, + String sourceRequestId, + String rejectedRequestId, + boolean callerAuthorityInvalidated, + String status, + String outcome) { + assertRawCanonicalInsertRejected( + dsl, sourceRequestId, rejectedRequestId, callerAuthorityInvalidated, status, outcome, null); + } + + private static void assertRawCanonicalRequiredSlotRejected( + DSLContext dsl, String sourceRequestId, String rejectedRequestId, String missingSlot) { + assertRawCanonicalInsertRejected( + dsl, sourceRequestId, rejectedRequestId, false, "PENDING", null, missingSlot); + } + + private static void assertRawCanonicalInsertRejected( + DSLContext dsl, + String sourceRequestId, + String rejectedRequestId, + boolean callerAuthorityInvalidated, + String status, + String outcome, + String missingSlot) { + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO account_join_operations " + + "(request_id, account_id, tenant_id, verified_caller_binding, " + + "scope_token_hash, connect_scope_digest, world_slug, realm_slug, realm_id, " + + "playable_state_namespace_id, playable_state_scope, game_instance_id, " + + "catalog_revision, pointer_version, intent_digest_version, intent_digest, " + + "entitlement_authority_availability, caller_bound_authority_invalidated, " + + "last_attempt_authority_availability, status, outcome, " + + "operation_representation_version, scope_digest_version, target_class, " + + "account_uuid, tenant_uuid, tenant_slug, playable_state_namespace_uuid, " + + "game_instance_uuid) " + + "SELECT ?, account_id, tenant_id, verified_caller_binding, scope_token_hash, " + + "connect_scope_digest, world_slug, realm_slug, realm_id, " + + "playable_state_namespace_id, playable_state_scope, game_instance_id, " + + "catalog_revision, pointer_version, intent_digest_version, intent_digest, " + + "entitlement_authority_availability, ?, last_attempt_authority_availability, " + + "?, ?, operation_representation_version, scope_digest_version, " + + selectedSlot("target_class", missingSlot) + + ", " + + selectedSlot("account_uuid", missingSlot) + + ", " + + selectedSlot("tenant_uuid", missingSlot) + + ", " + + selectedSlot("tenant_slug", missingSlot) + + ", " + + selectedSlot("playable_state_namespace_uuid", missingSlot) + + ", " + + selectedSlot("game_instance_uuid", missingSlot) + + " " + + "FROM account_join_operations WHERE request_id = ?", + rejectedRequestId, + callerAuthorityInvalidated, + status, + outcome, + sourceRequestId)) + .isInstanceOf(DataAccessException.class); + } + + private static String selectedSlot(String column, String missingSlot) { + if (!column.equals("target_class") + && !column.equals("account_uuid") + && !column.equals("tenant_uuid") + && !column.equals("tenant_slug") + && !column.equals("playable_state_namespace_uuid") + && !column.equals("game_instance_uuid")) { + throw new IllegalArgumentException("Unexpected canonical JOIN slot"); + } + return column.equals(missingSlot) ? "NULL" : column; + } + + private static Fixture fixture() { + String schema = "connect_scope_v2_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + flyway(dataSource, schema, "45").migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + return new Fixture(schema, dataSource, setupDsl, transactionDsl, transaction); + } + + private static Flyway flyway( + DriverManagerDataSource dataSource, String schema, String targetVersion) { + return Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target(targetVersion) + .load(); + } + + private static CanonicalConnectScopeRepositoryFixture scopeRepository(Fixture fixture) { + DSLContext transactionDsl = fixture.transactionDsl(); + AccountRepository accounts = new AccountRepository(transactionDsl); + LegacyTenantSourceEvidence sourceEvidence = new LegacyTenantSourceEvidence(transactionDsl); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(transactionDsl); + ApprovedLegacyTenantAssociationRepository approved = + new ApprovedLegacyTenantAssociationRepository( + transactionDsl, sourceEvidence, TEST_NAMESPACE, generations); + AccountTenantIdentityResolver retained = + new AccountTenantIdentityResolver(approved, sourceEvidence, TEST_NAMESPACE); + FreshTenantIdentityAssociationRepository fresh = + new FreshTenantIdentityAssociationRepository(transactionDsl, TEST_NAMESPACE); + return new CanonicalConnectScopeRepositoryFixture( + new AccountConnectScopeRepository(transactionDsl, accounts, retained, fresh), fresh); + } + + private static SeededRetainedIdentity seedRetainedIdentity(DSLContext dsl) { + String suffix = UUID.randomUUID().toString().replace("-", ""); + Record account = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, ?, ?) RETURNING id, account_uuid", + "connect-scope-v2-" + suffix, + "connect-scope-v2-" + suffix + "@example.test", + "opaque-test-hash", + RETAINED_TENANT_ID), + "Account insert must return exact persisted identity"); + long accountId = + Objects.requireNonNull( + account.get("id", Long.class), "Persisted Account row key is required"); + UUID accountUuid = + Objects.requireNonNull( + account.get("account_uuid", UUID.class), "Persisted Account UUID is required"); + Long membershipId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED') " + + "RETURNING id", + accountId, + RETAINED_TENANT_ID) + .fetchOne(0, Long.class), + "Retained membership insert must return its persisted id"); + dsl.execute( + "INSERT INTO account_legacy_tenant_sources " + + "(account_id, legacy_tenant_id, matching_membership_id, " + + "matching_membership_admission_allowed, profile_tenant_count, " + + "matching_profile_count, disposition) " + + "VALUES (?, ?, ?, FALSE, 0, 0, 'UNVERIFIED')", + accountId, + RETAINED_TENANT_ID, + membershipId); + dsl.execute( + "INSERT INTO account_legacy_membership_sources " + + "(membership_id, account_id, tenant_id, original_gameplay_admission_allowed, " + + "matches_account_legacy_tenant, disposition) " + + "VALUES (?, ?, ?, FALSE, TRUE, 'UNVERIFIED')", + membershipId, + accountId, + RETAINED_TENANT_ID); + return new SeededRetainedIdentity(accountId, accountUuid); + } + + private static void insertApprovedRetainedAssociation( + DSLContext dsl, UUID tenantUuid, UUID operationId, String sourceDigest) { + dsl.execute( + "INSERT INTO account_approved_legacy_tenant_associations " + + "(legacy_tenant_id, canonical_tenant_id, source_legacy_game_tenant_id, " + + "source_game_row_id, account_evidence_digest, operation_id, manifest_digest, " + + "manifest_signature, target_namespace, signer_key_id, approved_by, " + + "approval_reference, signed_at, operation_entry_count, manifest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1)", + RETAINED_TENANT_ID, + tenantUuid, + "legacy-game-tenant-700", + RETAINED_TENANT_ID, + sourceDigest, + operationId, + RETAINED_MANIFEST_DIGEST, + Base64.getEncoder().encodeToString(new byte[64]), + TEST_NAMESPACE, + "fixture-signing-key", + "fixture-operator", + "connect-scope-v2-fixture", + "2026-10-03T00:00:00Z"); + } + + private static UUID insertAccount(DSLContext dsl, String prefix) { + String suffix = UUID.randomUUID().toString().replace("-", ""); + return Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) " + + "RETURNING account_uuid", + prefix + "-" + suffix, + prefix + "-" + suffix + "@example.test", + "opaque-test-hash") + .fetchOne(0, UUID.class), + "Secondary Account insert must return its canonical UUID"); + } + + private static VerifiedJoinScope retainedV1Scope(long accountId) { + VerifiedJoinScope base = + new VerifiedJoinScope( + V1_TOKEN, + accountId, + RETAINED_TENANT_ID, + UUID.fromString("7ac47b2d-fbe5-45eb-a16c-3914cf70c71a"), + "retained-world", + "production", + "legacy-namespace-44", + "SHARED", + 44L, + 23L, + 17L, + "2026-10-03T00:00:00Z", + "2026-10-03T00:02:00Z", + "unused"); + return new VerifiedJoinScope( + base.connectScopeId(), + base.accountId(), + base.tenantId(), + base.realmId(), + base.worldSlug(), + base.realmSlug(), + base.playableStateNamespaceId(), + base.playableStateScope(), + base.gameInstanceId(), + base.catalogRevision(), + base.pointerVersion(), + base.evaluatedAt(), + base.connectScopeExpiresAt(), + AccountJoinDigest.scope(base)); + } + + private static CanonicalJoinScopeV2 v2Scope( + String token, UUID accountUuid, UUID tenantUuid, String tenantSlug) { + return new CanonicalJoinScopeV2( + token, + accountUuid, + tenantUuid, + UUID.fromString("e2b33891-a9a6-4b6f-9c2a-a71f078570dc"), + tenantSlug, + "world-" + tenantSlug, + "production", + UUID.fromString("156fc510-d536-4974-a350-79fbd4d6a1bc"), + "SHARED", + UUID.fromString("7701a6e2-d178-4a3f-97c8-72130c685f4b"), + 8L, + 5L, + "2026-10-03T00:00:00.1234567890Z", + "2026-10-03T00:00:00.1234567891Z"); + } + + private static FreshTenantCreationEvidence freshTenantEvidence(UUID tenantUuid) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceTenantKey = "f-" + UUID.randomUUID().toString().replace("-", ""); + String requestDigest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, requestId, sourceTenantKey, "Scope fixture tenant", null); + long sourceGameRowId = 701L; + String sourceKind = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + sourceKind, + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + sourceKind)); + } + + private static void insertRawCanonicalScope( + DSLContext dsl, + long accountId, + CanonicalJoinScopeV2 scope, + VerifiedTenantProvenance provenance, + String storedDigest) { + dsl.execute( + "INSERT INTO account_connect_scope_records " + + "(scope_token_hash, account_id, target_class, tenant_id, realm_id, world_slug, " + + "realm_slug, playable_state_namespace_id, playable_state_scope, game_instance_id, " + + "catalog_revision, pointer_version, evaluated_at, connect_scope_expires_at, " + + "snapshot_digest, scope_digest_version, account_uuid, tenant_uuid, tenant_slug, " + + "playable_state_namespace_uuid, game_instance_uuid, tenant_provenance_kind, " + + "tenant_provenance_legacy_tenant_id, tenant_source_operation_id, " + + "tenant_provenance_digest) " + + "VALUES (?, ?, 'PUBLIC_PRODUCTION', NULL, ?, ?, ?, NULL, ?, NULL, ?, ?, ?, ?, ?, " + + "2, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + AccountJoinDigest.tokenHash(scope.connectScopeId()), + accountId, + scope.realmId(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateScope(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + storedDigest, + scope.accountId(), + scope.tenantId(), + scope.tenantSlug(), + scope.playableStateNamespaceId(), + scope.gameInstanceId(), + provenance.kind().name(), + provenance.legacyTenantId(), + provenance.sourceOperationId(), + provenance.digest()); + } + + private static void assertAliasInsertRejected( + DSLContext dsl, String sourceHash, String uniqueHash, long numericAlias) { + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO account_connect_scope_records " + + "(scope_token_hash, account_id, target_class, tenant_id, realm_id, " + + "world_slug, realm_slug, playable_state_namespace_id, playable_state_scope, " + + "game_instance_id, catalog_revision, pointer_version, evaluated_at, " + + "connect_scope_expires_at, playtest_lifecycle_id, playtest_state_generation, " + + "snapshot_digest, scope_digest_version, account_uuid, tenant_uuid, " + + "tenant_slug, playable_state_namespace_uuid, game_instance_uuid, " + + "tenant_provenance_kind, tenant_provenance_legacy_tenant_id, " + + "tenant_source_operation_id, tenant_provenance_digest) " + + "SELECT ?, account_id, target_class, ?, realm_id, world_slug, realm_slug, " + + "playable_state_namespace_id, playable_state_scope, game_instance_id, " + + "catalog_revision, pointer_version, evaluated_at, connect_scope_expires_at, " + + "playtest_lifecycle_id, playtest_state_generation, snapshot_digest, " + + "scope_digest_version, account_uuid, tenant_uuid, tenant_slug, " + + "playable_state_namespace_uuid, game_instance_uuid, tenant_provenance_kind, " + + "tenant_provenance_legacy_tenant_id, tenant_source_operation_id, " + + "tenant_provenance_digest FROM account_connect_scope_records " + + "WHERE scope_token_hash = ?", + uniqueHash, + numericAlias, + sourceHash)) + .isInstanceOf(DataAccessException.class); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext setupDsl, + DSLContext transactionDsl, + TransactionTemplate transaction) {} + + private record SeededRetainedIdentity(long accountId, UUID accountUuid) {} + + private record CanonicalConnectScopeRepositoryFixture( + AccountConnectScopeRepository scopes, + FreshTenantIdentityAssociationRepository freshTenantIdentities) {} + + private static final String V2_TOKEN_FOR_RETAINED_SCOPE = "retained-uuid-scope-token"; +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptCanonicalIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptCanonicalIntegrationTest.java new file mode 100644 index 0000000000..764c447332 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountMembershipTransitionReceiptCanonicalIntegrationTest.java @@ -0,0 +1,1272 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Base64; +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 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.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.CanonicalMembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository.TransitionReceiptEvidence; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL storage proof for V1/V2 provisional receipts; fixture evidence is not auth proof. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountMembershipTransitionReceiptCanonicalIntegrationTest { + private static final String TEST_NAMESPACE = "account-service"; + private static final long RETAINED_TENANT_ID = 700L; + private static final String MANIFEST_DIGEST = "sha256:" + "b".repeat(64); + private static final String RECEIPT_V1_COLUMNS = + "receipt_stream_key, receipt_sequence, account_id, tenant_id, evidence_status, " + + "transition_type, request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, membership_authority_generation, " + + "authority_provenance, receipt_id, receipt_digest, created_at"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void retainedV1HistoryBindsOnceAndCanonicalAppendContinuesItsSequence() { + Fixture fixture = fixture(); + RetainedPair pair = seedRetainedPair(fixture, "INACTIVE", false, 2L, 2L); + MembershipTransitionReceipt v1Receipt = seedV47V1Receipt(fixture, pair, "retained-v1-left"); + Map v1RowBefore = + v1ReceiptProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID, 1L); + Map v1HeadBefore = + v1HeadProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID); + + restoreMembership(fixture, pair, 3L, 3L); + migrateToV48(fixture); + + assertThat(v1ReceiptProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID, 1L)) + .containsExactlyEntriesOf(v1RowBefore); + assertThat(v1HeadProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID)) + .containsEntry("last_receipt_sequence", 1L) + .containsEntry("receipt_stream_key", v1HeadBefore.get("receipt_stream_key")); + assertReceiptMutationRejected( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_membership_transition_receipts " + + "SET evidence_status = 'MUTATED' WHERE request_id = ?", + "retained-v1-left")); + assertReceiptMutationRejected( + () -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_membership_transition_receipts " + "WHERE request_id = ?", + "retained-v1-left")); + assertThat(v1ReceiptProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID, 1L)) + .containsExactlyEntriesOf(v1RowBefore); + assertThat(v1HeadProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID)) + .containsEntry("last_receipt_sequence", 1L) + .containsEntry("receipt_stream_key", v1HeadBefore.get("receipt_stream_key")); + assertThat(canonicalHeadProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID)) + .containsEntry("account_uuid", null) + .containsEntry("tenant_uuid", null) + .containsEntry("tenant_provenance_kind", null) + .containsEntry("tenant_source_operation_id", null) + .containsEntry("tenant_provenance_digest", null); + + AccountMembershipTransitionReceiptRepository canonical = repository(fixture); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + canonical.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_REACTIVATED", + "retained-v1-left"))) + .isInstanceOf(IllegalStateException.class); + assertThat(v1HeadProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID)) + .containsEntry("last_receipt_sequence", 1L); + CanonicalMembershipTransitionReceipt v2Receipt = + fixture + .transaction() + .execute( + status -> + canonical.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_REACTIVATED", + "canonical-v2-join")); + assertThat(v2Receipt.receiptSequence()).isEqualTo(2L); + assertThat(v2Receipt.accountId()).isEqualTo(pair.accountUuid()); + assertThat(v2Receipt.tenantId()).isEqualTo(pair.tenantUuid()); + assertThat(v2Receipt.membershipVersion()) + .containsExactly(Map.entry(pair.tenantUuid().toString(), "3")); + assertThat(v1ReceiptProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID, 1L)) + .containsExactlyEntriesOf(v1RowBefore); + assertThat(v1HeadProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID)) + .containsEntry("last_receipt_sequence", 2L); + assertThat(canonicalHeadProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID)) + .containsEntry("account_uuid", pair.accountUuid()) + .containsEntry("tenant_uuid", pair.tenantUuid()) + .containsEntry("tenant_provenance_kind", "APPROVED_RETAINED") + .containsEntry("tenant_source_operation_id", pair.sourceOperationId()) + .containsEntry("tenant_provenance_digest", MANIFEST_DIGEST); + + Optional canonicalReadback = + fixture + .transaction() + .execute(status -> canonical.findCanonicalByRequestId("canonical-v2-join")); + assertThat(canonicalReadback).contains(v2Receipt); + Optional retainedReadback = + fixture.transaction().execute(status -> canonical.findByRequestId("retained-v1-left")); + assertThat(retainedReadback).map(evidence -> evidence.receipt()).contains(v1Receipt); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + canonical.findLatestReceipt(pair.accountId(), RETAINED_TENANT_ID))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + canonical.appendTransition( + pair.membership(), "MEMBERSHIP_LEFT", "unsupported-v1-latest"))) + .isInstanceOf(IllegalStateException.class); + assertThat(v1HeadProjection(fixture.setupDsl(), pair.accountId(), RETAINED_TENANT_ID)) + .containsEntry("last_receipt_sequence", 2L); + } + + @Test + void freshCanonicalHeadHasNoNumericTenantAliasAndExactRetryDoesNotAdvanceIt() { + Fixture fixture = fixture(); + FreshPair pair = seedFreshPair(fixture, "ACTIVE", true, 2L, 1L, "fresh-v2-join"); + migrateToV48(fixture); + AccountMembershipTransitionReceiptRepository repository = repository(fixture); + assertFirstJoinSourceEvidence(fixture, pair, "fresh-v2-join"); + + CanonicalMembershipTransitionReceipt first = + fixture + .transaction() + .execute( + status -> + repository.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_JOINED", + "fresh-v2-join")); + CanonicalMembershipTransitionReceipt retry = + fixture + .transaction() + .execute( + status -> + repository.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_JOINED", + "fresh-v2-join")); + + assertThat(retry).isEqualTo(first); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + repository.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_REACTIVATED", + "fresh-v2-join"))) + .isInstanceOf(IllegalStateException.class); + assertThat(first.receiptSequence()).isEqualTo(1L); + assertThat(first.receiptStreamKey()) + .isEqualTo( + "account:membership-transition-receipt:v2:membership/" + + pair.accountUuid() + + "/" + + pair.tenantUuid()); + assertThat( + fixture + .setupDsl() + .fetchOne( + "SELECT tenant_id, tenant_uuid FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_uuid = ?", + pair.accountId(), + pair.tenantUuid())) + .satisfies( + row -> { + assertThat(row.get("tenant_id", Long.class)).isNull(); + assertThat(row.get("tenant_uuid", UUID.class)).isEqualTo(pair.tenantUuid()); + }); + Record canonicalReceiptRow = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT tenant_id FROM account_membership_transition_receipts " + + "WHERE request_id = ?", + "fresh-v2-join"), + "Expected canonical receipt row for fresh-v2-join"); + assertThat(canonicalReceiptRow.get("tenant_id", Long.class)).isNull(); + assertThat( + fixture + .setupDsl() + .fetchOne( + "SELECT tenant_id, tenant_uuid " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + pair.accountUuid(), + pair.tenantUuid())) + .satisfies( + row -> { + assertThat(row.get("tenant_id", Long.class)).isNull(); + assertThat(row.get("tenant_uuid", UUID.class)).isEqualTo(pair.tenantUuid()); + }); + assertThat(headSequence(fixture, pair.accountId(), pair.tenantUuid())).isEqualTo(1L); + assertThat(receiptCount(fixture, pair.accountId(), pair.tenantUuid())).isEqualTo(1L); + } + + @Test + void freshKnownJoinHistoryWithMissingReceiptHeadCannotRestartForAnotherRequest() { + Fixture fixture = fixture(); + FreshPair pair = seedFreshPair(fixture, "ACTIVE", true, 2L, 1L, "known-first-join"); + migrateToV48(fixture); + AccountMembershipTransitionReceiptRepository repository = repository(fixture); + assertFirstJoinSourceEvidence(fixture, pair, "known-first-join"); + + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + repository.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_JOINED", + "different-request-after-first-join"))) + .isInstanceOf(IllegalStateException.class); + assertThat(headCount(fixture, pair.accountId(), pair.tenantUuid())).isZero(); + assertThat(receiptCount(fixture, pair.accountId(), pair.tenantUuid())).isZero(); + assertFirstJoinSourceEvidence(fixture, pair, "known-first-join"); + } + + @Test + void retainedMembershipHistoryWithoutReceiptHeadCannotStartCanonicalSequence() { + Fixture fixture = fixture(); + RetainedPair pair = seedRetainedPair(fixture, "ACTIVE", true, 2L, 2L); + migrateToV48(fixture); + AccountMembershipTransitionReceiptRepository repository = repository(fixture); + + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + repository.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_JOINED", + "must-not-reset-retained-history"))) + .isInstanceOf(IllegalStateException.class); + assertThat(headCount(fixture, pair.accountId(), pair.tenantUuid())).isZero(); + assertThat(receiptCount(fixture, pair.accountId(), pair.tenantUuid())).isZero(); + } + + @Test + void concurrentMatchingRequestConvergesOnOneOriginalCanonicalReceipt() throws Exception { + Fixture fixture = fixture(); + FreshPair pair = seedFreshPair(fixture, "ACTIVE", true, 2L, 1L, "concurrent-v2-join"); + migrateToV48(fixture); + AccountMembershipTransitionReceiptRepository repository = repository(fixture); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit(() -> appendAfterStart(fixture, repository, pair, ready, start)); + Future second = + executor.submit(() -> appendAfterStart(fixture, repository, pair, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + CanonicalMembershipTransitionReceipt one = first.get(30, TimeUnit.SECONDS); + CanonicalMembershipTransitionReceipt two = second.get(30, TimeUnit.SECONDS); + assertThat(one).isEqualTo(two); + assertThat(headSequence(fixture, pair.accountId(), pair.tenantUuid())).isEqualTo(1L); + assertThat(receiptCount(fixture, pair.accountId(), pair.tenantUuid())).isEqualTo(1L); + } + } + + @Test + void rollbackAndUnprovedSourceLeaveNoCanonicalHeadOrReceipt() { + Fixture fixture = fixture(); + FreshPair pair = seedFreshPair(fixture, "ACTIVE", true, 2L, 1L, "rolled-back-v2-join"); + migrateToV48(fixture); + AccountMembershipTransitionReceiptRepository repository = repository(fixture); + + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> { + repository.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_JOINED", + "rolled-back-v2-join"); + throw new IllegalStateException("rollback fixture"); + })) + .hasMessage("rollback fixture"); + assertThat(headCount(fixture, pair.accountId(), pair.tenantUuid())).isZero(); + assertThat(receiptCount(fixture, pair.accountId(), pair.tenantUuid())).isZero(); + + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> + repository.appendCanonicalTransition( + pair.accountUuid(), + UUID.randomUUID(), + "MEMBERSHIP_JOINED", + "unmapped-v2-join"))) + .isInstanceOf(IllegalStateException.class); + assertThat(headCount(fixture, pair.accountId(), pair.tenantUuid())).isZero(); + assertThat(receiptCount(fixture, pair.accountId(), pair.tenantUuid())).isZero(); + } + + @Test + void canonicalAppendRequiresReadWriteOwnerTransactionAndHistoricalReadbackIsNotCurrent() { + Fixture fixture = fixture(); + FreshPair pair = seedFreshPair(fixture, "ACTIVE", true, 2L, 1L, "historical-join"); + migrateToV48(fixture); + AccountMembershipTransitionReceiptRepository repository = repository(fixture); + + assertThatThrownBy( + () -> + repository.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_JOINED", + "outside-transaction")) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + new TransactionTemplate(new DataSourceTransactionManager(fixture.dataSource())) { + { + setReadOnly(true); + } + }.execute( + status -> + repository.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_JOINED", + "read-only-transaction"))) + .isInstanceOf(IllegalStateException.class); + + CanonicalMembershipTransitionReceipt joined = + fixture + .transaction() + .execute( + status -> + repository.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_JOINED", + "historical-join")); + moveFreshMembershipToLeft(fixture, pair); + CanonicalMembershipTransitionReceipt left = + fixture + .transaction() + .execute( + status -> + repository.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_LEFT", + "historical-left")); + assertThat(left.receiptSequence()).isEqualTo(2L); + Optional historicalJoin = + fixture + .transaction() + .execute(status -> repository.findCanonicalByRequestId("historical-join")); + assertThat(historicalJoin).contains(joined); + Optional latestCanonical = + fixture + .transaction() + .execute( + status -> + repository.findLatestCanonicalReceipt(pair.accountUuid(), pair.tenantUuid())); + assertThat(latestCanonical).contains(left); + } + + private static CanonicalMembershipTransitionReceipt appendAfterStart( + Fixture fixture, + AccountMembershipTransitionReceiptRepository repository, + FreshPair pair, + CountDownLatch ready, + CountDownLatch start) + throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent canonical receipt start timed out"); + } + return fixture + .transaction() + .execute( + status -> + repository.appendCanonicalTransition( + pair.accountUuid(), + pair.tenantUuid(), + "MEMBERSHIP_JOINED", + "concurrent-v2-join")); + } + + private static RetainedPair seedRetainedPair( + Fixture fixture, + String lifecycleState, + boolean admissionAllowed, + long membershipVersion, + long authorityGeneration) { + long accountId = insertAccount(fixture.setupDsl(), "retained-receipt"); + UUID accountUuid = accountUuid(fixture.setupDsl(), accountId); + seedRetainedTenantEvidence(fixture.setupDsl(), RETAINED_TENANT_ID); + LegacyTenantSourceEvidence sourceEvidence = + new LegacyTenantSourceEvidence(fixture.transactionDsl()); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(fixture.transactionDsl()); + ApprovedLegacyTenantAssociationRepository associations = + new ApprovedLegacyTenantAssociationRepository( + fixture.transactionDsl(), sourceEvidence, TEST_NAMESPACE, generations); + UUID tenantUuid = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String retainedDigest = sourceEvidence.digest(RETAINED_TENANT_ID); + ResolveLegacyAccountTenantAssociationResponse ownerEvidence = + ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(RETAINED_TENANT_ID) + .setCanonicalTenantId(tenantUuid.toString()) + .setSourceLegacyGameTenantId("r-" + UUID.randomUUID().toString().replace("-", "")) + .setSourceGameRowId(positiveLong()) + .setAccountEvidenceDigest(retainedDigest) + .setOperationId(sourceOperationId.toString()) + .setManifestDigest(MANIFEST_DIGEST) + .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace(TEST_NAMESPACE) + .setSignerKeyId("owner-fixture") + .setApprovedBy("fixture@example.test") + .setApprovalReference("canonical-receipt-test") + .setSignedAt(Instant.parse("2026-10-03T00:00:00Z").toString()) + .setOperationEntryCount(1) + .setManifestSchemaVersion(1) + .build(); + var imported = + fixture + .transaction() + .execute(status -> associations.importApproved(RETAINED_TENANT_ID, ownerEvidence)); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + RETAINED_TENANT_ID, + TenantProvenanceKind.APPROVED_RETAINED, + imported.operationId(), + MANIFEST_DIGEST); + AccountTenantMembershipRepository memberships = + membershipRepository(fixture, associations, sourceEvidence); + var membership = new net.firedevops.firemud.accountservice.entity.AccountTenantMembership(); + var account = new net.firedevops.firemud.accountservice.entity.Account(); + account.setId(accountId); + membership.setAccount(account); + membership.setTenantId(RETAINED_TENANT_ID); + membership.setLifecycleState(lifecycleState); + membership.setGameplayAdmissionAllowed(admissionAllowed); + membership.setMembershipVersion(membershipVersion); + membership.setMembershipAuthorityGeneration(authorityGeneration); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + var persisted = + fixture + .transaction() + .execute( + status -> + memberships.saveCanonical(membership, accountUuid, tenantUuid, provenance)); + return new RetainedPair( + accountId, accountUuid, RETAINED_TENANT_ID, tenantUuid, sourceOperationId, persisted); + } + + private static FreshPair seedFreshPair( + Fixture fixture, + String lifecycleState, + boolean admissionAllowed, + long membershipVersion, + long authorityGeneration, + String requestId) { + long accountId = insertAccount(fixture.setupDsl(), "fresh-receipt"); + UUID accountUuid = accountUuid(fixture.setupDsl(), accountId); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence evidence = freshTenantEvidence(tenantUuid); + FreshTenantIdentityAssociationRepository fresh = + new FreshTenantIdentityAssociationRepository(fixture.transactionDsl(), TEST_NAMESPACE); + fixture.transaction().executeWithoutResult(status -> fresh.importVerified(evidence)); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + evidence.operationId(), + evidence.evidenceDigest()); + LegacyTenantSourceEvidence sourceEvidence = + new LegacyTenantSourceEvidence(fixture.transactionDsl()); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(fixture.transactionDsl()); + ApprovedLegacyTenantAssociationRepository associations = + new ApprovedLegacyTenantAssociationRepository( + fixture.transactionDsl(), sourceEvidence, TEST_NAMESPACE, generations); + AccountTenantMembershipRepository memberships = + membershipRepository(fixture, associations, sourceEvidence); + AccountTenantMembershipRoleSnapshotRepository roles = + new AccountTenantMembershipRoleSnapshotRepository(fixture.transactionDsl()); + AccountMembershipPairAuthorityRepository pairAuthority = + new AccountMembershipPairAuthorityRepository(fixture.transactionDsl()); + AccountAuthorityOutboxRepository authorityOutbox = + new AccountAuthorityOutboxRepository(fixture.transactionDsl()); + AccountConnectScopeRepository connectScopes = + new AccountConnectScopeRepository( + fixture.transactionDsl(), + new AccountRepository(fixture.transactionDsl()), + new AccountTenantIdentityResolver(associations, sourceEvidence, TEST_NAMESPACE), + fresh); + AccountJoinOperationRepository joinOperations = + new AccountJoinOperationRepository(fixture.transactionDsl(), connectScopes); + CanonicalJoinScopeV2 scope = canonicalFreshJoinScope(accountUuid, tenantUuid); + var membership = new net.firedevops.firemud.accountservice.entity.AccountTenantMembership(); + var account = new net.firedevops.firemud.accountservice.entity.Account(); + account.setId(accountId); + membership.setAccount(account); + membership.setLifecycleState(lifecycleState); + membership.setGameplayAdmissionAllowed(admissionAllowed); + membership.setMembershipVersion(membershipVersion); + membership.setMembershipAuthorityGeneration(authorityGeneration); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + var persisted = + fixture + .transaction() + .execute( + status -> { + joinOperations.lockAccount(accountId); + generations.initializeIssuerIfAbsent(AccountServiceImpl.ACCOUNT_JWT_ISSUER); + generations.initialize(AuthorityScope.account(accountUuid)); + generations.initializeTenantIfAbsent(tenantUuid); + generations.initialize(AuthorityScope.membership(accountUuid, tenantUuid)); + PairAuthority absence = + pairAuthority.enrollAbsence(accountUuid, tenantUuid, provenance); + + connectScopes.insertCanonical(accountId, scope, provenance); + if (!joinOperations.insertCanonicalIntent(requestId, scope, "receipt-fixture")) { + throw new IllegalStateException("Canonical JOIN fixture intent already exists"); + } + // Synthetic policy evidence satisfies the storage precondition only; it is not + // an authenticated entitlement result or production commit-gate proof. + joinOperations.bindCanonicalPolicyEvidence( + requestId, scope, "receipt-fixture", true, 9L); + var savedMembership = + memberships.saveCanonical(membership, accountUuid, tenantUuid, provenance); + roles.replaceCanonical( + savedMembership, + accountUuid, + tenantUuid, + provenance, + membershipVersion, + List.of("player")); + + CompositeSnapshot authority = + generations.readCompositeSnapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + accountUuid, + List.of(tenantUuid), + List.of(tenantUuid)); + // This test-only producer composes the unchanged event codec with the durable + // outbox and pair repositories; it is not Account's missing UUID JOIN publisher. + MembershipEvent candidate = + firstMembershipEvent( + requestId, accountUuid, tenantUuid, savedMembership, authority); + String streamKey = candidate.outboxStreamKey(); + Event appended = + authorityOutbox.append( + streamKey, + requestId, + candidate.eventId(), + candidate.eventDigest(), + candidate.canonicalJsonUtf8()); + Event readback = + authorityOutbox + .findEvent(streamKey, requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Fixture authority event readback is absent")); + Checkpoint checkpoint = + authorityOutbox + .readCheckpoint(streamKey) + .orElseThrow( + () -> + new IllegalStateException( + "Fixture authority event checkpoint is absent")); + if (!appended.equals(readback) + || appended.outboxSequence() != 1L + || checkpoint.outboxSequence() != 1L + || !checkpoint.sourceEventId().equals(candidate.eventId()) + || !checkpoint.sourceEventDigest().equals(candidate.eventDigest())) { + throw new IllegalStateException( + "Fixture authority event/checkpoint differs from its canonical preimage"); + } + PairAuthority committed = + pairAuthority.commitTransition( + absence, + new PairTransition( + true, + checkpoint.outboxSequence(), + checkpoint.sourceEventId(), + checkpoint.sourceEventDigest(), + false)); + if (!committed.membershipExists() + || committed.membershipVersion() != membershipVersion + || committed.membershipAuthorityGeneration() != authorityGeneration + || committed.lastEventSequence() != checkpoint.outboxSequence()) { + throw new IllegalStateException( + "Fixture first-event pair readback differs from membership source"); + } + return savedMembership; + }); + return new FreshPair(accountId, accountUuid, tenantUuid, evidence, persisted); + } + + private static CanonicalJoinScopeV2 canonicalFreshJoinScope(UUID accountUuid, UUID tenantUuid) { + return new CanonicalJoinScopeV2( + "canonical-receipt-scope-" + UUID.randomUUID(), + accountUuid, + tenantUuid, + UUID.randomUUID(), + "canonical-receipt-tenant", + "canonical-receipt-world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 1L, + 1L, + "2026-10-03T00:00:00Z", + "2026-10-03T01:00:00Z"); + } + + private static MembershipEvent firstMembershipEvent( + String requestId, + UUID accountUuid, + UUID tenantUuid, + net.firedevops.firemud.accountservice.entity.AccountTenantMembership membership, + CompositeSnapshot authority) { + String streamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid; + String eventId = + UUID.nameUUIDFromBytes( + (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + requestId) + .getBytes(StandardCharsets.UTF_8)) + .toString(); + ScopeState issuer = authority.issuer(); + ScopeState account = authority.account(); + ScopeState tenant = authority.tenants().get(0); + ScopeState member = authority.memberships().get(0); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", Long.toString(issuer.generation()), + "accountAuthorityGeneration", Long.toString(account.generation()), + "tenantAuthorityGeneration", + Map.of(tenantUuid.toString(), Long.toString(tenant.generation())), + "membershipAuthorityGeneration", + Map.of(tenantUuid.toString(), Long.toString(member.generation())), + "privateRealmGrantVersions", List.of()); + Map preimage = new LinkedHashMap<>(); + preimage.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + preimage.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + preimage.put("eventId", eventId); + preimage.put("requestId", requestId); + preimage.put("outboxStreamKey", streamKey); + preimage.put("outboxSequence", "1"); + preimage.put( + "sourceScope", + streamKey.substring(MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX.length())); + preimage.put("accountId", accountUuid.toString()); + preimage.put("tenantId", tenantUuid.toString()); + preimage.put("membershipExists", true); + preimage.put("membershipLifecycleState", membership.getLifecycleState()); + preimage.put( + "membershipVersion", + Map.of(tenantUuid.toString(), Long.toString(membership.getMembershipVersion()))); + preimage.put( + "membershipAuthorityGeneration", + Long.toString(membership.getMembershipAuthorityGeneration())); + preimage.put("authorityTuple", authorityTuple); + preimage.put("issuanceFence", Long.toString(authority.issuanceFence().value())); + preimage.put("roles", List.of("player")); + preimage.put("gameplayAdmissionAllowed", membership.isGameplayAdmissionAllowed()); + preimage.put("callerBoundAuthorityInvalidated", false); + return MembershipAuthorityEventV1Codec.seal(preimage); + } + + private static void restoreMembership( + Fixture fixture, RetainedPair pair, long membershipVersion, long authorityGeneration) { + AccountTenantIdentityResolver resolver = identityResolver(fixture); + AccountTenantMembershipRepository memberships = + new AccountTenantMembershipRepository( + fixture.transactionDsl(), + new AccountRepository(fixture.transactionDsl()), + resolver, + new FreshTenantIdentityAssociationRepository(fixture.transactionDsl(), TEST_NAMESPACE)); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + RETAINED_TENANT_ID, + TenantProvenanceKind.APPROVED_RETAINED, + pair.sourceOperationId(), + MANIFEST_DIGEST); + fixture + .transaction() + .executeWithoutResult( + status -> { + var membership = + memberships + .findCanonicalMembershipForUpdate(pair.accountUuid(), pair.tenantUuid()) + .orElseThrow(); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setMembershipVersion(membershipVersion); + membership.setMembershipAuthorityGeneration(authorityGeneration); + memberships.saveCanonical( + membership, pair.accountUuid(), pair.tenantUuid(), provenance); + }); + } + + private static void assertFirstJoinSourceEvidence( + Fixture fixture, FreshPair pair, String requestId) { + Record operation = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT status, operation_representation_version, account_id, tenant_id, " + + "account_uuid, tenant_uuid, " + + "intent_digest_version, request_digest_version, " + + "entitlement_authority_availability, allow_public_join, entitlement_version, " + + "request_digest " + + "FROM account_join_operations WHERE request_id = ?", + requestId)); + assertThat(operation.get("status", String.class)).isEqualTo("PENDING"); + assertThat(operation.get("operation_representation_version", Integer.class)).isEqualTo(2); + assertThat(operation.get("account_id", Long.class)).isEqualTo(pair.accountId()); + assertThat(operation.get("tenant_id", Long.class)).isNull(); + assertThat(operation.get("account_uuid", UUID.class)).isEqualTo(pair.accountUuid()); + assertThat(operation.get("tenant_uuid", UUID.class)).isEqualTo(pair.tenantUuid()); + assertThat(operation.get("intent_digest_version", Integer.class)).isEqualTo(2); + assertThat(operation.get("request_digest_version", Integer.class)).isEqualTo(2); + assertThat(operation.get("entitlement_authority_availability", String.class)) + .isEqualTo("AVAILABLE"); + assertThat(operation.get("allow_public_join", Boolean.class)).isTrue(); + assertThat(operation.get("entitlement_version", Long.class)).isEqualTo(9L); + assertThat(operation.get("request_digest", String.class)).matches("sha256:[0-9a-f]{64}"); + + Record pairAuthority = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT legacy_tenant_id, membership_exists, membership_version, " + + "membership_authority_generation, last_event_sequence, last_event_id, " + + "last_event_digest, tenant_provenance_kind, tenant_source_operation_id, " + + "tenant_provenance_digest " + + "FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + pair.accountUuid(), + pair.tenantUuid())); + assertThat(pairAuthority.get("membership_exists", Boolean.class)).isTrue(); + assertThat(pairAuthority.get("legacy_tenant_id", Long.class)).isNull(); + assertThat(pairAuthority.get("membership_version", Long.class)) + .isEqualTo(pair.membership().getMembershipVersion()); + assertThat(pairAuthority.get("membership_authority_generation", Long.class)) + .isEqualTo(pair.membership().getMembershipAuthorityGeneration()); + assertThat(pairAuthority.get("last_event_sequence", Long.class)).isEqualTo(1L); + assertThat(pairAuthority.get("tenant_provenance_kind", String.class)) + .isEqualTo(TenantProvenanceKind.FRESH_GAME_DESIGN.name()); + assertThat(pairAuthority.get("tenant_source_operation_id", UUID.class)) + .isEqualTo(pair.sourceEvidence().operationId()); + assertThat(pairAuthority.get("tenant_provenance_digest", String.class)) + .isEqualTo(pair.sourceEvidence().evidenceDigest()); + + String streamKey = membershipAuthorityStreamKey(pair.accountUuid(), pair.tenantUuid()); + Record checkpoint = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + streamKey)); + assertThat(checkpoint.get("last_sequence", Long.class)).isEqualTo(1L); + Record eventRow = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT outbox_sequence, request_id, event_id, event_digest, payload " + + "FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = 1", + streamKey)); + assertThat(eventRow.get("request_id", String.class)).isEqualTo(requestId); + assertThat(eventRow.get("event_id", String.class)) + .isEqualTo(pairAuthority.get("last_event_id", String.class)); + assertThat(eventRow.get("event_digest", String.class)) + .isEqualTo(pairAuthority.get("last_event_digest", String.class)); + MembershipEvent event = + MembershipAuthorityEventV1Codec.verify( + new String(eventRow.get("payload", byte[].class), StandardCharsets.UTF_8)); + assertThat(event.outboxSequence()).isEqualTo("1"); + assertThat(event.requestId()).isEqualTo(requestId); + assertThat(event.accountId()).isEqualTo(pair.accountUuid().toString()); + assertThat(event.tenantId()).isEqualTo(pair.tenantUuid().toString()); + assertThat(event.membershipVersion()) + .containsExactly(Map.entry(pair.tenantUuid().toString(), "2")); + } + + private static String membershipAuthorityStreamKey(UUID accountUuid, UUID tenantUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid; + } + + private static void moveFreshMembershipToLeft(Fixture fixture, FreshPair pair) { + AccountTenantMembershipRepository memberships = + new AccountTenantMembershipRepository( + fixture.transactionDsl(), + new AccountRepository(fixture.transactionDsl()), + identityResolver(fixture), + new FreshTenantIdentityAssociationRepository(fixture.transactionDsl(), TEST_NAMESPACE)); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + pair.sourceEvidence().operationId(), + pair.sourceEvidence().evidenceDigest()); + fixture + .transaction() + .executeWithoutResult( + status -> { + var membership = + memberships + .findCanonicalMembershipForUpdate(pair.accountUuid(), pair.tenantUuid()) + .orElseThrow(); + membership.setLifecycleState("INACTIVE"); + membership.setGameplayAdmissionAllowed(false); + membership.setMembershipVersion(membership.getMembershipVersion() + 1L); + membership.setMembershipAuthorityGeneration( + membership.getMembershipAuthorityGeneration() + 1L); + memberships.saveCanonical( + membership, pair.accountUuid(), pair.tenantUuid(), provenance); + }); + } + + private static AccountTenantMembershipRepository membershipRepository( + Fixture fixture, + ApprovedLegacyTenantAssociationRepository associations, + LegacyTenantSourceEvidence sourceEvidence) { + return new AccountTenantMembershipRepository( + fixture.transactionDsl(), + new AccountRepository(fixture.transactionDsl()), + new AccountTenantIdentityResolver(associations, sourceEvidence, TEST_NAMESPACE), + new FreshTenantIdentityAssociationRepository(fixture.transactionDsl(), TEST_NAMESPACE)); + } + + private static AccountTenantIdentityResolver identityResolver(Fixture fixture) { + LegacyTenantSourceEvidence source = new LegacyTenantSourceEvidence(fixture.transactionDsl()); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(fixture.transactionDsl()); + ApprovedLegacyTenantAssociationRepository associations = + new ApprovedLegacyTenantAssociationRepository( + fixture.transactionDsl(), source, TEST_NAMESPACE, generations); + return new AccountTenantIdentityResolver(associations, source, TEST_NAMESPACE); + } + + private static void seedRetainedTenantEvidence(DSLContext dsl, long tenantId) { + String suffix = UUID.randomUUID().toString().replace("-", ""); + Record donor = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, ?, ?) RETURNING id", + "receipt-donor-" + suffix, + "receipt-donor-" + suffix + "@example.test", + "fixture-hash", + tenantId)); + long donorId = donor.get("id", Long.class); + long membershipId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED') " + + "RETURNING id", + donorId, + tenantId) + .fetchOne(0, Long.class)); + dsl.execute( + "INSERT INTO account_legacy_tenant_sources " + + "(account_id, legacy_tenant_id, matching_membership_id, " + + "matching_membership_admission_allowed, profile_tenant_count, " + + "matching_profile_count, disposition) VALUES (?, ?, ?, FALSE, 0, 0, 'UNVERIFIED')", + donorId, + tenantId, + membershipId); + dsl.execute( + "INSERT INTO account_legacy_membership_sources " + + "(membership_id, account_id, tenant_id, original_gameplay_admission_allowed, " + + "matches_account_legacy_tenant, disposition) " + + "VALUES (?, ?, ?, FALSE, TRUE, 'UNVERIFIED')", + membershipId, + donorId, + tenantId); + } + + private static MembershipTransitionReceipt seedV47V1Receipt( + Fixture fixture, RetainedPair pair, String requestId) { + String streamKey = + MembershipTransitionReceiptDigest.receiptStreamKey(pair.accountId(), pair.tenantId()); + UUID receiptId = MembershipTransitionReceiptDigest.receiptIdForRequest(requestId); + String digest = + MembershipTransitionReceiptDigest.transitionDigest( + streamKey, + 1L, + receiptId, + "MEMBERSHIP_LEFT", + requestId, + pair.accountId(), + pair.tenantId(), + pair.membership().getId(), + pair.membership().getLifecycleState(), + pair.membership().isGameplayAdmissionAllowed(), + pair.membership().getMembershipVersion(), + pair.membership().getMembershipAuthorityGeneration(), + pair.membership().getAuthorityProvenance()); + return fixture + .transaction() + .execute( + status -> { + DSLContext dsl = fixture.transactionDsl(); + int insertedHead = + dsl.execute( + "INSERT INTO account_membership_transition_receipt_stream_heads " + + "(account_id, tenant_id, receipt_stream_key, last_receipt_sequence) " + + "VALUES (?, ?, ?, 1)", + pair.accountId(), + pair.tenantId(), + streamKey); + int insertedReceipt = + dsl.execute( + "INSERT INTO account_membership_transition_receipts " + + "(receipt_stream_key, receipt_sequence, account_id, tenant_id, " + + "evidence_status, transition_type, request_id, membership_id, " + + "membership_lifecycle_state, gameplay_admission_allowed, " + + "membership_version, membership_authority_generation, " + + "authority_provenance, receipt_id, receipt_digest) " + + "VALUES (?, 1, ?, ?, ?, 'MEMBERSHIP_LEFT', ?, ?, ?, ?, ?, ?, ?, ?, ?)", + streamKey, + pair.accountId(), + pair.tenantId(), + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + requestId, + pair.membership().getId(), + pair.membership().getLifecycleState(), + pair.membership().isGameplayAdmissionAllowed(), + pair.membership().getMembershipVersion(), + pair.membership().getMembershipAuthorityGeneration(), + pair.membership().getAuthorityProvenance(), + receiptId, + digest); + if (insertedHead != 1 || insertedReceipt != 1) { + throw new IllegalStateException( + "V47 V1 receipt fixture was not inserted exactly once"); + } + return new MembershipTransitionReceipt( + streamKey, + 1L, + receiptId, + digest, + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + "MEMBERSHIP_LEFT", + requestId, + pair.membership().getId()); + }); + } + + private static FreshTenantCreationEvidence freshTenantEvidence(UUID canonicalTenantId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceTenantKey = "f-" + UUID.randomUUID().toString().replace("-", ""); + String requestDigest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, requestId, sourceTenantKey, "Canonical receipt fixture", null); + long sourceGameRowId = positiveLong(); + String sourceKind = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + canonicalTenantId, + sourceGameRowId, + sourceTenantKey, + sourceKind, + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + canonicalTenantId, + sourceGameRowId, + sourceTenantKey, + sourceKind)); + } + + private static long insertAccount(DSLContext dsl, String prefix) { + String suffix = UUID.randomUUID().toString().replace("-", ""); + return Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + prefix + "-" + suffix, + prefix + "-" + suffix + "@example.test", + "fixture-hash") + .fetchOne(0, Long.class)); + } + + private static UUID accountUuid(DSLContext dsl, long accountId) { + return Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + } + + private static void migrateToV48(Fixture fixture) { + flyway(fixture.dataSource(), fixture.schema(), "48").migrate(); + } + + private static void assertReceiptMutationRejected(ThrowingCallable mutation) { + assertThatThrownBy(mutation) + .satisfies( + failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause.getMessage()) + .contains("Account membership transition receipts are append-only"); + }); + } + + private static AccountMembershipTransitionReceiptRepository repository(Fixture fixture) { + return new AccountMembershipTransitionReceiptRepository(fixture.transactionDsl()); + } + + private static Map v1ReceiptProjection( + DSLContext dsl, long accountId, long tenantId, long sequence) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT " + + RECEIPT_V1_COLUMNS + + " FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ? AND receipt_sequence = ?", + accountId, + tenantId, + sequence)) + .intoMap(); + } + + private static Map v1HeadProjection( + DSLContext dsl, long accountId, long tenantId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT account_id, tenant_id, receipt_stream_key, last_receipt_sequence " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + accountId, + tenantId)) + .intoMap(); + } + + private static Map canonicalHeadProjection( + DSLContext dsl, long accountId, long tenantId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT account_uuid, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + accountId, + tenantId)) + .intoMap(); + } + + private static long headSequence(Fixture fixture, long accountId, UUID tenantUuid) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT last_receipt_sequence FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid(fixture.setupDsl(), accountId), + tenantUuid) + .fetchOne(0, Long.class)); + } + + private static long headCount(Fixture fixture, long accountId, UUID tenantUuid) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid(fixture.setupDsl(), accountId), + tenantUuid) + .fetchOne(0, Long.class)); + } + + private static long receiptCount(Fixture fixture, long accountId, UUID tenantUuid) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_membership_transition_receipts " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid(fixture.setupDsl(), accountId), + tenantUuid) + .fetchOne(0, Long.class)); + } + + private static long positiveLong() { + long value = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return value == 0L ? 1L : value; + } + + private static Fixture fixture() { + String schema = "canonical_receipt_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + flyway(dataSource, schema, "47").migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + return new Fixture(schema, dataSource, setupDsl, transactionDsl, transaction); + } + + private static Flyway flyway( + DriverManagerDataSource dataSource, String schema, String targetVersion) { + return Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target(targetVersion) + .load(); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext setupDsl, + DSLContext transactionDsl, + TransactionTemplate transaction) {} + + private record RetainedPair( + long accountId, + UUID accountUuid, + long tenantId, + UUID tenantUuid, + UUID sourceOperationId, + net.firedevops.firemud.accountservice.entity.AccountTenantMembership membership) {} + + private record FreshPair( + long accountId, + UUID accountUuid, + UUID tenantUuid, + FreshTenantCreationEvidence sourceEvidence, + net.firedevops.firemud.accountservice.entity.AccountTenantMembership membership) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 351bd24b6f..9e92eff7d2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -100,8 +100,6 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { new TransactionTemplate(new DataSourceTransactionManager(dataSource)); DSLContext transactionAwareDsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - AccountJoinOperationRepository joinOperations = - new AccountJoinOperationRepository(transactionAwareDsl); LegacyTenantSourceEvidence legacyTenantSourceEvidence = new LegacyTenantSourceEvidence(transactionAwareDsl); AccountAuthorityGenerationRepository authorityGenerationRepository = @@ -115,14 +113,30 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { AccountTenantIdentityResolver tenantIdentityResolver = new AccountTenantIdentityResolver( approvedTenantAssociations, legacyTenantSourceEvidence, "account-service"); + FreshTenantIdentityAssociationRepository freshTenantIdentityRepository = + new FreshTenantIdentityAssociationRepository(transactionAwareDsl, "account-service"); + AccountRepository accountRepository = new AccountRepository(transactionAwareDsl); + AccountConnectScopeRepository connectScopes = + new AccountConnectScopeRepository( + transactionAwareDsl, + accountRepository, + tenantIdentityResolver, + freshTenantIdentityRepository); + AccountJoinOperationRepository joinOperations = + new AccountJoinOperationRepository(transactionAwareDsl, connectScopes); AccountTenantMembershipRepository memberships = new AccountTenantMembershipRepository( transactionAwareDsl, - new AccountRepository(transactionAwareDsl), + accountRepository, tenantIdentityResolver, - new FreshTenantIdentityAssociationRepository(transactionAwareDsl, "account-service")); + freshTenantIdentityRepository); AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(transactionAwareDsl); - AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(transactionAwareDsl); + AccountConnectScopeRepository scopes = + new AccountConnectScopeRepository( + transactionAwareDsl, + accountRepository, + tenantIdentityResolver, + freshTenantIdentityRepository); long accountId = Objects.requireNonNull( jdbc.queryForObject( @@ -443,8 +457,9 @@ void auditAttemptTimesUseUtcLocalDateTimeUnderNonUtcDatabaseSession() { transactionJdbc.update( "INSERT INTO account_audit_outbox " + "(audit_event_id, scope, producer_service, event_type, occurred_at, " - + "schema_version, payload_digest_version, payload_digest, payload, delivery_status) " - + "VALUES (?, 'platform', 'account-service', 'ACCOUNT_REGISTERED', ?, 1, 1, ?, '{}', 'PENDING')", + + "tenant_identity_version, tenant_uuid, schema_version, payload_digest_version, " + + "payload_digest, payload, delivery_status) " + + "VALUES (?, 'platform', 'account-service', 'ACCOUNT_REGISTERED', ?, 1, NULL, 1, 1, ?, '{}', 'PENDING')", defaultedEventId, LocalDateTime.ofInstant(beforeDefaultInsert, ZoneOffset.UTC), AccountAuditDigest.ofPayload("{}")); @@ -584,7 +599,20 @@ void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { "scope-uuid", "scope-uuid@example.com", "hash")); - AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(dsl); + LegacyTenantSourceEvidence tenantSourceEvidence = new LegacyTenantSourceEvidence(dsl); + AccountAuthorityGenerationRepository authorityGenerations = + new AccountAuthorityGenerationRepository(dsl); + ApprovedLegacyTenantAssociationRepository approvedTenantAssociations = + new ApprovedLegacyTenantAssociationRepository( + dsl, tenantSourceEvidence, "account-service", authorityGenerations); + AccountTenantIdentityResolver retainedTenantIdentities = + new AccountTenantIdentityResolver( + approvedTenantAssociations, tenantSourceEvidence, "account-service"); + FreshTenantIdentityAssociationRepository freshTenantIdentities = + new FreshTenantIdentityAssociationRepository(dsl, "account-service"); + AccountConnectScopeRepository scopes = + new AccountConnectScopeRepository( + dsl, repository, retainedTenantIdentities, freshTenantIdentities); VerifiedJoinScope scope = joinScope(accountId); scopes.insert(scope); @@ -604,23 +632,34 @@ void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { @Test void expiredConnectScopeCleanupPreservesEveryReferencedStatusAndMalformedEvidence() { JdbcTemplate jdbc = new JdbcTemplate(dataSource); - AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(dsl); - AccountJoinOperationRepository joinOperations = new AccountJoinOperationRepository(dsl); - LegacyTenantSourceEvidence sourceEvidence = new LegacyTenantSourceEvidence(dsl); + DSLContext transactionAwareDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + LegacyTenantSourceEvidence sourceEvidence = new LegacyTenantSourceEvidence(transactionAwareDsl); AccountAuthorityGenerationRepository authorityGenerations = - new AccountAuthorityGenerationRepository(dsl); + new AccountAuthorityGenerationRepository(transactionAwareDsl); ApprovedLegacyTenantAssociationRepository approvedTenantAssociations = new ApprovedLegacyTenantAssociationRepository( - dsl, sourceEvidence, "account-service", authorityGenerations); + transactionAwareDsl, sourceEvidence, "account-service", authorityGenerations); AccountTenantIdentityResolver tenantIdentityResolver = new AccountTenantIdentityResolver( approvedTenantAssociations, sourceEvidence, "account-service"); + FreshTenantIdentityAssociationRepository freshTenantIdentityRepository = + new FreshTenantIdentityAssociationRepository(transactionAwareDsl, "account-service"); + AccountRepository accountRepository = new AccountRepository(transactionAwareDsl); + AccountConnectScopeRepository scopes = + new AccountConnectScopeRepository( + transactionAwareDsl, + accountRepository, + tenantIdentityResolver, + freshTenantIdentityRepository); + AccountJoinOperationRepository joinOperations = + new AccountJoinOperationRepository(transactionAwareDsl, scopes); AccountTenantMembershipRepository memberships = new AccountTenantMembershipRepository( - dsl, - new AccountRepository(dsl), + transactionAwareDsl, + accountRepository, tenantIdentityResolver, - new FreshTenantIdentityAssociationRepository(dsl, "account-service")); + freshTenantIdentityRepository); long accountId = Objects.requireNonNull( jdbc.queryForObject( @@ -1357,7 +1396,10 @@ void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { + ".account_tenant_membership m WHERE account_id = ?", secondAccountId); String pendingJoinProjection = - "(to_jsonb(j) - 'reconciliation_attempt_count' - 'last_reconciliation_attempt_at' " + "(to_jsonb(j) - 'operation_representation_version' - 'scope_digest_version' " + + "- 'target_class' - 'account_uuid' - 'tenant_uuid' - 'tenant_slug' " + + "- 'playable_state_namespace_uuid' - 'game_instance_uuid' " + + "- 'reconciliation_attempt_count' - 'last_reconciliation_attempt_at' " + "- 'last_reconciliation_attempt_reason' - 'next_reconciliation_attempt_at')::text"; String pendingJoinBefore = jsonRow( @@ -1367,22 +1409,88 @@ void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { + schema + ".account_join_operations j WHERE request_id = ?", pendingJoinRequestId); + String connectScopeProjection = + "(to_jsonb(s) - 'scope_digest_version' - 'account_uuid' - 'tenant_uuid' " + + "- 'tenant_slug' - 'playable_state_namespace_uuid' - 'game_instance_uuid' " + + "- 'tenant_provenance_kind' - 'tenant_provenance_legacy_tenant_id' " + + "- 'tenant_source_operation_id' - 'tenant_provenance_digest')::text"; String connectScopeBefore = jsonRow( - "SELECT to_jsonb(s)::text FROM " + "SELECT " + + connectScopeProjection + + " FROM " + schema + ".account_connect_scope_records s WHERE scope_token_hash = ?", scopeTokenHash); - String outboxProjection = "(to_jsonb(o) - 'receiver_audit_projection_version')::text"; String outboxBefore = jsonRow( - "SELECT " - + outboxProjection - + " FROM " + "SELECT to_jsonb(o)::text FROM " + schema + ".account_audit_outbox o WHERE audit_event_id = ?", auditEventId); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .target("47") + .load() + .migrate(); + + long secondMembershipId = + Objects.requireNonNull( + (Number) + dsl.fetchValue( + "SELECT id FROM " + + schema + + ".account_tenant_membership WHERE account_id = ? AND tenant_id = 42", + secondAccountId)) + .longValue(); + String receiptStreamKey = + "account:membership-transition-receipt:v1:membership/" + secondAccountId + "/42"; + String receiptRequestId = "retained-v28-membership-transition"; + UUID receiptId = UUID.fromString("92b9c1a4-2840-4c48-9622-782b9aa83a07"); + String receiptPayload = "retained membership transition receipt"; + String receiptDigest = AccountAuditDigest.ofPayload(receiptPayload); + dsl.execute( + "INSERT INTO " + + schema + + ".account_membership_transition_receipt_stream_heads " + + "(account_id, tenant_id, receipt_stream_key, last_receipt_sequence) " + + "VALUES (?, 42, ?, 1)", + secondAccountId, + receiptStreamKey); + dsl.execute( + "INSERT INTO " + + schema + + ".account_membership_transition_receipts " + + "(receipt_stream_key, receipt_sequence, account_id, tenant_id, evidence_status, " + + "transition_type, request_id, membership_id, membership_lifecycle_state, " + + "gameplay_admission_allowed, membership_version, membership_authority_generation, " + + "authority_provenance, receipt_id, receipt_digest) " + + "VALUES (?, 1, ?, 42, 'PROVISIONAL_TRANSITION_RECEIPT', 'MEMBERSHIP_JOINED', ?, ?, " + + "'ACTIVE', TRUE, 2, 3, 'EXPLICIT_JOIN', ?, ?)", + receiptStreamKey, + secondAccountId, + receiptRequestId, + secondMembershipId, + receiptId, + receiptDigest); + String receiptStreamHeadBefore = + jsonRow( + "SELECT to_jsonb(h)::text FROM " + + schema + + ".account_membership_transition_receipt_stream_heads h " + + "WHERE account_id = ? AND tenant_id = 42", + secondAccountId); + String membershipTransitionReceiptBefore = + jsonRow( + "SELECT to_jsonb(r)::text FROM " + + schema + + ".account_membership_transition_receipts r WHERE receipt_id = ?", + receiptId); + Flyway.configure() .dataSource(dataSource) .locations(MIGRATION_LOCATION) @@ -1455,6 +1563,26 @@ void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { + ".account_join_operations j WHERE request_id = ?", pendingJoinRequestId)) .isEqualTo(pendingJoinBefore); + Record retainedJoinRepresentation = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_representation_version, scope_digest_version, target_class, " + + "account_uuid, tenant_uuid, tenant_slug, playable_state_namespace_uuid, " + + "game_instance_uuid FROM " + + schema + + ".account_join_operations WHERE request_id = ?", + pendingJoinRequestId), + "Retained JOIN representation defaults must be readable"); + assertThat(retainedJoinRepresentation.get("operation_representation_version", Integer.class)) + .isEqualTo(1); + assertThat(retainedJoinRepresentation.get("scope_digest_version", Integer.class)).isEqualTo(1); + assertThat(retainedJoinRepresentation.get("target_class", String.class)).isNull(); + assertThat(retainedJoinRepresentation.get("account_uuid", UUID.class)).isNull(); + assertThat(retainedJoinRepresentation.get("tenant_uuid", UUID.class)).isNull(); + assertThat(retainedJoinRepresentation.get("tenant_slug", String.class)).isNull(); + assertThat(retainedJoinRepresentation.get("playable_state_namespace_uuid", UUID.class)) + .isNull(); + assertThat(retainedJoinRepresentation.get("game_instance_uuid", UUID.class)).isNull(); assertThat( dsl.resultQuery( "SELECT COUNT(*) FROM " @@ -1469,20 +1597,104 @@ void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { .isEqualTo(1L); assertThat( jsonRow( - "SELECT to_jsonb(s)::text FROM " + "SELECT " + + connectScopeProjection + + " FROM " + schema + ".account_connect_scope_records s WHERE scope_token_hash = ?", scopeTokenHash)) .isEqualTo(connectScopeBefore); + Record retainedScopeIdentity = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT scope_digest_version, tenant_id, tenant_uuid, account_uuid, tenant_slug, " + + "playable_state_namespace_uuid, game_instance_uuid, " + + "tenant_provenance_kind, tenant_provenance_legacy_tenant_id, " + + "tenant_source_operation_id, tenant_provenance_digest FROM " + + schema + + ".account_connect_scope_records WHERE scope_token_hash = ?", + scopeTokenHash)); + assertThat(retainedScopeIdentity.get("scope_digest_version", Integer.class)).isEqualTo(1); + assertThat(retainedScopeIdentity.get("tenant_id", Long.class)).isEqualTo(42L); + for (String canonicalScopeColumn : + List.of( + "tenant_uuid", + "account_uuid", + "tenant_slug", + "playable_state_namespace_uuid", + "game_instance_uuid", + "tenant_provenance_kind", + "tenant_source_operation_id", + "tenant_provenance_digest")) { + assertThat(retainedScopeIdentity.get(canonicalScopeColumn)).isNull(); + } + assertThat(retainedScopeIdentity.get("tenant_provenance_legacy_tenant_id")).isNull(); assertThat( jsonRow( - "SELECT " - + outboxProjection - + " FROM " + "SELECT (to_jsonb(h) - 'receipt_head_id' - 'account_uuid' - 'tenant_uuid' " + + "- 'tenant_provenance_kind' - 'tenant_source_operation_id' " + + "- 'tenant_provenance_digest')::text FROM " + + schema + + ".account_membership_transition_receipt_stream_heads h " + + "WHERE account_id = ? AND tenant_id = 42", + secondAccountId)) + .isEqualTo(receiptStreamHeadBefore); + assertThat( + jsonRow( + "SELECT (to_jsonb(r) - 'receipt_head_id' - 'receipt_version' - 'account_uuid' " + + "- 'tenant_uuid' - 'tenant_provenance_kind' - 'tenant_source_operation_id' " + + "- 'tenant_provenance_digest')::text FROM " + + schema + + ".account_membership_transition_receipts r WHERE receipt_id = ?", + receiptId)) + .isEqualTo(membershipTransitionReceiptBefore); + Record retainedReceiptHeadIdentity = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT receipt_head_id, account_uuid, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest FROM " + + schema + + ".account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = 42", + secondAccountId)); + Long retainedReceiptHeadId = retainedReceiptHeadIdentity.get("receipt_head_id", Long.class); + assertThat(retainedReceiptHeadId).isNotNull().isPositive(); + Record retainedReceiptIdentity = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT receipt_head_id, receipt_version, account_uuid, tenant_uuid, " + + "tenant_provenance_kind, tenant_source_operation_id, tenant_provenance_digest " + + "FROM " + + schema + + ".account_membership_transition_receipts WHERE receipt_id = ?", + receiptId)); + assertThat(retainedReceiptIdentity.get("receipt_head_id", Long.class)) + .isEqualTo(retainedReceiptHeadId); + assertThat(retainedReceiptIdentity.get("receipt_version", Short.class)).isEqualTo((short) 1); + for (Record retainedIdentity : List.of(retainedReceiptHeadIdentity, retainedReceiptIdentity)) { + assertThat(retainedIdentity.get("account_uuid", UUID.class)).isNull(); + assertThat(retainedIdentity.get("tenant_uuid", UUID.class)).isNull(); + assertThat(retainedIdentity.get("tenant_provenance_kind", String.class)).isNull(); + assertThat(retainedIdentity.get("tenant_source_operation_id", UUID.class)).isNull(); + assertThat(retainedIdentity.get("tenant_provenance_digest", String.class)).isNull(); + } + assertThat( + jsonRow( + "SELECT (to_jsonb(o) - 'receiver_audit_projection_version' " + + "- 'tenant_identity_version' - 'tenant_uuid')::text FROM " + schema + ".account_audit_outbox o WHERE audit_event_id = ?", auditEventId)) .isEqualTo(outboxBefore); + Record retainedAuditIdentity = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_identity_version, tenant_uuid FROM " + + schema + + ".account_audit_outbox WHERE audit_event_id = ?", + auditEventId)); + assertThat(retainedAuditIdentity.get("tenant_identity_version", Integer.class)).isEqualTo(1); + assertThat(retainedAuditIdentity.get("tenant_uuid", UUID.class)).isNull(); assertThat( dsl.resultQuery( "SELECT COUNT(*) FROM " diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientAuditTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientAuditTest.java new file mode 100644 index 0000000000..03408d15fe --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientAuditTest.java @@ -0,0 +1,287 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; +import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptResponse; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class LoggingAdminClientAuditTest { + private static final UUID EVENT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final String TENANT_UUID = "33333333-3333-4333-8333-333333333333"; + + @Test + void canonicalUuidEnvelopeUsesExactReadbackAfterAmbiguousCreate() throws Exception { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = mockStub(); + when(stub.createLogEvent(any())) + .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE.withDescription("lost ack"))); + when(stub.readLogEventReceipt(any())).thenReturn(canonicalReceipt()); + LoggingAdminClient client = newClient(stub); + AccountAuditEnvelope envelope = canonicalEnvelope(); + + LoggingAdminClient.AuditDeliveryResult result = client.deliver(envelope); + + assertThat(result) + .isEqualTo(new LoggingAdminClient.AuditDeliveryResult("receipt-2", "log-9", false)); + ArgumentCaptor createCaptor = + ArgumentCaptor.forClass(CreateLogEventRequest.class); + ArgumentCaptor readCaptor = + ArgumentCaptor.forClass(ReadLogEventReceiptRequest.class); + verify(stub).createLogEvent(createCaptor.capture()); + verify(stub).readLogEventReceipt(readCaptor.capture()); + CreateLogEventRequest create = createCaptor.getValue(); + ReadLogEventReceiptRequest read = readCaptor.getValue(); + assertThat(create.getScope()).isEqualTo(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT); + assertThat(create.getTenantIdentityVersion()).isEqualTo(2); + assertThat(create.getTenantId()).isEmpty(); + assertThat(create.getTenantUuid()).isEqualTo(TENANT_UUID); + assertThat(create.getPayload().toStringUtf8()).isEqualTo(envelope.payload()); + assertThat(read.getTenantIdentityVersion()).isEqualTo(create.getTenantIdentityVersion()); + assertThat(read.getTenantUuid()).isEqualTo(create.getTenantUuid()); + assertThat(read.getAuditEventId()).isEqualTo(create.getAuditEventId()); + assertThat(read.getProducerService()).isEqualTo(create.getProducerService()); + assertThat(read.getEventType()).isEqualTo(create.getEventType()); + assertThat(read.getOccurredAt()).isEqualTo(create.getOccurredAt()); + assertThat(read.getSchemaVersion()).isEqualTo(create.getSchemaVersion()); + assertThat(read.getPayload()).isEqualTo(create.getPayload()); + assertThat(read.getPayloadDigestVersion()).isEqualTo(create.getPayloadDigestVersion()); + assertThat(read.getPayloadDigest()).isEqualTo(create.getPayloadDigest()); + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub, times(1)).createLogEvent(any()); + } + + @Test + void retainedNumericEnvelopeUsesExplicitVersionOneWireIdentity() throws Exception { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = mockStub(); + AccountAuditEnvelope envelope = retainedEnvelope(); + when(stub.createLogEvent(any())) + .thenReturn( + CreateLogEventResponse.newBuilder() + .setScope(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantId("73") + .setTenantIdentityVersion(1) + .setAuditEventId(EVENT_ID.toString()) + .setReceiptId("receipt-1") + .setLogEventId("log-8") + .setSchemaVersion(1) + .setPayloadDigestVersion(1) + .setPayloadDigest(envelope.payloadDigest()) + .setStatus(AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED) + .setOutcome(AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED) + .setAuditProjectionVersion(1) + .build()); + LoggingAdminClient client = newClient(stub); + + assertThat(client.deliver(envelope).receiptId()).isEqualTo("receipt-1"); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(CreateLogEventRequest.class); + verify(stub).createLogEvent(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getTenantIdentityVersion()).isEqualTo(1); + assertThat(requestCaptor.getValue().getTenantId()).isEqualTo("73"); + assertThat(requestCaptor.getValue().getTenantUuid()).isEmpty(); + verify(stub, never()).readLogEventReceipt(any()); + } + + @Test + void platformEnvelopeUsesVersionOneWithoutEitherTenantValue() throws Exception { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = mockStub(); + AccountAuditEnvelope envelope = platformEnvelope(); + when(stub.createLogEvent(any())) + .thenReturn( + CreateLogEventResponse.newBuilder() + .setScope(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM) + .setTenantIdentityVersion(1) + .setAuditEventId(EVENT_ID.toString()) + .setReceiptId("receipt-platform") + .setLogEventId("log-platform") + .setSchemaVersion(1) + .setPayloadDigestVersion(1) + .setPayloadDigest(envelope.payloadDigest()) + .setStatus(AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED) + .setOutcome(AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED) + .setAuditProjectionVersion(1) + .build()); + LoggingAdminClient client = newClient(stub); + + assertThat(client.deliver(envelope).receiptId()).isEqualTo("receipt-platform"); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(CreateLogEventRequest.class); + verify(stub).createLogEvent(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getTenantIdentityVersion()).isEqualTo(1); + assertThat(requestCaptor.getValue().getTenantId()).isEmpty(); + assertThat(requestCaptor.getValue().getTenantUuid()).isEmpty(); + } + + @Test + void changedTypedReceiptIdentityIsNotTerminalSuccess() throws Exception { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = mockStub(); + when(stub.createLogEvent(any())) + .thenReturn( + canonicalCreateReceipt().toBuilder() + .setTenantUuid("44444444-4444-4444-8444-444444444444") + .build()); + LoggingAdminClient client = newClient(stub); + + assertThatThrownBy(() -> client.deliver(canonicalEnvelope())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mismatched receipt evidence"); + verify(stub, never()).readLogEventReceipt(any()); + } + + @Test + void notFoundReceiptAfterAmbiguousCreateRemainsPending() throws Exception { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = mockStub(); + when(stub.createLogEvent(any())) + .thenThrow(new StatusRuntimeException(Status.DEADLINE_EXCEEDED)); + StatusRuntimeException notFound = new StatusRuntimeException(Status.NOT_FOUND); + when(stub.readLogEventReceipt(any())).thenThrow(notFound); + LoggingAdminClient client = newClient(stub); + + assertThatThrownBy(() -> client.deliver(canonicalEnvelope())).isSameAs(notFound); + verify(stub, times(1)).createLogEvent(any()); + verify(stub, times(1)).readLogEventReceipt(any()); + } + + @Test + void unavailableReceiptAfterAmbiguousCreateRemainsPending() throws Exception { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = mockStub(); + when(stub.createLogEvent(any())).thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); + StatusRuntimeException unavailable = new StatusRuntimeException(Status.UNAVAILABLE); + when(stub.readLogEventReceipt(any())).thenThrow(unavailable); + LoggingAdminClient client = newClient(stub); + + assertThatThrownBy(() -> client.deliver(canonicalEnvelope())).isSameAs(unavailable); + verify(stub, times(1)).createLogEvent(any()); + verify(stub, times(1)).readLogEventReceipt(any()); + } + + private static LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub mockStub() { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = + mock(LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static LoggingAdminClient newClient( + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub) throws Exception { + LoggingAdminClient client = + new LoggingAdminClient( + new ServiceEndpointsProperties(), + new CommonGrpcClientProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop()); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + return client; + } + + private static AccountAuditEnvelope canonicalEnvelope() { + String payload = "{\"join\":\"exact bytes\"}"; + return new AccountAuditEnvelope( + EVENT_ID, + "tenant", + AccountAuditTenantIdentity.canonicalTenantV2(TENANT_UUID), + "account-service", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + Instant.parse("2026-10-01T12:34:56.123456Z"), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + } + + private static AccountAuditEnvelope retainedEnvelope() { + String payload = "{\"retained\":true}"; + return new AccountAuditEnvelope( + EVENT_ID, + "tenant", + AccountAuditTenantIdentity.retainedTenantV1(73L), + "account-service", + "ACCOUNT_MEMBERSHIP_LEFT", + Instant.parse("2026-10-01T12:34:56Z"), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + } + + private static AccountAuditEnvelope platformEnvelope() { + String payload = "{\"registration\":true}"; + return new AccountAuditEnvelope( + EVENT_ID, + "platform", + AccountAuditTenantIdentity.platformV1(), + "account-service", + "ACCOUNT_REGISTERED", + Instant.parse("2026-10-01T12:34:56Z"), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + } + + private static ReadLogEventReceiptResponse canonicalReceipt() { + AccountAuditEnvelope envelope = canonicalEnvelope(); + return ReadLogEventReceiptResponse.newBuilder() + .setScope(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantIdentityVersion(2) + .setTenantUuid(TENANT_UUID) + .setAuditEventId(EVENT_ID.toString()) + .setReceiptId("receipt-2") + .setLogEventId("log-9") + .setSchemaVersion(1) + .setPayloadDigestVersion(1) + .setPayloadDigest(envelope.payloadDigest()) + .setStatus(AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED) + .setOutcome(AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE) + .setAuditProjectionVersion(1) + .build(); + } + + private static CreateLogEventResponse canonicalCreateReceipt() { + AccountAuditEnvelope envelope = canonicalEnvelope(); + return CreateLogEventResponse.newBuilder() + .setScope(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantIdentityVersion(2) + .setTenantUuid(TENANT_UUID) + .setAuditEventId(EVENT_ID.toString()) + .setReceiptId("receipt-2") + .setLogEventId("log-9") + .setSchemaVersion(1) + .setPayloadDigestVersion(1) + .setPayloadDigest(envelope.payloadDigest()) + .setStatus(AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED) + .setOutcome(AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED) + .setAuditProjectionVersion(1) + .build(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java index d276f2dec9..ed7553984c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java @@ -24,6 +24,7 @@ import java.util.concurrent.TimeUnit; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.service.AccountAuditDeliveryJob; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -54,10 +55,19 @@ class LoggingAdminClientTest { void acceptsOnlyExactCommittedReceiptWithCurrentProjectionVersion() throws Exception { var stub = mockStub(); when(stub.createLogEvent(any())).thenReturn(response(1)); - LoggingAdminClient.AuditDeliveryResult result = newClient(stub).deliver(validEnvelope()); + AccountAuditEnvelope envelope = validEnvelope(); + LoggingAdminClient.AuditDeliveryResult result = newClient(stub).deliver(envelope); assertThat(result.receiptId()).isEqualTo("receipt-1"); assertThat(result.logEventId()).isEqualTo("projection-1"); assertThat(result.minimized()).isFalse(); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(CreateLogEventRequest.class); + verify(stub).createLogEvent(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getTenantIdentityVersion()) + .isEqualTo(envelope.tenantIdentityVersion()); + assertThat(requestCaptor.getValue().getTenantId()).isEqualTo(Long.toString(TENANT_ID)); + assertThat(requestCaptor.getValue().getTenantUuid()).isEmpty(); } @ParameterizedTest @@ -191,8 +201,7 @@ void deliverRejectsNullOrNoncanonicalScopeBeforeTransport() throws Exception { var stub = mockStub(); LoggingAdminClient client = newClient(stub); - assertThrows( - IllegalArgumentException.class, () -> client.deliver(envelopeWithScope(null, null))); + assertThrows(NullPointerException.class, () -> client.deliver(envelopeWithScope(null, null))); assertThrows( IllegalArgumentException.class, () -> client.deliver(envelopeWithScope("other", null))); assertThrows( @@ -209,7 +218,7 @@ private static AccountAuditEnvelope validEnvelope() { return new AccountAuditEnvelope( UUID.fromString("8a5f6238-f0d9-4992-80cb-e7f447e0f913"), "tenant", - TENANT_ID, + AccountAuditTenantIdentity.retainedTenantV1(TENANT_ID), "account-service", "TEST_EVENT", Instant.parse("2026-01-01T00:00:00Z"), @@ -223,7 +232,9 @@ private static CreateLogEventResponse response(int projectionVersion) { AccountAuditEnvelope envelope = validEnvelope(); return CreateLogEventResponse.newBuilder() .setScope(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) - .setTenantId(Long.toString(TENANT_ID)) + .setTenantId(envelope.tenantId() == null ? "" : Long.toString(envelope.tenantId())) + .setTenantIdentityVersion(envelope.tenantIdentityVersion()) + .setTenantUuid(envelope.tenantUuid() == null ? "" : envelope.tenantUuid().toString()) .setAuditEventId(envelope.auditEventId().toString()) .setReceiptId("receipt-1") .setLogEventId("projection-1") @@ -238,10 +249,22 @@ private static CreateLogEventResponse response(int projectionVersion) { private static AccountAuditEnvelope envelopeWithScope(String scope, Long tenantId) { AccountAuditEnvelope envelope = validEnvelope(); + AccountAuditTenantIdentity identity; + if ("tenant".equals(scope)) { + identity = + tenantId == null + ? new AccountAuditTenantIdentity(AccountAuditTenantIdentity.VERSION_1, null, null) + : AccountAuditTenantIdentity.retainedTenantV1(tenantId); + } else { + identity = + tenantId == null + ? AccountAuditTenantIdentity.platformV1() + : AccountAuditTenantIdentity.retainedTenantV1(tenantId); + } return new AccountAuditEnvelope( envelope.auditEventId(), scope, - tenantId, + identity, envelope.producerService(), envelope.eventType(), envelope.occurredAt(), @@ -260,6 +283,8 @@ private static void assertPaymentEnvelope( assertEquals(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT, request.getScope()); assertEquals(Long.toString(TENANT_ID), request.getTenantId()); + assertEquals(AccountAuditTenantIdentity.VERSION_1, request.getTenantIdentityVersion()); + assertEquals("", request.getTenantUuid()); assertEquals(4, UUID.fromString(request.getAuditEventId()).version()); assertEquals("account-service", request.getProducerService()); assertEquals("PAYMENT_TXN", request.getEventType()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalMembershipTransitionReceiptDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalMembershipTransitionReceiptDigestTest.java new file mode 100644 index 0000000000..f0cc2f63cb --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalMembershipTransitionReceiptDigestTest.java @@ -0,0 +1,293 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.CanonicalMembershipTransitionReceipt; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; +import org.junit.jupiter.api.Test; + +class CanonicalMembershipTransitionReceiptDigestTest { + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String PROVENANCE_DIGEST = "sha256:" + "b".repeat(64); + private static final String REQUEST_ID = "join-雪-🧪"; + + @Test + void canonicalReceiptMatchesUtf8FramedGoldenVectorWithLargeCounters() { + CanonicalMembershipTransitionReceipt receipt = receipt(); + + assertThat(REQUEST_ID.getBytes(StandardCharsets.UTF_8)).hasSize(13); + assertThat(receipt.receiptStreamKey()) + .isEqualTo( + "account:membership-transition-receipt:v2:membership/" + ACCOUNT_ID + "/" + TENANT_ID); + assertThat(receipt.receiptId()) + .isEqualTo(UUID.fromString("bc2dad06-2211-383f-ae1f-22be6605a683")); + assertThat(MembershipTransitionReceiptDigest.transitionDigestV2(receipt)) + .isEqualTo("sha256:676bfbe8f62834bef3ae12ced5395a5a7784b038ff01681a9287a5e1358f2a59"); + } + + @Test + void v2ReceiptIdentityAndDigestAreDistinctFromRetainedV1Evidence() { + CanonicalMembershipTransitionReceipt receipt = receipt(); + + assertThat(receipt.receiptId()) + .isEqualTo(MembershipTransitionReceiptDigest.receiptIdForRequestV2(REQUEST_ID)); + assertThat(receipt.receiptId()) + .isNotEqualTo(MembershipTransitionReceiptDigest.receiptIdForRequest(REQUEST_ID)); + assertThat(receipt.receiptDigest()) + .isNotEqualTo(MembershipTransitionReceiptDigest.transitionDigestV2(receipt)); + assertThat(MembershipTransitionReceiptDigest.receiptStreamKeyV2(ACCOUNT_ID, TENANT_ID)) + .contains(ACCOUNT_ID.toString(), TENANT_ID.toString()) + .doesNotContain("/1/", "/2/"); + } + + @Test + void v2DigestChangesWithDeclaredStateSourceAndCounterEvidence() { + CanonicalMembershipTransitionReceipt original = receipt(); + String digest = MembershipTransitionReceiptDigest.transitionDigestV2(original); + + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy(original, "receiptSequence", 4L))) + .isNotEqualTo(digest); + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy(original, "requestId", "other-雪"))) + .isNotEqualTo(digest); + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy(original, "transitionType", "MEMBERSHIP_REACTIVATED"))) + .isNotEqualTo(digest); + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy(original, "transitionType", "MEMBERSHIP_LEFT"))) + .isNotEqualTo(digest); + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy( + original, + "accountId", + UUID.fromString("44444444-4444-4444-8444-444444444444")))) + .isNotEqualTo(digest); + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy( + original, "tenantId", UUID.fromString("55555555-5555-4555-8555-555555555555")))) + .isNotEqualTo(digest); + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy(original, "membershipVersion", "9007199254740994"))) + .isNotEqualTo(digest); + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy(original, "membershipAuthorityGeneration", 7L))) + .isNotEqualTo(digest); + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy(original, "tenantProvenanceKind", "FRESH_GAME_DESIGN"))) + .isNotEqualTo(digest); + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy( + original, + "tenantSourceOperationId", + UUID.fromString("66666666-6666-4666-8666-666666666666")))) + .isNotEqualTo(digest); + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy(original, "tenantProvenanceDigest", "sha256:" + "c".repeat(64)))) + .isNotEqualTo(digest); + + assertThat( + MembershipTransitionReceiptDigest.transitionDigestV2( + copy(original, "receiptDigest", "sha256:" + "c".repeat(64)))) + .isEqualTo(digest); + } + + @Test + void acceptsArbitraryPrecisionCanonicalMembershipVersionInDigestPreimage() { + CanonicalMembershipTransitionReceipt receipt = + copy(receipt(), "membershipVersion", "9223372036854775808"); + + assertThat(receipt.membershipVersion()) + .containsExactly(Map.entry(TENANT_ID.toString(), "9223372036854775808")); + assertThat(MembershipTransitionReceiptDigest.transitionDigestV2(receipt)) + .matches("sha256:[0-9a-f]{64}"); + } + + @Test + void rejectsMalformedTextIdentityMapsCountersAndTransitionState() { + assertThatThrownBy(() -> MembershipTransitionReceiptDigest.receiptIdForRequestV2("bad-\uD800")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> MembershipTransitionReceiptDigest.receiptStreamKeyV2(new UUID(0L, 0L), TENANT_ID)) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new CanonicalMembershipTransitionReceipt( + receipt().receiptStreamKey(), + 1L, + receipt().receiptId(), + receipt().receiptDigest(), + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + "MEMBERSHIP_JOINED", + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + "ACTIVE", + true, + Map.of(TENANT_ID.toString(), "01"), + 1L, + "EXPLICIT_JOIN", + "APPROVED_RETAINED", + SOURCE_OPERATION_ID, + PROVENANCE_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new CanonicalMembershipTransitionReceipt( + receipt().receiptStreamKey(), + 0L, + receipt().receiptId(), + receipt().receiptDigest(), + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + "MEMBERSHIP_JOINED", + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + "ACTIVE", + true, + Map.of(TENANT_ID.toString(), "9007199254740993"), + Long.MAX_VALUE, + "EXPLICIT_JOIN", + "APPROVED_RETAINED", + SOURCE_OPERATION_ID, + PROVENANCE_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new CanonicalMembershipTransitionReceipt( + receipt().receiptStreamKey(), + Long.MAX_VALUE, + receipt().receiptId(), + receipt().receiptDigest(), + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + "MEMBERSHIP_JOINED", + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + "ACTIVE", + true, + Map.of(TENANT_ID.toString(), "9007199254740993", ACCOUNT_ID.toString(), "1"), + Long.MAX_VALUE, + "EXPLICIT_JOIN", + "APPROVED_RETAINED", + SOURCE_OPERATION_ID, + PROVENANCE_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new CanonicalMembershipTransitionReceipt( + receipt().receiptStreamKey(), + Long.MAX_VALUE, + receipt().receiptId(), + receipt().receiptDigest(), + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + "MEMBERSHIP_JOINED", + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + "INACTIVE", + false, + Map.of(TENANT_ID.toString(), "9007199254740993"), + Long.MAX_VALUE, + "EXPLICIT_JOIN", + "APPROVED_RETAINED", + SOURCE_OPERATION_ID, + PROVENANCE_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CanonicalMembershipTransitionReceipt receipt() { + return new CanonicalMembershipTransitionReceipt( + MembershipTransitionReceiptDigest.receiptStreamKeyV2(ACCOUNT_ID, TENANT_ID), + Long.MAX_VALUE, + MembershipTransitionReceiptDigest.receiptIdForRequestV2(REQUEST_ID), + "sha256:" + "a".repeat(64), + MembershipTransitionReceiptDigest.EVIDENCE_STATUS, + "MEMBERSHIP_JOINED", + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + "ACTIVE", + true, + Map.of(TENANT_ID.toString(), "9007199254740993"), + Long.MAX_VALUE, + "EXPLICIT_JOIN", + "APPROVED_RETAINED", + SOURCE_OPERATION_ID, + PROVENANCE_DIGEST); + } + + private static CanonicalMembershipTransitionReceipt copy( + CanonicalMembershipTransitionReceipt receipt, String field, Object replacement) { + String requestId = "requestId".equals(field) ? (String) replacement : receipt.requestId(); + UUID accountId = "accountId".equals(field) ? (UUID) replacement : receipt.accountId(); + UUID tenantId = "tenantId".equals(field) ? (UUID) replacement : receipt.tenantId(); + String transitionType = + "transitionType".equals(field) ? (String) replacement : receipt.transitionType(); + String lifecycleState = + "transitionType".equals(field) && "MEMBERSHIP_LEFT".equals(transitionType) + ? "INACTIVE" + : receipt.membershipLifecycleState(); + boolean admissionAllowed = + "transitionType".equals(field) && "MEMBERSHIP_LEFT".equals(transitionType) + ? false + : receipt.gameplayAdmissionAllowed(); + String membershipVersionValue = + "membershipVersion".equals(field) + ? (String) replacement + : receipt.membershipVersion().get(receipt.tenantId().toString()); + Map membershipVersion = + "membershipVersion".equals(field) || "tenantId".equals(field) + ? Map.of(tenantId.toString(), membershipVersionValue) + : receipt.membershipVersion(); + return new CanonicalMembershipTransitionReceipt( + "accountId".equals(field) || "tenantId".equals(field) + ? MembershipTransitionReceiptDigest.receiptStreamKeyV2(accountId, tenantId) + : receipt.receiptStreamKey(), + "receiptSequence".equals(field) ? (long) replacement : receipt.receiptSequence(), + "requestId".equals(field) + ? MembershipTransitionReceiptDigest.receiptIdForRequestV2(requestId) + : receipt.receiptId(), + "receiptDigest".equals(field) ? (String) replacement : receipt.receiptDigest(), + receipt.evidenceStatus(), + transitionType, + requestId, + accountId, + tenantId, + lifecycleState, + admissionAllowed, + membershipVersion, + "membershipAuthorityGeneration".equals(field) + ? (long) replacement + : receipt.membershipAuthorityGeneration(), + receipt.authorityProvenance(), + "tenantProvenanceKind".equals(field) + ? (String) replacement + : receipt.tenantProvenanceKind(), + "tenantSourceOperationId".equals(field) + ? (UUID) replacement + : receipt.tenantSourceOperationId(), + "tenantProvenanceDigest".equals(field) + ? (String) replacement + : receipt.tenantProvenanceDigest()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java index 17d9160275..3eec065139 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java @@ -7,6 +7,8 @@ import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.sql.SQLException; @@ -18,6 +20,7 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; import net.firedevops.firemud.accountservice.jooq.tables.records.AccountAuditOutboxRecord; import org.jooq.DSLContext; import org.jooq.RecordContext; @@ -47,39 +50,19 @@ void appendReturnsRefreshedPersistedEnvelope() { AccountAuditOutboxRecord row = mock(AccountAuditOutboxRecord.class); when(dsl.newRecord(ACCOUNT_AUDIT_OUTBOX)).thenReturn(row); String persistedPayload = "{\"persisted\":\"exact material\"}"; - String persistedDigest = AccountAuditDigest.ofPayload(persistedPayload); LocalDateTime persistedOccurredAt = LocalDateTime.parse("2026-10-01T12:34:56.123456"); - doAnswer( - invocation -> { - when(row.getAuditEventId()).thenReturn(auditEventId); - when(row.getScope()).thenReturn("tenant"); - when(row.getTenantId()).thenReturn(73L); - when(row.getProducerService()).thenReturn("account-service"); - when(row.getEventType()).thenReturn("ACCOUNT_MEMBERSHIP_LEFT"); - when(row.getOccurredAt()).thenReturn(persistedOccurredAt); - when(row.getSchemaVersion()).thenReturn(1); - when(row.getPayloadDigestVersion()).thenReturn(1); - when(row.getPayloadDigest()).thenReturn(persistedDigest); - when(row.getPayload()).thenReturn(persistedPayload); - return null; - }) - .when(row) - .refresh(); + String persistedDigest = + arrangePersistedTenantRow(row, auditEventId, persistedOccurredAt, persistedPayload); AccountAuditEnvelope envelope = - repository.append( - auditEventId, - "tenant", - 73L, - "ACCOUNT_MEMBERSHIP_LEFT", - "{\"requested\":\"in-memory material\"}"); + repository.append(auditEventId, "tenant", 73L, "ACCOUNT_MEMBERSHIP_LEFT", persistedPayload); assertThat(envelope) .isEqualTo( new AccountAuditEnvelope( auditEventId, "tenant", - 73L, + AccountAuditTenantIdentity.retainedTenantV1(73L), "account-service", "ACCOUNT_MEMBERSHIP_LEFT", persistedOccurredAt.toInstant(ZoneOffset.UTC), @@ -89,6 +72,29 @@ void appendReturnsRefreshedPersistedEnvelope() { persistedPayload)); assertThat(envelope.payloadDigest()) .isEqualTo(AccountAuditDigest.ofPayload(envelope.payload())); + verify(row).setTenantIdentityVersion(1); + verify(row).setTenantUuid(null); + } + + @Test + void appendRejectsChangedStoredPayloadAndDigest() { + UUID auditEventId = UUID.randomUUID(); + AccountAuditOutboxRecord row = mock(AccountAuditOutboxRecord.class); + when(dsl.newRecord(ACCOUNT_AUDIT_OUTBOX)).thenReturn(row); + LocalDateTime persistedOccurredAt = LocalDateTime.parse("2026-10-01T12:34:56.123456"); + arrangePersistedTenantRow( + row, auditEventId, persistedOccurredAt, "{\"stored\":\"different material\"}"); + + assertThatThrownBy( + () -> + repository.append( + auditEventId, + "tenant", + 73L, + "ACCOUNT_MEMBERSHIP_LEFT", + "{\"requested\":\"original material\"}")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("did not preserve its exact envelope"); } @Test @@ -105,6 +111,160 @@ void appendFailsClosedWhenStoredEnvelopeCannotBeReadBack() { .hasMessageContaining("Stored audit envelope is missing"); } + @Test + void canonicalAppendRequiresAnActiveReadWriteOwnerTransactionBeforeStorage() { + assertThatThrownBy( + () -> + repository.appendCanonicalTenant( + UUID.randomUUID(), + "33333333-3333-4333-8333-333333333333", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + "{}")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active read-write owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void canonicalReadbackRequiresAnActiveReadWriteOwnerTransactionBeforeStorage() { + String payload = "{}"; + AccountAuditEnvelope expected = + new AccountAuditEnvelope( + UUID.randomUUID(), + "tenant", + AccountAuditTenantIdentity.canonicalTenantV2("33333333-3333-4333-8333-333333333333"), + "account-service", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + java.time.Instant.parse("2026-10-01T00:00:00Z"), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + + assertThatThrownBy(() -> repository.findExactCanonicalTenantEnvelopeForUpdate(expected)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active read-write owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void canonicalIdentityRejectsMissingMixedUnsupportedNilAndNoncanonicalValues() { + assertThatThrownBy(() -> AccountAuditTenantIdentity.canonicalTenantV2(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountAuditEnvelope( + UUID.randomUUID(), + "tenant", + null, + "account-service", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + java.time.Instant.parse("2026-10-01T00:00:00Z"), + 1, + 1, + AccountAuditDigest.ofPayload("{}"), + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountAuditTenantIdentity.canonicalTenantV2( + "00000000-0000-0000-0000-000000000000")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountAuditTenantIdentity.canonicalTenantV2( + "33333333-3333-4333-8333-33333333333A")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new AccountAuditTenantIdentity(3, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountAuditTenantIdentity( + AccountAuditTenantIdentity.VERSION_2, + 73L, + UUID.fromString("33333333-3333-4333-8333-333333333333"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountAuditEnvelope( + UUID.randomUUID(), + "platform", + AccountAuditTenantIdentity.retainedTenantV1(73L), + "account-service", + "ACCOUNT_REGISTERED", + java.time.Instant.parse("2026-10-01T00:00:00Z"), + 1, + 1, + AccountAuditDigest.ofPayload("{}"), + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountAuditEnvelope( + UUID.randomUUID(), + "tenant", + AccountAuditTenantIdentity.canonicalTenantV2( + "33333333-3333-4333-8333-333333333333"), + "account-service", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + java.time.Instant.parse("2026-10-01T00:00:00Z"), + 1, + 1, + "sha256:" + "0".repeat(64), + "{}")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + } + + @Test + void retainedIdentityIsExplicitVersionOneAndDigestRejectsMalformedUnicode() { + AccountAuditEnvelope retained = + new AccountAuditEnvelope( + UUID.randomUUID(), + "tenant", + AccountAuditTenantIdentity.retainedTenantV1(73L), + "account-service", + "ACCOUNT_MEMBERSHIP_LEFT", + java.time.Instant.parse("2026-10-01T00:00:00Z"), + 1, + 1, + AccountAuditDigest.ofPayload("{}"), + "{}"); + + assertThat(retained.tenantIdentityVersion()).isEqualTo(1); + assertThat(retained.tenantId()).isEqualTo(73L); + assertThat(retained.tenantUuid()).isNull(); + assertThatThrownBy(() -> AccountAuditDigest.ofPayload(String.valueOf((char) 0xD800))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("valid Unicode"); + } + + private static String arrangePersistedTenantRow( + AccountAuditOutboxRecord row, UUID auditEventId, LocalDateTime occurredAt, String payload) { + String digest = AccountAuditDigest.ofPayload(payload); + doAnswer( + invocation -> { + when(row.getAuditEventId()).thenReturn(auditEventId); + when(row.getScope()).thenReturn("tenant"); + when(row.getTenantId()).thenReturn(73L); + when(row.getTenantIdentityVersion()).thenReturn(1); + when(row.getTenantUuid()).thenReturn(null); + when(row.getProducerService()).thenReturn("account-service"); + when(row.getEventType()).thenReturn("ACCOUNT_MEMBERSHIP_LEFT"); + when(row.getOccurredAt()).thenReturn(occurredAt); + when(row.getSchemaVersion()).thenReturn(1); + when(row.getPayloadDigestVersion()).thenReturn(1); + when(row.getPayloadDigest()).thenReturn(digest); + when(row.getPayload()).thenReturn(payload); + return null; + }) + .when(row) + .refresh(); + return digest; + } + @Test void exactCommittedOrMinimizedTerminalReceiptAfterLostCompareAndSetIsANoOp() { for (String status : new String[] {"COMMITTED", "MINIMIZED"}) { @@ -273,6 +433,8 @@ private static AccountAuditOutboxRecord copyAsPersistedRow( persisted.setAuditEventId(source.getAuditEventId()); persisted.setScope(source.getScope()); persisted.setTenantId(source.getTenantId()); + persisted.setTenantIdentityVersion(source.getTenantIdentityVersion()); + persisted.setTenantUuid(source.getTenantUuid()); persisted.setProducerService(source.getProducerService()); persisted.setEventType(source.getEventType()); persisted.setOccurredAt(source.getOccurredAt()); @@ -311,6 +473,7 @@ private static AccountAuditOutboxRepository repositoryWithReadback( row.setDeliveryStatus(status); row.setReceiverReceiptId(receiptId); row.setReceiverLogEventId(logEventId); + row.setReceiverAuditProjectionVersion(1); rows.add(row); } return new MockResult[] {new MockResult(rowExists ? 1 : 0, rows)}; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepositoryTest.java new file mode 100644 index 0000000000..3e44ce5ad6 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepositoryTest.java @@ -0,0 +1,64 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class AccountConnectScopeRepositoryTest { + @Test + void canonicalScopeMethodsRequireOwnerTransactionBeforeCallingSqlOrSourceReaders() { + DSLContext dsl = mock(DSLContext.class); + AccountRepository accounts = mock(AccountRepository.class); + AccountTenantIdentityResolver retainedTenants = mock(AccountTenantIdentityResolver.class); + FreshTenantIdentityAssociationRepository freshTenants = + mock(FreshTenantIdentityAssociationRepository.class); + AccountConnectScopeRepository repository = + new AccountConnectScopeRepository(dsl, accounts, retainedTenants, freshTenants); + CanonicalJoinScopeV2 scope = + new CanonicalJoinScopeV2( + "opaque-scope-token", + UUID.fromString("46775955-2c40-42b9-bb7f-30b52ba4d4e5"), + UUID.fromString("58f72bb3-a1c9-49ec-84de-08a64c2bdfc7"), + UUID.fromString("e3c431d9-52e9-4b50-8aa1-ecb0400ee884"), + "tenant", + "world", + "production", + UUID.fromString("1cc10d35-a1f8-4ac7-9a51-a630bb02a8ad"), + "SHARED", + UUID.fromString("c69bbd57-5105-44fb-934f-90cf00fc3bb4"), + 1L, + 1L, + "2026-10-03T00:00:00Z", + "2026-10-03T00:01:00Z"); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + 42L, + TenantProvenanceKind.APPROVED_RETAINED, + UUID.fromString("9e0f2e18-84ab-4f7e-a6cf-7ebd3e39bd81"), + "sha256:" + "a".repeat(64)); + + assertThatThrownBy(() -> repository.insertCanonical(17L, scope, provenance)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Account connect scope access requires an active owner transaction"); + assertThatThrownBy(() -> repository.findCanonical(scope.connectScopeId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Account connect scope access requires an active owner transaction"); + assertThatThrownBy( + () -> repository.findCanonicalEvidenceByTokenHash("sha256:" + "b".repeat(64))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Account connect scope access requires an active owner transaction"); + + verifyNoInteractions(dsl, accounts, retainedTenants, freshTenants); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java new file mode 100644 index 0000000000..13fe40fe1a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java @@ -0,0 +1,67 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJoinOperationRepositoryCanonicalTest { + @Test + void canonicalIntentAndPolicyMethodsRequireOwnerTransactionBeforeReadingScopeOrJournal() { + DSLContext dsl = mock(DSLContext.class); + AccountConnectScopeRepository connectScopes = mock(AccountConnectScopeRepository.class); + AccountJoinOperationRepository repository = + new AccountJoinOperationRepository(dsl, connectScopes); + CanonicalJoinScopeV2 scope = + new CanonicalJoinScopeV2( + "opaque-canonical-scope-token", + UUID.fromString("46775955-2c40-42b9-bb7f-30b52ba4d4e5"), + UUID.fromString("58f72bb3-a1c9-49ec-84de-08a64c2bdfc7"), + UUID.fromString("e3c431d9-52e9-4b50-8aa1-ecb0400ee884"), + "tenant", + "world", + "production", + UUID.fromString("1cc10d35-a1f8-4ac7-9a51-a630bb02a8ad"), + "SHARED", + UUID.fromString("c69bbd57-5105-44fb-934f-90cf00fc3bb4"), + 1L, + 1L, + "2026-10-03T00:00:00Z", + "2026-10-03T00:01:00Z"); + boolean wasTransactionActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(false); + try { + assertThatThrownBy(() -> repository.insertCanonicalIntent("request-v2", scope, "caller")) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Canonical Account JOIN operation access requires an active owner transaction"); + assertThatThrownBy(() -> repository.findCanonicalEvidenceByRequestId("request-v2")) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Canonical Account JOIN operation access requires an active owner transaction"); + assertThatThrownBy( + () -> repository.bindCanonicalPolicyEvidence("request-v2", scope, "caller", true, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Canonical Account JOIN operation access requires an active owner transaction"); + assertThatThrownBy( + () -> + repository.recordCanonicalPolicyUnavailable( + "request-v2", scope, "caller", "ENTITLEMENT_UNAVAILABLE")) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Canonical Account JOIN operation access requires an active owner transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(wasTransactionActive); + } + + verifyNoInteractions(dsl, connectScopes); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java index e8539c2f37..414a2eda57 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.accountservice.client.LoggingAdminClient; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -103,6 +104,33 @@ void digestBindsExactUtf8PayloadBytes() { AccountAuditDigest.ofPayload("{\"accountId\": 1}")); } + @Test + void canonicalUuidEnvelopeCanReachTerminalDeliveryWithoutNumericAlias() { + String payload = "{\"tenant\":\"canonical\"}"; + AccountAuditEnvelope envelope = + new AccountAuditEnvelope( + UUID.randomUUID(), + "tenant", + AccountAuditTenantIdentity.canonicalTenantV2("33333333-3333-4333-8333-333333333333"), + "account-service", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + Instant.parse("2026-10-01T00:00:00Z"), + 1, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + when(outbox.pending(eq(50), Mockito.any(Instant.class))).thenReturn(List.of(envelope)); + when(client.deliver(envelope)) + .thenReturn(new LoggingAdminClient.AuditDeliveryResult("receipt-v2", "log-v2", false)); + + job.deliverPending(); + + verify(outbox).markDelivered(envelope.auditEventId(), "receipt-v2", "log-v2", false); + assertEquals(2, envelope.tenantIdentityVersion()); + assertNull(envelope.tenantId()); + assertEquals("33333333-3333-4333-8333-333333333333", envelope.tenantUuid().toString()); + } + private static AccountAuditEnvelope platformRegistration() { return platformRegistration(UUID.fromString("e9659715-e257-4f88-847e-700653e101d1")); } @@ -112,7 +140,7 @@ private static AccountAuditEnvelope platformRegistration(UUID auditEventId) { return new AccountAuditEnvelope( auditEventId, "platform", - null, + AccountAuditTenantIdentity.platformV1(), "account-service", "ACCOUNT_REGISTERED", Instant.parse("2026-09-24T00:00:00Z"), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java index c0eaf79001..88a860d2eb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountJoinReconciliationServiceTest.java @@ -6,9 +6,11 @@ import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -21,6 +23,7 @@ import java.util.UUID; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; @@ -665,11 +668,11 @@ void wrongPayloadDigestStaysPending() { when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); stubActiveMembership(fixture); + AccountAuditEnvelope wrongDigestEnvelope = + spy(joinAuditEnvelope(WORLD_SLUG, TENANT_ID, correctPayloadDigest())); + doReturn(sha256("wrong")).when(wrongDigestEnvelope).payloadDigest(); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) - .thenReturn( - Optional.of( - verifiedJoinAuditEvidence( - joinAuditEnvelope(WORLD_SLUG, TENANT_ID, sha256("wrong"))))); + .thenReturn(Optional.of(verifiedJoinAuditEvidence(wrongDigestEnvelope))); when(fixture.joinOperations.recordReconciliationAttempt( REQUEST_ID, 0, @@ -704,7 +707,7 @@ void wrongAuditPayloadTargetStaysPendingEvenWithValidDigest() { when(fixture.connectScopes.findEvidenceByTokenHash(pending.scopeTokenHash())) .thenReturn(Optional.of(scopeEvidence("PUBLIC_PRODUCTION", TENANT_ID, WORLD_SLUG))); stubActiveMembership(fixture); - String mismatchedPayload = joinAuditEnvelope("other-world", TENANT_ID, "unused").payload(); + String mismatchedPayload = joinAuditPayload("other-world", TENANT_ID); when(fixture.auditOutbox.findJoinEnvelopeForUpdate(joinAuditEventId(), TENANT_ID)) .thenReturn( Optional.of( @@ -1074,6 +1077,21 @@ private static JoinMembershipProof activeJoinMembership() { private static AccountAuditEnvelope joinAuditEnvelope( String payloadWorldSlug, long payloadTenantId, String digest) { + String payload = joinAuditPayload(payloadWorldSlug, payloadTenantId); + return new AccountAuditEnvelope( + joinAuditEventId(), + "tenant", + AccountAuditTenantIdentity.retainedTenantV1(TENANT_ID), + "account-service", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + NOW.minusSeconds(10), + 1, + 1, + digest, + payload); + } + + private static String joinAuditPayload(String payloadWorldSlug, long payloadTenantId) { String payload = "{\"accountId\":" + ACCOUNT_ID @@ -1088,17 +1106,7 @@ private static AccountAuditEnvelope joinAuditEnvelope( + ",\"requestId\":\"" + REQUEST_ID + "\"}"; - return new AccountAuditEnvelope( - joinAuditEventId(), - "tenant", - TENANT_ID, - "account-service", - "ACCOUNT_JOINED_PUBLIC_PRODUCTION", - NOW.minusSeconds(10), - 1, - 1, - digest, - payload); + return payload; } private static JoinAuditEvidence verifiedJoinAuditEvidence(AccountAuditEnvelope envelope) { @@ -1111,8 +1119,7 @@ private static UUID joinAuditEventId() { } private static String correctPayloadDigest() { - return AccountAuditDigest.ofPayload( - joinAuditEnvelope(WORLD_SLUG, TENANT_ID, "unused").payload()); + return AccountAuditDigest.ofPayload(joinAuditPayload(WORLD_SLUG, TENANT_ID)); } private static String sha256(String value) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java new file mode 100644 index 0000000000..a1376c7f88 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -0,0 +1,112 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountMembershipAuthorityEventProducerCanonicalJoinTest { + @Test + void canonicalFirstJoinRequiresWritableOwnerTransactionBeforeRepositoryReads() { + Repositories repositories = new Repositories(); + boolean previousActive = TransactionSynchronizationManager.isActualTransactionActive(); + boolean previousReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + try { + assertThatThrownBy( + () -> + repositories + .producer() + .publishCanonicalFirstJoinMembershipChange( + null, UUID.randomUUID().toString(), "verified-caller")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + repositories.verifyNoReads(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy( + () -> + repositories + .producer() + .publishCanonicalFirstJoinMembershipChange( + null, UUID.randomUUID().toString(), "verified-caller")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + repositories.verifyNoReads(); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previousActive); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(previousReadOnly); + } + } + + private static final class Repositories { + private final AccountJoinOperationRepository joinOperations = + mock(AccountJoinOperationRepository.class); + private final AccountMembershipPairAuthorityRepository pairAuthority = + mock(AccountMembershipPairAuthorityRepository.class); + private final AccountRepository accounts = mock(AccountRepository.class); + private final AccountTenantIdentityResolver tenantIdentities = + mock(AccountTenantIdentityResolver.class); + private final FreshTenantIdentityAssociationRepository freshAssociations = + mock(FreshTenantIdentityAssociationRepository.class); + private final AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + private final AccountAuthorityOutboxRepository authorityOutbox = + mock(AccountAuthorityOutboxRepository.class); + private final AccountMembershipTransitionReceiptRepository transitionReceipts = + mock(AccountMembershipTransitionReceiptRepository.class); + private final AccountTenantMembershipRepository memberships = + mock(AccountTenantMembershipRepository.class); + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshots = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + + private AccountMembershipAuthorityEventProducer producer() { + return new AccountMembershipAuthorityEventProducer( + joinOperations, + pairAuthority, + accounts, + tenantIdentities, + freshAssociations, + generations, + authorityOutbox, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), + transitionReceipts, + memberships, + roleSnapshots); + } + + private void verifyNoReads() { + verifyNoInteractions( + joinOperations, + pairAuthority, + accounts, + tenantIdentities, + freshAssociations, + generations, + authorityOutbox, + transitionReceipts, + memberships, + roleSnapshots); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java new file mode 100644 index 0000000000..6ac773e430 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.gamesession.dto; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import org.springframework.lang.Nullable; + +/** Exact committed owner evidence for one initial canonical CLOSED route. */ +public record CanonicalClosedAdmissionPointerSnapshot( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + String worldSlug, + String realmSlug, + long pointerVersion, + long catalogRevision, + String admissionState, + @Nullable UUID admissibleGameInstanceId, + UUID requestId, + String requestDigest, + String receiptDigest, + String actorPrincipal, + String reason, + long auditEventId, + Instant updatedAt, + CanonicalRealmCatalogSnapshot catalogSnapshot) { + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "CLOSED routing requires the nullable admissible instance to be absent; this constructor rejects any supplied UUID.") + public CanonicalClosedAdmissionPointerSnapshot { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(admissionState, "admissionState"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + Objects.requireNonNull(actorPrincipal, "actorPrincipal"); + Objects.requireNonNull(reason, "reason"); + Objects.requireNonNull(updatedAt, "updatedAt"); + Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + if (!"CLOSED".equals(admissionState) + || admissibleGameInstanceId != null + || pointerVersion != 1L + || catalogRevision != catalogSnapshot.catalogRevision() + || !targetNamespace.equals(catalogSnapshot.targetNamespace()) + || !canonicalTenantId.equals(catalogSnapshot.tenantId()) + || !realmId.equals(catalogSnapshot.realmId()) + || !worldSlug.equals(catalogSnapshot.worldSlug()) + || !realmSlug.equals(catalogSnapshot.realmSlug()) + || auditEventId <= 0L) { + throw new IllegalArgumentException( + "Canonical closed pointer snapshot does not match its exact initial catalog evidence"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java new file mode 100644 index 0000000000..c6ddb1c37e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; + +/** Immutable catalog evidence for one public-production realm; it is not admission authority. */ +public record CanonicalRealmCatalogSnapshot( + String targetNamespace, + UUID tenantId, + String tenantSlug, + String worldSlug, + UUID realmId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + UUID playableStateNamespaceId, + String characterCreationPolicy, + long catalogRevision, + UUID creationRequestId, + String requestDigest, + String receiptDigest, + IntakeReceipt sourceIntakeReceipt) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalRealmCatalogSnapshot { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(tenantId, "tenantId"); + Objects.requireNonNull(tenantSlug, "tenantSlug"); + Objects.requireNonNull(worldSlug, "worldSlug"); + requireNonNil(realmId, "realmId"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(realmDisplayName, "realmDisplayName"); + Objects.requireNonNull(stateScope, "stateScope"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(characterCreationPolicy, "characterCreationPolicy"); + requireNonNil(creationRequestId, "creationRequestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + if (!visible || !publicProduction || catalogRevision != 1L) { + throw new IllegalArgumentException("Unsupported canonical initial realm catalog state"); + } + var source = sourceIntakeReceipt.source(); + if (!targetNamespace.equals(source.targetNamespace()) + || !tenantId.equals(source.canonicalTenantId()) + || !tenantSlug.equals(source.tenantSlug()) + || !worldSlug.equals(source.worldSlug())) { + throw new IllegalArgumentException( + "Catalog selectors do not match the persisted authored-world source receipt"); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java new file mode 100644 index 0000000000..c07f92c6e1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Local audit inputs for one immutable initial canonical CLOSED admission pointer. */ +public record CreateCanonicalClosedAdmissionPointerRequest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID catalogCreationRequestId, + long catalogRevision, + String actorPrincipal, + String reason) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CreateCanonicalClosedAdmissionPointerRequest { + requireNonNil(requestId, "requestId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(catalogCreationRequestId, "catalogCreationRequestId"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + validateBoundedText(actorPrincipal, "actorPrincipal", 200, 800); + validateBoundedText(reason, "reason", 500, 2000); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void validateBoundedText( + String value, String name, int maximumCodePoints, int maximumUtf8Bytes) { + Objects.requireNonNull(value, name); + byte[] bytes = strictUtf8(value, name); + if (value.isBlank() + || value.codePointCount(0, value.length()) > maximumCodePoints + || bytes.length > maximumUtf8Bytes) { + throw new IllegalArgumentException(name + " must be bounded and nonblank"); + } + } + + private static byte[] strictUtf8(String value, String name) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(name + " must be well-formed UTF-8 text", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java new file mode 100644 index 0000000000..8bee96d53e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.gamesession.dto; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.lang.Nullable; + +/** Explicit input for one immutable public-production realm catalog creation. */ +public record CreateCanonicalRealmCatalogRequest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String characterCreationPolicy, + @Nullable UUID playtestLifecycleId, + @Nullable Long playtestStateGeneration) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "The two nullable lifecycle fields are rejected when supplied; null is their required ABSENT state for initial public production.") + public CreateCanonicalRealmCatalogRequest { + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceIntakeOperationId, "sourceIntakeOperationId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + Objects.requireNonNull(realmSlug, "realmSlug"); + if (realmSlug.isBlank() || strictUtf8(realmSlug, "realmSlug").length > 120) { + throw new IllegalArgumentException( + "realmSlug must be a nonblank selector of at most 120 UTF-8 bytes"); + } + Objects.requireNonNull(realmDisplayName, "realmDisplayName"); + if (realmDisplayName.isBlank() + || realmDisplayName.codePointCount(0, realmDisplayName.length()) > 100 + || strictUtf8(realmDisplayName, "realmDisplayName").length > 400) { + throw new IllegalArgumentException("realmDisplayName must be bounded and nonblank"); + } + if (!visible || !publicProduction) { + throw new IllegalArgumentException( + "Initial canonical realm creation requires visible public production"); + } + if (!"SHARED".equals(stateScope) && !"ISOLATED".equals(stateScope)) { + throw new IllegalArgumentException("stateScope must be exactly SHARED or ISOLATED"); + } + Objects.requireNonNull(characterCreationPolicy, "characterCreationPolicy"); + if (characterCreationPolicy.isBlank() + || characterCreationPolicy.codePointCount(0, characterCreationPolicy.length()) > 64 + || strictUtf8(characterCreationPolicy, "characterCreationPolicy").length > 256) { + throw new IllegalArgumentException( + "characterCreationPolicy must be an explicit bounded nonblank owner value"); + } + if (playtestLifecycleId != null || playtestStateGeneration != null) { + throw new IllegalArgumentException( + "Initial public-production creation cannot carry private/playtest lifecycle evidence"); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static byte[] strictUtf8(String value, String name) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(name + " must be well-formed UTF-8 text", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java new file mode 100644 index 0000000000..079d5556b7 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java @@ -0,0 +1,928 @@ +package net.firedevops.firemud.gamesession.repository; + +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalClosedAdmissionPointerRequest; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local persistence for one initial canonical CLOSED admission pointer per realm. */ +@Repository +public class GameSessionCanonicalAdmissionPointerRepository { + private static final int SCHEMA_VERSION = 1; + private static final int CANONICAL_REPRESENTATION_VERSION = 2; + private static final long INITIAL_POINTER_VERSION = 1L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String CLOSED = "CLOSED"; + private static final String ABSENT = "ABSENT"; + private static final String REQUEST_DOMAIN = "game-session-canonical-closed-pointer-request/v1"; + private static final String RECEIPT_DOMAIN = "game-session-canonical-closed-pointer-receipt/v1"; + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final GameplayAdmissionPointerEventRepository eventRepository; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories and DSLContext are internal Spring collaborators.") + public GameSessionCanonicalAdmissionPointerRepository( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameplayAdmissionPointerEventRepository eventRepository) { + this.dsl = dsl; + this.catalogRepository = catalogRepository; + this.eventRepository = eventRepository; + } + + /** + * Prepares from a committed catalog read without retaining an ambient owner transaction. The + * returned value is privately constructed and must be revalidated under the catalog row lock. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedInitialClosed prepareInitialClosed( + CreateCanonicalClosedAdmissionPointerRequest request) { + Objects.requireNonNull(request, "request"); + requireCommittedRead(); + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(request.targetNamespace(), request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Exact committed initial catalog request is missing")); + requireExactInitialCatalog(request, catalog); + return new PreparedInitialClosed(request, catalog, requestDigest(request, catalog)); + } + + /** + * Commits the CLOSED route, one append-only event, and its immutable request outcome atomically. + * The caller must perform a separate committed {@link #readByRequest} before returning evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void createInitialClosed(PreparedInitialClosed prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireWritableOwnerTransaction(); + CreateCanonicalClosedAdmissionPointerRequest request = prepared.request(); + CanonicalRealmCatalogSnapshot catalog = + catalogRepository.lockExactInitialPublicProduction( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision()); + requireExactInitialCatalog(request, catalog); + if (!prepared.catalogSnapshot().equals(catalog)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Locked catalog snapshot changed after canonical CLOSED pointer preparation"); + } + + String requestDigest = requestDigest(request, catalog); + if (!prepared.requestDigest().equals(requestDigest)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Prepared canonical CLOSED pointer digest does not match its exact inputs"); + } + + Record priorRequest = findRequest(request.targetNamespace(), request.requestId()); + if (priorRequest != null) { + requireSameRequest(priorRequest, request, catalog, requestDigest); + return; + } + if (pointerExistsForRealm(request.realmId())) { + throw new CanonicalClosedPointerConflictException( + "Canonical realm already has an admission-pointer representation"); + } + + Instant updatedAt = Instant.now().truncatedTo(ChronoUnit.MICROS); + Long pointerId; + long auditEventId; + String receiptDigest; + try { + Record insertedPointer = + dsl.fetchOne( + "INSERT INTO gameplay_admission_pointer (" + + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "created_at, updated_at, public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state) " + + "VALUES (?, ?, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, " + + "?, ?, NULL, ?, ?, NULL, 2, ?, ?, 'CLOSED') RETURNING id", + catalog.worldSlug(), + catalog.realmSlug(), + toLocalDateTime(updatedAt), + toLocalDateTime(updatedAt), + catalog.catalogRevision(), + catalog.realmId(), + catalog.targetNamespace(), + catalog.tenantId()); + if (insertedPointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer insert returned no owner row"); + } + pointerId = insertedPointer.get("id", Long.class); + if (pointerId == null || pointerId <= 0L) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer row id is invalid"); + } + + auditEventId = + eventRepository.appendCanonicalClosed( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + catalog.catalogRevision(), + request.actorPrincipal(), + request.reason(), + request.requestId(), + updatedAt); + receiptDigest = receiptDigest(request, catalog, requestDigest, auditEventId, updatedAt); + dsl.execute( + "INSERT INTO game_session_canonical_closed_admission_pointer_request (" + + "target_namespace, request_id, request_digest, canonical_tenant_id, realm_id, " + + "catalog_creation_request_id, catalog_revision, catalog_request_digest, " + + "catalog_receipt_digest, actor_principal, reason, admission_state, pointer_version, " + + "audit_event_id, receipt_digest, updated_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'CLOSED', 1, ?, ?, CAST(? AS TIMESTAMPTZ))", + request.targetNamespace(), + request.requestId(), + requestDigest, + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision(), + catalog.requestDigest(), + catalog.receiptDigest(), + request.actorPrincipal(), + request.reason(), + auditEventId, + receiptDigest, + OffsetDateTime.ofInstant(updatedAt, ZoneOffset.UTC)); + } catch (org.jooq.exception.IntegrityConstraintViolationException exception) { + throw new CanonicalClosedPointerConflictException( + "Canonical CLOSED pointer creation conflicts with committed realm or request authority", + exception); + } + } + + /** + * Prepares an explicit expected-closed check from the exact original committed CLOSED request. + * Missing request, pointer, event, or catalog history is invalid evidence and never establishes a + * never-open origin. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedExpectedClosed prepareExpectedClosed( + String targetNamespace, + UUID originalRequestId, + long expectedPointerVersion, + long expectedCatalogRevision) { + requireReadSelector(targetNamespace, originalRequestId); + requirePositive(expectedPointerVersion, "expectedPointerVersion"); + requirePositive(expectedCatalogRevision, "expectedCatalogRevision"); + requireCommittedRead(); + + CanonicalClosedAdmissionPointerSnapshot origin = + readByRequest(targetNamespace, originalRequestId) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Exact original committed canonical CLOSED origin is missing")); + requireExpectedVersions(origin, expectedPointerVersion, expectedCatalogRevision); + return new PreparedExpectedClosed(origin, expectedPointerVersion, expectedCatalogRevision); + } + + /** + * Locks and revalidates one prepared original CLOSED origin in the caller's read-write READ + * COMMITTED owner transaction. The returned token is local repository evidence only; it is not + * World hold/readback, caller authentication, or authorization to transition the pointer. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ExpectedClosedEvidence lockExpectedClosed(PreparedExpectedClosed prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireWritableOwnerTransaction(); + CanonicalClosedAdmissionPointerSnapshot committedOrigin = prepared.committedOrigin(); + CreateCanonicalClosedAdmissionPointerRequest originRequest = + requestFromSnapshot(committedOrigin); + + CanonicalRealmCatalogSnapshot lockedCatalog = + catalogRepository.lockExactInitialPublicProduction( + originRequest.targetNamespace(), + originRequest.canonicalTenantId(), + originRequest.realmId(), + originRequest.catalogCreationRequestId(), + prepared.expectedCatalogRevision()); + if (!committedOrigin.catalogSnapshot().equals(lockedCatalog)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact catalog origin changed after expected-CLOSED preparation"); + } + + Record lockedPointer = lockCanonicalPointer(originRequest); + if (lockedPointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED pointer row is missing"); + } + Record outcome = findRequest(originRequest.targetNamespace(), originRequest.requestId()); + if (outcome == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED request outcome is missing"); + } + + CanonicalClosedAdmissionPointerSnapshot lockedOrigin = + verifyOrigin( + originRequest.targetNamespace(), + originRequest.requestId(), + outcome, + lockedCatalog, + lockedPointer); + requireExpectedVersions( + lockedOrigin, prepared.expectedPointerVersion(), prepared.expectedCatalogRevision()); + if (!committedOrigin.equals(lockedOrigin)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED origin changed after preparation"); + } + return new ExpectedClosedEvidence(lockedOrigin); + } + + /** Reads and verifies the immutable request outcome from committed owner rows. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByRequest( + String targetNamespace, UUID requestId) { + requireReadSelector(targetNamespace, requestId); + requireCommittedRead(); + Record outcome = findRequest(targetNamespace, requestId); + if (outcome == null) { + return Optional.empty(); + } + try { + CreateCanonicalClosedAdmissionPointerRequest request = requestFromOutcome(outcome); + if (!targetNamespace.equals(request.targetNamespace()) + || !requestId.equals(request.requestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its read selector"); + } + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(targetNamespace, request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome lost its catalog reference")); + Record pointer = findCanonicalPointer(request); + return Optional.of(verifyOrigin(targetNamespace, requestId, outcome, catalog, pointer)); + } catch (InvalidCanonicalClosedPointerEvidenceException + | GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException + | GameSessionCanonicalRealmCatalogRepository.CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer evidence is invalid", exception); + } + } + + private Record findRequest(String targetNamespace, UUID requestId) { + return dsl.fetchOne( + "SELECT * FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND request_id = ?", + targetNamespace, + requestId); + } + + private Record lockCanonicalPointer(CreateCanonicalClosedAdmissionPointerRequest request) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer " + + "WHERE representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ? FOR UPDATE", + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId()); + } + + private CanonicalClosedAdmissionPointerSnapshot verifyOrigin( + String targetNamespace, + UUID requestId, + Record outcome, + CanonicalRealmCatalogSnapshot catalog, + Record pointer) { + try { + CreateCanonicalClosedAdmissionPointerRequest request = requestFromOutcome(outcome); + if (!targetNamespace.equals(request.targetNamespace()) + || !requestId.equals(request.requestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its read selector"); + } + requireExactInitialCatalog(request, catalog); + String computedRequestDigest = requestDigest(request, catalog); + if (!computedRequestDigest.equals(required(outcome, "request_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer request digest does not match committed request inputs"); + } + if (!catalog.requestDigest().equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its exact catalog digests"); + } + + long eventId = required(outcome, "audit_event_id", Long.class); + Instant updatedAt = outcomeTimestamp(outcome); + String computedReceiptDigest = + receiptDigest(request, catalog, computedRequestDigest, eventId, updatedAt); + if (!computedReceiptDigest.equals(required(outcome, "receipt_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer receipt digest does not match its committed result"); + } + requireOutcomeMatches( + outcome, + request, + catalog, + computedRequestDigest, + computedReceiptDigest, + eventId, + updatedAt); + + if (pointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome has no committed routing row"); + } + requirePointerMatches(pointer, request, catalog, updatedAt); + + Record event = findCanonicalEvent(eventId); + if (event == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome has no committed audit event"); + } + requireEventMatches(event, request, catalog, eventId, updatedAt); + + return new CanonicalClosedAdmissionPointerSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + INITIAL_POINTER_VERSION, + catalog.catalogRevision(), + CLOSED, + null, + request.requestId(), + computedRequestDigest, + computedReceiptDigest, + request.actorPrincipal(), + request.reason(), + eventId, + updatedAt, + catalog); + } catch (InvalidCanonicalClosedPointerEvidenceException + | GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException + | GameSessionCanonicalRealmCatalogRepository.CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer evidence is invalid", exception); + } + } + + private static CreateCanonicalClosedAdmissionPointerRequest requestFromSnapshot( + CanonicalClosedAdmissionPointerSnapshot snapshot) { + return new CreateCanonicalClosedAdmissionPointerRequest( + snapshot.requestId(), + snapshot.targetNamespace(), + snapshot.canonicalTenantId(), + snapshot.realmId(), + snapshot.catalogSnapshot().creationRequestId(), + snapshot.catalogRevision(), + snapshot.actorPrincipal(), + snapshot.reason()); + } + + static void requireExpectedVersions( + CanonicalClosedAdmissionPointerSnapshot origin, + long expectedPointerVersion, + long expectedCatalogRevision) { + if (origin.pointerVersion() != expectedPointerVersion + || origin.catalogRevision() != expectedCatalogRevision) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Expected pointer and catalog versions do not match the exact original CLOSED origin"); + } + } + + private boolean pointerExistsForRealm(UUID realmId) { + return dsl.fetchExists( + dsl.selectOne() + .from(org.jooq.impl.DSL.table("gameplay_admission_pointer")) + .where(org.jooq.impl.DSL.field("realm_id", UUID.class).eq(realmId))); + } + + private Record findCanonicalPointer(CreateCanonicalClosedAdmissionPointerRequest request) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer " + + "WHERE representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ?", + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId()); + } + + private Record findCanonicalEvent(long eventId) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer_event " + + "WHERE representation_version = 2 AND id = ?", + eventId); + } + + private static CreateCanonicalClosedAdmissionPointerRequest requestFromOutcome(Record outcome) { + return new CreateCanonicalClosedAdmissionPointerRequest( + required(outcome, "request_id", UUID.class), + required(outcome, "target_namespace", String.class), + required(outcome, "canonical_tenant_id", UUID.class), + required(outcome, "realm_id", UUID.class), + required(outcome, "catalog_creation_request_id", UUID.class), + required(outcome, "catalog_revision", Long.class), + required(outcome, "actor_principal", String.class), + required(outcome, "reason", String.class)); + } + + private static void requireSameRequest( + Record outcome, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest) { + if (!request.requestId().equals(required(outcome, "request_id", UUID.class)) + || !requestDigest.equals(required(outcome, "request_digest", String.class)) + || !request.targetNamespace().equals(required(outcome, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(outcome, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(outcome, "realm_id", UUID.class)) + || !request + .catalogCreationRequestId() + .equals(required(outcome, "catalog_creation_request_id", UUID.class)) + || request.catalogRevision() != required(outcome, "catalog_revision", Long.class) + || !catalog + .requestDigest() + .equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class)) + || !request.actorPrincipal().equals(required(outcome, "actor_principal", String.class)) + || !request.reason().equals(required(outcome, "reason", String.class))) { + throw new CanonicalClosedPointerConflictException( + "Canonical CLOSED pointer request identity was reused with changed input"); + } + } + + private static void requireExactInitialCatalog( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + if (!catalog.visible() + || !catalog.publicProduction() + || catalog.catalogRevision() != request.catalogRevision() + || catalog.catalogRevision() != INITIAL_POINTER_VERSION + || !request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer request does not identify the exact initial public catalog"); + } + } + + private static void requireOutcomeMatches( + Record outcome, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + String receiptDigest, + long eventId, + Instant updatedAt) { + if (!CLOSED.equals(required(outcome, "admission_state", String.class)) + || required(outcome, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(outcome, "audit_event_id", Long.class) != eventId + || !request.requestId().equals(required(outcome, "request_id", UUID.class)) + || !request.targetNamespace().equals(required(outcome, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(outcome, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(outcome, "realm_id", UUID.class)) + || !request + .catalogCreationRequestId() + .equals(required(outcome, "catalog_creation_request_id", UUID.class)) + || request.catalogRevision() != required(outcome, "catalog_revision", Long.class) + || !requestDigest.equals(required(outcome, "request_digest", String.class)) + || !receiptDigest.equals(required(outcome, "receipt_digest", String.class)) + || !catalog + .requestDigest() + .equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class)) + || !request.actorPrincipal().equals(required(outcome, "actor_principal", String.class)) + || !request.reason().equals(required(outcome, "reason", String.class)) + || !updatedAt.equals(outcomeTimestamp(outcome))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome conflicts with its request or catalog authority"); + } + } + + private static void requirePointerMatches( + Record pointer, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + Instant updatedAt) { + if (required(pointer, "representation_version", Integer.class) + != CANONICAL_REPRESENTATION_VERSION + || !request.targetNamespace().equals(required(pointer, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(pointer, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(pointer, "realm_id", UUID.class)) + || !catalog.worldSlug().equals(required(pointer, "world_slug", String.class)) + || !catalog.realmSlug().equals(required(pointer, "realm_slug", String.class)) + || required(pointer, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(pointer, "catalog_revision", Long.class) != request.catalogRevision() + || !CLOSED.equals(required(pointer, "admission_state", String.class)) + || pointer.get("tenant_id", Long.class) != null + || pointer.get("game_instance_id", Long.class) != null + || pointer.get("playable_state_namespace_id", UUID.class) != null + || hasLegacyPointerCatalogCopy(pointer) + || !updatedAt.equals(toInstant(pointer.get("created_at", java.time.LocalDateTime.class))) + || !updatedAt.equals(toInstant(pointer.get("updated_at", java.time.LocalDateTime.class)))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer row is aliased, policy-copied or inconsistent with its catalog"); + } + } + + private static boolean hasLegacyPointerCatalogCopy(Record pointer) { + return pointer.get("world_display_name", String.class) != null + || pointer.get("realm_display_name", String.class) != null + || pointer.get("visible", Boolean.class) != null + || pointer.get("public_production_realm", Boolean.class) != null + || pointer.get("requires_character_selection", Boolean.class) != null + || pointer.get("state_scope", String.class) != null + || pointer.get("character_creation_policy", String.class) != null + || pointer.get("last_updated_by", String.class) != null + || pointer.get("last_update_reason", String.class) != null; + } + + private static void requireEventMatches( + Record event, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + long eventId, + Instant updatedAt) { + if (required(event, "id", Long.class) != eventId + || required(event, "representation_version", Integer.class) + != CANONICAL_REPRESENTATION_VERSION + || !request.targetNamespace().equals(required(event, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(event, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(event, "realm_id", UUID.class)) + || !catalog.worldSlug().equals(required(event, "world_slug", String.class)) + || !catalog.realmSlug().equals(required(event, "realm_slug", String.class)) + || required(event, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(event, "catalog_revision", Long.class) != request.catalogRevision() + || !CLOSED.equals(required(event, "admission_state", String.class)) + || !request + .requestId() + .toString() + .equals(required(event, "control_plane_request_id", String.class)) + || !request.actorPrincipal().equals(required(event, "actor_principal", String.class)) + || !request.reason().equals(required(event, "reason", String.class)) + || event.get("tenant_id", Long.class) != null + || event.get("game_instance_id", Long.class) != null + || event.get("prepared_version_upgrade_id", String.class) != null + || hasLegacyEventCatalogCopy(event) + || !updatedAt.equals(toInstant(event.get("occurred_at", java.time.LocalDateTime.class)))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer audit event conflicts with its pointer or catalog authority"); + } + } + + private static boolean hasLegacyEventCatalogCopy(Record event) { + return event.get("world_display_name", String.class) != null + || event.get("realm_display_name", String.class) != null + || event.get("visible", Boolean.class) != null + || event.get("public_production_realm", Boolean.class) != null + || event.get("requires_character_selection", Boolean.class) != null + || event.get("state_scope", String.class) != null + || event.get("character_creation_policy", String.class) != null; + } + + private static Instant outcomeTimestamp(Record outcome) { + OffsetDateTime updatedAt = required(outcome, "updated_at", OffsetDateTime.class); + return updatedAt.toInstant(); + } + + static String requestDigest( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + return digest(requestDigestFields(request, catalog)); + } + + private static List requestDigestFields( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + return List.of( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.requestId().toString(), + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + catalog.requestDigest(), + catalog.receiptDigest(), + request.actorPrincipal(), + request.reason(), + CLOSED, + ABSENT); + } + + static String receiptDigest( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + long auditEventId, + Instant updatedAt) { + return digest(receiptDigestFields(request, catalog, requestDigest, auditEventId, updatedAt)); + } + + private static List receiptDigestFields( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + long auditEventId, + Instant updatedAt) { + requirePositive(auditEventId, "auditEventId"); + return List.of( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.requestId().toString(), + requestDigest, + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + catalog.worldSlug(), + catalog.realmSlug(), + Long.toString(INITIAL_POINTER_VERSION), + Long.toString(request.catalogRevision()), + Long.toString(auditEventId), + Objects.requireNonNull(updatedAt, "updatedAt").toString(), + CLOSED, + ABSENT); + } + + private static String digest(List fields) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String value : fields) { + byte[] bytes = strictUtf8(value); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must be well-formed UTF-8 text", exception); + } + } + + private static void requireReadSelector(String targetNamespace, UUID requestId) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) { + throw new InvalidCanonicalClosedPointerEvidenceException(name + " must be positive"); + } + } + + private static T required(Record record, String fieldName, Class type) { + T value = record.get(fieldName, type); + if (value == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer " + fieldName + " is missing"); + } + return value; + } + + private void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires a read-write transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical CLOSED pointer DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires READ COMMITTED isolation"); + } + return null; + }); + Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); + if (isolationRow == null + || !"read committed".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires READ COMMITTED isolation"); + } + Record readOnlyRow = dsl.fetchOne("SHOW transaction_read_only"); + if (readOnlyRow == null || !"off".equalsIgnoreCase(readOnlyRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires a read-write transaction"); + } + } + + private void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical CLOSED pointer operation requires a committed-outcome owner read"); + } + } + + /** + * Opaque preflight result; callers cannot construct a preparation or change its catalog proof. + */ + public static final class PreparedInitialClosed { + private final CreateCanonicalClosedAdmissionPointerRequest request; + private final CanonicalRealmCatalogSnapshot catalogSnapshot; + private final String requestDigest; + + private PreparedInitialClosed( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalogSnapshot, + String requestDigest) { + this.request = Objects.requireNonNull(request, "request"); + this.catalogSnapshot = Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + this.requestDigest = Objects.requireNonNull(requestDigest, "requestDigest"); + } + + private CreateCanonicalClosedAdmissionPointerRequest request() { + return request; + } + + private CanonicalRealmCatalogSnapshot catalogSnapshot() { + return catalogSnapshot; + } + + private String requestDigest() { + return requestDigest; + } + } + + /** Opaque committed-origin preflight; callers cannot construct it or replace its exact origin. */ + public static final class PreparedExpectedClosed { + private final CanonicalClosedAdmissionPointerSnapshot committedOrigin; + private final long expectedPointerVersion; + private final long expectedCatalogRevision; + + private PreparedExpectedClosed( + CanonicalClosedAdmissionPointerSnapshot committedOrigin, + long expectedPointerVersion, + long expectedCatalogRevision) { + this.committedOrigin = Objects.requireNonNull(committedOrigin, "committedOrigin"); + this.expectedPointerVersion = expectedPointerVersion; + this.expectedCatalogRevision = expectedCatalogRevision; + } + + private CanonicalClosedAdmissionPointerSnapshot committedOrigin() { + return committedOrigin; + } + + private long expectedPointerVersion() { + return expectedPointerVersion; + } + + private long expectedCatalogRevision() { + return expectedCatalogRevision; + } + } + + /** + * Opaque local evidence that the exact original canonical CLOSED v1 pointer, its creation event, + * immutable request outcome, and initial catalog were positively verified under owner locks. This + * evidence is not caller authentication, World lifecycle or hold evidence, or OPEN authority. + */ + public static final class ExpectedClosedEvidence { + private final CanonicalClosedAdmissionPointerSnapshot verifiedOrigin; + + private ExpectedClosedEvidence(CanonicalClosedAdmissionPointerSnapshot verifiedOrigin) { + this.verifiedOrigin = Objects.requireNonNull(verifiedOrigin, "verifiedOrigin"); + } + + public String targetNamespace() { + return verifiedOrigin.targetNamespace(); + } + + public UUID originalRequestId() { + return verifiedOrigin.requestId(); + } + + public UUID canonicalTenantId() { + return verifiedOrigin.canonicalTenantId(); + } + + public UUID realmId() { + return verifiedOrigin.realmId(); + } + + public long pointerVersion() { + return verifiedOrigin.pointerVersion(); + } + + public long catalogRevision() { + return verifiedOrigin.catalogRevision(); + } + + public String requestDigest() { + return verifiedOrigin.requestDigest(); + } + + public String receiptDigest() { + return verifiedOrigin.receiptDigest(); + } + + public long auditEventId() { + return verifiedOrigin.auditEventId(); + } + + public boolean isNeverOpenOrigin() { + return CLOSED.equals(verifiedOrigin.admissionState()) + && verifiedOrigin.pointerVersion() == INITIAL_POINTER_VERSION + && verifiedOrigin.admissibleGameInstanceId() == null; + } + } + + public static class CanonicalClosedPointerConflictException extends IllegalStateException { + public CanonicalClosedPointerConflictException(String message) { + super(message); + } + + public CanonicalClosedPointerConflictException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class InvalidCanonicalClosedPointerEvidenceException extends IllegalStateException { + public InvalidCanonicalClosedPointerEvidenceException(String message) { + super(message); + } + + public InvalidCanonicalClosedPointerEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java new file mode 100644 index 0000000000..484e63638c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java @@ -0,0 +1,1074 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Game Session-owned immutable initial realm catalog creation and exact readback. + * + *

This is an unwired catalog source. It never creates or opens an admission pointer and does not + * establish World lifecycle, membership, entitlement, or creator authorization. + */ +@Repository +public class GameSessionCanonicalRealmCatalogRepository { + private static final int SCHEMA_VERSION = 1; + private static final long INITIAL_CATALOG_REVISION = 1L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String REQUEST_DOMAIN = "game-session-canonical-realm-catalog-request/v1"; + private static final String RECEIPT_DOMAIN = "game-session-canonical-realm-catalog-receipt/v1"; + + private static final Table CATALOG = + DSL.table(DSL.name("game_session_canonical_realm_catalog")); + private static final Table SHARED_NAMESPACES = + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")); + + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_SLUG = DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field REALM_ID = DSL.field(DSL.name("realm_id"), UUID.class); + private static final Field REALM_SLUG = DSL.field(DSL.name("realm_slug"), String.class); + private static final Field REALM_DISPLAY_NAME = + DSL.field(DSL.name("realm_display_name"), String.class); + private static final Field VISIBLE = DSL.field(DSL.name("visible"), Boolean.class); + private static final Field PUBLIC_PRODUCTION = + DSL.field(DSL.name("public_production"), Boolean.class); + private static final Field STATE_SCOPE = DSL.field(DSL.name("state_scope"), String.class); + private static final Field PLAYABLE_STATE_NAMESPACE_ID = + DSL.field(DSL.name("playable_state_namespace_id"), UUID.class); + private static final Field CHARACTER_CREATION_POLICY = + DSL.field(DSL.name("character_creation_policy"), String.class); + private static final Field CATALOG_REVISION = + DSL.field(DSL.name("catalog_revision"), Long.class); + private static final Field CREATION_REQUEST_ID = + DSL.field(DSL.name("creation_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + private static final Field SOURCE_INTAKE_OPERATION_ID = + DSL.field(DSL.name("source_intake_operation_id"), UUID.class); + private static final Field SOURCE_INTAKE_SCHEMA_VERSION = + DSL.field(DSL.name("source_intake_schema_version"), Integer.class); + private static final Field SOURCE_INTAKE_REQUEST_ID = + DSL.field(DSL.name("source_intake_request_id"), UUID.class); + private static final Field SOURCE_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("source_intake_request_digest"), String.class); + private static final Field SOURCE_INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("source_intake_receipt_digest"), String.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Integer.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("source_registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("source_request_digest"), String.class); + private static final Field SOURCE_WORLD_DISPLAY_NAME = + DSL.field(DSL.name("source_world_display_name"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_provenance_kind"), String.class); + private static final Field BINDING_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + + private static final Field LEGACY_TENANT_ID = DSL.field(DSL.name("tenant_id"), Long.class); + private static final Field SHARED_NAMESPACE_ID = + DSL.field(DSL.name("playable_state_namespace_id"), UUID.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Fail-fast validation is local; no overridable callback or partially initialized object escapes.") + public GameSessionCanonicalRealmCatalogRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Resolves exact committed authored-world evidence before the catalog write transaction begins. + * The returned opaque prepared value can only be constructed by this repository and is verified + * again against the locked immutable owner rows during creation. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedInitialPublicProduction prepareInitialPublicProduction( + CreateCanonicalRealmCatalogRequest request) { + Objects.requireNonNull(request, "request"); + requireCommittedRead(); + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + request.targetNamespace(), + request.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException( + "Canonical tenant source binding is missing from committed Game Session owner storage"); + } + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + request.targetNamespace(), + request.sourceIntakeOperationId()); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Exact committed authored-world source intake is missing"); + } + IntakeReceipt committedSource = toIntakeReceipt(intake); + requireTenantBindingMatches(binding, committedSource.source()); + requireRequestMatchesSource(request, committedSource); + requireFreshSource(committedSource.source()); + requireNoRetainedTenantAssociation(request.targetNamespace(), request.canonicalTenantId()); + return new PreparedInitialPublicProduction(request, committedSource); + } + + /** + * Creates one public-production catalog snapshot under the caller's read-write owner transaction. + * Exact retries read back the original immutable result; changed intent conflicts. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalRealmCatalogSnapshot createInitialPublicProduction( + PreparedInitialPublicProduction prepared) { + Objects.requireNonNull(prepared, "prepared"); + CreateCanonicalRealmCatalogRequest request = prepared.request(); + requireWritableOwnerTransaction(); + + IntakeReceipt sourceReceipt = lockAndReadFreshSource(request); + if (!prepared.committedSource().equals(sourceReceipt)) { + throw new InvalidCatalogEvidenceException( + "Committed authored-world evidence changed before canonical catalog creation"); + } + // Retained association capture locks the V6 namespace family before committing an association. + // Taking the same relation lock before this check serializes both SHARED and ISOLATED creation + // against that owner transaction without deriving a link to any retained numeric tenant. + dsl.execute("LOCK TABLE gameplay_tenant_shared_playable_state_namespace IN ROW EXCLUSIVE MODE"); + requireNoRetainedTenantAssociation(request.targetNamespace(), request.canonicalTenantId()); + + String requestDigest = requestDigest(request, sourceReceipt); + Record existing = findByRequest(request.targetNamespace(), request.requestId()); + if (existing != null) { + return requireExactRetry(existing, request, sourceReceipt, requestDigest); + } + if (findPublicForTenant(request.targetNamespace(), request.canonicalTenantId()) != null) { + throw new CatalogConflictException( + "Canonical tenant already has a public-production realm catalog result"); + } + if (findByRealmSlug(request.targetNamespace(), request.canonicalTenantId(), request.realmSlug()) + != null) { + throw new CatalogConflictException("Realm selector is already owned by this tenant"); + } + + UUID realmId = UUID.randomUUID(); + requireNonNil(realmId, "allocated realmId"); + UUID namespaceId = + "SHARED".equals(request.stateScope()) + ? getOrCreateSharedNamespace(request.targetNamespace(), sourceReceipt) + : allocateIsolatedNamespace(); + UUID namespace = namespaceId; + String receiptDigest = + receiptDigest( + request, sourceReceipt, realmId, namespace, INITIAL_CATALOG_REVISION, requestDigest); + + int inserted = + dsl.insertInto(CATALOG) + .set(TARGET_NAMESPACE, request.targetNamespace()) + .set(CANONICAL_TENANT_ID, request.canonicalTenantId()) + .set(TENANT_SLUG, sourceReceipt.source().tenantSlug()) + .set(WORLD_SLUG, sourceReceipt.source().worldSlug()) + .set(REALM_ID, realmId) + .set(REALM_SLUG, request.realmSlug()) + .set(REALM_DISPLAY_NAME, request.realmDisplayName()) + .set(VISIBLE, request.visible()) + .set(PUBLIC_PRODUCTION, request.publicProduction()) + .set(STATE_SCOPE, request.stateScope()) + .set(PLAYABLE_STATE_NAMESPACE_ID, namespace) + .set(CHARACTER_CREATION_POLICY, request.characterCreationPolicy()) + .set(CATALOG_REVISION, INITIAL_CATALOG_REVISION) + .set(CREATION_REQUEST_ID, request.requestId()) + .set(REQUEST_DIGEST, requestDigest) + .set(RECEIPT_DIGEST, receiptDigest) + .set(SOURCE_INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(SOURCE_INTAKE_SCHEMA_VERSION, SCHEMA_VERSION) + .set(SOURCE_INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, sourceReceipt.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(SOURCE_SCHEMA_VERSION, sourceReceipt.source().schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, sourceReceipt.source().registrationRequestId()) + .set(SOURCE_OPERATION_ID, sourceReceipt.source().operationId()) + .set(SOURCE_REQUEST_DIGEST, sourceReceipt.source().requestDigest()) + .set(SOURCE_WORLD_DISPLAY_NAME, sourceReceipt.source().worldDisplayName()) + .set(SOURCE_GAME_ROW_ID, sourceReceipt.source().sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, sourceReceipt.source().sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, sourceReceipt.source().provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, sourceReceipt.source().evidenceDigest()) + .onConflictDoNothing() + .execute(); + + Record persisted = findByRequest(request.targetNamespace(), request.requestId()); + if (persisted == null) { + if (inserted == 0) { + throw new CatalogConflictException( + "Canonical realm selector or public-production claim conflicts with existing authority"); + } + throw new InvalidCatalogEvidenceException( + "Canonical realm catalog creation did not read back its persisted request"); + } + return requireExactRetry(persisted, request, sourceReceipt, requestDigest); + } + + /** Reads one exact immutable result by its stable creation request identity. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByRequest( + String targetNamespace, UUID requestId) { + requireReadSelector(targetNamespace, requestId); + requireCommittedRead(); + Record record = findByRequest(targetNamespace, requestId); + return record == null ? Optional.empty() : Optional.of(toSnapshot(record)); + } + + /** + * Locks and fully verifies one exact initial public-production catalog row in the caller's owner + * transaction. The returned snapshot is produced by the same validation used for committed + * catalog reads; callers must compare it with their committed preflight snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalRealmCatalogSnapshot lockExactInitialPublicProduction( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID creationRequestId, + long catalogRevision) { + requireWritableOwnerTransaction(); + requireReadSelector(targetNamespace, canonicalTenantId); + requireNonNil(realmId, "realmId"); + requireNonNil(creationRequestId, "creationRequestId"); + if (catalogRevision != INITIAL_CATALOG_REVISION) { + throw new CatalogConflictException( + "Initial public-production catalog revision must be exactly one"); + } + Record record = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(REALM_ID.eq(realmId)) + .and(CREATION_REQUEST_ID.eq(creationRequestId)) + .and(CATALOG_REVISION.eq(catalogRevision))) + .forUpdate() + .fetchOne(); + if (record == null) { + throw new InvalidCatalogEvidenceException( + "Exact initial public-production catalog row is missing from Game Session owner storage"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(record); + if (!snapshot.visible() + || !snapshot.publicProduction() + || snapshot.catalogRevision() != INITIAL_CATALOG_REVISION + || !snapshot.targetNamespace().equals(targetNamespace) + || !snapshot.tenantId().equals(canonicalTenantId) + || !snapshot.realmId().equals(realmId) + || !snapshot.creationRequestId().equals(creationRequestId)) { + throw new InvalidCatalogEvidenceException( + "Locked catalog row is not the exact initial public-production authority"); + } + return snapshot; + } + + /** + * Returns the unique visible public-production catalog snapshot, or no authority when absent. + * Multiple or internally conflicting results fail closed rather than selecting by order. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readUniqueVisiblePublicProduction( + String targetNamespace, UUID canonicalTenantId) { + requireReadSelector(targetNamespace, canonicalTenantId); + requireCommittedRead(); + var rows = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(PUBLIC_PRODUCTION.isTrue())) + .orderBy(CREATION_REQUEST_ID.asc()) + .limit(2) + .fetch(); + if (rows.isEmpty()) { + return Optional.empty(); + } + if (rows.size() != 1) { + throw new CatalogConflictException( + "Public-production catalog authority is ambiguous for this canonical tenant"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(rows.getFirst()); + if (!snapshot.visible() || !snapshot.publicProduction()) { + throw new InvalidCatalogEvidenceException( + "Public-production catalog readback is not visible player-addressable authority"); + } + return Optional.of(snapshot); + } + + private IntakeReceipt lockAndReadFreshSource(CreateCanonicalRealmCatalogRequest request) { + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? FOR UPDATE", + request.targetNamespace(), + request.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException( + "Canonical tenant source binding is missing from Game Session owner storage"); + } + + // Lock order is stable: tenant source-binding row, then exact authored-world intake row, + // followed by the shared-namespace family serialization lock in createInitialPublicProduction. + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ? FOR UPDATE", + request.targetNamespace(), + request.sourceIntakeOperationId()); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Exact committed authored-world source intake is missing"); + } + IntakeReceipt receipt = toIntakeReceipt(intake); + requireTenantBindingMatches(binding, receipt.source()); + requireRequestMatchesSource(request, receipt); + requireFreshSource(receipt.source()); + return receipt; + } + + private void requireRequestMatchesSource( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt receipt) { + if (!request.targetNamespace().equals(receipt.source().targetNamespace()) + || !request.canonicalTenantId().equals(receipt.source().canonicalTenantId()) + || !request.sourceIntakeOperationId().equals(receipt.operationId())) { + throw new InvalidCatalogEvidenceException( + "Authored-world source intake does not match the exact requested tenant scope"); + } + } + + private UUID getOrCreateSharedNamespace(String targetNamespace, IntakeReceipt sourceReceipt) { + UUID tenantId = sourceReceipt.source().canonicalTenantId(); + Record current = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ? FOR UPDATE", + tenantId); + if (current != null) { + UUID currentId = required(current, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + validateSharedNamespaceSource(current); + if (!targetNamespace.equals(required(current, TARGET_NAMESPACE, "shared namespace target"))) { + throw new CatalogConflictException( + "Canonical tenant shared namespace belongs to a different Game Session namespace"); + } + if (current.get(LEGACY_TENANT_ID) != null) { + throw new InvalidCatalogEvidenceException( + "Canonical shared namespace conflicts with an existing numeric namespace row"); + } + return currentId; + } + + UUID namespaceId = UUID.randomUUID(); + requireNonNil(namespaceId, "allocated shared namespace"); + AuthoredWorldSourceEvidence source = sourceReceipt.source(); + int inserted = + dsl.insertInto(SHARED_NAMESPACES) + .set(LEGACY_TENANT_ID, (Long) null) + .set(SHARED_NAMESPACE_ID, namespaceId) + .set(CANONICAL_TENANT_ID, tenantId) + .set(TARGET_NAMESPACE, targetNamespace) + .set(SOURCE_INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(SOURCE_INTAKE_SCHEMA_VERSION, SCHEMA_VERSION) + .set(SOURCE_INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, sourceReceipt.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(SOURCE_SCHEMA_VERSION, source.schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, source.registrationRequestId()) + .set(SOURCE_OPERATION_ID, source.operationId()) + .set(SOURCE_REQUEST_DIGEST, source.requestDigest()) + .set(SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, source.provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, source.evidenceDigest()) + .onConflictDoNothing() + .execute(); + if (inserted == 0) { + Record raced = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ? FOR UPDATE", + tenantId); + if (raced != null) { + validateSharedNamespaceSource(raced); + if (raced.get(LEGACY_TENANT_ID) == null + && targetNamespace.equals( + required(raced, TARGET_NAMESPACE, "shared namespace target"))) { + return required(raced, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + } + } + throw new CatalogConflictException("Canonical shared namespace allocation conflicts"); + } + Record persisted = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenantId); + if (persisted == null) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace allocation did not read back from Game Session storage"); + } + validateSharedNamespaceSource(persisted); + return required(persisted, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + } + + private UUID allocateIsolatedNamespace() { + UUID namespaceId = UUID.randomUUID(); + requireNonNil(namespaceId, "allocated isolated namespace"); + if (dsl.fetchOne( + "SELECT playable_state_namespace_id " + + "FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE playable_state_namespace_id = ?", + namespaceId) + != null) { + throw new CatalogConflictException( + "Allocated isolated namespace collides with shared identity"); + } + return namespaceId; + } + + private void validateSharedNamespaceSource(Record namespace) { + UUID tenantId = required(namespace, CANONICAL_TENANT_ID, "canonical shared tenant id"); + String targetNamespace = required(namespace, TARGET_NAMESPACE, "shared namespace target"); + UUID intakeOperation = + required(namespace, SOURCE_INTAKE_OPERATION_ID, "shared namespace source operation"); + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + targetNamespace, + intakeOperation); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace source intake readback is missing"); + } + IntakeReceipt receipt = toIntakeReceipt(intake); + AuthoredWorldSourceEvidence source = receipt.source(); + if (!tenantId.equals(source.canonicalTenantId()) + || !targetNamespace.equals(source.targetNamespace()) + || !receipt + .intakeRequestId() + .equals( + required(namespace, SOURCE_INTAKE_REQUEST_ID, "shared namespace intake request")) + || !receipt + .requestDigest() + .equals( + required(namespace, SOURCE_INTAKE_REQUEST_DIGEST, "shared namespace intake digest")) + || !receipt + .receiptDigest() + .equals( + required( + namespace, SOURCE_INTAKE_RECEIPT_DIGEST, "shared namespace receipt digest")) + || !source + .registrationRequestId() + .equals( + required( + namespace, SOURCE_REGISTRATION_REQUEST_ID, "shared namespace registration")) + || !source + .operationId() + .equals(required(namespace, SOURCE_OPERATION_ID, "shared namespace source operation")) + || !source + .requestDigest() + .equals( + required( + namespace, SOURCE_REQUEST_DIGEST, "shared namespace source request digest")) + || !Long.valueOf(source.sourceGameRowId()) + .equals(required(namespace, SOURCE_GAME_ROW_ID, "shared namespace source row")) + || !source + .sourceGameTenantKey() + .equals( + required(namespace, SOURCE_GAME_TENANT_KEY, "shared namespace source tenant key")) + || !source + .provenanceKind() + .equals(required(namespace, SOURCE_PROVENANCE_KIND, "shared namespace provenance")) + || !source + .evidenceDigest() + .equals( + required(namespace, SOURCE_EVIDENCE_DIGEST, "shared namespace evidence digest"))) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace differs from its immutable authored-world source receipt"); + } + requireFreshSource(source); + requireNoRetainedTenantAssociation(targetNamespace, tenantId); + } + + private CanonicalRealmCatalogSnapshot requireExactRetry( + Record existing, + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt sourceReceipt, + String expectedRequestDigest) { + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(existing); + if (!request.requestId().equals(snapshot.creationRequestId()) + || !expectedRequestDigest.equals(snapshot.requestDigest()) + || !sourceReceipt.equals(snapshot.sourceIntakeReceipt())) { + throw new CatalogConflictException( + "Canonical realm creation request identity was reused with changed input or source evidence"); + } + return snapshot; + } + + private CanonicalRealmCatalogSnapshot toSnapshot(Record record) { + try { + IntakeReceipt sourceReceipt = toCatalogSourceReceipt(record); + UUID requestId = required(record, CREATION_REQUEST_ID, "catalog request id"); + String targetNamespace = required(record, TARGET_NAMESPACE, "catalog target namespace"); + UUID canonicalTenantId = required(record, CANONICAL_TENANT_ID, "catalog tenant id"); + UUID sourceIntakeOperationId = + required(record, SOURCE_INTAKE_OPERATION_ID, "catalog source intake operation"); + String realmSlug = required(record, REALM_SLUG, "catalog realm slug"); + String realmDisplayName = required(record, REALM_DISPLAY_NAME, "catalog realm display name"); + boolean visible = Boolean.TRUE.equals(record.get(VISIBLE)); + boolean publicProduction = Boolean.TRUE.equals(record.get(PUBLIC_PRODUCTION)); + String stateScope = required(record, STATE_SCOPE, "catalog state scope"); + String characterCreationPolicy = + required(record, CHARACTER_CREATION_POLICY, "catalog character-creation policy"); + String expectedRequestDigest = + requestDigest( + requestId, + targetNamespace, + canonicalTenantId, + sourceIntakeOperationId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + characterCreationPolicy, + sourceReceipt); + String persistedRequestDigest = required(record, REQUEST_DIGEST, "catalog request digest"); + UUID realmId = required(record, REALM_ID, "catalog realm id"); + UUID namespaceId = + required(record, PLAYABLE_STATE_NAMESPACE_ID, "catalog playable-state namespace"); + long revision = required(record, CATALOG_REVISION, "catalog revision"); + String expectedReceiptDigest = + receiptDigest( + targetNamespace, + canonicalTenantId, + requestId, + sourceReceipt, + realmId, + namespaceId, + revision, + persistedRequestDigest); + if (!expectedRequestDigest.equals(persistedRequestDigest) + || !expectedReceiptDigest.equals( + required(record, RECEIPT_DIGEST, "catalog receipt digest"))) { + throw new InvalidCatalogEvidenceException( + "Persisted canonical realm catalog request or receipt digest does not match its contents"); + } + + verifyPersistedSourceReceipt(sourceReceipt); + verifyNamespaceSelection( + targetNamespace, canonicalTenantId, stateScope, realmId, namespaceId); + return new CanonicalRealmCatalogSnapshot( + targetNamespace, + canonicalTenantId, + required(record, TENANT_SLUG, "catalog tenant slug"), + required(record, WORLD_SLUG, "catalog world slug"), + realmId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + namespaceId, + characterCreationPolicy, + revision, + requestId, + persistedRequestDigest, + required(record, RECEIPT_DIGEST, "catalog receipt digest"), + sourceReceipt); + } catch (InvalidCatalogEvidenceException | CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCatalogEvidenceException( + "Persisted canonical realm catalog evidence is invalid", exception); + } + } + + private void verifyNamespaceSelection( + String targetNamespace, + UUID canonicalTenantId, + String stateScope, + UUID realmId, + UUID namespaceId) { + if ("SHARED".equals(stateScope)) { + Record shared = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + canonicalTenantId); + if (shared == null + || shared.get(LEGACY_TENANT_ID) != null + || !namespaceId.equals(required(shared, SHARED_NAMESPACE_ID, "shared namespace id"))) { + throw new InvalidCatalogEvidenceException( + "SHARED realm catalog does not resolve to its canonical tenant namespace row"); + } + validateSharedNamespaceSource(shared); + } else { + if (dsl.fetchOne( + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE playable_state_namespace_id = ?", + namespaceId) + != null) { + throw new InvalidCatalogEvidenceException( + "ISOLATED realm namespace conflicts with the canonical tenant SHARED namespace"); + } + List sameNamespace = + dsl.select(REALM_ID) + .from(CATALOG) + .where(PLAYABLE_STATE_NAMESPACE_ID.eq(namespaceId).and(STATE_SCOPE.eq("ISOLATED"))) + .limit(2) + .fetch(); + if (sameNamespace.size() > 1 + || (sameNamespace.size() == 1 + && !realmId.equals(sameNamespace.getFirst().get(REALM_ID)))) { + throw new InvalidCatalogEvidenceException( + "ISOLATED playable-state namespace is already owned by another realm"); + } + } + requireNoRetainedTenantAssociation(targetNamespace, canonicalTenantId); + } + + private void verifyPersistedSourceReceipt(IntakeReceipt expected) { + AuthoredWorldSourceEvidence source = expected.source(); + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + source.targetNamespace(), + source.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException("Persisted tenant source binding is missing"); + } + requireTenantBindingMatches(binding, source); + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + source.targetNamespace(), + expected.operationId()); + if (intake == null || !expected.equals(toIntakeReceipt(intake))) { + throw new InvalidCatalogEvidenceException( + "Canonical realm catalog does not match exact immutable source-intake readback"); + } + requireFreshSource(source); + } + + private IntakeReceipt toCatalogSourceReceipt(Record record) { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required(record, SOURCE_SCHEMA_VERSION, "source schema version"), + required(record, TARGET_NAMESPACE, "source target namespace"), + required(record, SOURCE_REGISTRATION_REQUEST_ID, "source registration request"), + required(record, SOURCE_OPERATION_ID, "source operation"), + required(record, SOURCE_REQUEST_DIGEST, "source request digest"), + required(record, CANONICAL_TENANT_ID, "source canonical tenant"), + required(record, TENANT_SLUG, "source tenant slug"), + required(record, WORLD_SLUG, "source world slug"), + required(record, SOURCE_WORLD_DISPLAY_NAME, "source world display name"), + required(record, SOURCE_GAME_ROW_ID, "source game row"), + required(record, SOURCE_GAME_TENANT_KEY, "source game tenant key"), + required(record, SOURCE_PROVENANCE_KIND, "source provenance"), + required(record, SOURCE_EVIDENCE_DIGEST, "source evidence digest")); + if (!Integer.valueOf(SCHEMA_VERSION) + .equals(required(record, SOURCE_INTAKE_SCHEMA_VERSION, "source intake schema version"))) { + throw new InvalidCatalogEvidenceException( + "Unsupported persisted source-intake schema version"); + } + return new IntakeReceipt( + required(record, SOURCE_INTAKE_OPERATION_ID, "source intake operation"), + required(record, SOURCE_INTAKE_REQUEST_ID, "source intake request"), + required(record, SOURCE_INTAKE_REQUEST_DIGEST, "source intake request digest"), + source, + required(record, SOURCE_INTAKE_RECEIPT_DIGEST, "source intake receipt digest")); + } + + private IntakeReceipt toIntakeReceipt(Record record) { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required( + record, + DSL.field(DSL.name("source_schema_version"), Integer.class), + "source schema"), + required(record, TARGET_NAMESPACE, "source target namespace"), + required(record, SOURCE_REGISTRATION_REQUEST_ID, "source registration request"), + required(record, SOURCE_OPERATION_ID, "source operation"), + required(record, SOURCE_REQUEST_DIGEST, "source request digest"), + required(record, CANONICAL_TENANT_ID, "source canonical tenant"), + required(record, TENANT_SLUG, "source tenant slug"), + required(record, WORLD_SLUG, "source world slug"), + required( + record, + DSL.field(DSL.name("world_display_name"), String.class), + "source world display name"), + required(record, SOURCE_GAME_ROW_ID, "source game row"), + required(record, SOURCE_GAME_TENANT_KEY, "source game tenant key"), + required( + record, + DSL.field(DSL.name("source_provenance_kind"), String.class), + "source provenance"), + required(record, SOURCE_EVIDENCE_DIGEST, "source evidence digest")); + Integer intakeSchema = + required(record, DSL.field(DSL.name("schema_version"), Integer.class), "intake schema"); + if (!Integer.valueOf(SCHEMA_VERSION).equals(intakeSchema)) { + throw new InvalidCatalogEvidenceException( + "Unsupported persisted source-intake schema version"); + } + return new IntakeReceipt( + required(record, DSL.field(DSL.name("operation_id"), UUID.class), "intake operation"), + required(record, DSL.field(DSL.name("intake_request_id"), UUID.class), "intake request"), + required( + record, DSL.field(DSL.name("request_digest"), String.class), "intake request digest"), + source, + required( + record, DSL.field(DSL.name("receipt_digest"), String.class), "intake receipt digest")); + } + + private void requireTenantBindingMatches(Record binding, AuthoredWorldSourceEvidence source) { + if (!source + .targetNamespace() + .equals(required(binding, TARGET_NAMESPACE, "tenant binding namespace")) + || !source + .canonicalTenantId() + .equals(required(binding, CANONICAL_TENANT_ID, "tenant binding canonical id")) + || !source.tenantSlug().equals(required(binding, TENANT_SLUG, "tenant binding slug")) + || !Long.valueOf(source.sourceGameRowId()) + .equals(required(binding, SOURCE_GAME_ROW_ID, "tenant binding source row")) + || !source + .sourceGameTenantKey() + .equals(required(binding, SOURCE_GAME_TENANT_KEY, "tenant binding source key")) + || !source + .provenanceKind() + .equals(required(binding, BINDING_PROVENANCE_KIND, "tenant binding provenance"))) { + throw new InvalidCatalogEvidenceException( + "Authored-world receipt conflicts with the immutable canonical tenant source binding"); + } + } + + private void requireFreshSource(AuthoredWorldSourceEvidence source) { + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidCatalogEvidenceException( + "Initial canonical catalog creation requires fresh Game Design tenant source provenance"); + } + } + + private void requireNoRetainedTenantAssociation(String targetNamespace, UUID canonicalTenantId) { + if (dsl.fetchOne( + "SELECT operation_id FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + targetNamespace, + canonicalTenantId) + != null) { + throw new CatalogConflictException( + "Canonical tenant already has retained numeric Game Session identity evidence"); + } + } + + private Record findByRequest(String targetNamespace, UUID requestId) { + return dsl.selectFrom(CATALOG) + .where(TARGET_NAMESPACE.eq(targetNamespace).and(CREATION_REQUEST_ID.eq(requestId))) + .fetchOne(); + } + + private Record findPublicForTenant(String targetNamespace, UUID tenantId) { + return dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(tenantId)) + .and(PUBLIC_PRODUCTION.isTrue())) + .fetchOne(); + } + + private Record findByRealmSlug(String targetNamespace, UUID tenantId, String realmSlug) { + return dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(tenantId)) + .and(REALM_SLUG.eq(realmSlug))) + .fetchOne(); + } + + static String requestDigest( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt sourceReceipt) { + return requestDigest( + request.requestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.sourceIntakeOperationId(), + request.realmSlug(), + request.realmDisplayName(), + request.visible(), + request.publicProduction(), + request.stateScope(), + request.characterCreationPolicy(), + sourceReceipt); + } + + private static String requestDigest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String characterCreationPolicy, + IntakeReceipt sourceReceipt) { + AuthoredWorldSourceEvidence source = sourceReceipt.source(); + return digest( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + requestId.toString(), + targetNamespace, + canonicalTenantId.toString(), + sourceIntakeOperationId.toString(), + sourceReceipt.intakeRequestId().toString(), + sourceReceipt.requestDigest(), + sourceReceipt.receiptDigest(), + Integer.toString(source.schemaVersion()), + source.registrationRequestId().toString(), + source.operationId().toString(), + source.requestDigest(), + source.canonicalTenantId().toString(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + Long.toString(source.sourceGameRowId()), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + realmSlug, + realmDisplayName, + Boolean.toString(visible), + Boolean.toString(publicProduction), + stateScope, + characterCreationPolicy, + "ABSENT", + "ABSENT"); + } + + private static String receiptDigest( + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt sourceReceipt, + UUID realmId, + UUID namespaceId, + long revision, + String requestDigest) { + return receiptDigest( + request.targetNamespace(), + request.canonicalTenantId(), + request.requestId(), + sourceReceipt, + realmId, + namespaceId, + revision, + requestDigest); + } + + private static String receiptDigest( + String targetNamespace, + UUID canonicalTenantId, + UUID requestId, + IntakeReceipt sourceReceipt, + UUID realmId, + UUID namespaceId, + long revision, + String requestDigest) { + return digest( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + targetNamespace, + canonicalTenantId.toString(), + requestId.toString(), + requestDigest, + realmId.toString(), + namespaceId.toString(), + Long.toString(revision), + sourceReceipt.operationId().toString(), + sourceReceipt.receiptDigest()); + } + + private static String digest(String... values) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String value : values) { + byte[] bytes = strictUtf8(value); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must be well-formed UTF-8 text", exception); + } + } + + private void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical realm catalog creation requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical realm catalog creation requires a read-write transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical realm catalog DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical realm catalog creation requires READ COMMITTED isolation"); + } + return null; + }); + Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); + if (isolationRow == null + || !"read committed".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical realm catalog creation requires READ COMMITTED isolation"); + } + Record readOnlyRow = dsl.fetchOne("SHOW transaction_read_only"); + if (readOnlyRow == null || !"off".equalsIgnoreCase(readOnlyRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical realm catalog creation requires a read-write transaction"); + } + } + + private void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical realm catalog read requires a committed-outcome owner read"); + } + } + + private static void requireReadSelector(String targetNamespace, UUID identity) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(identity, "identity"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static T required(Record record, Field field, String label) { + T value = record.get(field); + if (value == null) { + throw new InvalidCatalogEvidenceException("Persisted " + label + " is missing"); + } + return value; + } + + /** Opaque source preflight result; callers cannot manufacture a committed owner receipt. */ + public static final class PreparedInitialPublicProduction { + private final CreateCanonicalRealmCatalogRequest request; + private final IntakeReceipt committedSource; + + private PreparedInitialPublicProduction( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt committedSource) { + this.request = Objects.requireNonNull(request, "request"); + this.committedSource = Objects.requireNonNull(committedSource, "committedSource"); + } + + private CreateCanonicalRealmCatalogRequest request() { + return request; + } + + private IntakeReceipt committedSource() { + return committedSource; + } + } + + public static final class CatalogConflictException extends IllegalStateException { + public CatalogConflictException(String message) { + super(message); + } + } + + public static final class InvalidCatalogEvidenceException extends IllegalStateException { + public InvalidCatalogEvidenceException(String message) { + super(message); + } + + public InvalidCatalogEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index 7210542b41..f76b6bcd89 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -5,25 +5,34 @@ import static net.firedevops.firemud.gamesession.jooq.tables.GameplayAdmissionPointerEvent.GAMEPLAY_ADMISSION_POINTER_EVENT; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerEventRecord; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import org.jooq.Condition; import org.jooq.DSLContext; +import org.jooq.Field; import org.jooq.Record; import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; @Repository @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class GameplayAdmissionPointerEventRepository { + private static final Field REPRESENTATION_VERSION = + DSL.field(DSL.name("representation_version"), Integer.class); + private static final int RETAINED_REPRESENTATION_VERSION = 1; private static final int POINTER_KEY_QUERY_CHUNK_SIZE = 500; private final DSLContext dsl; @@ -39,7 +48,8 @@ public List findByWorldSlugAndRealmSlugOrderByIdD GAMEPLAY_ADMISSION_POINTER_EVENT .WORLD_SLUG .eq(worldSlug) - .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug))) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug)) + .and(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION))) .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) .fetch(this::toEntity); } @@ -52,7 +62,8 @@ public List findByTenantIdAndWorldSlugAndRealmSlu .TENANT_ID .eq(tenantId) .and(GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG.eq(worldSlug)) - .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug))) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug)) + .and(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION))) .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) .fetch(this::toEntity); } @@ -65,7 +76,8 @@ public Optional findLatestByTenantIdAndWorldSlugA .TENANT_ID .eq(tenantId) .and(GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG.eq(worldSlug)) - .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug))) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug)) + .and(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION))) .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) .limit(1) .fetchOptional(this::toEntity); @@ -94,7 +106,7 @@ public List findLatestByPointerKeys(List REPRESENTATION_VERSION = + DSL.field(DSL.name("representation_version"), Integer.class); + private static final int RETAINED_REPRESENTATION_VERSION = 1; + private final DSLContext dsl; public GameplayAdmissionPointerRepository(DSLContext dsl) { @@ -34,7 +40,9 @@ public GameplayAdmissionPointerRepository(DSLContext dsl) { } public long count() { - return dsl.fetchCount(GAMEPLAY_ADMISSION_POINTER); + return dsl.fetchCount( + dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + .where(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION))); } public Optional findByTenantIdAndWorldSlugAndRealmSlug( @@ -45,7 +53,8 @@ public Optional findByTenantIdAndWorldSlugAndRealmSlug .TENANT_ID .eq(tenantId) .and(GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.eq(worldSlug)) - .and(GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.eq(realmSlug))) + .and(GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.eq(realmSlug)) + .and(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION))) .fetchOptional(this::toEntity); } @@ -74,7 +83,8 @@ public List findAllByTenantIdAndGameInstanceId( GAMEPLAY_ADMISSION_POINTER .TENANT_ID .eq(tenantId) - .and(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID.eq(gameInstanceId))) + .and(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID.eq(gameInstanceId)) + .and(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION))) .orderBy( GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.asc(), GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.asc()) @@ -83,6 +93,7 @@ public List findAllByTenantIdAndGameInstanceId( public List findAllByOrderByWorldSlugAscRealmSlugAsc() { return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + .where(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION)) .orderBy( GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.asc(), GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.asc()) @@ -239,7 +250,8 @@ public GameplayAdmissionPointer updateExisting( .ID .eq(entity.getId()) .and(GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION.eq(expectedPointerVersion)) - .and(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION.eq(expectedCatalogRevision))) + .and(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION.eq(expectedCatalogRevision)) + .and(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION))) .execute(); } catch (IntegrityConstraintViolationException ex) { throw new IllegalStateException( @@ -269,18 +281,28 @@ private static boolean isPositive(Long value) { } public void deleteAllInBatch() { - dsl.deleteFrom(GAMEPLAY_ADMISSION_POINTER).execute(); + dsl.deleteFrom(GAMEPLAY_ADMISSION_POINTER) + .where(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION)) + .execute(); } private Optional findById(Long id) { return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) - .where(GAMEPLAY_ADMISSION_POINTER.ID.eq(id)) + .where( + GAMEPLAY_ADMISSION_POINTER + .ID + .eq(id) + .and(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION))) .fetchOptional(this::toEntity); } private Optional findByIdForUpdate(Long id) { return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) - .where(GAMEPLAY_ADMISSION_POINTER.ID.eq(id)) + .where( + GAMEPLAY_ADMISSION_POINTER + .ID + .eq(id) + .and(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION))) .forUpdate() .fetchOptional(this::toEntity); } @@ -292,7 +314,8 @@ private long countByRuntimeTarget(Long tenantId, Long gameInstanceId) { GAMEPLAY_ADMISSION_POINTER .TENANT_ID .eq(tenantId) - .and(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID.eq(gameInstanceId)))); + .and(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID.eq(gameInstanceId)) + .and(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION)))); } private long countByRuntimeTargetExcludingId( @@ -304,7 +327,8 @@ private long countByRuntimeTargetExcludingId( .TENANT_ID .eq(tenantId) .and(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID.eq(gameInstanceId)) - .and(GAMEPLAY_ADMISSION_POINTER.ID.ne(excludedId)))); + .and(GAMEPLAY_ADMISSION_POINTER.ID.ne(excludedId)) + .and(REPRESENTATION_VERSION.eq(RETAINED_REPRESENTATION_VERSION)))); } private void lockRuntimeTargets( diff --git a/services/game-session-service/src/main/resources/db/migration/V12.1__canonical_realm_catalog.sql b/services/game-session-service/src/main/resources/db/migration/V12.1__canonical_realm_catalog.sql new file mode 100644 index 0000000000..cfa3f364c6 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V12.1__canonical_realm_catalog.sql @@ -0,0 +1,488 @@ +-- Preserve all retained numeric keys and namespace bytes. The namespace UUID is the stable +-- primary identity; tenant_id remains nullable/unique for the existing numeric runtime selector. +-- [jooq ignore start] +-- This PostgreSQL-only identity reshape replaces V6's implicit constraint name. H2's jOOQ schema +-- export assigns a different generated name; no generated typed binding consumes these columns. +ALTER TABLE gameplay_tenant_shared_playable_state_namespace + DROP CONSTRAINT gameplay_tenant_shared_playable_state_namespace_pkey; + +ALTER TABLE gameplay_tenant_shared_playable_state_namespace + ALTER COLUMN tenant_id DROP NOT NULL; + +ALTER TABLE gameplay_tenant_shared_playable_state_namespace + ADD CONSTRAINT pk_gameplay_tenant_shared_playable_state_namespace + PRIMARY KEY (playable_state_namespace_id), + ADD CONSTRAINT uq_gameplay_tenant_shared_namespace_legacy_tenant + UNIQUE (tenant_id), + ADD COLUMN canonical_tenant_id uuid, + ADD COLUMN target_namespace character varying(63), + ADD COLUMN source_intake_operation_id uuid, + ADD COLUMN source_intake_schema_version integer, + ADD COLUMN source_intake_request_id uuid, + ADD COLUMN source_intake_request_digest character varying(71), + ADD COLUMN source_intake_receipt_digest character varying(71), + ADD COLUMN source_schema_version integer, + ADD COLUMN source_registration_request_id uuid, + ADD COLUMN source_operation_id uuid, + ADD COLUMN source_request_digest character varying(71), + ADD COLUMN source_game_row_id bigint, + ADD COLUMN source_game_tenant_key character varying(36), + ADD COLUMN source_provenance_kind character varying(32), + ADD COLUMN source_evidence_digest character varying(71), + ADD CONSTRAINT uq_gameplay_tenant_shared_namespace_canonical_tenant + UNIQUE (canonical_tenant_id), + ADD CONSTRAINT fk_gameplay_tenant_shared_namespace_tenant_source + FOREIGN KEY (target_namespace, canonical_tenant_id) + REFERENCES game_session_authored_world_tenant_source_binding + (target_namespace, canonical_tenant_id), + ADD CONSTRAINT fk_gameplay_tenant_shared_namespace_source_intake + FOREIGN KEY (source_intake_operation_id) + REFERENCES game_session_authored_world_source_intake (operation_id), + ADD CONSTRAINT chk_gameplay_tenant_shared_namespace_non_nil + CHECK ( + canonical_tenant_id IS NULL + OR playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + ), + ADD CONSTRAINT chk_gameplay_tenant_shared_namespace_identity_mode CHECK ( + (tenant_id IS NOT NULL + AND canonical_tenant_id IS NULL + AND target_namespace IS NULL + AND source_intake_operation_id IS NULL + AND source_intake_schema_version IS NULL + AND source_intake_request_id IS NULL + AND source_intake_request_digest IS NULL + AND source_intake_receipt_digest IS NULL + AND source_schema_version IS NULL + AND source_registration_request_id IS NULL + AND source_operation_id IS NULL + AND source_request_digest IS NULL + AND source_game_row_id IS NULL + AND source_game_tenant_key IS NULL + AND source_provenance_kind IS NULL + AND source_evidence_digest IS NULL) + OR (tenant_id IS NULL + AND canonical_tenant_id IS NOT NULL + AND target_namespace IS NOT NULL + AND source_intake_operation_id IS NOT NULL + AND source_intake_schema_version IS NOT NULL + AND source_intake_schema_version = 1 + AND source_intake_request_id IS NOT NULL + AND source_intake_request_digest IS NOT NULL + AND source_intake_receipt_digest IS NOT NULL + AND source_schema_version IS NOT NULL + AND source_schema_version = 1 + AND source_registration_request_id IS NOT NULL + AND source_operation_id IS NOT NULL + AND source_request_digest IS NOT NULL + AND source_game_row_id IS NOT NULL + AND source_game_tenant_key IS NOT NULL + AND source_provenance_kind IS NOT NULL + AND source_provenance_kind = 'NEW_GAME_ROW' + AND source_evidence_digest IS NOT NULL) + ), + ADD CONSTRAINT chk_gameplay_tenant_shared_namespace_fresh_source CHECK ( + canonical_tenant_id IS NULL + OR (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_intake_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_intake_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_registration_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_game_row_id > 0 + AND char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$') + ); +-- [jooq ignore stop] + +CREATE TABLE game_session_canonical_realm_catalog ( + target_namespace character varying(63) NOT NULL, + canonical_tenant_id uuid NOT NULL, + tenant_slug character varying(120) NOT NULL, + world_slug character varying(120) NOT NULL, + realm_id uuid NOT NULL, + realm_slug character varying(120) NOT NULL, + realm_display_name character varying(200) NOT NULL, + visible boolean NOT NULL, + public_production boolean NOT NULL, + state_scope character varying(16) NOT NULL, + playable_state_namespace_id uuid NOT NULL, + character_creation_policy character varying(64) NOT NULL, + catalog_revision bigint NOT NULL, + creation_request_id uuid NOT NULL, + request_digest character varying(71) NOT NULL, + receipt_digest character varying(71) NOT NULL, + source_intake_operation_id uuid NOT NULL, + source_intake_schema_version integer NOT NULL, + source_intake_request_id uuid NOT NULL, + source_intake_request_digest character varying(71) NOT NULL, + source_intake_receipt_digest character varying(71) NOT NULL, + source_schema_version integer NOT NULL, + source_registration_request_id uuid NOT NULL, + source_operation_id uuid NOT NULL, + source_request_digest character varying(71) NOT NULL, + source_world_display_name character varying(400) NOT NULL, + source_game_row_id bigint NOT NULL, + source_game_tenant_key character varying(36) NOT NULL, + source_provenance_kind character varying(32) NOT NULL, + source_evidence_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_canonical_realm_catalog + PRIMARY KEY (target_namespace, realm_id), + CONSTRAINT uq_gs_canonical_realm_catalog_realm_id + UNIQUE (realm_id), + CONSTRAINT uq_gs_canonical_realm_catalog_request + UNIQUE (target_namespace, creation_request_id), + CONSTRAINT uq_gs_canonical_realm_catalog_tenant_slug + UNIQUE (target_namespace, canonical_tenant_id, realm_slug), + CONSTRAINT fk_gs_canonical_realm_catalog_tenant_source + FOREIGN KEY ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + source_provenance_kind + ) + REFERENCES game_session_authored_world_tenant_source_binding ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT fk_gs_canonical_realm_catalog_source_intake + FOREIGN KEY (source_intake_operation_id) + REFERENCES game_session_authored_world_source_intake (operation_id), + CONSTRAINT chk_gs_canonical_realm_catalog_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_ids CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND creation_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_intake_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_intake_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_registration_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + ), + CONSTRAINT chk_gs_canonical_realm_catalog_selector CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND char_length(realm_slug) BETWEEN 1 AND 120 + AND octet_length(realm_slug) BETWEEN 1 AND 120 + AND realm_slug !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_public_initial CHECK ( + visible AND public_production + ), + CONSTRAINT chk_gs_canonical_realm_catalog_scope CHECK ( + state_scope IN ('SHARED', 'ISOLATED') + ), + CONSTRAINT chk_gs_canonical_realm_catalog_revision CHECK (catalog_revision = 1), + CONSTRAINT chk_gs_canonical_realm_catalog_policy CHECK ( + char_length(character_creation_policy) BETWEEN 1 AND 64 + AND octet_length(character_creation_policy) <= 256 + AND character_creation_policy !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_names CHECK ( + char_length(realm_display_name) BETWEEN 1 AND 100 + AND octet_length(realm_display_name) <= 400 + AND realm_display_name !~ '^[[:space:]]*$' + AND char_length(source_world_display_name) BETWEEN 1 AND 100 + AND octet_length(source_world_display_name) <= 400 + AND source_world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_versions CHECK ( + source_intake_schema_version = 1 + AND source_schema_version = 1 + ), + CONSTRAINT chk_gs_canonical_realm_catalog_source_key CHECK ( + source_game_row_id > 0 + AND char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_provenance CHECK ( + source_provenance_kind = 'NEW_GAME_ROW' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_digests CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE UNIQUE INDEX uq_gs_canonical_realm_catalog_public_tenant + ON game_session_canonical_realm_catalog (target_namespace, canonical_tenant_id) + WHERE public_production; + +CREATE UNIQUE INDEX uq_gs_canonical_realm_catalog_isolated_namespace + ON game_session_canonical_realm_catalog (playable_state_namespace_id) + WHERE state_scope = 'ISOLATED'; + +-- [jooq ignore start] +CREATE FUNCTION reject_game_session_canonical_realm_catalog_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session canonical realm catalog evidence is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION protect_fresh_shared_namespace_identity() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF OLD.canonical_tenant_id IS NOT NULL OR NEW.canonical_tenant_id IS NOT NULL THEN + RAISE EXCEPTION 'Game Session fresh shared namespace identity is immutable' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_fresh_shared_namespace_immutable +BEFORE UPDATE OR DELETE ON gameplay_tenant_shared_playable_state_namespace +FOR EACH ROW EXECUTE FUNCTION protect_fresh_shared_namespace_identity(); + +CREATE TRIGGER game_session_canonical_realm_catalog_immutable +BEFORE UPDATE OR DELETE ON game_session_canonical_realm_catalog +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_realm_catalog_mutation(); + +CREATE TRIGGER game_session_canonical_realm_catalog_no_truncate +BEFORE TRUNCATE ON game_session_canonical_realm_catalog +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_realm_catalog_mutation(); + +CREATE FUNCTION require_game_session_canonical_realm_source_evidence() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + PERFORM pg_advisory_xact_lock( + hashtextextended(NEW.target_namespace || ':' || NEW.canonical_tenant_id::text, 1)); + IF NOT EXISTS ( + SELECT 1 + FROM game_session_authored_world_source_intake source_intake + WHERE source_intake.operation_id = NEW.source_intake_operation_id + AND source_intake.schema_version = NEW.source_intake_schema_version + AND source_intake.target_namespace = NEW.target_namespace + AND source_intake.intake_request_id = NEW.source_intake_request_id + AND source_intake.request_digest = NEW.source_intake_request_digest + AND source_intake.source_schema_version = NEW.source_schema_version + AND source_intake.source_registration_request_id = NEW.source_registration_request_id + AND source_intake.source_operation_id = NEW.source_operation_id + AND source_intake.source_request_digest = NEW.source_request_digest + AND source_intake.canonical_tenant_id = NEW.canonical_tenant_id + AND source_intake.tenant_slug = NEW.tenant_slug + AND source_intake.world_slug = NEW.world_slug + AND source_intake.world_display_name = NEW.source_world_display_name + AND source_intake.source_game_row_id = NEW.source_game_row_id + AND source_intake.source_game_tenant_key = NEW.source_game_tenant_key + AND source_intake.source_provenance_kind = NEW.source_provenance_kind + AND source_intake.source_evidence_digest = NEW.source_evidence_digest + AND source_intake.receipt_digest = NEW.source_intake_receipt_digest + ) THEN + RAISE EXCEPTION 'Canonical realm catalog requires exact committed authored-world intake evidence' + USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT 1 + FROM game_session_retained_tenant_association retained + WHERE retained.target_namespace = NEW.target_namespace + AND retained.canonical_tenant_id = NEW.canonical_tenant_id + ) THEN + RAISE EXCEPTION 'Canonical realm catalog cannot replace retained numeric tenant namespace authority' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_realm_catalog_requires_source +BEFORE INSERT ON game_session_canonical_realm_catalog +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_realm_source_evidence(); + +CREATE FUNCTION require_game_session_canonical_namespace_allocation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + PERFORM pg_advisory_xact_lock(hashtextextended(NEW.playable_state_namespace_id::text, 0)); + IF NEW.state_scope = 'SHARED' THEN + IF NOT EXISTS ( + SELECT 1 + FROM gameplay_tenant_shared_playable_state_namespace shared_namespace + WHERE shared_namespace.tenant_id IS NULL + AND shared_namespace.canonical_tenant_id = NEW.canonical_tenant_id + AND shared_namespace.target_namespace = NEW.target_namespace + AND shared_namespace.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'SHARED canonical realm requires its exact tenant namespace allocation' + USING ERRCODE = '23514'; + END IF; + ELSIF EXISTS ( + SELECT 1 + FROM gameplay_tenant_shared_playable_state_namespace shared_namespace + WHERE shared_namespace.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'ISOLATED canonical realm namespace conflicts with a tenant SHARED namespace' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_catalog_requires_namespace +BEFORE INSERT ON game_session_canonical_realm_catalog +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_namespace_allocation(); + +CREATE FUNCTION require_game_session_shared_namespace_source() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + PERFORM pg_advisory_xact_lock(hashtextextended(NEW.playable_state_namespace_id::text, 0)); + IF NEW.canonical_tenant_id IS NULL AND EXISTS ( + SELECT 1 + FROM game_session_canonical_realm_catalog catalog + WHERE catalog.state_scope = 'ISOLATED' + AND catalog.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'Legacy tenant SHARED namespace conflicts with a canonical ISOLATED realm namespace' + USING ERRCODE = '23514'; + END IF; + IF NEW.canonical_tenant_id IS NOT NULL AND NOT EXISTS ( + SELECT 1 + FROM game_session_authored_world_source_intake source_intake + WHERE source_intake.operation_id = NEW.source_intake_operation_id + AND source_intake.schema_version = NEW.source_intake_schema_version + AND source_intake.target_namespace = NEW.target_namespace + AND source_intake.intake_request_id = NEW.source_intake_request_id + AND source_intake.request_digest = NEW.source_intake_request_digest + AND source_intake.source_schema_version = NEW.source_schema_version + AND source_intake.source_registration_request_id = NEW.source_registration_request_id + AND source_intake.source_operation_id = NEW.source_operation_id + AND source_intake.source_request_digest = NEW.source_request_digest + AND source_intake.canonical_tenant_id = NEW.canonical_tenant_id + AND source_intake.source_game_row_id = NEW.source_game_row_id + AND source_intake.source_game_tenant_key = NEW.source_game_tenant_key + AND source_intake.source_provenance_kind = NEW.source_provenance_kind + AND source_intake.source_evidence_digest = NEW.source_evidence_digest + AND source_intake.receipt_digest = NEW.source_intake_receipt_digest + ) THEN + RAISE EXCEPTION 'Fresh SHARED namespace requires exact committed authored-world source receipt' + USING ERRCODE = '23514'; + END IF; + IF NEW.canonical_tenant_id IS NOT NULL AND EXISTS ( + SELECT 1 + FROM game_session_retained_tenant_association retained + WHERE retained.target_namespace = NEW.target_namespace + AND retained.canonical_tenant_id = NEW.canonical_tenant_id + ) THEN + RAISE EXCEPTION 'Fresh SHARED namespace cannot replace retained numeric namespace authority' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_fresh_shared_namespace_requires_source +BEFORE INSERT OR UPDATE ON gameplay_tenant_shared_playable_state_namespace +FOR EACH ROW EXECUTE FUNCTION require_game_session_shared_namespace_source(); + +CREATE FUNCTION require_game_session_shared_namespace_catalog_reference() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.canonical_tenant_id IS NOT NULL AND NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_realm_catalog catalog + WHERE catalog.state_scope = 'SHARED' + AND catalog.target_namespace = NEW.target_namespace + AND catalog.canonical_tenant_id = NEW.canonical_tenant_id + AND catalog.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'Fresh shared namespace cannot commit without its canonical realm catalog result' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER game_session_shared_namespace_requires_catalog +AFTER INSERT ON gameplay_tenant_shared_playable_state_namespace +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_shared_namespace_catalog_reference(); + +CREATE FUNCTION protect_fresh_shared_namespace_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM gameplay_tenant_shared_playable_state_namespace + WHERE canonical_tenant_id IS NOT NULL + ) THEN + RAISE EXCEPTION 'Game Session fresh shared namespace identity is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER game_session_fresh_shared_namespace_no_truncate +BEFORE TRUNCATE ON gameplay_tenant_shared_playable_state_namespace +FOR EACH STATEMENT EXECUTE FUNCTION protect_fresh_shared_namespace_truncate(); + +-- A retained association can only be recorded for a tenant that has not already acquired fresh +-- canonical realm/SHARED namespace authority. Existing association capture takes SHARE locks on +-- the namespace family; this tenant-scoped advisory fence also serializes any owner-local insert +-- with the catalog's source-evidence trigger. Existing rows and exact retries are unaffected. +CREATE FUNCTION reject_retained_association_for_fresh_canonical_tenant() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + PERFORM pg_advisory_xact_lock( + hashtextextended(NEW.target_namespace || ':' || NEW.canonical_tenant_id::text, 1)); + IF EXISTS ( + SELECT 1 + FROM game_session_canonical_realm_catalog catalog + WHERE catalog.target_namespace = NEW.target_namespace + AND catalog.canonical_tenant_id = NEW.canonical_tenant_id + ) OR EXISTS ( + SELECT 1 + FROM gameplay_tenant_shared_playable_state_namespace shared_namespace + WHERE shared_namespace.target_namespace = NEW.target_namespace + AND shared_namespace.canonical_tenant_id = NEW.canonical_tenant_id + ) THEN + RAISE EXCEPTION 'Retained numeric association cannot replace fresh canonical tenant namespace authority' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_retained_association_rejects_fresh_tenant +BEFORE INSERT ON game_session_retained_tenant_association +FOR EACH ROW EXECUTE FUNCTION reject_retained_association_for_fresh_canonical_tenant(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V13__canonical_closed_admission_pointer.sql b/services/game-session-service/src/main/resources/db/migration/V13__canonical_closed_admission_pointer.sql new file mode 100644 index 0000000000..4ebd0592f9 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V13__canonical_closed_admission_pointer.sql @@ -0,0 +1,460 @@ +-- Preserve every retained pointer and audit value as representation version 1. New canonical +-- closed-only rows use version 2 and leave legacy numeric and catalog-policy copies absent. +-- [jooq ignore start] +ALTER TABLE gameplay_admission_pointer + ADD COLUMN representation_version integer NOT NULL DEFAULT 1, + ADD COLUMN target_namespace character varying(63), + ADD COLUMN canonical_tenant_id uuid, + ADD COLUMN admission_state character varying(16); + +ALTER TABLE gameplay_admission_pointer + ALTER COLUMN tenant_id DROP NOT NULL, + ALTER COLUMN game_instance_id DROP NOT NULL, + ALTER COLUMN world_display_name DROP NOT NULL, + ALTER COLUMN realm_display_name DROP NOT NULL, + ALTER COLUMN visible DROP NOT NULL, + ALTER COLUMN public_production_realm DROP NOT NULL, + ALTER COLUMN public_production_realm DROP DEFAULT, + ALTER COLUMN requires_character_selection DROP NOT NULL, + ALTER COLUMN state_scope DROP NOT NULL, + ALTER COLUMN character_creation_policy DROP NOT NULL, + ALTER COLUMN last_updated_by DROP NOT NULL, + ALTER COLUMN last_update_reason DROP NOT NULL; + +ALTER TABLE gameplay_admission_pointer + DROP CONSTRAINT gameplay_admission_pointer_identity_pair_complete; + +ALTER TABLE gameplay_admission_pointer + ADD CONSTRAINT chk_gameplay_admission_pointer_representation CHECK ( + (representation_version = 1 + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND admission_state IS NULL + AND tenant_id IS NOT NULL + AND game_instance_id IS NOT NULL + AND world_display_name IS NOT NULL + AND realm_display_name IS NOT NULL + AND visible IS NOT NULL + AND public_production_realm IS NOT NULL + AND requires_character_selection IS NOT NULL + AND state_scope IS NOT NULL + AND character_creation_policy IS NOT NULL + AND last_updated_by IS NOT NULL + AND last_update_reason IS NOT NULL) + OR (representation_version = 2 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NULL + AND admission_state IS NOT NULL + AND admission_state = 'CLOSED' + AND tenant_id IS NULL + AND game_instance_id IS NULL + AND pointer_version = 1 + AND catalog_revision = 1 + AND world_display_name IS NULL + AND realm_display_name IS NULL + AND visible IS NULL + AND public_production_realm IS NULL + AND requires_character_selection IS NULL + AND state_scope IS NULL + AND character_creation_policy IS NULL + AND last_updated_by IS NULL + AND last_update_reason IS NULL)) + , + ADD CONSTRAINT gameplay_admission_pointer_identity_pair_complete CHECK ( + (representation_version = 1 + AND ((realm_id IS NULL) = (playable_state_namespace_id IS NULL))) + OR (representation_version = 2 + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NULL)) + , + ADD CONSTRAINT chk_gameplay_admission_pointer_canonical_identity CHECK ( + representation_version <> 2 + OR (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid)) + , + ADD CONSTRAINT fk_gameplay_admission_pointer_canonical_catalog + FOREIGN KEY (target_namespace, realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id); + +ALTER TABLE gameplay_admission_pointer_event + ADD COLUMN representation_version integer NOT NULL DEFAULT 1, + ADD COLUMN target_namespace character varying(63), + ADD COLUMN canonical_tenant_id uuid, + ADD COLUMN admission_state character varying(16); + +ALTER TABLE gameplay_admission_pointer_event + ALTER COLUMN tenant_id DROP NOT NULL, + ALTER COLUMN game_instance_id DROP NOT NULL, + ALTER COLUMN world_display_name DROP NOT NULL, + ALTER COLUMN realm_display_name DROP NOT NULL, + ALTER COLUMN visible DROP NOT NULL, + ALTER COLUMN public_production_realm DROP NOT NULL, + ALTER COLUMN public_production_realm DROP DEFAULT, + ALTER COLUMN requires_character_selection DROP NOT NULL, + ALTER COLUMN state_scope DROP NOT NULL, + ALTER COLUMN character_creation_policy DROP NOT NULL; + +ALTER TABLE gameplay_admission_pointer_event + DROP CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete; + +ALTER TABLE gameplay_admission_pointer_event + ADD CONSTRAINT chk_gameplay_admission_pointer_event_representation CHECK ( + (representation_version = 1 + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND admission_state IS NULL + AND tenant_id IS NOT NULL + AND game_instance_id IS NOT NULL + AND world_display_name IS NOT NULL + AND realm_display_name IS NOT NULL + AND visible IS NOT NULL + AND public_production_realm IS NOT NULL + AND requires_character_selection IS NOT NULL + AND state_scope IS NOT NULL + AND character_creation_policy IS NOT NULL) + OR (representation_version = 2 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NULL + AND catalog_revision IS NOT NULL + AND catalog_revision = 1 + AND admission_state IS NOT NULL + AND admission_state = 'CLOSED' + AND tenant_id IS NULL + AND game_instance_id IS NULL + AND pointer_version = 1 + AND world_display_name IS NULL + AND realm_display_name IS NULL + AND visible IS NULL + AND public_production_realm IS NULL + AND requires_character_selection IS NULL + AND state_scope IS NULL + AND character_creation_policy IS NULL + AND prepared_version_upgrade_id IS NULL)) + , + ADD CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete CHECK ( + (representation_version = 1 + AND ((realm_id IS NULL) = (playable_state_namespace_id IS NULL))) + OR (representation_version = 2 + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NULL)) + , + ADD CONSTRAINT chk_gameplay_admission_pointer_event_canonical_identity CHECK ( + representation_version <> 2 + OR (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid)) + , + ADD CONSTRAINT fk_gameplay_admission_pointer_event_canonical_catalog + FOREIGN KEY (target_namespace, realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id); + +CREATE UNIQUE INDEX uq_gameplay_admission_pointer_event_canonical_realm_version + ON gameplay_admission_pointer_event (target_namespace, canonical_tenant_id, realm_id, pointer_version) + WHERE representation_version = 2; + +CREATE TABLE game_session_canonical_closed_admission_pointer_request ( + target_namespace character varying(63) NOT NULL, + request_id uuid NOT NULL, + request_digest character varying(71) NOT NULL, + canonical_tenant_id uuid NOT NULL, + realm_id uuid NOT NULL, + catalog_creation_request_id uuid NOT NULL, + catalog_revision bigint NOT NULL, + catalog_request_digest character varying(71) NOT NULL, + catalog_receipt_digest character varying(71) NOT NULL, + actor_principal character varying(200) NOT NULL, + reason character varying(500) NOT NULL, + admission_state character varying(16) NOT NULL, + pointer_version bigint NOT NULL, + audit_event_id bigint NOT NULL, + receipt_digest character varying(71) NOT NULL, + updated_at timestamp with time zone NOT NULL, + CONSTRAINT pk_gs_canonical_closed_pointer_request PRIMARY KEY (target_namespace, request_id), + CONSTRAINT uq_gs_canonical_closed_pointer_request_realm + UNIQUE (target_namespace, canonical_tenant_id, realm_id), + CONSTRAINT uq_gs_canonical_closed_pointer_request_event UNIQUE (audit_event_id), + CONSTRAINT fk_gs_canonical_closed_pointer_request_catalog + FOREIGN KEY (target_namespace, realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id), + CONSTRAINT fk_gs_canonical_closed_pointer_request_event + FOREIGN KEY (audit_event_id) REFERENCES gameplay_admission_pointer_event (id), + CONSTRAINT chk_gs_canonical_closed_pointer_request_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND catalog_creation_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND catalog_revision = 1 + AND pointer_version = 1 + AND audit_event_id > 0 + AND admission_state = 'CLOSED'), + CONSTRAINT chk_gs_canonical_closed_pointer_request_digests CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND catalog_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND catalog_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gs_canonical_closed_pointer_request_audit CHECK ( + char_length(actor_principal) BETWEEN 1 AND 200 + AND actor_principal !~ '^[[:space:]]*$' + AND char_length(reason) BETWEEN 1 AND 500 + AND reason !~ '^[[:space:]]*$') +); + +CREATE FUNCTION reject_game_session_canonical_closed_pointer_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'TRUNCATE' THEN + IF TG_TABLE_NAME = 'game_session_canonical_closed_admission_pointer_request' + AND EXISTS (SELECT 1 FROM game_session_canonical_closed_admission_pointer_request) + THEN + RAISE EXCEPTION 'Canonical CLOSED pointer request outcomes are immutable survivor evidence' + USING ERRCODE = '23514'; + ELSIF TG_TABLE_NAME = 'gameplay_admission_pointer' + AND EXISTS ( + SELECT 1 FROM gameplay_admission_pointer WHERE representation_version = 2) + THEN + RAISE EXCEPTION 'Canonical CLOSED admission pointers are immutable survivor evidence' + USING ERRCODE = '23514'; + ELSIF TG_TABLE_NAME = 'gameplay_admission_pointer_event' + AND EXISTS ( + SELECT 1 FROM gameplay_admission_pointer_event WHERE representation_version = 2) + THEN + RAISE EXCEPTION 'Canonical CLOSED pointer events are immutable survivor evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; + END IF; + + IF TG_TABLE_NAME = 'game_session_canonical_closed_admission_pointer_request' THEN + RAISE EXCEPTION 'Canonical CLOSED pointer evidence is immutable' + USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'gameplay_admission_pointer' + OR TG_TABLE_NAME = 'gameplay_admission_pointer_event' + THEN + IF OLD.representation_version = 2 + OR (TG_OP = 'UPDATE' AND NEW.representation_version = 2) + THEN + RAISE EXCEPTION 'Canonical CLOSED pointer evidence is immutable' + USING ERRCODE = '23514'; + END IF; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER gameplay_admission_pointer_canonical_immutable +BEFORE UPDATE OR DELETE ON gameplay_admission_pointer +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE TRIGGER gameplay_admission_pointer_canonical_no_truncate +BEFORE TRUNCATE ON gameplay_admission_pointer +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE TRIGGER gameplay_admission_pointer_event_canonical_immutable +BEFORE UPDATE OR DELETE ON gameplay_admission_pointer_event +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE TRIGGER gameplay_admission_pointer_event_canonical_no_truncate +BEFORE TRUNCATE ON gameplay_admission_pointer_event +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE TRIGGER game_session_canonical_closed_pointer_request_immutable +BEFORE UPDATE OR DELETE ON game_session_canonical_closed_admission_pointer_request +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE TRIGGER game_session_canonical_closed_pointer_request_no_truncate +BEFORE TRUNCATE ON game_session_canonical_closed_admission_pointer_request +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE FUNCTION require_game_session_canonical_closed_pointer_catalog() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.representation_version = 2 AND NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_realm_catalog catalog + WHERE catalog.target_namespace = NEW.target_namespace + AND catalog.canonical_tenant_id = NEW.canonical_tenant_id + AND catalog.realm_id = NEW.realm_id + AND catalog.world_slug = NEW.world_slug + AND catalog.realm_slug = NEW.realm_slug + AND catalog.catalog_revision = NEW.catalog_revision + AND catalog.visible + AND catalog.public_production + ) THEN + RAISE EXCEPTION 'Canonical CLOSED pointer requires its exact initial public catalog row' + USING ERRCODE = '23514'; + END IF; + IF NEW.representation_version = 2 AND EXISTS ( + SELECT 1 + FROM game_session_retained_tenant_association retained + WHERE retained.target_namespace = NEW.target_namespace + AND retained.canonical_tenant_id = NEW.canonical_tenant_id + ) THEN + RAISE EXCEPTION 'Canonical CLOSED pointer cannot replace retained numeric tenant authority' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER gameplay_admission_pointer_canonical_requires_catalog +BEFORE INSERT ON gameplay_admission_pointer +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_closed_pointer_catalog(); + +CREATE FUNCTION require_game_session_canonical_closed_pointer_atomic_evidence() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + expected_target_namespace character varying(63); + expected_tenant_id uuid; + expected_realm_id uuid; + expected_pointer_version bigint; + expected_event_id bigint; + expected_request_id uuid; +BEGIN + IF TG_TABLE_NAME = 'gameplay_admission_pointer' THEN + IF NEW.representation_version <> 2 THEN + RETURN NULL; + END IF; + expected_target_namespace := NEW.target_namespace; + expected_tenant_id := NEW.canonical_tenant_id; + expected_realm_id := NEW.realm_id; + expected_pointer_version := NEW.pointer_version; + ELSIF TG_TABLE_NAME = 'gameplay_admission_pointer_event' THEN + IF NEW.representation_version <> 2 THEN + RETURN NULL; + END IF; + expected_target_namespace := NEW.target_namespace; + expected_tenant_id := NEW.canonical_tenant_id; + expected_realm_id := NEW.realm_id; + expected_pointer_version := NEW.pointer_version; + expected_event_id := NEW.id; + ELSE + expected_target_namespace := NEW.target_namespace; + expected_tenant_id := NEW.canonical_tenant_id; + expected_realm_id := NEW.realm_id; + expected_pointer_version := NEW.pointer_version; + expected_event_id := NEW.audit_event_id; + expected_request_id := NEW.request_id; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM gameplay_admission_pointer pointer + JOIN gameplay_admission_pointer_event event + ON event.representation_version = 2 + AND event.target_namespace = pointer.target_namespace + AND event.canonical_tenant_id = pointer.canonical_tenant_id + AND event.realm_id = pointer.realm_id + AND event.pointer_version = pointer.pointer_version + JOIN game_session_canonical_closed_admission_pointer_request outcome + ON outcome.target_namespace = pointer.target_namespace + AND outcome.canonical_tenant_id = pointer.canonical_tenant_id + AND outcome.realm_id = pointer.realm_id + AND outcome.pointer_version = pointer.pointer_version + AND outcome.audit_event_id = event.id + JOIN game_session_canonical_realm_catalog catalog + ON catalog.target_namespace = pointer.target_namespace + AND catalog.canonical_tenant_id = pointer.canonical_tenant_id + AND catalog.realm_id = pointer.realm_id + AND catalog.catalog_revision = pointer.catalog_revision + AND catalog.creation_request_id = outcome.catalog_creation_request_id + AND catalog.request_digest = outcome.catalog_request_digest + AND catalog.receipt_digest = outcome.catalog_receipt_digest + AND catalog.visible + AND catalog.public_production + WHERE pointer.representation_version = 2 + AND pointer.target_namespace = expected_target_namespace + AND pointer.canonical_tenant_id = expected_tenant_id + AND pointer.realm_id = expected_realm_id + AND pointer.pointer_version = expected_pointer_version + AND pointer.admission_state = 'CLOSED' + AND pointer.tenant_id IS NULL + AND pointer.game_instance_id IS NULL + AND pointer.playable_state_namespace_id IS NULL + AND pointer.world_slug = catalog.world_slug + AND pointer.realm_slug = catalog.realm_slug + AND pointer.world_display_name IS NULL + AND pointer.realm_display_name IS NULL + AND pointer.visible IS NULL + AND pointer.public_production_realm IS NULL + AND pointer.requires_character_selection IS NULL + AND pointer.state_scope IS NULL + AND pointer.character_creation_policy IS NULL + AND pointer.last_updated_by IS NULL + AND pointer.last_update_reason IS NULL + AND event.id = outcome.audit_event_id + AND event.target_namespace = pointer.target_namespace + AND event.canonical_tenant_id = pointer.canonical_tenant_id + AND event.realm_id = pointer.realm_id + AND event.pointer_version = pointer.pointer_version + AND event.catalog_revision = catalog.catalog_revision + AND event.admission_state = 'CLOSED' + AND event.tenant_id IS NULL + AND event.game_instance_id IS NULL + AND event.world_slug = catalog.world_slug + AND event.realm_slug = catalog.realm_slug + AND event.world_display_name IS NULL + AND event.realm_display_name IS NULL + AND event.visible IS NULL + AND event.public_production_realm IS NULL + AND event.requires_character_selection IS NULL + AND event.state_scope IS NULL + AND event.character_creation_policy IS NULL + AND event.prepared_version_upgrade_id IS NULL + AND event.control_plane_request_id = outcome.request_id::text + AND event.actor_principal = outcome.actor_principal + AND event.reason = outcome.reason + AND outcome.admission_state = 'CLOSED' + AND outcome.request_digest ~ '^sha256:[0-9a-f]{64}$' + AND outcome.receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND outcome.pointer_version = pointer.pointer_version + AND outcome.catalog_revision = catalog.catalog_revision + AND outcome.target_namespace = pointer.target_namespace + AND outcome.canonical_tenant_id = pointer.canonical_tenant_id + AND outcome.realm_id = pointer.realm_id + AND outcome.updated_at = (pointer.updated_at AT TIME ZONE 'UTC') + AND outcome.updated_at = (pointer.created_at AT TIME ZONE 'UTC') + AND event.occurred_at = (outcome.updated_at AT TIME ZONE 'UTC') + AND (expected_event_id IS NULL OR event.id = expected_event_id) + AND (expected_request_id IS NULL OR outcome.request_id = expected_request_id) + ) THEN + RAISE EXCEPTION 'Canonical CLOSED pointer, event, outcome and exact catalog must commit together' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER gameplay_admission_pointer_canonical_atomic_evidence +AFTER INSERT ON gameplay_admission_pointer +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_closed_pointer_atomic_evidence(); + +CREATE CONSTRAINT TRIGGER gameplay_admission_pointer_event_canonical_atomic_evidence +AFTER INSERT ON gameplay_admission_pointer_event +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_closed_pointer_atomic_evidence(); + +CREATE CONSTRAINT TRIGGER game_session_canonical_closed_pointer_request_atomic_evidence +AFTER INSERT ON game_session_canonical_closed_admission_pointer_request +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_closed_pointer_atomic_evidence(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceUuidIdentityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceUuidIdentityIntegrationTest.java index 701199dbee..5ca3f3d788 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceUuidIdentityIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceUuidIdentityIntegrationTest.java @@ -62,7 +62,8 @@ void freshRepositoryIdentityIsPersistedAndRetainedRowsRemainUnmapped() { String retainedAfterMigration = dsl.resultQuery( - "SELECT (to_jsonb(game_instance) - 'game_instance_uuid')::text " + "SELECT (to_jsonb(game_instance) - 'owner_account_uuid' " + + "- 'game_instance_uuid')::text " + "FROM game_instances AS game_instance WHERE id = ?", RETAINED_INSTANCE_ID) .fetchOne(0, String.class); @@ -71,6 +72,10 @@ void freshRepositoryIdentityIsPersistedAndRetainedRowsRemainUnmapped() { dsl.fetchOne( "SELECT game_instance_uuid FROM game_instances WHERE id = ?", RETAINED_INSTANCE_ID); assertThat(retainedUuid.get("game_instance_uuid", UUID.class)).isNull(); + Record retainedOwnerUuid = + dsl.fetchOne( + "SELECT owner_account_uuid FROM game_instances WHERE id = ?", RETAINED_INSTANCE_ID); + assertThat(retainedOwnerUuid.get("owner_account_uuid", UUID.class)).isNull(); GameInstanceRepository repository = new GameInstanceRepository(dsl); GameInstance retained = repository.findById(RETAINED_INSTANCE_ID).orElseThrow(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryIntegrationTest.java index 035005be80..2fe36e802b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryIntegrationTest.java @@ -245,6 +245,12 @@ void sourceAndTenantClaimsRejectMutationDeleteTruncateAndClaimOnlyCommit() { assertThatThrownBy( () -> fixture.dsl.execute("TRUNCATE TABLE game_session_authored_world_source_intake")) .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot truncate a table referenced in a foreign key constraint"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "TRUNCATE TABLE game_session_authored_world_source_intake CASCADE")) + .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("authored-world source evidence is immutable"); assertThatThrownBy( () -> @@ -271,11 +277,17 @@ void sourceAndTenantClaimsRejectMutationDeleteTruncateAndClaimOnlyCommit() { "TRUNCATE TABLE game_session_authored_world_tenant_source_binding")) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("cannot truncate a table referenced in a foreign key constraint"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "TRUNCATE TABLE game_session_authored_world_tenant_source_binding CASCADE")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("authored-world source evidence is immutable"); assertThatThrownBy( () -> fixture.dsl.execute( "TRUNCATE TABLE game_session_authored_world_tenant_source_binding, " - + "game_session_authored_world_source_intake")) + + "game_session_authored_world_source_intake CASCADE")) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("authored-world source evidence is immutable"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest.java new file mode 100644 index 0000000000..78bb2ee14b --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest.java @@ -0,0 +1,988 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +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.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalClosedAdmissionPointerRequest; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.CanonicalClosedPointerConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.ExpectedClosedEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.PreparedExpectedClosed; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.PreparedInitialClosed; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalAdmissionPointerRepositoryIntegrationTest { + private static final String NAMESPACE = "canonical-closed-pointer-it"; + private static final long RETAINED_TENANT_ID = 917L; + private static final long RETAINED_INSTANCE_ID = 501L; + private static final long RETAINED_CATALOG_REVISION = 7L; + private static final UUID RETAINED_REALM_ID = uuid(801); + private static final UUID RETAINED_NAMESPACE_ID = uuid(802); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void commitsCatalogBackedClosedPointerWithoutNumericOrRuntimeAliases() { + Fixture fixture = fixture(true); + Created created = fixture.create(uuid(20), "Café 🐉 owner", "initial close reason"); + + assertThat(created.snapshot.admissionState()).isEqualTo("CLOSED"); + assertThat(created.snapshot.admissibleGameInstanceId()).isNull(); + assertThat(created.snapshot.pointerVersion()).isEqualTo(1L); + assertThat(created.snapshot.catalogSnapshot()).isEqualTo(created.catalog); + assertThat(created.snapshot.updatedAt()) + .isEqualTo(created.snapshot.updatedAt().truncatedTo(java.time.temporal.ChronoUnit.MICROS)); + assertThat(fixture.count("gameplay_admission_pointer")).isEqualTo(2L); + assertThat(fixture.count("gameplay_admission_pointer_event WHERE representation_version = 2")) + .isEqualTo(1L); + assertThat(fixture.count("game_session_canonical_closed_admission_pointer_request")) + .isEqualTo(1L); + + Record pointer = + fixture.required( + "SELECT * FROM gameplay_admission_pointer WHERE representation_version = 2"); + assertThat(pointer.get("tenant_id", Long.class)).isNull(); + assertThat(pointer.get("game_instance_id", Long.class)).isNull(); + assertThat(pointer.get("canonical_tenant_id", UUID.class)) + .isEqualTo(created.catalog.tenantId()); + assertThat(pointer.get("realm_id", UUID.class)).isEqualTo(created.catalog.realmId()); + assertThat(pointer.get("playable_state_namespace_id", UUID.class)).isNull(); + assertThat(pointer.get("catalog_revision", Long.class)).isEqualTo(1L); + assertThat(pointer.get("admission_state", String.class)).isEqualTo("CLOSED"); + assertThat(pointer.get("world_display_name", String.class)).isNull(); + assertThat(pointer.get("character_creation_policy", String.class)).isNull(); + + Record event = + fixture.required( + "SELECT tenant_id, game_instance_id, realm_id, playable_state_namespace_id, " + + "catalog_revision, admission_state FROM gameplay_admission_pointer_event " + + "WHERE representation_version = 2"); + assertThat(event.get("tenant_id", Long.class)).isNull(); + assertThat(event.get("game_instance_id", Long.class)).isNull(); + assertThat(event.get("realm_id", UUID.class)).isEqualTo(created.catalog.realmId()); + assertThat(event.get("playable_state_namespace_id", UUID.class)).isNull(); + assertThat(event.get("catalog_revision", Long.class)).isEqualTo(1L); + assertThat(event.get("admission_state", String.class)).isEqualTo("CLOSED"); + } + + @Test + void canonicalClosedRowsRejectNumericRuntimeAndNamespaceAliasesWithoutGrowingEvidence() { + Fixture fixture = fixture(true); + CreateCanonicalClosedAdmissionPointerRequest request = + fixture.createCatalog(uuid(30), uuid(40), "shape actor", "shape reason"); + CanonicalRealmCatalogSnapshot catalog = + fixture + .catalogRepository + .readByRequest(NAMESPACE, request.catalogCreationRequestId()) + .orElseThrow(); + String insertCanonicalPointer = + "INSERT INTO gameplay_admission_pointer (" + + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "created_at, updated_at, public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state) " + + "SELECT catalog.world_slug, catalog.realm_slug, NULL, NULL, ?, ?, 1, NULL, NULL, " + + "NULL, NULL, NULL, NULL, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, NULL, " + + "catalog.catalog_revision, catalog.realm_id, ?, 2, catalog.target_namespace, " + + "catalog.canonical_tenant_id, 'CLOSED' " + + "FROM game_session_canonical_realm_catalog catalog " + + "WHERE catalog.target_namespace = ? AND catalog.creation_request_id = ?"; + + assertThatThrownBy( + () -> + fixture.dsl.execute( + insertCanonicalPointer, + RETAINED_TENANT_ID, + RETAINED_INSTANCE_ID, + null, + NAMESPACE, + request.catalogCreationRequestId())) + .satisfies( + failure -> + assertPostgresCheckViolation( + failure, "chk_gameplay_admission_pointer_representation")); + assertThatThrownBy( + () -> + fixture.dsl.execute( + insertCanonicalPointer, + null, + null, + catalog.playableStateNamespaceId(), + NAMESPACE, + request.catalogCreationRequestId())) + .satisfies( + failure -> + assertPostgresCheckViolation( + failure, "chk_gameplay_admission_pointer_representation")); + + assertThat(fixture.count("gameplay_admission_pointer")).isEqualTo(1L); + assertThat(fixture.count("gameplay_admission_pointer_event")).isEqualTo(1L); + assertThat(fixture.count("game_session_canonical_realm_catalog")).isEqualTo(1L); + assertThat(fixture.count("game_session_canonical_closed_admission_pointer_request")).isZero(); + assertThat(fixture.pointerRepository.readByRequest(NAMESPACE, request.requestId())).isEmpty(); + assertThat( + fixture.catalogRepository.readByRequest(NAMESPACE, request.catalogCreationRequestId())) + .contains(catalog); + assertThat( + fixture + .required( + "SELECT (to_jsonb(pointer) - 'representation_version' - 'target_namespace' " + + "- 'canonical_tenant_id' - 'admission_state')::text AS row_json " + + "FROM gameplay_admission_pointer pointer WHERE id = ?", + fixture.retainedPointerId) + .get("row_json", String.class)) + .isEqualTo(fixture.retainedPointerBeforeV13); + assertThat( + fixture + .required( + "SELECT (to_jsonb(event) - 'representation_version' - 'target_namespace' " + + "- 'canonical_tenant_id' - 'admission_state')::text AS row_json " + + "FROM gameplay_admission_pointer_event event WHERE id = ?", + fixture.retainedEventId) + .get("row_json", String.class)) + .isEqualTo(fixture.retainedEventBeforeV13); + } + + @Test + void exactRetryAndLostResponseReadbackPreserveTheOriginalOutcomeAndEvent() { + Fixture fixture = fixture(false); + CreateCanonicalClosedAdmissionPointerRequest request = + fixture.createCatalog(uuid(21), uuid(31), "actor/é", "close/東京"); + PreparedInitialClosed prepared = fixture.pointerRepository.prepareInitialClosed(request); + fixture.commit(prepared); + CanonicalClosedAdmissionPointerSnapshot original = + fixture.pointerRepository.readByRequest(NAMESPACE, request.requestId()).orElseThrow(); + fixture.commit(fixture.pointerRepository.prepareInitialClosed(request)); + CanonicalClosedAdmissionPointerSnapshot replay = + fixture.pointerRepository.readByRequest(NAMESPACE, request.requestId()).orElseThrow(); + + assertThat(replay).isEqualTo(original); + assertThat(replay.updatedAt()).isEqualTo(original.updatedAt()); + assertThat(replay.auditEventId()).isEqualTo(original.auditEventId()); + assertThat(fixture.count("gameplay_admission_pointer WHERE representation_version = 2")) + .isEqualTo(1L); + assertThat(fixture.count("gameplay_admission_pointer_event WHERE representation_version = 2")) + .isEqualTo(1L); + assertThat(fixture.count("game_session_canonical_closed_admission_pointer_request")) + .isEqualTo(1L); + } + + @Test + void expectedClosedLocksAndReturnsOnlyTheExactNeverOpenOriginEvidence() { + Fixture fixture = fixture(false); + Created created = fixture.create(uuid(28), "expected-close actor", "expected-close reason"); + PreparedExpectedClosed prepared = + fixture.pointerRepository.prepareExpectedClosed( + NAMESPACE, created.snapshot.requestId(), 1L, 1L); + + ExpectedClosedEvidence evidence = fixture.lockExpectedClosed(prepared); + + assertThat(evidence.isNeverOpenOrigin()).isTrue(); + assertThat(evidence.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(evidence.originalRequestId()).isEqualTo(created.snapshot.requestId()); + assertThat(evidence.canonicalTenantId()).isEqualTo(created.catalog.tenantId()); + assertThat(evidence.realmId()).isEqualTo(created.catalog.realmId()); + assertThat(evidence.pointerVersion()).isEqualTo(1L); + assertThat(evidence.catalogRevision()).isEqualTo(1L); + assertThat(evidence.auditEventId()).isEqualTo(created.snapshot.auditEventId()); + assertThat(evidence.requestDigest()).isEqualTo(created.snapshot.requestDigest()); + assertThat(evidence.receiptDigest()).isEqualTo(created.snapshot.receiptDigest()); + } + + @Test + void expectedClosedRejectsMissingForgedAndWrongVersionOriginSelectors() { + Fixture fixture = fixture(false); + Created created = fixture.create(uuid(29), "expected-close actor", "expected-close reason"); + + assertThatThrownBy( + () -> fixture.pointerRepository.prepareExpectedClosed(NAMESPACE, uuid(998), 1L, 1L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("origin is missing"); + assertThatThrownBy( + () -> + fixture.pointerRepository.prepareExpectedClosed( + NAMESPACE + "-other", created.snapshot.requestId(), 1L, 1L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("origin is missing"); + assertThatThrownBy( + () -> + fixture.pointerRepository.prepareExpectedClosed( + NAMESPACE, created.snapshot.requestId(), 2L, 1L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("versions do not match"); + assertThatThrownBy( + () -> + fixture.pointerRepository.prepareExpectedClosed( + NAMESPACE, created.snapshot.requestId(), 1L, 2L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("versions do not match"); + } + + @Test + void expectedClosedLockRejectsDriftAndPartialOriginalEvidence() { + Fixture drifted = fixture(false); + Created created = drifted.create(uuid(38), "drift actor", "original reason"); + PreparedExpectedClosed driftPrepared = + drifted.pointerRepository.prepareExpectedClosed( + NAMESPACE, created.snapshot.requestId(), 1L, 1L); + drifted.dsl.execute( + "ALTER TABLE gameplay_admission_pointer_event " + + "DISABLE TRIGGER gameplay_admission_pointer_event_canonical_immutable"); + drifted.dsl.execute( + "UPDATE gameplay_admission_pointer_event SET reason = 'changed after prepare' WHERE id = ?", + created.snapshot.auditEventId()); + drifted.dsl.execute( + "ALTER TABLE gameplay_admission_pointer_event " + + "ENABLE TRIGGER gameplay_admission_pointer_event_canonical_immutable"); + + assertThatThrownBy(() -> drifted.lockExpectedClosed(driftPrepared)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("audit event conflicts"); + + Fixture partial = fixture(false); + Created partialCreated = partial.create(uuid(39), "partial actor", "partial origin reason"); + PreparedExpectedClosed partialPrepared = + partial.pointerRepository.prepareExpectedClosed( + NAMESPACE, partialCreated.snapshot.requestId(), 1L, 1L); + partial.dsl.execute( + "ALTER TABLE game_session_canonical_closed_admission_pointer_request " + + "DISABLE TRIGGER ALL"); + partial.dsl.execute("ALTER TABLE gameplay_admission_pointer_event DISABLE TRIGGER ALL"); + partial.dsl.execute( + "DELETE FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND request_id = ?", + NAMESPACE, + partialCreated.snapshot.requestId()); + partial.dsl.execute( + "DELETE FROM gameplay_admission_pointer_event WHERE id = ?", + partialCreated.snapshot.auditEventId()); + partial.dsl.execute( + "ALTER TABLE game_session_canonical_closed_admission_pointer_request " + + "ENABLE TRIGGER ALL"); + partial.dsl.execute("ALTER TABLE gameplay_admission_pointer_event ENABLE TRIGGER ALL"); + + assertThatThrownBy(() -> partial.lockExpectedClosed(partialPrepared)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("request outcome is missing"); + assertThatThrownBy( + () -> + partial.pointerRepository.prepareExpectedClosed( + NAMESPACE, partialCreated.snapshot.requestId(), 1L, 1L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("origin is missing"); + } + + @Test + void expectedClosedRequiresCommittedPreflightAndWritableReadCommittedOwnerLock() { + Fixture fixture = fixture(false); + Created created = fixture.create(uuid(40), "boundary actor", "boundary reason"); + PreparedExpectedClosed prepared = + fixture.pointerRepository.prepareExpectedClosed( + NAMESPACE, created.snapshot.requestId(), 1L, 1L); + + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> + fixture.pointerRepository.prepareExpectedClosed( + NAMESPACE, created.snapshot.requestId(), 1L, 1L))) + .hasMessageContaining("committed-outcome owner read"); + assertThatThrownBy(() -> fixture.pointerRepository.lockExpectedClosed(prepared)) + .hasMessageContaining("active owner transaction"); + + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute(status -> fixture.pointerRepository.lockExpectedClosed(prepared))) + .hasMessageContaining("read-write transaction"); + + TransactionTemplate serializable = new TransactionTemplate(fixture.transactionManager); + serializable.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThatThrownBy( + () -> + serializable.execute( + status -> fixture.pointerRepository.lockExpectedClosed(prepared))) + .hasMessageContaining("READ COMMITTED"); + + assertThat(fixture.lockExpectedClosed(prepared).isNeverOpenOrigin()).isTrue(); + } + + @Test + void changedAuditOrCatalogInputUnderTheSameRequestConflictsWithoutAddingRows() { + Fixture fixture = fixture(false); + CreateCanonicalClosedAdmissionPointerRequest original = + fixture.createCatalog(uuid(22), uuid(32), "actor", "first reason"); + fixture.commit(fixture.pointerRepository.prepareInitialClosed(original)); + CreateCanonicalClosedAdmissionPointerRequest changedReason = + new CreateCanonicalClosedAdmissionPointerRequest( + original.requestId(), + original.targetNamespace(), + original.canonicalTenantId(), + original.realmId(), + original.catalogCreationRequestId(), + original.catalogRevision(), + original.actorPrincipal(), + "changed reason"); + CreateCanonicalClosedAdmissionPointerRequest changedActor = + new CreateCanonicalClosedAdmissionPointerRequest( + original.requestId(), + original.targetNamespace(), + original.canonicalTenantId(), + original.realmId(), + original.catalogCreationRequestId(), + original.catalogRevision(), + "changed actor", + original.reason()); + PreparedInitialClosed changedReasonPrepared = + fixture.pointerRepository.prepareInitialClosed(changedReason); + PreparedInitialClosed changedActorPrepared = + fixture.pointerRepository.prepareInitialClosed(changedActor); + CreateCanonicalClosedAdmissionPointerRequest changedCatalogReference = + new CreateCanonicalClosedAdmissionPointerRequest( + original.requestId(), + original.targetNamespace(), + original.canonicalTenantId(), + original.realmId(), + uuid(999), + original.catalogRevision(), + original.actorPrincipal(), + original.reason()); + + assertThatThrownBy(() -> fixture.commit(changedReasonPrepared)) + .isInstanceOf(CanonicalClosedPointerConflictException.class) + .hasMessageContaining("changed input"); + assertThatThrownBy(() -> fixture.commit(changedActorPrepared)) + .isInstanceOf(CanonicalClosedPointerConflictException.class) + .hasMessageContaining("changed input"); + assertThatThrownBy( + () -> fixture.pointerRepository.prepareInitialClosed(changedCatalogReference)) + .hasMessageContaining("catalog request is missing"); + assertThat(fixture.count("gameplay_admission_pointer WHERE representation_version = 2")) + .isEqualTo(1L); + assertThat(fixture.count("gameplay_admission_pointer_event WHERE representation_version = 2")) + .isEqualTo(1L); + assertThat(fixture.count("game_session_canonical_closed_admission_pointer_request")) + .isEqualTo(1L); + } + + @Test + void concurrentExactCreationLeavesOnePointerEventAndImmutableOutcome() throws Exception { + Fixture fixture = fixture(false); + CreateCanonicalClosedAdmissionPointerRequest request = + fixture.createCatalog(uuid(23), uuid(33), "concurrent actor", "same intent"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(() -> raceCreate(fixture, request, ready, start)); + Future second = executor.submit(() -> raceCreate(fixture, request, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(first.get(30, TimeUnit.SECONDS)).isNull(); + assertThat(second.get(30, TimeUnit.SECONDS)).isNull(); + } + + assertThat(fixture.count("gameplay_admission_pointer WHERE representation_version = 2")) + .isEqualTo(1L); + assertThat(fixture.count("gameplay_admission_pointer_event WHERE representation_version = 2")) + .isEqualTo(1L); + assertThat(fixture.count("game_session_canonical_closed_admission_pointer_request")) + .isEqualTo(1L); + assertThat(fixture.pointerRepository.readByRequest(NAMESPACE, request.requestId())).isPresent(); + } + + @Test + void rollingBackOwnerTransactionLeavesNoPointerEventOrOutcome() { + Fixture fixture = fixture(false); + CreateCanonicalClosedAdmissionPointerRequest request = + fixture.createCatalog(uuid(24), uuid(34), "rollback actor", "rollback reason"); + PreparedInitialClosed prepared = fixture.pointerRepository.prepareInitialClosed(request); + Void rolledBack = + fixture.transactions.execute( + status -> { + fixture.pointerRepository.createInitialClosed(prepared); + status.setRollbackOnly(); + return null; + }); + + assertThat(rolledBack).isNull(); + assertThat(fixture.count("gameplay_admission_pointer WHERE representation_version = 2")) + .isZero(); + assertThat(fixture.count("gameplay_admission_pointer_event WHERE representation_version = 2")) + .isZero(); + assertThat(fixture.count("game_session_canonical_closed_admission_pointer_request")).isZero(); + assertThat(fixture.pointerRepository.readByRequest(NAMESPACE, request.requestId())).isEmpty(); + } + + @Test + void committedReadbackRequiresExactOwnerTransactionBoundaries() { + Fixture fixture = fixture(false); + CreateCanonicalClosedAdmissionPointerRequest request = + fixture.createCatalog(uuid(25), uuid(35), "boundary actor", "boundary reason"); + PreparedInitialClosed prepared = fixture.pointerRepository.prepareInitialClosed(request); + + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> fixture.pointerRepository.prepareInitialClosed(request))) + .hasMessageContaining("committed-outcome owner read"); + assertThatThrownBy(() -> fixture.pointerRepository.createInitialClosed(prepared)) + .hasMessageContaining("active owner transaction"); + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute( + status -> { + fixture.pointerRepository.createInitialClosed(prepared); + return null; + })) + .hasMessageContaining("read-write transaction"); + TransactionTemplate serializable = new TransactionTemplate(fixture.transactionManager); + serializable.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThatThrownBy( + () -> + serializable.execute( + status -> { + fixture.pointerRepository.createInitialClosed(prepared); + return null; + })) + .hasMessageContaining("READ COMMITTED"); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> + fixture.pointerRepository.readByRequest(NAMESPACE, request.requestId()))) + .hasMessageContaining("committed-outcome owner read"); + assertThat(fixture.pointerRepository.readByRequest(NAMESPACE, request.requestId())).isEmpty(); + } + + @Test + void partialPointerCannotCommitWithoutItsAuditAndRequestOutcome() { + Fixture fixture = fixture(false); + CreateCanonicalClosedAdmissionPointerRequest request = + fixture.createCatalog(uuid(27), uuid(37), "partial actor", "partial reason"); + + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> + fixture.transactionalDsl.execute( + "INSERT INTO gameplay_admission_pointer (world_slug, realm_slug, " + + "world_display_name, realm_display_name, tenant_id, game_instance_id, " + + "pointer_version, visible, requires_character_selection, state_scope, " + + "character_creation_policy, last_updated_by, last_update_reason, " + + "created_at, updated_at, public_production_realm, catalog_revision, " + + "realm_id, playable_state_namespace_id, representation_version, " + + "target_namespace, canonical_tenant_id, admission_state) " + + "SELECT world_slug, realm_slug, NULL, NULL, NULL, NULL, 1, NULL, NULL, " + + "NULL, NULL, NULL, NULL, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, NULL, " + + "catalog_revision, realm_id, NULL, 2, target_namespace, " + + "canonical_tenant_id, 'CLOSED' FROM game_session_canonical_realm_catalog " + + "WHERE creation_request_id = ?", + request.catalogCreationRequestId()))) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining( + "Canonical CLOSED pointer, event, outcome and exact catalog must commit together"); + assertThat(fixture.count("gameplay_admission_pointer WHERE representation_version = 2")) + .isZero(); + assertThat(fixture.count("gameplay_admission_pointer_event WHERE representation_version = 2")) + .isZero(); + assertThat(fixture.count("game_session_canonical_closed_admission_pointer_request")).isZero(); + } + + @Test + void retainedNumericReadersRemainIsolatedAndCanonicalMutationGuardsHold() { + Fixture fixture = fixture(true); + Created created = fixture.create(uuid(26), "retained-safe actor", "retained-safe reason"); + + assertThat(fixture.legacyPointerRepository.count()).isEqualTo(1L); + assertThat( + fixture.legacyPointerRepository.findByTenantIdAndWorldSlugAndRealmSlug( + RETAINED_TENANT_ID, "legacy-world", "legacy-realm")) + .isPresent(); + assertThat( + fixture.legacyPointerRepository.findAllByTenantIdAndGameInstanceId( + RETAINED_TENANT_ID, RETAINED_INSTANCE_ID)) + .hasSize(1); + assertThat(fixture.legacyPointerRepository.findAllByOrderByWorldSlugAscRealmSlugAsc()) + .hasSize(1) + .allSatisfy(pointer -> assertThat(pointer.getTenantId()).isEqualTo(RETAINED_TENANT_ID)); + assertThat( + fixture.eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( + RETAINED_TENANT_ID, "legacy-world", "legacy-realm")) + .hasSize(1) + .first() + .satisfies(event -> assertThat(event.getGameInstanceId()).isEqualTo(RETAINED_INSTANCE_ID)); + assertThat( + fixture + .required( + "SELECT tenant_id, game_instance_id, realm_id, playable_state_namespace_id " + + "FROM gameplay_admission_pointer WHERE id = ?", + fixture.retainedPointerId) + .get("realm_id", UUID.class)) + .isEqualTo(RETAINED_REALM_ID); + assertThat( + fixture + .required( + "SELECT tenant_id, game_instance_id, realm_id, playable_state_namespace_id " + + "FROM gameplay_admission_pointer WHERE id = ?", + fixture.retainedPointerId) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_NAMESPACE_ID); + assertThat( + fixture + .required( + "SELECT (to_jsonb(pointer) - 'representation_version' - 'target_namespace' " + + "- 'canonical_tenant_id' - 'admission_state')::text AS row_json " + + "FROM gameplay_admission_pointer pointer WHERE id = ?", + fixture.retainedPointerId) + .get("row_json", String.class)) + .isEqualTo(fixture.retainedPointerBeforeV13); + assertThat( + fixture + .required( + "SELECT (to_jsonb(event) - 'representation_version' - 'target_namespace' " + + "- 'canonical_tenant_id' - 'admission_state')::text AS row_json " + + "FROM gameplay_admission_pointer_event event WHERE id = ?", + fixture.retainedEventId) + .get("row_json", String.class)) + .isEqualTo(fixture.retainedEventBeforeV13); + Record retainedPointer = + fixture.required( + "SELECT representation_version, target_namespace, canonical_tenant_id, " + + "catalog_revision, admission_state " + + "FROM gameplay_admission_pointer WHERE id = ?", + fixture.retainedPointerId); + assertThat(retainedPointer.get("representation_version", Integer.class)).isEqualTo(1); + assertThat(retainedPointer.get("target_namespace", String.class)).isNull(); + assertThat(retainedPointer.get("canonical_tenant_id", UUID.class)).isNull(); + assertThat(retainedPointer.get("catalog_revision", Long.class)) + .isEqualTo(RETAINED_CATALOG_REVISION); + assertThat(retainedPointer.get("admission_state", String.class)).isNull(); + Record retainedEvent = + fixture.required( + "SELECT representation_version, target_namespace, canonical_tenant_id, realm_id, " + + "playable_state_namespace_id, catalog_revision, admission_state " + + "FROM gameplay_admission_pointer_event " + + "WHERE id = ?", + fixture.retainedEventId); + assertThat(retainedEvent.get("representation_version", Integer.class)).isEqualTo(1); + assertThat(retainedEvent.get("target_namespace", String.class)).isNull(); + assertThat(retainedEvent.get("canonical_tenant_id", UUID.class)).isNull(); + assertThat(retainedEvent.get("realm_id", UUID.class)).isEqualTo(RETAINED_REALM_ID); + assertThat(retainedEvent.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_NAMESPACE_ID); + assertThat(retainedEvent.get("catalog_revision", Long.class)) + .isEqualTo(RETAINED_CATALOG_REVISION); + assertThat(retainedEvent.get("admission_state", String.class)).isNull(); + + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE gameplay_admission_pointer SET tenant_id = ? " + + "WHERE representation_version = 2", + RETAINED_TENANT_ID)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE gameplay_admission_pointer SET admission_state = 'OPEN' " + + "WHERE representation_version = 2")) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM gameplay_admission_pointer WHERE representation_version = 2")) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE gameplay_admission_pointer_event SET reason = 'rewritten' " + + "WHERE representation_version = 2")) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM gameplay_admission_pointer_event WHERE representation_version = 2")) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> fixture.dsl.execute("TRUNCATE gameplay_admission_pointer_event")) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_canonical_closed_admission_pointer_request " + + "SET reason = 'rewritten'")) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_closed_admission_pointer_request")) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "TRUNCATE game_session_canonical_closed_admission_pointer_request")) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> fixture.dsl.execute("TRUNCATE gameplay_admission_pointer")) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.pointerRepository.readByRequest(NAMESPACE, created.snapshot.requestId())) + .isPresent(); + } + + private Void raceCreate( + Fixture fixture, + CreateCanonicalClosedAdmissionPointerRequest request, + CountDownLatch ready, + CountDownLatch start) + throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for canonical closed-pointer race"); + } + fixture.commit(fixture.pointerRepository.prepareInitialClosed(request)); + return null; + } + + private static void assertPostgresCheckViolation(Throwable failure, String constraintName) { + Throwable cause = failure; + while (cause.getCause() != null && cause.getCause() != cause) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(java.sql.SQLException.class); + java.sql.SQLException postgresFailure = (java.sql.SQLException) cause; + assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); + assertThat(postgresFailure.getMessage()).contains(constraintName); + } + + private Fixture fixture(boolean seedRetained) { + String schema = "gs_canonical_closed_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("11")) + .load() + .migrate(); + + DSLContext initialDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + Long retainedPointerId = null; + if (seedRetained) { + initialDsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + RETAINED_TENANT_ID, + RETAINED_NAMESPACE_ID); + initialDsl.execute( + "INSERT INTO gameplay_admission_pointer " + + "(world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id) " + + "VALUES ('legacy-world', 'Legacy World', 'legacy-realm', 'Legacy Realm', ?, ?, " + + "1, true, false, 'SHARED', 'ALLOW_NEW', 'fixture', 'retained evidence', true, " + + "?, ?, ?)", + RETAINED_TENANT_ID, + RETAINED_INSTANCE_ID, + RETAINED_CATALOG_REVISION, + RETAINED_REALM_ID, + RETAINED_NAMESPACE_ID); + retainedPointerId = + java.util.Objects.requireNonNull( + initialDsl.fetchOne( + "SELECT id FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID), + "Retained pointer seed was not committed before V13") + .get("id", Long.class); + } + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("12")) + .load() + .migrate(); + Long retainedEventId = null; + String retainedPointerBeforeV13 = null; + String retainedEventBeforeV13 = null; + if (seedRetained) { + initialDsl.execute( + "INSERT INTO gameplay_admission_pointer_event " + + "(world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, actor_principal, reason, " + + "control_plane_request_id, occurred_at, public_production_realm, " + + "catalog_revision, realm_id, playable_state_namespace_id) " + + "VALUES ('legacy-world', 'legacy-realm', 'Legacy World', 'Legacy Realm', ?, ?, " + + "1, true, false, 'SHARED', 'ALLOW_NEW', 'fixture', 'retained event', " + + "'legacy-request', CURRENT_TIMESTAMP, true, ?, ?, ?)", + RETAINED_TENANT_ID, + RETAINED_INSTANCE_ID, + RETAINED_CATALOG_REVISION, + RETAINED_REALM_ID, + RETAINED_NAMESPACE_ID); + retainedEventId = + java.util.Objects.requireNonNull( + initialDsl.fetchOne( + "SELECT id FROM gameplay_admission_pointer_event WHERE tenant_id = ?", + RETAINED_TENANT_ID), + "Retained pointer event seed was not committed before V13") + .get("id", Long.class); + retainedPointerBeforeV13 = + java.util.Objects.requireNonNull( + initialDsl.fetchOne( + "SELECT to_jsonb(pointer)::text AS row_json FROM gameplay_admission_pointer pointer " + + "WHERE id = ?", + retainedPointerId), + "Retained pointer JSON must be readable before V13") + .get("row_json", String.class); + retainedEventBeforeV13 = + java.util.Objects.requireNonNull( + initialDsl.fetchOne( + "SELECT to_jsonb(event)::text AS row_json FROM gameplay_admission_pointer_event event " + + "WHERE id = ?", + retainedEventId), + "Retained pointer event JSON must be readable before V13") + .get("row_json", String.class); + } + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(dsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(dsl); + GameplayAdmissionPointerEventRepository eventRepository = + new GameplayAdmissionPointerEventRepository(dsl); + return new Fixture( + initialDsl, + dsl, + transactionManager, + transactions, + sourceRepository, + catalogRepository, + new GameSessionCanonicalAdmissionPointerRepository(dsl, catalogRepository, eventRepository), + new net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository(dsl), + eventRepository, + retainedPointerId, + retainedEventId, + retainedPointerBeforeV13, + retainedEventBeforeV13); + } + + private static AuthoredWorldSourceEvidence source(UUID tenantId, String worldSlug) { + UUID registrationRequestId = + UUID.nameUUIDFromBytes( + ("registration-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + UUID sourceOperationId = + UUID.nameUUIDFromBytes( + ("operation-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + String tenantSlug = "tenant-" + tenantId.toString().substring(0, 8); + String worldDisplayName = "Authored World"; + String sourceGameTenantKey = "gds-tenant-" + tenantId.toString().substring(0, 8); + long sourceGameRowId = Math.abs(tenantId.getMostSignificantBits()) + 10L; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Created( + CanonicalRealmCatalogSnapshot catalog, CanonicalClosedAdmissionPointerSnapshot snapshot) {} + + private record Fixture( + DSLContext dsl, + DSLContext transactionalDsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository + legacyPointerRepository, + GameplayAdmissionPointerEventRepository eventRepository, + Long retainedPointerId, + Long retainedEventId, + String retainedPointerBeforeV13, + String retainedEventBeforeV13) { + CreateCanonicalClosedAdmissionPointerRequest createCatalog( + UUID catalogRequestId, UUID pointerRequestId, String actor, String reason) { + UUID tenantId = UUID.randomUUID(); + String worldSlug = "world-" + catalogRequestId.toString().substring(0, 8); + AuthoredWorldSourceEvidence evidence = source(tenantId, worldSlug); + UUID intakeRequestId = + UUID.nameUUIDFromBytes( + ("intake-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + IntakeReceipt receipt = + java.util.Objects.requireNonNull( + transactions.execute(status -> sourceRepository.register(intakeRequestId, evidence))); + CreateCanonicalRealmCatalogRequest catalogRequest = + new CreateCanonicalRealmCatalogRequest( + catalogRequestId, + NAMESPACE, + tenantId, + receipt.operationId(), + "realm-" + catalogRequestId.toString().substring(0, 8), + "Public Realm", + true, + true, + "SHARED", + "owner-policy-v1", + null, + null); + var preparedCatalog = catalogRepository.prepareInitialPublicProduction(catalogRequest); + CanonicalRealmCatalogSnapshot catalog = + java.util.Objects.requireNonNull( + transactions.execute( + status -> catalogRepository.createInitialPublicProduction(preparedCatalog))); + return new CreateCanonicalClosedAdmissionPointerRequest( + pointerRequestId, + NAMESPACE, + catalog.tenantId(), + catalog.realmId(), + catalog.creationRequestId(), + catalog.catalogRevision(), + actor, + reason); + } + + Created create(UUID pointerRequestId, String actor, String reason) { + CreateCanonicalClosedAdmissionPointerRequest request = + createCatalog(UUID.randomUUID(), pointerRequestId, actor, reason); + commit(pointerRepository.prepareInitialClosed(request)); + return new Created( + catalogRepository + .readByRequest(NAMESPACE, request.catalogCreationRequestId()) + .orElseThrow(), + pointerRepository.readByRequest(NAMESPACE, pointerRequestId).orElseThrow()); + } + + void commit(PreparedInitialClosed prepared) { + Void result = + transactions.execute( + status -> { + pointerRepository.createInitialClosed(prepared); + return null; + }); + assertThat(result).isNull(); + } + + long count(String tableOrPredicate) { + return java.util.Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM " + tableOrPredicate), + "Count query must return one row") + .get(0, Long.class); + } + + ExpectedClosedEvidence lockExpectedClosed(PreparedExpectedClosed prepared) { + return java.util.Objects.requireNonNull( + transactions.execute(status -> pointerRepository.lockExpectedClosed(prepared))); + } + + Record required(String sql, Object... bindings) { + return java.util.Objects.requireNonNull(dsl.fetchOne(sql, bindings)); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java new file mode 100644 index 0000000000..0e107db1ce --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -0,0 +1,718 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +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.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.CatalogConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.PreparedInitialPublicProduction; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalRealmCatalogRepositoryIntegrationTest { + private static final String NAMESPACE = "canonical-realm-catalog-it"; + private static final long RETAINED_TENANT_ID = 917L; + private static final long ODD_RETAINED_TENANT_ID = 918L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final UUID RETAINED_REALM_ID = uuid(801); + private static final UUID RETAINED_PLAYABLE_NAMESPACE_ID = uuid(802); + private static final UUID RETAINED_SHARED_NAMESPACE_ID = uuid(803); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumericEvidence() { + Fixture fixture = fixture(true); + IntakeReceipt source = fixture.register(tenant(1), "new-world", "Fresh World", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest request = + request( + source, uuid(20), " Public Realm / East ", "Public Realm", "owner-policy-v2", "SHARED"); + String retainedNamespaceXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class); + String retainedPointerXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class); + String oddRetainedNamespaceXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("xmin", String.class); + + CanonicalRealmCatalogSnapshot created = fixture.create(request); + CanonicalRealmCatalogSnapshot replay = fixture.create(request); + + assertThat(created).isEqualTo(replay); + assertThat(created.tenantId()).isEqualTo(tenant(1)); + assertThat(created.tenantSlug()).isEqualTo(source.source().tenantSlug()); + assertThat(created.worldSlug()).isEqualTo("new-world"); + assertThat(created.realmSlug()).isEqualTo(" Public Realm / East "); + assertThat(created.stateScope()).isEqualTo("SHARED"); + assertThat(created.catalogRevision()).isEqualTo(1L); + assertThat(created.playableStateNamespaceId()).isNotEqualTo(RETAINED_SHARED_NAMESPACE_ID); + assertThat(created.sourceIntakeReceipt()).isEqualTo(source); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + assertThat(fixture.catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, tenant(1))) + .contains(created); + + assertThat( + requiredRecord( + fixture.dsl, + "SELECT tenant_id, canonical_tenant_id, playable_state_namespace_id " + + "FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenant(1))) + .satisfies( + row -> { + assertThat(row.get("tenant_id", Long.class)).isNull(); + assertThat(row.get("canonical_tenant_id", UUID.class)).isEqualTo(tenant(1)); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(created.playableStateNamespaceId()); + }); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT realm_id, playable_state_namespace_id FROM gameplay_admission_pointer " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("realm_id", UUID.class)) + .isEqualTo(RETAINED_REALM_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_PLAYABLE_NAMESPACE_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedNamespaceXmin); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedPointerXmin); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(NIL_UUID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(oddRetainedNamespaceXmin); + + // The existing runtime selector remains supported by the new nullable-tenant identity layout. + fixture.dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?) " + + "ON CONFLICT (tenant_id) DO NOTHING", + RETAINED_TENANT_ID, + uuid(804)); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")))) + .isEqualTo(3); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedNamespaceXmin); + + assertThatThrownBy( + () -> + fixture.create( + request( + source, + uuid(21), + "another-realm", + "Another Realm", + "owner-mode", + "SHARED"))) + .isInstanceOf(CatalogConflictException.class) + .hasMessageContaining("already has a public-production"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_canonical_realm_catalog SET realm_slug = ? " + + "WHERE creation_request_id = ?", + "rewritten-realm", + request.requestId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", + request.requestId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy(() -> fixture.dsl.execute("TRUNCATE game_session_canonical_realm_catalog")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot truncate a table referenced in a foreign key constraint"); + // The disposable schema's CASCADE form reaches the statement immutability guards after + // PostgreSQL's separate catalog/pointer foreign-key precondition has been satisfied. + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE game_session_canonical_realm_catalog CASCADE")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE gameplay_tenant_shared_playable_state_namespace " + + "SET playable_state_namespace_id = ? WHERE canonical_tenant_id = ?", + uuid(805), + tenant(1))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenant(1))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE gameplay_tenant_shared_playable_state_namespace")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + } + + @Test + void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenance() { + Fixture fixture = fixture(false); + IntakeReceipt source = fixture.register(tenant(2), "world-two", "World Two", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest request = + request(source, uuid(30), "realm", "Realm", "owner-mode", "SHARED"); + + PreparedInitialPublicProduction prepared = + fixture.catalogRepository.prepareInitialPublicProduction(request); + assertThatThrownBy(() -> fixture.catalogRepository.createInitialPublicProduction(prepared)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute( + status -> fixture.catalogRepository.createInitialPublicProduction(prepared))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("read-write"); + + CanonicalRealmCatalogSnapshot created = fixture.create(request); + String beforeXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_canonical_realm_catalog " + + "WHERE creation_request_id = ?", + request.requestId()) + .get("xmin", String.class); + CreateCanonicalRealmCatalogRequest changed = + request(source, request.requestId(), "realm", "Changed Realm", "owner-mode", "SHARED"); + assertThatThrownBy(() -> fixture.create(changed)).isInstanceOf(CatalogConflictException.class); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_canonical_realm_catalog " + + "WHERE creation_request_id = ?", + request.requestId()) + .get("xmin", String.class)) + .isEqualTo(beforeXmin); + + CreateCanonicalRealmCatalogRequest wrongSource = + new CreateCanonicalRealmCatalogRequest( + uuid(32), + NAMESPACE, + source.source().canonicalTenantId(), + uuid(33), + "other-realm", + "Other Realm", + true, + true, + "SHARED", + "owner-mode", + null, + null); + assertThatThrownBy(() -> fixture.catalogRepository.prepareInitialPublicProduction(wrongSource)) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("source intake is missing"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + + IntakeReceipt otherTenantSource = + fixture.register(tenant(9), "world-nine", "World Nine", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest mismatchedSource = + new CreateCanonicalRealmCatalogRequest( + uuid(34), + NAMESPACE, + source.source().canonicalTenantId(), + otherTenantSource.operationId(), + "mismatched-realm", + "Mismatched Realm", + true, + true, + "SHARED", + "owner-mode", + null, + null); + assertThatThrownBy( + () -> fixture.catalogRepository.prepareInitialPublicProduction(mismatchedSource)) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("conflicts with the immutable canonical tenant source binding"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + + IntakeReceipt retained = + fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V30"); + assertThatThrownBy( + () -> + fixture.create( + request(retained, uuid(31), "retained-realm", "Realm", "owner-mode", "SHARED"))) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("fresh Game Design"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + } + + @Test + void isolatedCreationAllocatesDistinctRealmLocalNamespacesOutsideSharedRegistry() { + Fixture fixture = fixture(true); + IntakeReceipt firstSource = + fixture.register(tenant(4), "world-four", "World Four", "NEW_GAME_ROW"); + IntakeReceipt secondSource = + fixture.register(tenant(5), "world-five", "World Five", "NEW_GAME_ROW"); + + CanonicalRealmCatalogSnapshot first = + fixture.create( + request(firstSource, uuid(40), "realm-four", "Realm Four", "owner-mode", "ISOLATED")); + CanonicalRealmCatalogSnapshot second = + fixture.create( + request(secondSource, uuid(50), "realm-five", "Realm Five", "owner-mode", "ISOLATED")); + + assertThat(first.playableStateNamespaceId()).isNotEqualTo(second.playableStateNamespaceId()); + assertThat(first.tenantSlug()).isNotEqualTo(first.worldSlug()); + assertThat(second.tenantSlug()).isNotEqualTo(second.worldSlug()); + assertThat( + fixture.dsl.fetch( + "SELECT canonical_tenant_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id IS NOT NULL")) + .isEmpty(); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, uuid(40))).contains(first); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, uuid(50))).contains(second); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE gameplay_tenant_shared_playable_state_namespace " + + "SET playable_state_namespace_id = ? WHERE tenant_id = ?", + first.playableStateNamespaceId(), + RETAINED_TENANT_ID)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "Legacy tenant SHARED namespace conflicts with a canonical ISOLATED realm namespace"); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + } + + @Test + void concurrentExactCreationRecoversOneDurableRealmAndNamespace() throws Exception { + Fixture fixture = fixture(false); + IntakeReceipt source = + fixture.register(tenant(6), "concurrent-world", "Concurrent World", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest request = + request(source, uuid(60), "concurrent-realm", "Concurrent Realm", "owner-mode", "SHARED"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> raceCreate(fixture, ready, start, request)); + Future second = + executor.submit(() -> raceCreate(fixture, ready, start, request)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + CanonicalRealmCatalogSnapshot firstResult = first.get(20, TimeUnit.SECONDS); + CanonicalRealmCatalogSnapshot secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(firstResult).isEqualTo(secondResult); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(firstResult); + assertThat( + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")))) + .isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void freshCatalogAndRetainedAssociationCannotBothAcquireTenantAuthorityInEitherOrder() { + Fixture associationFirst = fixture(false); + IntakeReceipt associationFirstSource = + associationFirst.register( + tenant(7), "association-first-world", "Association First", "NEW_GAME_ROW"); + associationFirst.insertRetainedAssociation(associationFirstSource, uuid(70)); + CreateCanonicalRealmCatalogRequest afterAssociation = + request( + associationFirstSource, + uuid(71), + "association-first-realm", + "Association First Realm", + "owner-mode", + "SHARED"); + assertThatThrownBy( + () -> + associationFirst.catalogRepository.prepareInitialPublicProduction(afterAssociation)) + .isInstanceOf(CatalogConflictException.class) + .hasMessageContaining("retained numeric Game Session identity"); + assertThat( + associationFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isZero(); + assertThat( + associationFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_retained_tenant_association")))) + .isEqualTo(1); + + Fixture catalogFirst = fixture(false); + IntakeReceipt catalogFirstSource = + catalogFirst.register(tenant(8), "catalog-first-world", "Catalog First", "NEW_GAME_ROW"); + CanonicalRealmCatalogSnapshot catalog = + catalogFirst.create( + request( + catalogFirstSource, + uuid(80), + "catalog-first-realm", + "Catalog First Realm", + "owner-mode", + "SHARED")); + assertThatThrownBy(() -> catalogFirst.insertRetainedAssociation(catalogFirstSource, uuid(81))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot replace fresh canonical tenant namespace authority"); + assertThat( + catalogFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat(catalogFirst.catalogRepository.readByRequest(NAMESPACE, uuid(80))).contains(catalog); + assertThat( + catalogFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_retained_tenant_association")))) + .isZero(); + } + + private CanonicalRealmCatalogSnapshot raceCreate( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + CreateCanonicalRealmCatalogRequest request) + throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for canonical realm creation race"); + } + return fixture.create(request); + } + + private static CreateCanonicalRealmCatalogRequest request( + IntakeReceipt source, + UUID requestId, + String realmSlug, + String displayName, + String policy, + String scope) { + return new CreateCanonicalRealmCatalogRequest( + requestId, + NAMESPACE, + source.source().canonicalTenantId(), + source.operationId(), + realmSlug, + displayName, + true, + true, + scope, + policy, + null, + null); + } + + private static AuthoredWorldSourceEvidence source( + UUID tenantId, String worldSlug, String displayName, String provenance) { + UUID registrationRequestId = + UUID.nameUUIDFromBytes( + ("registration-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + UUID sourceOperationId = + UUID.nameUUIDFromBytes( + ("operation-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + String tenantSlug = "tenant-" + tenantId.toString().substring(0, 8); + long sourceGameRowId = Math.abs(tenantId.getMostSignificantBits()) + 10L; + String sourceGameTenantKey = "gds-tenant-" + tenantId.toString().substring(0, 8); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + provenance); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + provenance, + evidenceDigest); + } + + private Fixture fixture(boolean seedRetainedNumericRows) { + String schema = "gs_canonical_realm_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("11")) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + if (seedRetainedNumericRows) { + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + RETAINED_TENANT_ID, + RETAINED_SHARED_NAMESPACE_ID); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + ODD_RETAINED_TENANT_ID, + NIL_UUID); + dsl.execute( + "INSERT INTO gameplay_admission_pointer " + + "(world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "legacy-world", + "Legacy World", + "legacy-realm", + "Legacy Realm", + RETAINED_TENANT_ID, + 501L, + 1L, + true, + false, + "SHARED", + "ALLOW_NEW", + "fixture", + "retained evidence", + true, + RETAINED_REALM_ID, + RETAINED_PLAYABLE_NAMESPACE_ID); + } + + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext transactionalDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + transactionalDsl, + new GameSessionAuthoredWorldSourceRepository(transactionalDsl), + new GameSessionCanonicalRealmCatalogRepository(transactionalDsl), + transactionManager, + transactions); + } + + private static UUID tenant(int value) { + return uuid(100 + value); + } + + private static Record requiredRecord(DSLContext dsl, String sql, Object... bindings) { + return java.util.Objects.requireNonNull( + dsl.fetchOne(sql, bindings), "Expected owner evidence row is missing"); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + DSLContext dsl, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions) { + IntakeReceipt register(UUID tenantId, String worldSlug, String displayName, String provenance) { + AuthoredWorldSourceEvidence source = + GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.source( + tenantId, worldSlug, displayName, provenance); + UUID intakeRequestId = + UUID.nameUUIDFromBytes( + ("intake-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + IntakeReceipt receipt = + transactions.execute(status -> sourceRepository.register(intakeRequestId, source)); + return java.util.Objects.requireNonNull(receipt); + } + + CanonicalRealmCatalogSnapshot create(CreateCanonicalRealmCatalogRequest request) { + PreparedInitialPublicProduction prepared = + catalogRepository.prepareInitialPublicProduction(request); + CanonicalRealmCatalogSnapshot snapshot = + transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); + return java.util.Objects.requireNonNull(snapshot); + } + + void insertRetainedAssociation(IntakeReceipt source, UUID requestId) { + AuthoredWorldSourceEvidence evidence = source.source(); + String digest = "sha256:" + "a".repeat(64); + dsl.execute( + "INSERT INTO game_session_retained_tenant_association (" + + "operation_id, approval_schema_version, target_namespace, association_request_id, " + + "request_digest, approval_operation_id, signer_key_id, approved_by, " + + "approval_reference, signed_at, legacy_game_session_tenant_id, canonical_tenant_id, " + + "source_game_row_id, source_game_tenant_key, provenance_kind, " + + "game_session_evidence_digest, approval_manifest_digest, approval_signature, " + + "snapshot_canonical_json, snapshot_evidence_digest, receipt_digest) " + + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + UUID.nameUUIDFromBytes( + ("retained-operation-" + requestId) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)), + NAMESPACE, + requestId, + digest, + UUID.nameUUIDFromBytes( + ("approval-operation-" + requestId) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)), + "fixture-key", + "fixture-operator", + "fixture-reference", + "2026-10-03T00:00:00Z", + RETAINED_TENANT_ID, + evidence.canonicalTenantId(), + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.provenanceKind(), + evidence.evidenceDigest(), + digest, + "A".repeat(86) + "==", + "{}", + digest, + digest); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java b/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java index 5f518df665..0c293cc276 100644 --- a/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java +++ b/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java @@ -24,7 +24,7 @@ class V11__enforce_tenant_public_realm_cardinalityTest { private static final Pattern MIGRATION_FILE = Pattern.compile("^V([^_]+)__.*\\.sql$"); @Test - void keepsAdmissionPointerMigrationsUniqueAndOrderedFromTheV7AuditThroughV12() + void keepsAdmissionPointerMigrationsUniqueAndOrderedFromTheV7AuditThroughV13() throws IOException, URISyntaxException { var auditMigrationUrl = getClass() @@ -55,7 +55,9 @@ void keepsAdmissionPointerMigrationsUniqueAndOrderedFromTheV7AuditThroughV12() "V10.1__game_instance_owner_account_uuid.sql", "V11__enforce_tenant_public_realm_cardinality.sql", "V11.1__game_instance_uuid_identity.sql", - "V12__index_gameplay_admission_pointer_event_tenant_lookup.sql"); + "V12__index_gameplay_admission_pointer_event_tenant_lookup.sql", + "V12.1__canonical_realm_catalog.sql", + "V13__canonical_closed_admission_pointer.sql"); String v7 = readMigration("V7__audit_gameplay_catalog_revision.sql"); String normalizedV7 = normalizeSql(v7); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java new file mode 100644 index 0000000000..e501ca164b --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java @@ -0,0 +1,232 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalClosedAdmissionPointerRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.junit.jupiter.api.Test; + +class GameSessionCanonicalAdmissionPointerRepositoryTest { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String TARGET_NAMESPACE = "canonical-closed-pointer-test"; + + @Test + void requestAndReceiptDigestsMatchFixedOrderUtf8GoldenVectors() { + CreateCanonicalClosedAdmissionPointerRequest request = request("Café 🐉", "close 東京"); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + String requestDigest = + GameSessionCanonicalAdmissionPointerRepository.requestDigest(request, catalog); + + assertThat(requestDigest) + .isEqualTo("sha256:0dc3926970e3d5be36349ff3fe259869fed779f3429b767e2e20ece407313d24"); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.requestDigest( + request("Café 🐲", "close 東京"), catalog)) + .isNotEqualTo(requestDigest); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, + catalog, + requestDigest, + 123L, + Instant.parse("2026-10-03T00:00:00.123456Z"))) + .isEqualTo("sha256:5d465f6eec3f08d0de06c5562ba60d2bd44d335c41f82355c4adc158d5806286"); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, + catalog, + requestDigest, + 124L, + Instant.parse("2026-10-03T00:00:00.123456Z"))) + .isNotEqualTo("sha256:5d465f6eec3f08d0de06c5562ba60d2bd44d335c41f82355c4adc158d5806286"); + } + + @Test + void requestRejectsNilIdentityAndNonCanonicalTargetNamespace() { + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + NIL_UUID, TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), "Canonical_Closed", uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 0L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("catalogRevision must be positive"); + } + + @Test + void requestRejectsMalformedOrUnboundedAuditText() { + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), + TARGET_NAMESPACE, + uuid(2), + uuid(3), + uuid(4), + 1L, + "bad" + (char) 0xD800, + "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bounded and nonblank"); + } + + @Test + void expectedClosedVersionCheckRequiresTheExactInitialPointerAndCatalogTuple() { + CreateCanonicalClosedAdmissionPointerRequest request = request("origin actor", "origin reason"); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + String requestDigest = + GameSessionCanonicalAdmissionPointerRepository.requestDigest(request, catalog); + Instant updatedAt = Instant.parse("2026-10-03T00:00:00.123456Z"); + CanonicalClosedAdmissionPointerSnapshot origin = + new CanonicalClosedAdmissionPointerSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + 1L, + catalog.catalogRevision(), + "CLOSED", + null, + request.requestId(), + requestDigest, + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, catalog, requestDigest, 123L, updatedAt), + request.actorPrincipal(), + request.reason(), + 123L, + updatedAt, + catalog); + + assertThatCode( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 1L, 1L)) + .doesNotThrowAnyException(); + assertThatThrownBy( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 2L, 1L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("versions do not match"); + assertThatThrownBy( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 1L, 2L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("versions do not match"); + } + + private static CreateCanonicalClosedAdmissionPointerRequest request( + String actorPrincipal, String reason) { + return new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, actorPrincipal, reason); + } + + private static CanonicalRealmCatalogSnapshot catalogSnapshot() { + UUID tenantId = uuid(2); + UUID registrationRequestId = uuid(10); + UUID sourceOperationId = uuid(11); + String tenantSlug = "unit-tenant"; + String worldSlug = "authored-world"; + String worldDisplayName = "Authored World"; + String sourceGameTenantKey = "gds-unit-tenant"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + TARGET_NAMESPACE, + registrationRequestId, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + TARGET_NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceGameTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + TARGET_NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceGameTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + UUID intakeRequestId = uuid(12); + String intakeRequestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, source); + IntakeReceipt sourceReceipt = + new IntakeReceipt( + uuid(13), + intakeRequestId, + intakeRequestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + uuid(13), intakeRequestDigest, source.evidenceDigest())); + return new CanonicalRealmCatalogSnapshot( + TARGET_NAMESPACE, + tenantId, + tenantSlug, + worldSlug, + uuid(3), + "Arcology", + "Public Realm", + true, + true, + "SHARED", + uuid(14), + "owner-policy-v1", + 1L, + uuid(4), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + sourceReceipt); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java new file mode 100644 index 0000000000..b3418aceca --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java @@ -0,0 +1,222 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.junit.jupiter.api.Test; + +class GameSessionCanonicalRealmCatalogRepositoryTest { + private static final String NAMESPACE = "canonical-realm-catalog-test"; + private static final UUID TENANT_ID = uuid(1); + private static final UUID INTAKE_OPERATION_ID = uuid(2); + private static final UUID INTAKE_REQUEST_ID = uuid(3); + private static final UUID CREATE_REQUEST_ID = uuid(4); + + @Test + void explicitPublicRequestPreservesRealmSelectorAndOpaqueOwnerPolicyExactly() { + CreateCanonicalRealmCatalogRequest request = + request(" Production Realm/West ", "Café 🐉", "realm-local-characters-v7"); + + assertThat(request.realmSlug()).isEqualTo(" Production Realm/West "); + assertThat(request.characterCreationPolicy()).isEqualTo("realm-local-characters-v7"); + assertThat(request.visible()).isTrue(); + assertThat(request.publicProduction()).isTrue(); + assertThat(request.stateScope()).isEqualTo("SHARED"); + } + + @Test + void rejectsMissingPublicStatePrivateLifecycleAndMalformedUtf8Inputs() { + assertThatThrownBy(() -> request("realm", "Display", "policy", false, true, "SHARED")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("visible public production"); + assertThatThrownBy(() -> request("realm", "Display", "policy", true, false, "SHARED")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("visible public production"); + assertThatThrownBy(() -> request("realm", "Display", "policy", true, true, "PRIVATE")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("stateScope"); + assertThatThrownBy( + () -> + new CreateCanonicalRealmCatalogRequest( + CREATE_REQUEST_ID, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + "realm", + "Display", + true, + true, + "SHARED", + "policy", + uuid(5), + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("private/playtest"); + String malformedUtf8 = "bad" + (char) 0xD800; + assertThatThrownBy(() -> request(malformedUtf8, "Display", "policy")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy(() -> request("realm", malformedUtf8, "policy")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy(() -> request("realm", "Display", malformedUtf8)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + } + + @Test + void requestDigestIsStableAndBindsEachCreationInputAndExactSourceReceipt() { + IntakeReceipt source = sourceReceipt(); + CreateCanonicalRealmCatalogRequest original = request("Arcology", "The City", "owner-mode"); + String digest = GameSessionCanonicalRealmCatalogRepository.requestDigest(original, source); + + assertThat(GameSessionCanonicalRealmCatalogRepository.requestDigest(original, source)) + .isEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("arcology", "The City", "owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "Another Display", "owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "The City", "owner-mode", true, true, "ISOLATED"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "The City", "another-owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "The City", "owner-mode", uuid(6)), source)) + .isNotEqualTo(digest); + } + + @Test + void snapshotRejectsTenantAndWorldSelectorsThatDifferFromPersistedSource() { + IntakeReceipt source = sourceReceipt(); + assertThatThrownBy( + () -> + new CanonicalRealmCatalogSnapshot( + NAMESPACE, + TENANT_ID, + "different-tenant", + "authored-world", + uuid(7), + "realm", + "Realm", + true, + true, + "SHARED", + uuid(8), + "policy", + 1, + CREATE_REQUEST_ID, + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("do not match"); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, String display, String policy) { + return request(realmSlug, display, policy, true, true, "SHARED"); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, + String display, + String policy, + boolean visible, + boolean production, + String scope) { + return new CreateCanonicalRealmCatalogRequest( + CREATE_REQUEST_ID, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + realmSlug, + display, + visible, + production, + scope, + policy, + null, + null); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, String display, String policy, UUID requestId) { + return new CreateCanonicalRealmCatalogRequest( + requestId, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + realmSlug, + display, + true, + true, + "SHARED", + policy, + null, + null); + } + + private static IntakeReceipt sourceReceipt() { + String tenantSlug = "stable-tenant"; + String worldSlug = "authored-world"; + String worldDisplayName = "Authored World"; + String sourceTenantKey = "game-design-tenant-42"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, uuid(10), TENANT_ID, tenantSlug, worldSlug, worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + uuid(10), + uuid(11), + sourceRequestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + uuid(10), + uuid(11), + sourceRequestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + String intakeRequestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(INTAKE_REQUEST_ID, source); + String intakeReceiptDigest = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + INTAKE_OPERATION_ID, intakeRequestDigest, source.evidenceDigest()); + return new IntakeReceipt( + INTAKE_OPERATION_ID, INTAKE_REQUEST_ID, intakeRequestDigest, source, intakeReceiptDigest); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java index 8ddcdfdd87..305c7f8a53 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java @@ -176,6 +176,7 @@ private static void createSchema(DSLContext dsl) { """ CREATE TABLE gameplay_admission_pointer_event ( id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + representation_version INTEGER NOT NULL DEFAULT 1, world_slug VARCHAR(120) NOT NULL, realm_slug VARCHAR(120) NOT NULL, world_display_name VARCHAR(200) NOT NULL, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index a9aa71e28d..54cca24522 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -310,6 +310,7 @@ realm_display_name VARCHAR(200) NOT NULL, tenant_id BIGINT NOT NULL, game_instance_id BIGINT NOT NULL, pointer_version BIGINT NOT NULL, + representation_version INT NOT NULL DEFAULT 1, catalog_revision BIGINT NOT NULL, realm_id UUID, playable_state_namespace_id UUID, @@ -364,6 +365,7 @@ private static void createAuditSchema(DSLContext dsl) { """ CREATE TABLE gameplay_admission_pointer_event ( id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + representation_version INTEGER NOT NULL DEFAULT 1, world_slug VARCHAR(120) NOT NULL, realm_slug VARCHAR(120) NOT NULL, world_display_name VARCHAR(200) NOT NULL, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java index 348c071737..40ea86284f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java @@ -234,6 +234,7 @@ private static void createSchema(DSLContext dsl) { dsl.execute( "CREATE TABLE gameplay_admission_pointer (" + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, world_slug VARCHAR(120) NOT NULL, " + + "representation_version INT NOT NULL DEFAULT 1, " + "world_display_name VARCHAR(200) NOT NULL, realm_slug VARCHAR(120) NOT NULL, " + "realm_display_name VARCHAR(200) NOT NULL, tenant_id BIGINT NOT NULL, game_instance_id BIGINT NOT NULL, " + "pointer_version BIGINT NOT NULL, catalog_revision BIGINT NOT NULL, realm_id UUID, " @@ -245,6 +246,7 @@ private static void createSchema(DSLContext dsl) { dsl.execute( "CREATE TABLE gameplay_admission_pointer_event (" + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, world_slug VARCHAR(120) NOT NULL, " + + "representation_version INT NOT NULL DEFAULT 1, " + "realm_slug VARCHAR(120) NOT NULL, world_display_name VARCHAR(200) NOT NULL, " + "realm_display_name VARCHAR(200) NOT NULL, tenant_id BIGINT NOT NULL, game_instance_id BIGINT NOT NULL, " + "pointer_version BIGINT NOT NULL, catalog_revision BIGINT, realm_id UUID, " diff --git a/services/logging-admin-service/build.gradle.kts b/services/logging-admin-service/build.gradle.kts index 3f355d19a2..386d60a8c7 100644 --- a/services/logging-admin-service/build.gradle.kts +++ b/services/logging-admin-service/build.gradle.kts @@ -12,4 +12,5 @@ firemudJooq { } dependencies { + testImplementation(libs.bouncycastle.pkix) } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java index b80457862e..2a95bc77ee 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java @@ -1,8 +1,12 @@ package net.firedevops.firemud.loggingadmin.dto; +import java.util.UUID; + public record AccountAuditReceiptDto( AccountAuditScope scope, + int tenantIdentityVersion, Long tenantId, + UUID tenantUuid, String auditEventId, String receiptId, long logEventId, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java index 0e187d9160..bb4cc72f06 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java @@ -3,6 +3,7 @@ import com.google.protobuf.ByteString; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; +import java.util.UUID; /** The immutable Account audit envelope accepted by the existing CreateLogEvent RPC. */ @SuppressFBWarnings( @@ -11,7 +12,9 @@ "Protobuf ByteString is immutable, so retaining and exposing the payload is safe.") public record CreateLogEventRequest( AccountAuditScope scope, + int tenantIdentityVersion, Long tenantId, + UUID tenantUuid, String auditEventId, String producerService, String eventType, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java index 2d3eeeb6c7..6aaffc6365 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java @@ -8,7 +8,9 @@ public record AccountAuditReceipt( long logEventId, UUID receiptId, String scope, + int tenantIdentityVersion, Long tenantId, + UUID tenantUuid, String auditEventId, String producerService, String eventType, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java index ef646e3987..96bfc130f1 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java @@ -31,15 +31,16 @@ public AccountAuditReceiptRepository(DSLContext dsl) { public AccountAuditReceiptInsertResult insertIfAbsent( CreateLogEventRequest request, UUID receiptId) { - long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); long logEventId = insertOrFindProjection(request); int inserted = dsl.insertInto(ACCOUNT_AUDIT_RECEIPTS) .set(ACCOUNT_AUDIT_RECEIPTS.LOG_EVENT_ID, logEventId) .set(ACCOUNT_AUDIT_RECEIPTS.RECEIPT_ID, receiptId) .set(ACCOUNT_AUDIT_RECEIPTS.SCOPE, request.scope().databaseValue()) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_IDENTITY_VERSION, request.tenantIdentityVersion()) .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_ID, request.tenantId()) - .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY, tenantKey) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY, tenantKey(request)) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_UUID, request.tenantUuid()) .set(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID, request.auditEventId()) .set(ACCOUNT_AUDIT_RECEIPTS.PRODUCER_SERVICE, request.producerService()) .set(ACCOUNT_AUDIT_RECEIPTS.EVENT_TYPE, request.eventType()) @@ -54,7 +55,7 @@ public AccountAuditReceiptInsertResult insertIfAbsent( .onConflictDoNothing() .execute(); AccountAuditReceipt receipt = - findByIdentity(request, tenantKey) + findByIdentity(request) .orElseThrow( () -> new IllegalStateException( @@ -63,11 +64,12 @@ public AccountAuditReceiptInsertResult insertIfAbsent( } private long insertOrFindProjection(CreateLogEventRequest request) { - Long tenantKey = request.tenantId() == null ? Long.valueOf(0L) : request.tenantId(); dsl.insertInto(LOG_EVENTS) .set(LOG_EVENTS.SCOPE, request.scope().databaseValue()) + .set(LOG_EVENTS.TENANT_IDENTITY_VERSION, request.tenantIdentityVersion()) .set(LOG_EVENTS.TENANT_ID, request.tenantId()) - .set(LOG_EVENTS.TENANT_KEY, tenantKey) + .set(LOG_EVENTS.TENANT_KEY, tenantKey(request)) + .set(LOG_EVENTS.TENANT_UUID, request.tenantUuid()) .set(LOG_EVENTS.AUDIT_EVENT_ID, request.auditEventId()) .set(LOG_EVENTS.TYPE, ACCOUNT_AUDIT_PROJECTION_TYPE) .set(LOG_EVENTS.MESSAGE, ACCOUNT_AUDIT_PROJECTION_MESSAGE_PREFIX + request.auditEventId()) @@ -76,38 +78,47 @@ private long insertOrFindProjection(CreateLogEventRequest request) { .onConflictDoNothing() .execute(); - var tenantCondition = - request.tenantId() == null - ? LOG_EVENTS.TENANT_ID.isNull() - : LOG_EVENTS.TENANT_ID.eq(request.tenantId()); + var identityCondition = + LOG_EVENTS + .SCOPE + .eq(request.scope().databaseValue()) + .and(LOG_EVENTS.TENANT_IDENTITY_VERSION.eq(request.tenantIdentityVersion())) + .and(LOG_EVENTS.AUDIT_EVENT_ID.eq(request.auditEventId())); + identityCondition = + request.tenantIdentityVersion() == 1 + ? identityCondition.and(LOG_EVENTS.TENANT_KEY.eq(tenantKey(request))) + : identityCondition.and(LOG_EVENTS.TENANT_UUID.eq(request.tenantUuid())); Long logEventId = - dsl.select(LOG_EVENTS.ID) - .from(LOG_EVENTS) - .where( - LOG_EVENTS - .SCOPE - .eq(request.scope().databaseValue()) - .and(tenantCondition) - .and(LOG_EVENTS.AUDIT_EVENT_ID.eq(request.auditEventId()))) - .fetchOne(LOG_EVENTS.ID); + dsl.select(LOG_EVENTS.ID).from(LOG_EVENTS).where(identityCondition).fetchOne(LOG_EVENTS.ID); if (logEventId == null) { throw new IllegalStateException("Account audit projection identity did not resolve"); } return logEventId; } - public Optional findByIdentity( - CreateLogEventRequest request, long tenantKey) { + public Optional findByIdentity(CreateLogEventRequest request) { + var identityCondition = + ACCOUNT_AUDIT_RECEIPTS + .SCOPE + .eq(request.scope().databaseValue()) + .and(ACCOUNT_AUDIT_RECEIPTS.TENANT_IDENTITY_VERSION.eq(request.tenantIdentityVersion())) + .and(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(request.auditEventId())); + identityCondition = + request.tenantIdentityVersion() == 1 + ? identityCondition.and(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY.eq(tenantKey(request))) + : identityCondition.and(ACCOUNT_AUDIT_RECEIPTS.TENANT_UUID.eq(request.tenantUuid())); return dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) - .where( - ACCOUNT_AUDIT_RECEIPTS - .SCOPE - .eq(request.scope().databaseValue()) - .and(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY.eq(tenantKey)) - .and(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(request.auditEventId()))) + .where(identityCondition) .fetchOptional(this::toEntity); } + private static Long tenantKey(CreateLogEventRequest request) { + if (request.tenantIdentityVersion() != 1) { + return null; + } + return request.tenantId() == null ? Long.valueOf(0L) : request.tenantId(); + } + private AccountAuditReceipt toEntity(Record record) { AccountAuditReceiptsRecord receiptRecord = (AccountAuditReceiptsRecord) record; return new AccountAuditReceipt( @@ -115,7 +126,9 @@ private AccountAuditReceipt toEntity(Record record) { receiptRecord.getLogEventId(), receiptRecord.getReceiptId(), receiptRecord.getScope(), + receiptRecord.getTenantIdentityVersion(), receiptRecord.getTenantId(), + receiptRecord.getTenantUuid(), receiptRecord.getAuditEventId(), receiptRecord.getProducerService(), receiptRecord.getEventType(), diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java index 630124a3f9..72ebc2ae31 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java @@ -35,6 +35,7 @@ public class LogEventServiceImpl implements LogEventService { private static final Logger logger = LoggingUtil.getLogger(LogEventServiceImpl.class); private static final String ACCOUNT_SERVICE = "account-service"; private static final String SHA_256_PREFIX = "sha256:"; + private static final UUID NIL_UUID = new UUID(0L, 0L); private final AccountAuditReceiptRepository repository; @@ -65,11 +66,8 @@ public AccountAuditReceiptDto readLogEventReceipt(CreateLogEventRequest request) validateExactPayload(request); } try { - long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); AccountAuditReceipt receipt = - repository - .findByIdentity(request, tenantKey) - .orElseThrow(AuditReceiptNotFoundException::new); + repository.findByIdentity(request).orElseThrow(AuditReceiptNotFoundException::new); return receiptOutcome(receipt, request, false, payloadSupplied); } catch (AuditReceiptNotFoundException ex) { throw ex; @@ -130,7 +128,9 @@ private static boolean metadataMatches( AccountAuditReceipt receipt, CreateLogEventRequest request) { Instant occurredAt = request.occurredAt(); return receipt.scope().equals(request.scope().databaseValue()) + && receipt.tenantIdentityVersion() == request.tenantIdentityVersion() && Objects.equals(receipt.tenantId(), request.tenantId()) + && Objects.equals(receipt.tenantUuid(), request.tenantUuid()) && receipt.auditEventId().equals(request.auditEventId()) && receipt.producerService().equals(request.producerService()) && receipt.eventType().equals(request.eventType()) @@ -149,7 +149,9 @@ private static AccountAuditReceiptDto toDto( "platform".equals(receipt.scope()) ? net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM : net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.TENANT, + receipt.tenantIdentityVersion(), receipt.tenantId(), + receipt.tenantUuid(), receipt.auditEventId(), receipt.receiptId().toString(), receipt.logEventId(), @@ -183,12 +185,29 @@ private static void validateEnvelopeMetadata(CreateLogEventRequest request) { if (!isCanonicalUuid(request.auditEventId())) { throw new IllegalArgumentException("auditEventId must be a canonical UUID"); } - if (request.scope() == net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM) { + if (request.tenantIdentityVersion() == 1) { + if (request.tenantUuid() != null) { + throw new IllegalArgumentException("tenantUuid must be absent for tenant identity v1"); + } + if (request.scope() == net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM) { + if (request.tenantId() != null) { + throw new IllegalArgumentException("tenantId must be absent for platform scope"); + } + } else if (request.tenantId() == null || request.tenantId() <= 0) { + throw new IllegalArgumentException("tenantId must be positive for tenant scope"); + } + } else if (request.tenantIdentityVersion() == 2) { + if (request.scope() != net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.TENANT) { + throw new IllegalArgumentException("tenant identity v2 requires tenant scope"); + } if (request.tenantId() != null) { - throw new IllegalArgumentException("tenantId must be absent for platform scope"); + throw new IllegalArgumentException("tenantId must be absent for tenant identity v2"); + } + if (request.tenantUuid() == null || NIL_UUID.equals(request.tenantUuid())) { + throw new IllegalArgumentException("tenantUuid must be a non-nil UUID for identity v2"); } - } else if (request.tenantId() == null || request.tenantId() <= 0) { - throw new IllegalArgumentException("tenantId must be positive for tenant scope"); + } else { + throw new IllegalArgumentException("tenantIdentityVersion must be 1 or 2"); } if (request.payloadDigestVersion() != 1) { throw new IllegalArgumentException("payloadDigestVersion must be 1"); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java index d151caca53..b06d6935ff 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java @@ -47,6 +47,7 @@ public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdmi private static final Set MODERATION_POLICY_CALLERS = Set.of("game-session-service", "social-groups-service"); private static final String ACCOUNT_SERVICE = "account-service"; + private static final UUID NIL_UUID = new UUID(0L, 0L); private static final Map> ACCOUNT_AUDIT_CALLER_ALLOWLIST = Map.of( "CreateLogEvent", Set.of(ACCOUNT_SERVICE), @@ -215,7 +216,6 @@ public void createLogEvent( Status.PERMISSION_DENIED.withDescription(ex.getMessage()).asRuntimeException()); return; } - responseObserver.onError( Status.UNAVAILABLE .withDescription("Account audit ingress is unavailable") @@ -264,7 +264,9 @@ private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toA ReadLogEventReceiptRequest request) { return toAuditRequest( request.getScope(), + request.getTenantIdentityVersion(), request.getTenantId(), + request.getTenantUuid(), request.getAuditEventId(), request.getProducerService(), request.getEventType(), @@ -277,7 +279,9 @@ private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toA private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( net.firedevops.firemud.loggingadmin.v1.AccountAuditScope requestScope, + int tenantIdentityVersion, String tenantIdText, + String tenantUuidText, String auditEventId, String producerService, String eventType, @@ -292,14 +296,27 @@ private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toA case ACCOUNT_AUDIT_SCOPE_TENANT -> AccountAuditScope.TENANT; default -> throw new IllegalArgumentException("scope must be platform or tenant"); }; - Long tenantId; - if (scope == AccountAuditScope.TENANT) { - tenantId = RequestIdValidation.requirePositiveLong(tenantIdText, "tenantId"); - } else { - if (!tenantIdText.isEmpty()) { + Long tenantId = null; + UUID tenantUuid = null; + if (tenantIdentityVersion == 1) { + if (!tenantUuidText.isEmpty()) { + throw new IllegalArgumentException("tenantUuid must be absent for tenant identity v1"); + } + if (scope == AccountAuditScope.TENANT) { + tenantId = parseCanonicalTenantId(tenantIdText); + } else if (!tenantIdText.isEmpty()) { throw new IllegalArgumentException("tenantId must be absent for platform scope"); } - tenantId = null; + } else if (tenantIdentityVersion == 2) { + if (scope != AccountAuditScope.TENANT) { + throw new IllegalArgumentException("tenant identity v2 requires tenant scope"); + } + if (!tenantIdText.isEmpty()) { + throw new IllegalArgumentException("tenantId must be absent for tenant identity v2"); + } + tenantUuid = parseCanonicalTenantUuid(tenantUuidText); + } else { + throw new IllegalArgumentException("tenantIdentityVersion must be 1 or 2"); } if (!ACCOUNT_SERVICE.equals(producerService)) { throw new IllegalArgumentException( @@ -316,7 +333,9 @@ private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toA } return new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( scope, + tenantIdentityVersion, tenantId, + tenantUuid, auditEventId, ACCOUNT_SERVICE, eventType, @@ -327,6 +346,34 @@ private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toA payloadDigest); } + private static Long parseCanonicalTenantId(String tenantIdText) { + if (tenantIdText == null || !tenantIdText.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("tenantId must be a canonical positive BIGINT decimal"); + } + try { + return Long.parseLong(tenantIdText); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException("tenantId must fit a positive BIGINT", ex); + } + } + + private static UUID parseCanonicalTenantUuid(String tenantUuidText) { + if (tenantUuidText == null || tenantUuidText.isEmpty()) { + throw new IllegalArgumentException("tenantUuid is required for tenant identity v2"); + } + UUID tenantUuid; + try { + tenantUuid = UUID.fromString(tenantUuidText); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException( + "tenantUuid must be a canonical lowercase non-nil UUID", ex); + } + if (!tenantUuid.toString().equals(tenantUuidText) || NIL_UUID.equals(tenantUuid)) { + throw new IllegalArgumentException("tenantUuid must be a canonical lowercase non-nil UUID"); + } + return tenantUuid; + } + static CreateLogEventResponse toCreateLogEventResponse(AccountAuditReceiptDto receipt) { return CreateLogEventResponse.newBuilder() .setScope(toProtoScope(receipt.scope())) @@ -337,6 +384,8 @@ static CreateLogEventResponse toCreateLogEventResponse(AccountAuditReceiptDto re .setSchemaVersion(receipt.schemaVersion()) .setPayloadDigestVersion(receipt.payloadDigestVersion()) .setPayloadDigest(receipt.payloadDigest()) + .setTenantIdentityVersion(receipt.tenantIdentityVersion()) + .setTenantUuid(receipt.tenantUuid() == null ? "" : receipt.tenantUuid().toString()) .setStatus(toProtoStatus(receipt.status())) .setOutcome(toProtoOutcome(receipt.outcome())) .setAuditProjectionVersion(1) @@ -354,6 +403,8 @@ private static ReadLogEventReceiptResponse toReadLogEventReceiptResponse( .setSchemaVersion(receipt.schemaVersion()) .setPayloadDigestVersion(receipt.payloadDigestVersion()) .setPayloadDigest(receipt.payloadDigest()) + .setTenantIdentityVersion(receipt.tenantIdentityVersion()) + .setTenantUuid(receipt.tenantUuid() == null ? "" : receipt.tenantUuid().toString()) .setStatus(toProtoStatus(receipt.status())) .setOutcome(toProtoOutcome(receipt.outcome())) .setAuditProjectionVersion(1) diff --git a/services/logging-admin-service/src/main/resources/db/migration/V3.1__canonical_uuid_account_audit_identity.sql b/services/logging-admin-service/src/main/resources/db/migration/V3.1__canonical_uuid_account_audit_identity.sql new file mode 100644 index 0000000000..4405e77e00 --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V3.1__canonical_uuid_account_audit_identity.sql @@ -0,0 +1,140 @@ +ALTER TABLE log_events + ADD COLUMN tenant_identity_version INTEGER; + +ALTER TABLE log_events + ADD COLUMN tenant_uuid UUID; + +UPDATE log_events +SET tenant_identity_version = 1 +WHERE audit_event_id IS NOT NULL; + +ALTER TABLE log_events + ALTER COLUMN tenant_key DROP NOT NULL; + +ALTER TABLE log_events + DROP CONSTRAINT chk_log_events_scope_tenant; + +ALTER TABLE log_events + ADD CONSTRAINT chk_log_events_scope_tenant + CHECK ( + ( + audit_event_id IS NULL + AND tenant_identity_version IS NULL + AND tenant_uuid IS NULL + AND ( + ( + scope = 'platform' + AND tenant_id IS NULL + AND tenant_key IS NOT NULL + AND tenant_key = 0 + ) + OR ( + scope = 'tenant' + AND tenant_id IS NOT NULL + AND tenant_key IS NOT NULL + AND tenant_key IN (0, tenant_id) + ) + ) + ) + OR ( + audit_event_id IS NOT NULL + AND tenant_identity_version IS NOT NULL + AND ( + ( + tenant_identity_version = 1 + AND tenant_uuid IS NULL + AND ( + ( + scope = 'platform' + AND tenant_id IS NULL + AND tenant_key IS NOT NULL + AND tenant_key = 0 + ) + OR ( + scope = 'tenant' + AND tenant_id IS NOT NULL + AND tenant_id > 0 + AND tenant_key IS NOT NULL + AND tenant_key = tenant_id + ) + ) + ) + OR ( + tenant_identity_version = 2 + AND scope = 'tenant' + AND tenant_id IS NULL + AND tenant_key IS NULL + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + ) + ) + ) + ) /* [jooq ignore start] */ NOT VALID /* [jooq ignore stop] */; + +ALTER INDEX uq_log_events_account_audit_identity + RENAME TO uq_log_events_account_audit_v1_identity; + +CREATE UNIQUE INDEX uq_log_events_account_audit_v2_identity + ON log_events (scope, tenant_uuid, audit_event_id) + WHERE audit_event_id IS NOT NULL AND tenant_identity_version = 2; + +ALTER TABLE account_audit_receipts + ADD COLUMN tenant_identity_version INTEGER; + +ALTER TABLE account_audit_receipts + ADD COLUMN tenant_uuid UUID; + +UPDATE account_audit_receipts +SET tenant_identity_version = 1; + +ALTER TABLE account_audit_receipts + ALTER COLUMN tenant_key DROP NOT NULL; + +ALTER TABLE account_audit_receipts + DROP CONSTRAINT chk_account_audit_receipt_scope; + +ALTER TABLE account_audit_receipts + ALTER COLUMN tenant_identity_version SET NOT NULL; + +ALTER TABLE account_audit_receipts + ADD CONSTRAINT chk_account_audit_receipt_scope + CHECK ( + ( + tenant_identity_version = 1 + AND tenant_uuid IS NULL + AND ( + ( + scope = 'platform' + AND tenant_id IS NULL + AND tenant_key IS NOT NULL + AND tenant_key = 0 + ) + OR ( + scope = 'tenant' + AND tenant_id IS NOT NULL + AND tenant_id > 0 + AND tenant_key IS NOT NULL + AND tenant_key = tenant_id + ) + ) + ) + OR ( + tenant_identity_version = 2 + AND scope = 'tenant' + AND tenant_id IS NULL + AND tenant_key IS NULL + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + ) + ) /* [jooq ignore start] */ NOT VALID /* [jooq ignore stop] */; + +ALTER INDEX uq_account_audit_receipt_identity + RENAME TO uq_account_audit_receipt_v1_identity; + +CREATE UNIQUE INDEX uq_account_audit_receipt_v2_identity + ON account_audit_receipts (scope, tenant_uuid, audit_event_id) + WHERE tenant_identity_version = 2; + +CREATE INDEX idx_account_audit_receipts_tenant_uuid_event + ON account_audit_receipts (tenant_uuid, audit_event_id) + WHERE tenant_identity_version = 2; diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/CanonicalAuditIdentityMigrationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/CanonicalAuditIdentityMigrationIntegrationTest.java new file mode 100644 index 0000000000..b83b1bdd20 --- /dev/null +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/CanonicalAuditIdentityMigrationIntegrationTest.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.loggingadmin; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class CanonicalAuditIdentityMigrationIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void versionThreePointOnePreservesRetainedVersionOneReceiptAndProjectionBytes() + throws SQLException { + migrateThrough("3"); + String eventId = "6ca11f0d-72e3-4c3f-b745-679775108404"; + UUID receiptId = UUID.fromString("ef23c682-65f9-4b4d-9ed8-071f8b29aa4f"); + byte[] payload = + "{\"retained\":\"exact-v1-bytes\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8); + List projectionBefore; + List receiptBefore; + + try (Connection connection = connection()) { + insertVersionOneRows(connection, eventId, receiptId, payload); + projectionBefore = readProjection(connection, eventId); + receiptBefore = readReceipt(connection, eventId); + } + + migrateThrough("3.1"); + + try (Connection connection = connection()) { + assertThat(readProjection(connection, eventId)).containsExactlyElementsOf(projectionBefore); + assertThat(readReceipt(connection, eventId)).containsExactlyElementsOf(receiptBefore); + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT tenant_identity_version, tenant_uuid FROM log_events " + + "WHERE audit_event_id = ?"); + PreparedStatement receiptStatement = + connection.prepareStatement( + "SELECT tenant_identity_version, tenant_uuid, payload FROM account_audit_receipts " + + "WHERE audit_event_id = ?")) { + statement.setString(1, eventId); + receiptStatement.setString(1, eventId); + try (ResultSet projection = statement.executeQuery(); + ResultSet receipt = receiptStatement.executeQuery()) { + assertThat(projection.next()).isTrue(); + assertThat(projection.getInt(1)).isEqualTo(1); + assertThat(projection.getObject(2)).isNull(); + assertThat(receipt.next()).isTrue(); + assertThat(receipt.getInt(1)).isEqualTo(1); + assertThat(receipt.getObject(2)).isNull(); + assertThat(receipt.getBytes(3)).containsExactly(payload); + } + } + } + } + + private static void migrateThrough(String target) { + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas("logging_admin_service") + .defaultSchema("logging_admin_service") + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion(target)) + .load() + .migrate(); + } + + private static Connection connection() throws SQLException { + Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + connection.setSchema("logging_admin_service"); + return connection; + } + + private static void insertVersionOneRows( + Connection connection, String eventId, UUID receiptId, byte[] payload) throws SQLException { + long logEventId; + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO log_events " + + "(tenant_id, scope, tenant_key, audit_event_id, type, message, timestamp) " + + "VALUES (42, 'tenant', 42, ?, 'ACCOUNT_AUDIT', ?, ?) RETURNING id")) { + statement.setString(1, eventId); + statement.setString(2, "Account audit event " + eventId); + statement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.of(2026, 9, 24, 0, 0))); + try (ResultSet result = statement.executeQuery()) { + result.next(); + logEventId = result.getLong(1); + } + } + + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO account_audit_receipts " + + "(log_event_id, receipt_id, scope, tenant_id, tenant_key, audit_event_id, " + + "producer_service, event_type, occurred_at_seconds, occurred_at_nanos, " + + "schema_version, payload_digest_version, payload_digest, payload, status, outcome) " + + "VALUES (?, ?, 'tenant', 42, 42, ?, 'account-service', 'ACCOUNT_REGISTERED', " + + "1790208000, 123456789, 1, 1, ?, ?, 'COMMITTED', 'ACCEPTED')")) { + statement.setLong(1, logEventId); + statement.setObject(2, receiptId); + statement.setString(3, eventId); + statement.setString(4, "sha256:" + "a".repeat(64)); + statement.setBytes(5, payload); + statement.executeUpdate(); + } + } + + private static List readProjection(Connection connection, String eventId) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT id, tenant_id, scope, tenant_key, audit_event_id, type, message, timestamp, " + + "account_id FROM log_events WHERE audit_event_id = ?")) { + statement.setString(1, eventId); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + return readRow(result, 9); + } + } + } + + private static List readReceipt(Connection connection, String eventId) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT id, log_event_id, receipt_id, scope, tenant_id, tenant_key, audit_event_id, " + + "producer_service, event_type, occurred_at_seconds, occurred_at_nanos, " + + "schema_version, payload_digest_version, payload_digest, payload, status, outcome, " + + "created_at FROM account_audit_receipts WHERE audit_event_id = ?")) { + statement.setString(1, eventId); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + List fields = readRow(result, 18); + fields.set(14, HexFormat.of().formatHex((byte[]) fields.get(14))); + return fields; + } + } + } + + private static List readRow(ResultSet result, int fieldCount) throws SQLException { + List fields = new ArrayList<>(fieldCount); + for (int column = 1; column <= fieldCount; column++) { + fields.add(result.getObject(column)); + } + return fields; + } +} diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAccountUuidMigrationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAccountUuidMigrationIntegrationTest.java index 3741570201..09ea61e0b3 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAccountUuidMigrationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAccountUuidMigrationIntegrationTest.java @@ -35,6 +35,10 @@ @SuppressWarnings("resource") class LoggingAccountUuidMigrationIntegrationTest { private static final String MIGRATION_LOCATION = "classpath:db/migration"; + private static final List EXPECTED_LATEST_MIGRATION_VERSIONS = + List.of("1", "2", "3", "3.1", "4", "5", "6", "1000", "1001", "1002"); + private static final List EXPECTED_MIGRATION_VERSIONS_THROUGH_V5 = + List.of("1", "2", "3", "3.1", "4", "5"); @Container static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -54,7 +58,8 @@ void freshSchemaMigratesWithCanonicalAccountUuidsAndNumericLocalIdentifiers() th assertThat(columnType(schema, "player_reports", "id")).isEqualTo("int8"); assertThat(columnType(schema, "log_events", "account_id")).isEqualTo("int8"); // Runtime discovery includes Saga migrations V1000–V1002 after service migration V6. - assertThat(history(schema)).hasSize(9); + assertThat(historyVersions(schema)) + .containsExactlyElementsOf(EXPECTED_LATEST_MIGRATION_VERSIONS); } @Test @@ -79,7 +84,8 @@ void emptyAffectedTablesUpgradeFromV5AndGenericLogAccountIdRemainsNumeric() thro schema, "SELECT account_id FROM log_events WHERE message = 'preserve generic log'")) .isEqualTo(42L); // The fixture applies the same Saga migrations as the full runtime discovery. - assertThat(history(schema)).hasSize(9); + assertThat(historyVersions(schema)) + .containsExactlyElementsOf(EXPECTED_LATEST_MIGRATION_VERSIONS); } @Test @@ -186,7 +192,8 @@ void migrationWaitsForConcurrentWriterAndRefusesAfterItsRowCommits() throws Exce assertThrows(ExecutionException.class, () -> migration.get(10, TimeUnit.SECONDS)); assertThat(failure).hasStackTraceContaining("Account-owned recovery is required"); assertThat(history(schema)).isEqualTo(historyBefore); - assertThat(history(schema)).hasSize(5); + assertThat(historyVersions(schema)) + .containsExactlyElementsOf(EXPECTED_MIGRATION_VERSIONS_THROUGH_V5); assertThat(columnType(schema, "moderation_actions", "account_id")).isEqualTo("int8"); assertThat(scalarLong(schema, "SELECT count(*) FROM moderation_actions")).isEqualTo(1L); assertThat( @@ -284,6 +291,10 @@ private static List history(String schema) throws SQLException { return entries; } + private static List historyVersions(String schema) throws SQLException { + return history(schema).stream().map(entry -> entry.substring(0, entry.indexOf(':'))).toList(); + } + private static List rows(String schema, String table) throws SQLException { List records = new ArrayList<>(); try (Connection connection = connection(); diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index 20da86ad93..567c296829 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -155,6 +155,117 @@ void accountAuditReceiptAndProjectionShareStableIdentityAcrossRetryAndConflict() .containsExactly("Account audit event " + eventId); } + @Test + void canonicalUuidReceiptIsIsolatedFromRetainedNumericIdentityAndMinimizesSafely() { + String eventId = "a4e2f840-e844-46a7-8d30-8d17a220ce44"; + UUID tenantUuid = UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21"); + String payload = "{\"accountId\":95,\"auditMarker\":\"uuid-retry-proof\"}"; + CreateLogEventRequest numericRequest = tenantAuditRequest(eventId, payload); + CreateLogEventRequest uuidRequest = uuidTenantAuditRequest(eventId, tenantUuid, payload); + + var retainedNumeric = logEventService.createLogEvent(numericRequest); + var acceptedUuid = logEventService.createLogEvent(uuidRequest); + var duplicateUuid = logEventService.createLogEvent(uuidRequest); + var conflictUuid = + logEventService.createLogEvent( + uuidTenantAuditRequest(eventId, tenantUuid, "{\"changed\":true}")); + var readback = logEventService.readLogEventReceipt(uuidRequest); + + assertThat(acceptedUuid.tenantIdentityVersion()).isEqualTo(2); + assertThat(acceptedUuid.tenantId()).isNull(); + assertThat(acceptedUuid.tenantUuid()).isEqualTo(tenantUuid); + assertThat(duplicateUuid.outcome()).isEqualTo(AccountAuditReceiptOutcome.DUPLICATE); + assertThat(duplicateUuid.receiptId()).isEqualTo(acceptedUuid.receiptId()); + assertThat(conflictUuid.status()).isEqualTo(AccountAuditReceiptStatus.CONFLICT); + assertThat(readback.tenantUuid()).isEqualTo(tenantUuid); + assertThat(readback.logEventId()).isEqualTo(acceptedUuid.logEventId()); + assertThat(acceptedUuid.logEventId()).isNotEqualTo(retainedNumeric.logEventId()); + + LogEventsRecord numericProjection = + dsl.selectFrom(LOG_EVENTS).where(LOG_EVENTS.ID.eq(retainedNumeric.logEventId())).fetchOne(); + LogEventsRecord uuidProjection = + dsl.selectFrom(LOG_EVENTS).where(LOG_EVENTS.ID.eq(acceptedUuid.logEventId())).fetchOne(); + AccountAuditReceiptsRecord uuidReceipt = + dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) + .where(ACCOUNT_AUDIT_RECEIPTS.RECEIPT_ID.eq(UUID.fromString(acceptedUuid.receiptId()))) + .fetchOne(); + assertThat(numericProjection.getTenantId()).isEqualTo(42L); + assertThat(numericProjection.getTenantKey()).isEqualTo(42L); + assertThat(numericProjection.getTenantIdentityVersion()).isEqualTo(1); + assertThat(numericProjection.getTenantUuid()).isNull(); + assertThat(uuidProjection.getTenantId()).isNull(); + assertThat(uuidProjection.getTenantKey()).isNull(); + assertThat(uuidProjection.getTenantIdentityVersion()).isEqualTo(2); + assertThat(uuidProjection.getTenantUuid()).isEqualTo(tenantUuid); + assertThat(uuidProjection.getMessage()).isEqualTo("Account audit event " + eventId); + assertThat(uuidProjection.getMessage()).doesNotContain("accountId", "uuid-retry-proof"); + assertThat(uuidReceipt.getTenantId()).isNull(); + assertThat(uuidReceipt.getTenantKey()).isNull(); + assertThat(uuidReceipt.getTenantUuid()).isEqualTo(tenantUuid); + assertThat(uuidReceipt.getPayload()).isEqualTo(payload.getBytes(StandardCharsets.UTF_8)); + assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isEqualTo(2); + assertThat(logQueryService.queryLogs(new QueryLogsRequest(42L, eventId))) + .containsExactly("Account audit event " + eventId); + + dsl.update(ACCOUNT_AUDIT_RECEIPTS) + .set(ACCOUNT_AUDIT_RECEIPTS.PAYLOAD, (byte[]) null) + .set(ACCOUNT_AUDIT_RECEIPTS.STATUS, "MINIMIZED") + .set(ACCOUNT_AUDIT_RECEIPTS.OUTCOME, "NON_REPLAYABLE") + .where(ACCOUNT_AUDIT_RECEIPTS.RECEIPT_ID.eq(UUID.fromString(acceptedUuid.receiptId()))) + .execute(); + + var minimizedReadback = logEventService.readLogEventReceipt(uuidRequest); + assertThat(minimizedReadback.tenantIdentityVersion()).isEqualTo(2); + assertThat(minimizedReadback.tenantUuid()).isEqualTo(tenantUuid); + assertThat(minimizedReadback.status()).isEqualTo(AccountAuditReceiptStatus.MINIMIZED); + assertThat(minimizedReadback.outcome()).isEqualTo(AccountAuditReceiptOutcome.NON_REPLAYABLE); + assertThat(uuidProjection.getMessage()).doesNotContain(payload); + } + + @Test + void malformedPersistedIdentityCannotBypassDatabaseChecksOrGrowProjectionRows() { + int before = dsl.fetchCount(LOG_EVENTS); + + assertThatThrownBy( + () -> + insertMalformedProjection( + "b7abbe36-8a74-4527-b0d7-c3117de24001", null, 42L, null, 42L)) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_log_events_scope_tenant"); + assertThatThrownBy( + () -> + insertMalformedProjection( + "b7abbe36-8a74-4527-b0d7-c3117de24002", 1, 42L, null, null)) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_log_events_scope_tenant"); + assertThatThrownBy( + () -> + insertMalformedProjection( + "b7abbe36-8a74-4527-b0d7-c3117de24003", 2, null, new UUID(0L, 0L), null)) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_log_events_scope_tenant"); + assertThatThrownBy(() -> insertMalformedProjection(null, null, 42L, null, null)) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_log_events_scope_tenant"); + + assertThat(dsl.fetchCount(LOG_EVENTS)).isEqualTo(before); + } + + private void insertMalformedProjection( + String eventId, Integer identityVersion, Long tenantId, UUID tenantUuid, Long tenantKey) { + dsl.insertInto(LOG_EVENTS) + .set(LOG_EVENTS.SCOPE, "tenant") + .set(LOG_EVENTS.TENANT_IDENTITY_VERSION, identityVersion) + .set(LOG_EVENTS.TENANT_ID, tenantId) + .set(LOG_EVENTS.TENANT_KEY, tenantKey) + .set(LOG_EVENTS.TENANT_UUID, tenantUuid) + .set(LOG_EVENTS.AUDIT_EVENT_ID, eventId) + .set(LOG_EVENTS.TYPE, "ACCOUNT_AUDIT") + .set(LOG_EVENTS.MESSAGE, "Account audit event " + eventId) + .set(LOG_EVENTS.TIMESTAMP, LocalDateTime.now()) + .execute(); + } + @Test void auditEventIdHasDistinctPlatformAndTenantReceiptIdentities() { String eventId = "9a25cba0-b6f3-40c2-82ec-4ffcad2f2081"; @@ -267,10 +378,43 @@ void receiptFailureRollsBackTheAlreadyInsertedAuditProjection() { } } + @Test + void canonicalUuidReceiptFailureRollsBackItsProjection() { + String eventId = "58d4fb8a-0910-42ab-8af1-80cf8c81b26a"; + UUID tenantUuid = UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21"); + dsl.execute( + "CREATE OR REPLACE FUNCTION fail_test_account_audit_receipt() RETURNS trigger " + + "LANGUAGE plpgsql AS $$ BEGIN IF NEW.audit_event_id = '" + + eventId + + "' THEN RAISE EXCEPTION 'injected receipt insert failure'; END IF; RETURN NEW; END $$"); + dsl.execute( + "CREATE TRIGGER fail_test_account_audit_receipt BEFORE INSERT ON account_audit_receipts " + + "FOR EACH ROW EXECUTE FUNCTION fail_test_account_audit_receipt()"); + try { + assertThatThrownBy( + () -> + logEventService.createLogEvent( + uuidTenantAuditRequest( + eventId, tenantUuid, "{\"auditMarker\":\"rollback\"}"))) + .isInstanceOf(AuditStorageUnavailableException.class); + assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isZero(); + assertThat( + dsl.fetchCount( + ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) + .isZero(); + } finally { + dsl.execute( + "DROP TRIGGER IF EXISTS fail_test_account_audit_receipt ON account_audit_receipts"); + dsl.execute("DROP FUNCTION IF EXISTS fail_test_account_audit_receipt()"); + } + } + @Test void concurrentExactRetriesCreateOneProjectionAndReturnTheSameIdentifiers() throws Exception { String eventId = "4b7d9ee5-62f5-44dd-8b35-dcf6490d7404"; - CreateLogEventRequest request = tenantAuditRequest(eventId, "{\"accountId\":94}"); + CreateLogEventRequest request = + uuidTenantAuditRequest( + eventId, UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21"), "{\"accountId\":94}"); CountDownLatch start = new CountDownLatch(1); ExecutorService executor = Executors.newFixedThreadPool(2); try { @@ -296,7 +440,7 @@ void concurrentExactRetriesCreateOneProjectionAndReturnTheSameIdentifiers() thro } @Test - void v3ThroughV5PreserveRetainedRowsAndEnforceNewReceiptAndProjectionChecks() { + void v3ThroughV6PreserveRetainedRowsAndEnforceNewReceiptAndProjectionChecks() { String schema = "logging_admin_migration_" + UUID.randomUUID().toString().replace("-", ""); UUID retainedInvalidReceiptId = UUID.fromString("30000000-0000-4000-8000-000000000002"); String retainedInvalidDigest = "sha256:" + "g".repeat(64); @@ -464,6 +608,18 @@ void v3ThroughV5PreserveRetainedRowsAndEnforceNewReceiptAndProjectionChecks() { "ACCOUNT_AUDIT", "retained zero tenant projection", LocalDateTime.of(2025, 3, 1, 15, 0))); + assertThat( + dsl.fetch( + "SELECT tenant_identity_version, tenant_uuid FROM " + + schema + + ".log_events WHERE message IN (?, ?) ORDER BY message", + "retained negative tenant projection", + "retained zero tenant projection")) + .allSatisfy( + row -> { + assertThat(row.get("tenant_identity_version", Integer.class)).isEqualTo(1); + assertThat(row.get("tenant_uuid", UUID.class)).isNull(); + }); assertThat( dsl.fetchSingle("SELECT COUNT(*) FROM " + schema + ".account_audit_receipts") .get(0, Integer.class)) @@ -630,7 +786,8 @@ void v3ThroughV5PreserveRetainedRowsAndEnforceNewReceiptAndProjectionChecks() { dsl.execute( "INSERT INTO " + schema - + ".log_events (tenant_id, type, message, timestamp) VALUES (?, ?, ?, ?)", + + ".log_events (scope, tenant_id, tenant_key, tenant_identity_version, tenant_uuid, " + + "type, message, timestamp) VALUES ('tenant', ?, 0, NULL, NULL, ?, ?, ?)", 84L, "PAYMENT", "legacy insert", @@ -656,8 +813,8 @@ void v3ThroughV5PreserveRetainedRowsAndEnforceNewReceiptAndProjectionChecks() { dsl.execute( "INSERT INTO " + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " - + "VALUES (?, ?, ?, ?, ?, ?)", + + ".log_events (scope, tenant_id, tenant_key, tenant_identity_version, tenant_uuid, " + + "audit_event_id, type, message) VALUES (?, ?, ?, 1, NULL, ?, ?, ?)", "tenant", 86L, 86L, @@ -674,8 +831,9 @@ void v3ThroughV5PreserveRetainedRowsAndEnforceNewReceiptAndProjectionChecks() { dsl.execute( "INSERT INTO " + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " - + "VALUES ('platform', NULL, 0, '60000000-0000-4000-8000-000000000002', " + + ".log_events (scope, tenant_id, tenant_key, tenant_identity_version, tenant_uuid, " + + "audit_event_id, type, message) " + + "VALUES ('platform', NULL, 0, 1, NULL, '60000000-0000-4000-8000-000000000002', " + "'ACCOUNT_AUDIT', 'Account audit event 60000000-0000-4000-8000-000000000002')"); assertThat( dsl.fetchSingle( @@ -696,13 +854,14 @@ void v3ThroughV5PreserveRetainedRowsAndEnforceNewReceiptAndProjectionChecks() { dsl.execute( "INSERT INTO " + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " - + "VALUES ('tenant', ?, ?, ?, 'ACCOUNT_AUDIT', 'invalid tenant projection')", + + ".log_events (scope, tenant_id, tenant_key, tenant_identity_version, " + + "tenant_uuid, audit_event_id, type, message) " + + "VALUES ('tenant', ?, ?, 1, NULL, ?, 'ACCOUNT_AUDIT', 'invalid tenant projection')", invalidTenantId, invalidTenantId, eventId)) .isInstanceOf(DataIntegrityViolationException.class) - .hasMessageContaining("chk_log_events_tenant_audit_positive_tenant_id"); + .hasMessageContaining("chk_log_events_scope_tenant"); assertThatThrownBy( () -> dsl.execute( @@ -714,7 +873,7 @@ void v3ThroughV5PreserveRetainedRowsAndEnforceNewReceiptAndProjectionChecks() { invalidTenantId, "60000000-0000-4000-8000-000000000001")) .isInstanceOf(DataIntegrityViolationException.class) - .hasMessageContaining("chk_log_events_tenant_audit_positive_tenant_id"); + .hasMessageContaining("chk_log_events_scope_tenant"); } assertThat( dsl.fetchSingle( @@ -729,8 +888,9 @@ void v3ThroughV5PreserveRetainedRowsAndEnforceNewReceiptAndProjectionChecks() { dsl.execute( "INSERT INTO " + schema - + ".log_events (scope, tenant_id, tenant_key, type, message) " - + "VALUES ('tenant', ?, 0, 'PAYMENT', 'new non-audit legacy row')", + + ".log_events (scope, tenant_id, tenant_key, tenant_identity_version, tenant_uuid, " + + "type, message) VALUES ('tenant', ?, 0, NULL, NULL, 'PAYMENT', " + + "'new non-audit legacy row')", legacyTenantId); } @@ -739,8 +899,9 @@ void v3ThroughV5PreserveRetainedRowsAndEnforceNewReceiptAndProjectionChecks() { dsl.execute( "INSERT INTO " + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " - + "VALUES ('tenant', 73, 74, '50000000-0000-4000-8000-000000000001', " + + ".log_events (scope, tenant_id, tenant_key, tenant_identity_version, " + + "tenant_uuid, audit_event_id, type, message) " + + "VALUES ('tenant', 73, 74, 1, NULL, '50000000-0000-4000-8000-000000000001', " + "'ACCOUNT_AUDIT', 'mismatched key')")) .isInstanceOf(DataIntegrityViolationException.class) .hasMessageContaining("chk_log_events_scope_tenant"); @@ -762,14 +923,16 @@ private void insertMigrationReceipt( "WITH projection AS (" + "INSERT INTO " + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message, timestamp) " - + "VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id) " + + ".log_events (scope, tenant_id, tenant_key, tenant_identity_version, tenant_uuid, " + + "audit_event_id, type, message, timestamp) " + + "VALUES (?, ?, ?, 1, NULL, ?, ?, ?, ?) RETURNING id) " + "INSERT INTO " + schema - + ".account_audit_receipts (receipt_id, scope, tenant_id, tenant_key, audit_event_id, " - + "producer_service, event_type, occurred_at_seconds, occurred_at_nanos, schema_version, " + + ".account_audit_receipts (receipt_id, scope, tenant_id, tenant_key, " + + "tenant_identity_version, tenant_uuid, audit_event_id, producer_service, event_type, " + + "occurred_at_seconds, occurred_at_nanos, schema_version, " + "payload_digest_version, payload_digest, payload, status, outcome, log_event_id) " - + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS BYTEA), ?, ?, projection.id " + + "SELECT ?, ?, ?, ?, 1, NULL, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS BYTEA), ?, ?, projection.id " + "FROM projection", "tenant", 73L, @@ -841,12 +1004,15 @@ private void assertBackfilledReceipt( String timestamp) { var receipt = dsl.fetchOne( - "SELECT receipt.scope, receipt.tenant_id, receipt.tenant_key, receipt.audit_event_id, " + "SELECT receipt.scope, receipt.tenant_id, receipt.tenant_key, " + + "receipt.tenant_identity_version, receipt.tenant_uuid, receipt.audit_event_id, " + "receipt.receipt_id, receipt.producer_service, receipt.event_type, " + "receipt.occurred_at_seconds, receipt.occurred_at_nanos, receipt.schema_version, " + "receipt.payload_digest_version, receipt.payload, receipt.payload_digest, " + "receipt.status, receipt.outcome, receipt.log_event_id, event.id AS projection_id, " - + "event.type, event.message, event.timestamp, event.account_id FROM " + + "event.tenant_identity_version AS projection_identity_version, " + + "event.tenant_uuid AS projection_tenant_uuid, event.type, event.message, " + + "event.timestamp, event.account_id FROM " + schema + ".account_audit_receipts AS receipt JOIN " + schema @@ -857,6 +1023,8 @@ private void assertBackfilledReceipt( assertThat(receipt.get("scope", String.class)).isEqualTo(scope); assertThat(receipt.get("tenant_id", Long.class)).isEqualTo(tenantId); assertThat(receipt.get("tenant_key", Long.class)).isEqualTo(tenantId == null ? 0L : tenantId); + assertThat(receipt.get("tenant_identity_version", Integer.class)).isEqualTo(1); + assertThat(receipt.get("tenant_uuid", UUID.class)).isNull(); assertThat(receipt.get("audit_event_id", String.class)).isEqualTo(eventId); assertThat(receipt.get("receipt_id", UUID.class)).isEqualTo(UUID.fromString(receiptId)); assertThat(receipt.get("producer_service", String.class)).isEqualTo("account-service"); @@ -872,6 +1040,8 @@ private void assertBackfilledReceipt( assertThat(receipt.get("outcome", String.class)).isEqualTo(outcome); assertThat(receipt.get("log_event_id", Long.class)) .isEqualTo(receipt.get("projection_id", Long.class)); + assertThat(receipt.get("projection_identity_version", Integer.class)).isEqualTo(1); + assertThat(receipt.get("projection_tenant_uuid", UUID.class)).isNull(); assertThat(receipt.get("type", String.class)).isEqualTo("ACCOUNT_AUDIT"); assertThat(receipt.get("message", String.class)).isEqualTo("Account audit event " + eventId); assertThat(receipt.get("message", String.class)).doesNotContain("retained"); @@ -922,7 +1092,9 @@ private static CreateLogEventRequest auditRequest( ByteString payloadBytes = ByteString.copyFrom(payload, StandardCharsets.UTF_8); return new CreateLogEventRequest( scope, + 1, tenantId, + null, eventId, "account-service", "ACCOUNT_AUDIT_INTEGRATION_TEST", @@ -933,6 +1105,24 @@ private static CreateLogEventRequest auditRequest( digest(payloadBytes.toByteArray())); } + private static CreateLogEventRequest uuidTenantAuditRequest( + String eventId, UUID tenantUuid, String payload) { + ByteString payloadBytes = ByteString.copyFrom(payload, StandardCharsets.UTF_8); + return new CreateLogEventRequest( + AccountAuditScope.TENANT, + 2, + null, + tenantUuid, + eventId, + "account-service", + "ACCOUNT_AUDIT_INTEGRATION_TEST", + Instant.parse("2026-09-24T00:00:00Z"), + 1, + payloadBytes, + 1, + digest(payloadBytes.toByteArray())); + } + private static CreateLogEventRequest withOccurredAt( CreateLogEventRequest request, Instant occurredAt) { return auditRequest( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditCanonicalIdentityMtlsTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditCanonicalIdentityMtlsTest.java new file mode 100644 index 0000000000..e4db010c74 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditCanonicalIdentityMtlsTest.java @@ -0,0 +1,572 @@ +package net.firedevops.firemud.loggingadmin.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +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.nio.charset.StandardCharsets; +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.HexFormat; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptDto; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.dto.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.service.LogEventService; +import net.firedevops.firemud.loggingadmin.service.LogQueryService; +import net.firedevops.firemud.loggingadmin.service.ModerationService; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptResponse; +import net.firedevops.firemud.test.TlsTestSupport; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** Physical receiver transport, peer-certificate authorization, and wire-codec proof. */ +class AccountAuditCanonicalIdentityMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_PEER_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final Metadata.Key AUTHORIZATION = + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); + private static final UUID TENANT_UUID = UUID.fromString("e90c7b8a-3743-4f1c-9a03-a6e7c1d26211"); + private static final String PAYLOAD_TEXT = "canonical account audit payload"; + private static final String PAYLOAD_DIGEST = digest(PAYLOAD_TEXT); + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static TestPki pki; + + private LogEventService logEventService; + 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=Fresh Account Audit Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null); + pki = + new TestPki( + caCertificate, + issueLeaf(caName, caKeyPair.getPrivate(), "logging-admin-server", null), + issueLeaf(caName, caKeyPair.getPrivate(), "account-service", ACCOUNT_PEER_URI), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "game-session-service", + "spiffe://firemud/ns/test/sa/game-session-service"), + issueLeaf( + caName, + caKeyPair.getPrivate(), + "wrong-namespace-account-service", + "spiffe://firemud/ns/other-test/sa/account-service"), + issueLeaf(caName, caKeyPair.getPrivate(), "shared-workload-certificate", null)); + } + + @BeforeEach + void startPhysicalReceiver() throws Exception { + logEventService = mock(LogEventService.class); + // The exact-peer Create gate stays unavailable; Read returns an offline mock receipt fixture. + when(logEventService.readLogEventReceipt(any())) + .thenAnswer( + invocation -> + receipt(invocation.getArgument(0), "read", AccountAuditReceiptOutcome.DUPLICATE)); + + LoggingAdminGrpcService service = + new LoggingAdminGrpcService( + mock(LogQueryService.class), + logEventService, + mock(ModerationService.class), + new SimpleMeterRegistry(), + NAMESPACE); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.serverCertificate().getPrivateKey(), + pki.serverCertificate().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void canonicalUuidCreateIsUnavailableAndReadEchoesExactIdentityOverSocketMtls() throws Exception { + ManagedChannel channel = channel(pki.accountCertificate(), null); + try { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = stub(channel); + CreateLogEventRequest createRequest = request(2, "", TENANT_UUID.toString()); + ReadLogEventReceiptRequest readRequest = readRequest(createRequest); + + assertAccountAuditCreateUnavailable(() -> stub.createLogEvent(createRequest)); + ReadLogEventReceiptResponse read = stub.readLogEventReceipt(readRequest); + + assertMockSeededReceiptEvidence(read, readRequest); + assertReadServiceSawIdentity(2, null, TENANT_UUID); + } finally { + stopChannel(channel); + } + } + + @Test + void retainedV1NumericCreateIsUnavailableAndReadEchoesIdentityOverSocketMtls() throws Exception { + ManagedChannel channel = channel(pki.accountCertificate(), null); + try { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = stub(channel); + CreateLogEventRequest createRequest = request(1, "42", ""); + ReadLogEventReceiptRequest readRequest = readRequest(createRequest); + + assertAccountAuditCreateUnavailable(() -> stub.createLogEvent(createRequest)); + ReadLogEventReceiptResponse read = stub.readLogEventReceipt(readRequest); + + assertMockSeededReceiptEvidence(read, readRequest); + assertReadServiceSawIdentity(1, 42L, null); + } finally { + stopChannel(channel); + } + } + + @Test + void retainedV1PlatformCreateIsUnavailableAndReadEchoesIdentityOverSocketMtls() throws Exception { + ManagedChannel channel = channel(pki.accountCertificate(), null); + try { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = stub(channel); + CreateLogEventRequest createRequest = + request(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM, 1, "", ""); + ReadLogEventReceiptRequest readRequest = readRequest(createRequest); + + assertAccountAuditCreateUnavailable(() -> stub.createLogEvent(createRequest)); + ReadLogEventReceiptResponse read = stub.readLogEventReceipt(readRequest); + + assertMockSeededReceiptEvidence(read, readRequest); + assertReadServiceSawIdentity(1, null, null); + } finally { + stopChannel(channel); + } + } + + @Test + void missingClientCertificateIsRejectedByTls() throws Exception { + ManagedChannel channel = channel(null, null); + try { + assertTlsDenied(stub(channel), request(2, "", TENANT_UUID.toString())); + } finally { + stopChannel(channel); + } + verifyNoInteractions(logEventService); + } + + @Test + void wrongServiceValidCaCertificateCannotInvokeEitherAccountAuditMethod() throws Exception { + assertWrongWorkloadCannotInvokeEitherMethod(pki.wrongServiceCertificate()); + } + + @Test + void wrongNamespaceCertificateCannotInvokeEitherAccountAuditMethod() throws Exception { + assertWrongWorkloadCannotInvokeEitherMethod(pki.wrongNamespaceCertificate()); + } + + @Test + void sharedCertificateWithoutWorkloadUriCannotInvokeEitherAccountAuditMethod() throws Exception { + assertWrongWorkloadCannotInvokeEitherMethod(pki.noWorkloadUriCertificate()); + } + + @Test + void jwtOnlyCallerCannotBypassMissingClientCertificate() throws Exception { + Metadata headers = new Metadata(); + headers.put(AUTHORIZATION, "Bearer header.payload.signature"); + ManagedChannel channel = channel(null, headers); + try { + assertTlsDenied(stub(channel), request(2, "", TENANT_UUID.toString())); + } finally { + stopChannel(channel); + } + verifyNoInteractions(logEventService); + } + + @Test + void createGatePrecedesIdentityValidationAndReadRejectsMalformedIdentity() throws Exception { + ManagedChannel channel = channel(pki.accountCertificate(), null); + try { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = stub(channel); + CreateLogEventRequest mixedV1 = request(1, "42", TENANT_UUID.toString()); + CreateLogEventRequest unknownVersion = request(3, "", TENANT_UUID.toString()); + CreateLogEventRequest unsetVersion = request(0, "", ""); + + assertAccountAuditCreateUnavailable(() -> stub.createLogEvent(mixedV1)); + assertApplicationDeniedAsInvalidArgument( + () -> stub.readLogEventReceipt(readRequest(mixedV1))); + assertAccountAuditCreateUnavailable(() -> stub.createLogEvent(unknownVersion)); + assertApplicationDeniedAsInvalidArgument( + () -> stub.readLogEventReceipt(readRequest(unknownVersion))); + assertAccountAuditCreateUnavailable(() -> stub.createLogEvent(unsetVersion)); + assertApplicationDeniedAsInvalidArgument( + () -> stub.readLogEventReceipt(readRequest(unsetVersion))); + } finally { + stopChannel(channel); + } + verifyNoInteractions(logEventService); + } + + private void assertWrongWorkloadCannotInvokeEitherMethod(TestCertificate certificate) + throws Exception { + ManagedChannel channel = channel(certificate, null); + try { + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub = stub(channel); + CreateLogEventRequest create = request(2, "", TENANT_UUID.toString()); + assertApplicationDeniedAsPermissionDenied(() -> stub.createLogEvent(create)); + assertApplicationDeniedAsPermissionDenied( + () -> stub.readLogEventReceipt(readRequest(create))); + } finally { + stopChannel(channel); + } + verifyNoInteractions(logEventService); + } + + private void assertTlsDenied( + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub, CreateLogEventRequest request) { + Throwable createFailure = catchFailure(() -> stub.createLogEvent(request)); + assertTlsRejection(createFailure, "CreateLogEvent"); + Throwable readFailure = catchFailure(() -> stub.readLogEventReceipt(readRequest(request))); + assertTlsRejection(readFailure, "ReadLogEventReceipt"); + } + + private static void assertTlsRejection(Throwable failure, String method) { + assertThat(failure) + .as("%s must fail as a gRPC call with TLS rejection: %s", method, diagnostics(failure)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .as("%s must not be accepted as a transport timeout: %s", method, diagnostics(failure)) + .isNotEqualTo(Status.Code.DEADLINE_EXCEEDED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "%s cause chain must identify TLS certificate rejection: %s", + method, diagnostics(failure)) + .isTrue(); + } + + private static void assertApplicationDeniedAsPermissionDenied(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + + private static void assertApplicationDeniedAsInvalidArgument(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + } + + private static void assertAccountAuditCreateUnavailable(Runnable call) { + Throwable failure = catchFailure(call); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE); + } + + private static void assertMockSeededReceiptEvidence( + ReadLogEventReceiptResponse receipt, ReadLogEventReceiptRequest request) { + assertThat(receipt.getScope()).isEqualTo(request.getScope()); + assertThat(receipt.getTenantIdentityVersion()).isEqualTo(request.getTenantIdentityVersion()); + assertThat(receipt.getTenantId()).isEqualTo(request.getTenantId()); + assertThat(receipt.getTenantUuid()).isEqualTo(request.getTenantUuid()); + assertThat(receipt.getAuditEventId()).isEqualTo(request.getAuditEventId()); + assertThat(receipt.getReceiptId()).isEqualTo("read-receipt"); + assertThat(receipt.getLogEventId()).isEqualTo("731"); + assertThat(receipt.getSchemaVersion()).isEqualTo(request.getSchemaVersion()); + assertThat(receipt.getPayloadDigestVersion()).isEqualTo(request.getPayloadDigestVersion()); + assertThat(receipt.getPayloadDigest()).isEqualTo(request.getPayloadDigest()); + assertThat(receipt.getStatus()) + .isEqualTo( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus + .ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED); + assertThat(receipt.getOutcome()) + .isEqualTo( + net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome + .ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE); + assertThat(receipt.getAuditProjectionVersion()).isEqualTo(1); + } + + private void assertReadServiceSawIdentity(int version, Long tenantId, UUID tenantUuid) { + ArgumentCaptor readCaptor = + ArgumentCaptor.forClass( + net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest.class); + verify(logEventService, never()).createLogEvent(any()); + verify(logEventService).readLogEventReceipt(readCaptor.capture()); + assertThat(readCaptor.getValue().tenantIdentityVersion()).isEqualTo(version); + assertThat(readCaptor.getValue().tenantId()).isEqualTo(tenantId); + assertThat(readCaptor.getValue().tenantUuid()).isEqualTo(tenantUuid); + } + + private static LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub( + ManagedChannel channel) { + return LoggingAdminServiceGrpc.newBlockingStub(channel).withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private ManagedChannel channel(TestCertificate clientCertificate, Metadata headers) + throws Exception { + NettyChannelBuilder builder = + NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .sslContext(clientSslContext(clientCertificate)); + if (headers != null) { + builder.intercept(MetadataUtils.newAttachHeadersInterceptor(headers)); + } + return builder.build(); + } + + private static io.grpc.netty.shaded.io.netty.handler.ssl.SslContext clientSslContext( + TestCertificate clientCertificate) throws Exception { + var builder = GrpcSslContexts.forClient().trustManager(pki.caCertificate()); + if (clientCertificate != null) { + builder.keyManager(clientCertificate.getPrivateKey(), clientCertificate.certificate()); + } + return builder.build(); + } + + private static CreateLogEventRequest request( + int tenantIdentityVersion, String tenantId, String tenantUuid) { + return request( + AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT, tenantIdentityVersion, tenantId, tenantUuid); + } + + private static CreateLogEventRequest request( + AccountAuditScope scope, int tenantIdentityVersion, String tenantId, String tenantUuid) { + ByteString payload = ByteString.copyFrom(PAYLOAD_TEXT, StandardCharsets.UTF_8); + return CreateLogEventRequest.newBuilder() + .setScope(scope) + .setTenantIdentityVersion(tenantIdentityVersion) + .setTenantId(tenantId) + .setTenantUuid(tenantUuid) + .setAuditEventId("11111111-1111-4111-8111-111111111111") + .setProducerService("account-service") + .setEventType("ACCOUNT_CREATED") + .setOccurredAt(Timestamp.newBuilder().setSeconds(1_700_000_000L).setNanos(123_000_000)) + .setSchemaVersion(1) + .setPayload(payload) + .setPayloadDigestVersion(1) + .setPayloadDigest(PAYLOAD_DIGEST) + .build(); + } + + private static ReadLogEventReceiptRequest readRequest(CreateLogEventRequest request) { + return ReadLogEventReceiptRequest.newBuilder() + .setScope(request.getScope()) + .setTenantIdentityVersion(request.getTenantIdentityVersion()) + .setTenantId(request.getTenantId()) + .setTenantUuid(request.getTenantUuid()) + .setAuditEventId(request.getAuditEventId()) + .setProducerService(request.getProducerService()) + .setEventType(request.getEventType()) + .setOccurredAt(request.getOccurredAt()) + .setSchemaVersion(request.getSchemaVersion()) + .setPayload(request.getPayload()) + .setPayloadDigestVersion(request.getPayloadDigestVersion()) + .setPayloadDigest(request.getPayloadDigest()) + .build(); + } + + private static Throwable catchFailure(Runnable action) { + try { + action.run(); + return null; + } catch (Throwable throwable) { + return throwable; + } + } + + private static String diagnostics(Throwable throwable) { + if (throwable == null) { + return "RPC unexpectedly completed"; + } + StringBuilder result = new StringBuilder(); + for (Throwable current = throwable; current != null; current = current.getCause()) { + if (!result.isEmpty()) { + result.append(" <- "); + } + result.append(current.getClass().getName()).append(": ").append(current.getMessage()); + } + return result.toString(); + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static AccountAuditReceiptDto receipt( + net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest request, + String operation, + AccountAuditReceiptOutcome outcome) { + return new AccountAuditReceiptDto( + request.scope(), + request.tenantIdentityVersion(), + request.tenantId(), + request.tenantUuid(), + request.auditEventId(), + operation + "-receipt", + 731L, + request.schemaVersion(), + request.payloadDigestVersion(), + request.payloadDigest(), + AccountAuditReceiptStatus.COMMITTED, + outcome); + } + + private static String digest(String value) { + try { + byte[] digest = + java.security.MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8)); + return "sha256:" + HexFormat.of().formatHex(digest); + } catch (Exception exception) { + throw new AssertionError("unable to calculate deterministic test payload digest", exception); + } + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String commonName, String workloadUri) + throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + GeneralName[] subjectAltNames = + workloadUri == null + ? new GeneralName[] { + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + } + : new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + }; + X509Certificate certificate = + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + new GeneralNames(subjectAltNames)); + 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) { + PrivateKey getPrivateKey() { + return privateKey; + } + } + + private record TestPki( + X509Certificate caCertificate, + TestCertificate serverCertificate, + TestCertificate accountCertificate, + TestCertificate wrongServiceCertificate, + TestCertificate wrongNamespaceCertificate, + TestCertificate noWorkloadUriCertificate) {} +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java index 87c958c626..0798d9e677 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java @@ -107,18 +107,7 @@ void changedImmutableMetadataReturnsIdempotencyConflict() { @Test void changedEventTypeWithinIdentityReturnsIdempotencyConflict() { CreateLogEventRequest original = request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"); - CreateLogEventRequest changed = - new CreateLogEventRequest( - original.scope(), - original.tenantId(), - original.auditEventId(), - original.producerService(), - "ACCOUNT_RECOVERY", - original.occurredAt(), - original.schemaVersion(), - original.payload(), - original.payloadDigestVersion(), - original.payloadDigest()); + CreateLogEventRequest changed = withEventType(original, "ACCOUNT_RECOVERY"); when(repository.insertIfAbsent(eq(changed), any(UUID.class))) .thenReturn( new AccountAuditReceiptInsertResult( @@ -151,7 +140,7 @@ void minimizedReadAcceptsOmittedPayloadWithMatchingIdentityMetadataAndDigest() { CreateLogEventRequest original = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{\"retained\":true}"); CreateLogEventRequest digestOnly = withPayload(original, ByteString.EMPTY); - when(repository.findByIdentity(eq(digestOnly), eq(0L))) + when(repository.findByIdentity(eq(digestOnly))) .thenReturn(Optional.of(receipt(original, null, "MINIMIZED", "NON_REPLAYABLE"))); var result = service.readLogEventReceipt(digestOnly); @@ -159,7 +148,7 @@ void minimizedReadAcceptsOmittedPayloadWithMatchingIdentityMetadataAndDigest() { assertEquals(AccountAuditReceiptStatus.MINIMIZED, result.status()); assertEquals(AccountAuditReceiptOutcome.NON_REPLAYABLE, result.outcome()); assertEquals(RECEIPT_ID.toString(), result.receiptId()); - verify(repository).findByIdentity(eq(digestOnly), eq(0L)); + verify(repository).findByIdentity(eq(digestOnly)); } @Test @@ -174,9 +163,8 @@ void minimizedReadReportsConflictForChangedDigestOrImmutableMetadata() { CreateLogEventRequest changedEventType = withEventType(withPayload(original, ByteString.EMPTY), "ACCOUNT_RECOVERY"); AccountAuditReceipt minimized = receipt(original, null, "MINIMIZED", "NON_REPLAYABLE"); - when(repository.findByIdentity(eq(changedDigest), eq(42L))).thenReturn(Optional.of(minimized)); - when(repository.findByIdentity(eq(changedEventType), eq(42L))) - .thenReturn(Optional.of(minimized)); + when(repository.findByIdentity(eq(changedDigest))).thenReturn(Optional.of(minimized)); + when(repository.findByIdentity(eq(changedEventType))).thenReturn(Optional.of(minimized)); var digestResult = service.readLogEventReceipt(changedDigest); var metadataResult = service.readLogEventReceipt(changedEventType); @@ -225,8 +213,8 @@ void retainedReadRequiresFullPayloadAndReturnsConflictForOmittedOrChangedPayload request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{\"changed\":true}"); AccountAuditReceipt retained = receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"); - when(repository.findByIdentity(eq(omitted), eq(0L))).thenReturn(Optional.of(retained)); - when(repository.findByIdentity(eq(changed), eq(0L))).thenReturn(Optional.of(retained)); + when(repository.findByIdentity(eq(omitted))).thenReturn(Optional.of(retained)); + when(repository.findByIdentity(eq(changed))).thenReturn(Optional.of(retained)); var omittedResult = service.readLogEventReceipt(omitted); var changedResult = service.readLogEventReceipt(changed); @@ -243,7 +231,7 @@ void exactEmptyPayloadReadRemainsDistinctFromDigestOnlyMinimizedRead() { request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, ""); AccountAuditReceipt retained = receipt(emptyPayload, new byte[0], "COMMITTED", "ACCEPTED"); AccountAuditReceipt minimized = receipt(emptyPayload, null, "MINIMIZED", "NON_REPLAYABLE"); - when(repository.findByIdentity(eq(emptyPayload), eq(0L))) + when(repository.findByIdentity(eq(emptyPayload))) .thenReturn(Optional.of(retained), Optional.of(minimized)); var retainedResult = service.readLogEventReceipt(emptyPayload); @@ -258,7 +246,7 @@ void exactEmptyPayloadReadRemainsDistinctFromDigestOnlyMinimizedRead() { @Test void missingReadbackThrowsForCanonicalNotFoundMapping() { CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); - when(repository.findByIdentity(request, 0L)).thenReturn(Optional.empty()); + when(repository.findByIdentity(request)).thenReturn(Optional.empty()); assertThrows(AuditReceiptNotFoundException.class, () -> service.readLogEventReceipt(request)); } @@ -269,7 +257,9 @@ void unsupportedDigestVersionFailsBeforeRepositoryAccess() { CreateLogEventRequest unsupported = new CreateLogEventRequest( valid.scope(), + valid.tenantIdentityVersion(), valid.tenantId(), + valid.tenantUuid(), valid.auditEventId(), valid.producerService(), valid.eventType(), @@ -283,13 +273,87 @@ void unsupportedDigestVersionFailsBeforeRepositoryAccess() { verifyNoInteractions(repository); } + @Test + void canonicalUuidIdentityIsReturnedAndComparedOnRetryAndReadback() { + UUID tenantUuid = UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21"); + CreateLogEventRequest request = + uuidRequest(AccountAuditScope.TENANT, tenantUuid, Instant.EPOCH, "{}"); + AccountAuditReceipt receipt = + receipt(request, request.payload().toByteArray(), "COMMITTED", "ACCEPTED"); + when(repository.insertIfAbsent(eq(request), any(UUID.class))) + .thenReturn(new AccountAuditReceiptInsertResult(receipt, false)); + when(repository.findByIdentity(request)).thenReturn(Optional.of(receipt)); + + var duplicate = service.createLogEvent(request); + var readback = service.readLogEventReceipt(request); + + assertEquals(2, duplicate.tenantIdentityVersion()); + assertEquals(tenantUuid, duplicate.tenantUuid()); + assertEquals(AccountAuditReceiptOutcome.DUPLICATE, duplicate.outcome()); + assertEquals(2, readback.tenantIdentityVersion()); + assertEquals(tenantUuid, readback.tenantUuid()); + assertEquals(LOG_EVENT_ID, readback.logEventId()); + } + + @Test + void changedTenantIdentityVersionConflictsWithRetainedReceiptMetadata() { + UUID tenantUuid = UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21"); + CreateLogEventRequest original = + uuidRequest(AccountAuditScope.TENANT, tenantUuid, Instant.EPOCH, "{}"); + CreateLogEventRequest changed = request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"); + when(repository.insertIfAbsent(eq(changed), any(UUID.class))) + .thenReturn( + new AccountAuditReceiptInsertResult( + receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"), + false)); + + var result = service.createLogEvent(changed); + + assertEquals(AccountAuditReceiptStatus.CONFLICT, result.status()); + assertEquals(AccountAuditReceiptOutcome.IDEMPOTENCY_CONFLICT, result.outcome()); + } + + @Test + void missingOrContradictoryTenantIdentityFailsBeforeRepositoryAccess() { + CreateLogEventRequest validPlatform = + request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); + CreateLogEventRequest missingVersion = withIdentity(validPlatform, 0, null, null); + CreateLogEventRequest mixedV1 = + withIdentity( + request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"), + 1, + 42L, + UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21")); + CreateLogEventRequest platformV2 = + withIdentity( + validPlatform, 2, null, UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21")); + CreateLogEventRequest numericV2 = + withIdentity( + request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"), + 2, + 42L, + UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21")); + CreateLogEventRequest nilV2 = + withIdentity( + request(AccountAuditScope.TENANT, 42L, Instant.EPOCH, "{}"), 2, null, new UUID(0L, 0L)); + + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(missingVersion)); + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(mixedV1)); + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(platformV2)); + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(numericV2)); + assertThrows(IllegalArgumentException.class, () -> service.createLogEvent(nilV2)); + verifyNoInteractions(repository); + } + @Test void payloadDigestMismatchFailsBeforeRepositoryAccess() { CreateLogEventRequest valid = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); CreateLogEventRequest mismatched = new CreateLogEventRequest( valid.scope(), + valid.tenantIdentityVersion(), valid.tenantId(), + valid.tenantUuid(), valid.auditEventId(), valid.producerService(), valid.eventType(), @@ -309,6 +373,8 @@ void invalidUtf8PayloadFailsBeforeRepositoryAccess() { CreateLogEventRequest request = new CreateLogEventRequest( AccountAuditScope.PLATFORM, + 1, + null, null, AUDIT_EVENT_ID, "account-service", @@ -328,7 +394,27 @@ private static CreateLogEventRequest request( ByteString payload = ByteString.copyFrom(payloadText, StandardCharsets.UTF_8); return new CreateLogEventRequest( scope, + 1, tenantId, + null, + AUDIT_EVENT_ID, + "account-service", + "ACCOUNT_REGISTERED", + occurredAt, + 1, + payload, + 1, + digest(payload.toByteArray())); + } + + private static CreateLogEventRequest uuidRequest( + AccountAuditScope scope, UUID tenantUuid, Instant occurredAt, String payloadText) { + ByteString payload = ByteString.copyFrom(payloadText, StandardCharsets.UTF_8); + return new CreateLogEventRequest( + scope, + 2, + null, + tenantUuid, AUDIT_EVENT_ID, "account-service", "ACCOUNT_REGISTERED", @@ -339,6 +425,23 @@ private static CreateLogEventRequest request( digest(payload.toByteArray())); } + private static CreateLogEventRequest withIdentity( + CreateLogEventRequest request, int identityVersion, Long tenantId, UUID tenantUuid) { + return new CreateLogEventRequest( + request.scope(), + identityVersion, + tenantId, + tenantUuid, + request.auditEventId(), + request.producerService(), + request.eventType(), + request.occurredAt(), + request.schemaVersion(), + request.payload(), + request.payloadDigestVersion(), + request.payloadDigest()); + } + private static CreateLogEventRequest withPayload( CreateLogEventRequest request, ByteString payload) { return withPayloadAndDigest(request, payload, request.payloadDigest()); @@ -348,7 +451,9 @@ private static CreateLogEventRequest withPayloadAndDigest( CreateLogEventRequest request, ByteString payload, String payloadDigest) { return new CreateLogEventRequest( request.scope(), + request.tenantIdentityVersion(), request.tenantId(), + request.tenantUuid(), request.auditEventId(), request.producerService(), request.eventType(), @@ -363,7 +468,9 @@ private static CreateLogEventRequest withEventType( CreateLogEventRequest request, String eventType) { return new CreateLogEventRequest( request.scope(), + request.tenantIdentityVersion(), request.tenantId(), + request.tenantUuid(), request.auditEventId(), request.producerService(), eventType, @@ -378,7 +485,9 @@ private static CreateLogEventRequest withPayloadDigestVersion( CreateLogEventRequest request, int payloadDigestVersion) { return new CreateLogEventRequest( request.scope(), + request.tenantIdentityVersion(), request.tenantId(), + request.tenantUuid(), request.auditEventId(), request.producerService(), request.eventType(), @@ -396,7 +505,9 @@ private static AccountAuditReceipt receipt( LOG_EVENT_ID, RECEIPT_ID, request.scope().databaseValue(), + request.tenantIdentityVersion(), request.tenantId(), + request.tenantUuid(), request.auditEventId(), request.producerService(), request.eventType(), diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index d745490dae..e85e7868ef 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -164,6 +165,8 @@ void offlineFixtureMapsAcceptedReceiptToTypedCreateResponse() { AccountAuditReceiptDto receipt = new AccountAuditReceiptDto( AccountAuditScope.PLATFORM, + 1, + null, null, "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", "receipt-1", @@ -191,6 +194,69 @@ void offlineFixtureMapsAcceptedReceiptToTypedCreateResponse() { response.getOutcome()); } + @Test + void offlineFixtureMapsCanonicalUuidReceiptToTypedCreateResponse() { + UUID tenantUuid = UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21"); + String digest = digest("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); + AccountAuditReceiptDto receipt = + new AccountAuditReceiptDto( + AccountAuditScope.TENANT, + 2, + null, + tenantUuid, + "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", + "receipt-uuid", + 78L, + 1, + 1, + digest, + AccountAuditReceiptStatus.COMMITTED, + AccountAuditReceiptOutcome.ACCEPTED); + + CreateLogEventResponse response = LoggingAdminGrpcService.toCreateLogEventResponse(receipt); + + assertEquals(2, response.getTenantIdentityVersion()); + assertEquals(tenantUuid.toString(), response.getTenantUuid()); + assertEquals("", response.getTenantId()); + assertEquals(1, response.getAuditProjectionVersion()); + assertEquals("receipt-uuid", response.getReceiptId()); + assertEquals("78", response.getLogEventId()); + } + + @Test + void receiptReadRejectsNoncanonicalOrMixedTenantIdentityBeforeServiceCall() { + LogEventService logEventService = Mockito.mock(LogEventService.class); + LoggingAdminGrpcService service = newService(logEventService); + ReadLogEventReceiptRequest noncanonicalNumeric = + validReadRequest().toBuilder() + .setScope( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantId("042") + .build(); + ReadLogEventReceiptRequest mixedUuid = + validReadRequest().toBuilder() + .setScope( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantId("42") + .setTenantUuid("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21") + .build(); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> service.readLogEventReceipt(noncanonicalNumeric, responseObserver(response, error))); + assertEquals(Status.Code.INVALID_ARGUMENT, Status.fromThrowable(error.get()).getCode()); + assertNull(response.get()); + + error.set(null); + invokeWithPeer( + "account-service", + () -> service.readLogEventReceipt(mixedUuid, responseObserver(response, error))); + assertEquals(Status.Code.INVALID_ARGUMENT, Status.fromThrowable(error.get()).getCode()); + verifyNoInteractions(logEventService); + } + @Test void adminJwtClaimsDoNotAuthorizeAuditIngressWithoutAccountPeer() { SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); @@ -261,6 +327,8 @@ void accountMtlSPeerCanReadTypedReceiptWithoutJwt() { .thenReturn( new AccountAuditReceiptDto( AccountAuditScope.PLATFORM, + 1, + null, null, "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", "receipt-1", @@ -290,6 +358,59 @@ void accountMtlSPeerCanReadTypedReceiptWithoutJwt() { verify(logEventService).readLogEventReceipt(any()); } + @Test + void accountMtlsPeerCanReadCanonicalUuidReceiptAndEchoesTypedIdentity() { + UUID tenantUuid = UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21"); + String digest = digest("{\"accountId\":42}".getBytes(StandardCharsets.UTF_8)); + LogEventService logEventService = Mockito.mock(LogEventService.class); + when(logEventService.readLogEventReceipt(any())) + .thenReturn( + new AccountAuditReceiptDto( + AccountAuditScope.TENANT, + 2, + null, + tenantUuid, + "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", + "receipt-uuid", + 78L, + 1, + 1, + digest, + AccountAuditReceiptStatus.COMMITTED, + AccountAuditReceiptOutcome.DUPLICATE)); + ReadLogEventReceiptRequest request = + validReadRequest().toBuilder() + .setScope( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantId("") + .setTenantIdentityVersion(2) + .setTenantUuid(tenantUuid.toString()) + .build(); + LoggingAdminGrpcService service = newService(logEventService); + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + + invokeWithPeer( + "account-service", + () -> service.readLogEventReceipt(request, responseObserver(response, error))); + + assertNull(error.get()); + assertNotNull(response.get()); + assertEquals(2, response.get().getTenantIdentityVersion()); + assertEquals(tenantUuid.toString(), response.get().getTenantUuid()); + assertEquals("", response.get().getTenantId()); + assertEquals("receipt-uuid", response.get().getReceiptId()); + assertEquals("78", response.get().getLogEventId()); + assertEquals(1, response.get().getAuditProjectionVersion()); + verify(logEventService) + .readLogEventReceipt( + argThat( + dto -> + dto.tenantIdentityVersion() == 2 + && dto.tenantId() == null + && tenantUuid.equals(dto.tenantUuid()))); + } + @Test void accountMtlsPeerCanReadMinimizedReceiptThroughActualService() { AccountAuditReceiptRepository repository = Mockito.mock(AccountAuditReceiptRepository.class); @@ -300,6 +421,8 @@ void accountMtlsPeerCanReadMinimizedReceiptThroughActualService() { net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest serviceRequest = new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( AccountAuditScope.PLATFORM, + wireRequest.getTenantIdentityVersion(), + null, null, wireRequest.getAuditEventId(), wireRequest.getProducerService(), @@ -316,6 +439,8 @@ void accountMtlsPeerCanReadMinimizedReceiptThroughActualService() { 77L, receiptId, "platform", + 1, + null, null, serviceRequest.auditEventId(), serviceRequest.producerService(), @@ -328,7 +453,7 @@ void accountMtlsPeerCanReadMinimizedReceiptThroughActualService() { null, "MINIMIZED", "NON_REPLAYABLE"); - when(repository.findByIdentity(serviceRequest, 0L)).thenReturn(Optional.of(receipt)); + when(repository.findByIdentity(serviceRequest)).thenReturn(Optional.of(receipt)); LoggingAdminGrpcService service = newService(new LogEventServiceImpl(repository)); AtomicReference response = new AtomicReference<>(); AtomicReference error = new AtomicReference<>(); @@ -349,7 +474,7 @@ void accountMtlsPeerCanReadMinimizedReceiptThroughActualService() { net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome .ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE, response.get().getOutcome()); - verify(repository).findByIdentity(serviceRequest, 0L); + verify(repository).findByIdentity(serviceRequest); } @Test @@ -976,6 +1101,7 @@ private static CreateLogEventRequest validCreateRequest() { return CreateLogEventRequest.newBuilder() .setScope( net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM) + .setTenantIdentityVersion(1) .setAuditEventId("d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3") .setProducerService("account-service") .setEventType("ACCOUNT_REGISTERED") @@ -991,6 +1117,7 @@ private static ReadLogEventReceiptRequest validReadRequest() { CreateLogEventRequest create = validCreateRequest(); return ReadLogEventReceiptRequest.newBuilder() .setScope(create.getScope()) + .setTenantIdentityVersion(create.getTenantIdentityVersion()) .setAuditEventId(create.getAuditEventId()) .setProducerService(create.getProducerService()) .setEventType(create.getEventType())