diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 35307d9a7c..459404b601 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: @@ -998,12 +997,14 @@ jobs: run: | ./gradlew :game-design-service:integrationTest \ --tests integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest \ + --tests net.firedevops.firemud.gamedesign.service.PublishAttemptServiceTransactionIntegrationTest \ :game-design-service:test \ --tests net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest \ -PfullCheck --continue --no-build-cache --no-configuration-cache bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest \ + --require-suite net.firedevops.firemud.gamedesign.service.PublishAttemptServiceTransactionIntegrationTest \ --require-suite net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest \ --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionChange()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#concurrentExactRetriesPersistOneOriginalDescriptor()' \ @@ -1011,7 +1012,8 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#corruptFailureReadbackRollsBackTheOutcomeInsert()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#concurrentSuccessAndFailureCandidatesPersistOnlyTheFirstOutcome()' \ --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim()' \ - --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#v35MigrationPreservesRetainedUnboundDescriptorAndCanonicalResolveDeniesIt()' \ + --require-case 'integration.net.firedevops.firemud.gamedesign.service.LaunchDescriptorServiceIntegrationTest#v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill()' \ + --require-case 'net.firedevops.firemud.gamedesign.service.PublishAttemptServiceTransactionIntegrationTest#reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogether()' \ --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#exactGameSessionPeerResolvesAndEchoesTheFullCanonicalDescriptor()' \ --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#gameSessionAndWorldPeersReadExactDescriptorAndEchoReadRequestIdentity()' \ --require-case 'net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldLaunchDescriptorMtlsTest#worldPeerCannotResolveBeforeDescriptorProducerAccess()' \ @@ -1034,6 +1036,7 @@ jobs: name: game-design-authored-source-launch-descriptor-proof-${{ github.sha }} path: | services/game-design-service/build/test-results/integrationTest/TEST-*LaunchDescriptorServiceIntegrationTest.xml + services/game-design-service/build/test-results/integrationTest/TEST-*PublishAttemptServiceTransactionIntegrationTest.xml services/game-design-service/build/test-results/test/TEST-*AuthoredWorldLaunchDescriptorMtlsTest.xml if-no-files-found: warn retention-days: 7 @@ -1242,6 +1245,8 @@ jobs: --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#serviceCommitsReadsBackAndReplaysExactStoredRequestWithoutAnotherSourceRead()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#serviceRollbackAndRejectedSourceLeaveNoClaims()' \ --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#serviceLostPostCommitReadbackRetryReturnsOriginalCommittedReceiptWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#worldSelectorReadReturnsExactCommittedReceiptWithoutEnrollment()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepositoryIntegrationTest#worldSelectorReadRejectsAmbientOwnerTransactionAndMalformedScope()' \ game-session-service - name: Upload Game Session authored-world intake PostgreSQL proof results @@ -1499,6 +1504,29 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run Game Session canonical launch preparation PostgreSQL component proof + if: ${{ matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:integrationTest \ + --tests integration.net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationServiceIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationServiceIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationServiceIntegrationTest#commitsExactFreshSourceCatalogAndSyntheticDescriptorThenReplaysWithoutChangingRetainedRows()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationServiceIntegrationTest#ownerRollbackLeavesNoPartialPreparationAndImmutableRowsRejectMutation()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationServiceIntegrationTest#concurrentExactPreparationsReturnOneImmutableOperation()' \ + game-session-service + + - name: Upload Game Session canonical launch preparation PostgreSQL proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-session-canonical-launch-preparation-postgresql-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/integrationTest/TEST-*GameSessionCanonicalLaunchPreparationServiceIntegrationTest.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: | @@ -2089,18 +2117,32 @@ jobs: --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#contradictoryLatestEventDeniesLeftWithoutMembershipOrOutboxMutation()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#auditFailureRollsBackCompleteOwnerLeftTransaction()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#concurrentLeftAndReactivationSerializeAsCompleteAccountTransitions()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#durablePendingClaimRecoversExactOperationAfterLostAcknowledgementWithoutEnvelope()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#changedDigestRequestOrSourceCannotReplaceDurablePendingClaim()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#rollingBackPendingClaimLeavesNoPartialExchange()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#concurrentExactPendingClaimsConvergeOnOneDurableOperation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#concurrentChangedPendingEvidenceWritersKeepOneFirstWrite()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#terminalSuccessWithoutItsExactBoundEnvelopeCannotCommit()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinPostgresIntegrationTest#membershipTransitionReceiptsRejectMutationAndStillAllowAppendAndStreamAdvance()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinReconciliationPostgresIntegrationTest#exactPersistedEvidenceRecoversExpiredScopeAndSameRequestRetryWithoutDuplicates()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinReconciliationPostgresIntegrationTest#twoWorkersRecoverThresholdPendingEvidenceWithoutDuplicatingMembershipOrAudit()' \ --require-case 'net.firedevops.firemud.accountservice.AccountJoinReconciliationPostgresIntegrationTest#retainedScopeDeletionAndExpiredScopeWithoutMembershipProofRemainPendingWithDiagnostics()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountConnectStorageUuidMigrationIntegrationTest#freshMigrationsAndEmptyV39UpgradeUseCanonicalUuidColumns()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountConnectStorageUuidMigrationIntegrationTest#migrationWaitsForConcurrentWriterThenRejectsItsCommittedEvidence()' \ - --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginExchangeRepositoryIntegrationTest#claimOnlyTransactionRollsBackPendingExchange()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#concurrentExactIssuanceClaimsHaveOneTerminalFirstWriter()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#lostIssuanceResponseRecoversExactEncryptedResultFromDurableReadback(Path)' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#directDeletionOfIssuanceOperationOrResponseEnvelopeIsRejected()' \ account-service + - name: Upload Account bare LOGIN storage PostgreSQL proof + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-bare-login-storage-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountBareLoginExchangeRepositoryIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Verify Account current recipient source composition PostgreSQL proof if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | @@ -2109,6 +2151,21 @@ jobs: --require-suite net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest \ --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#postJoinSnapshotCarriesCurrentCompositeSourcesWithoutRewritingMembershipEvent()' \ --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#membershipSourceReaderReadsRetainedInactiveRetryAndReactivationWithoutMutation()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#activeMembershipCaptureCommitsBesideSyntheticV35SourceAndExactReadbackDoesNotRewriteIt()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#bareLoginCurrentAuthorityReaderReturnsExactRedactedReadbackWithoutMutation()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#bareLoginCurrentAuthorityReaderRejectsMissingCaptureForValidCommittedSource()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#bareLoginCurrentAuthorityReaderRechecksDeadlineAfterAuthorityRead()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#bareLoginCurrentAuthorityReaderRejectsSourceAfterAccountAuthorityAndFenceAdvance()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#concurrentCaptureWaitsForAccountOwnerAdvanceAndBindsTheNewFence()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#concurrentCurrentAuthorityReadWaitsForAdvanceThenRejectsOriginalSource()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#captureRollbackLeavesNeitherCaptureNorPartialCommittedSource()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#absentAndInactiveMembershipRejectCaptureWithoutInitializingOrRejoining()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#capturedEvidenceCannotBeReplacedByChangedIdentityDigestOrFenceValues()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#directRepositoryRejectsCaptureForAnotherPersistedAccountUuid()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#populatedCaptureIsImmutableAndTerminalSourceCannotBeBackfilled()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#captureSourcesPreserveIndependentlyAdvancedAuthorityVersionsAndCheckpoints()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#historicalCaptureSourcesRemainUnchangedWhenCurrentMembershipAdvances()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#existingCaptureSourcesAuthenticateAbsenceAndRejectMixedSourceOrRoleEvidence()' \ account-service - name: Upload Account current recipient source composition PostgreSQL proof @@ -2120,6 +2177,59 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Verify Account initial private-token identity fence PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountBareLoginTokenIdentityFencePostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginTokenIdentityFencePostgresIntegrationTest#initialCapturePersistsExactSyntheticEvidenceAndExactRetriesDoNotChurn()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginTokenIdentityFencePostgresIntegrationTest#missingRequireInitialDoesNotCreateOrBackfillEvidence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginTokenIdentityFencePostgresIntegrationTest#changedRequestOperationAccountOrTokenEvidenceCannotReplaceCapture()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginTokenIdentityFencePostgresIntegrationTest#captureRequiresOutgoingTokenBindingAndRejectsLateTerminalCapture()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginTokenIdentityFencePostgresIntegrationTest#missingAccountAndMismatchedCanonicalAccountIdentityAreDenied()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginTokenIdentityFencePostgresIntegrationTest#rollbackLeavesNoPartialInitialCapture()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginTokenIdentityFencePostgresIntegrationTest#concurrentExactInitialCapturesConvergeOnOneImmutableRow()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginTokenIdentityFencePostgresIntegrationTest#accountFenceAdvanceSerializesCaptureAndMakesHistoricalCurrentEvidenceStale()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginTokenIdentityFencePostgresIntegrationTest#actualOwnerTransactionMustBeWritableReadCommittedAndConnectionBound()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountBareLoginTokenIdentityFencePostgresIntegrationTest#directSqlMismatchedCurrentFenceInsertAndCaptureMutationAreDenied()' \ + account-service + + - name: Upload Account initial private-token identity fence PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-initial-private-token-fence-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountBareLoginTokenIdentityFencePostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Verify Account fresh explicit-empty global-role source PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourcePostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourcePostgresIntegrationTest#freshRepositoryAndDatabaseAccountsHaveStableIndependentExplicitEmptySources()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourcePostgresIntegrationTest#v55DoesNotBackfillRetainedOrPreexistingFreshProvenanceRows()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourcePostgresIntegrationTest#nonnullLegacyPlayerAndCanonicalRoleScalarsDoNotInventSources()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourcePostgresIntegrationTest#directSourceWritesAndWrongScopeEvidenceCannotManufactureOrEraseBirthState()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourcePostgresIntegrationTest#abortedFreshInsertLeavesNoAccountOrPartialSourceAndReadRequiresWritableTransaction()' \ + --require-suite net.firedevops.firemud.accountservice.repository.AccountRepositoryIntegrationTest \ + --require-case 'net.firedevops.firemud.accountservice.repository.AccountRepositoryIntegrationTest#globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows()' \ + account-service + + - name: Upload Account fresh explicit-empty global-role source PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-fresh-global-role-source-postgresql-proof-${{ github.sha }} + path: | + services/account-service/build/test-results/integrationTest/TEST-*AccountGlobalRoleSourcePostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountRepositoryIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: πŸ”Ž Verify Account authority exhaustion rollback proof if: ${{ matrix.module == 'account-service' }} run: | @@ -2213,6 +2323,9 @@ jobs: --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#canonicalRuntimeReadRejectsUnmappedTenantUuidWithoutEnrollment()' \ --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#strictExistingMembershipReadDeniesFreshAssociationWithoutEnrollmentOrMutation()' \ --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#membershipSourceReaderRejectsAmbientAccountTransaction()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#freshGlobalRoleSourceComposesWithExistingMembershipVectorAndPreservesIndependentVersions()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#retainedAccountWithoutFreshGlobalRoleSourceIsDeniedWithoutEnrollment()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#tenantAdvanceWaitsForFreshCaptureSourceLocksAndPreservesCapturedVector()' \ account-service - name: Upload Account existing-only membership source PostgreSQL proof @@ -2324,7 +2437,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/decisions/README.md b/design/architecture/decisions/README.md index 6d46df38b0..9adeaccef6 100644 --- a/design/architecture/decisions/README.md +++ b/design/architecture/decisions/README.md @@ -279,6 +279,7 @@ Validation precedence is fixed: first parse every checked queue row and validate | [ADR 0182](./adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) | Accepted | `PO-3.2` | `PO-3.1`, `PO-4.4`, `SF-1.3`, `PO-1.1` | Separated hosted runtime and certificate-identity lifecycles | | [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) | Proposed - Pending Human Review | `GR-1.2` | `GR-1.4`, `GR-4.1`, `AS-1.2`, `AS-1.4`, `SF-1.4`, `SF-2.3`, `PO-4.2` | Pending command-plan ordering, `planOrdinal`, command-root allocation, UUIDv7 scalar, canonical serialization, and additional child/fan-out allocation mechanics | | [ADR 0184](./adr-0184-emergency-tcp-proxy-identity-withdrawal.md) | Accepted | `SF-1.3` | `PO-2.1`, `PO-2.2`, `PO-3.2`, `PO-4.4` | Emergency trust cutoff for a withdrawn TCP Proxy bridge identity | +| [ADR 0185](./adr-0185-account-owned-global-role-administration-and-bootstrap.md) | Accepted | `AA-1.1` | `SF-1.1`, `PO-1.1` | Account-owned human global-role administration and protected first-administrator bootstrap boundary | Capability identifiers are defined in the [FireMUD Product Capability Taxonomy](../../product/capability-taxonomy.md). diff --git a/design/architecture/decisions/adr-0035-single-record-issued-token-registry.md b/design/architecture/decisions/adr-0035-single-record-issued-token-registry.md index 12be4e0f59..93e91bbe08 100644 --- a/design/architecture/decisions/adr-0035-single-record-issued-token-registry.md +++ b/design/architecture/decisions/adr-0035-single-record-issued-token-registry.md @@ -48,6 +48,8 @@ The Account durable authority record, its immutable versioned evidence bundle, a Account exposes one immutable, versioned `account-auth-evidence-bundle/v1` for each authorization operation. At one Account linearization point, the bundle contains only Account-owned authority state: the complete applicable registry tuple, both cutoff objects, live applicable global and tenant-role evidence with its role-freshness source, `issuanceFence`, the exact token-identity fence, `membershipVersion` (the exact tenant-ID map, or `{}` when non-applicable), the exact Account scope, a positive `bundleVersion`, the durable source transaction or outbox version, the monotonic source fence, projection freshness/source evidence, and `outboxCheckpoints`. `outboxCheckpoints` contains one exact `{outboxStreamKey, outboxSequence}` checkpoint for every applicable authority stream defined by the scope. Checkpoints cover the exact `account:auth-authority:v1:` stream keys involved in the bundle, with no aggregate maximum or cross-stream sequence substituted for an individual stream checkpoint. Redis registry and lease state plus Game Session binding and installation state are not Account-linearized bundle fields. The immutable bundle reference is `{bundleVersion, sourceVersion, sourceFence, linearization}`; branch decisions, role freshness, generations, and operator references must carry and match that exact reference. +The reference names the existing durable Account capture: `sourceVersion` identifies that immutable capture, and `sourceFence` is the Account-controlled fence for committing and reading that capture. They are capture metadata, not an aggregate or maximum of independently advancing issuer, account, tenant, membership, role or cutoff source versions. The bundle preserves every applicable source's exact version and checkpoint separately, captured consistently at the Account linearization point. Neither reference field replaces `issuanceFence`, an exact-token fence, revocation authority, any per-source version or checkpoint, or current-source validation. A capture remains immutable when a source subsequently advances; its historical readback is not proof that the source is still current. Exact readback must match the complete capture reference, operation and token binding, applicable source set, values, versions and checkpoints. Mixed captures, substituted source evidence, and mismatched references fail closed rather than being repaired by taking a maximum or rereading individual fields. This interpretation was approved by the human architecture owner on 2026-10-04; it clarifies the accepted bundle contract without enabling runtime issuance. + Account issuance and refresh use one Account transaction or composite CAS/fence to create the durable Account evidence and the versioned `account-auth-evidence-bundle/v1` reference. That transaction/CAS does not create the Coordination Redis registry record or any Redis lease or Game Session binding/installation. Each operation-bound registry, lease, binding transition, and installation postcondition is separately versioned, fenced, and idempotent outside the Account transaction and carries the same immutable `operationId`, caller `requestId`, canonical request digest, token digest, and `issuanceFence`; retries and reconciliation apply only missing postconditions. A steady-state gameplay binding instead retains the canonical ADR 0031 binding schema and does not acquire operation-scoped fields after its transition is terminal. `operationId` identifies the one durable Account operation and cannot change after creation. `requestId` is the immutable logical retry identity supplied by the owning API; where a public surface uses `requestId` as its operation ID, it remains the same single identity and no second public identifier is introduced. The canonical token digest is `tokenHash`, the fixed-length SHA-256 digest of the complete compact JWT, and it is immutable for that token identity; it is distinct from the canonical request digest, which never contains raw JWT bytes. The registry record stores the matching Account `bundleVersion`, `sourceVersion`, `sourceFence`, and freshness/linearization evidence with its tuple. Lease, operation-bound binding transition, and installation evidence stores its owning service's positive version/fence plus the exact registry identity and Account bundle reference it satisfies. Every registry-backed JWT authorization attempt, including `IssueConnectToken` with a presented `player-bootstrap`, performs exactly one atomic issued-token registry lookup, which must return the exact `state=active` record and its positive registry version, then reads exactly one complete immutable Account bundle and each applicable downstream owner evidence at the exact version/fence named by the registry or durable operation. It compares the JWT, registry tuple, every applicable cutoff as its complete generation-plus-`outboxStreamKey`-plus-`outboxSequence` tuple, every applicable `outboxCheckpoint`, separate `membershipVersion`, Account fences, and each independently owned lease, binding, or installation version as one decision. The `membershipVersion` claim, registry field, Account evidence value, and each applicable lease, binding, rebind, rotation, installation, and retry carrier must preserve exactly equal map structure and key/value pairs, including canonical `{}` for non-applicable membership; no omitted, `null`, scalar, or sentinel form is equal. `membershipVersion` remains an independent comparison from `authorityTuple.membershipAuthorityGeneration`; both values must match the same applicable Account authority snapshot. If an owner reports that a requested bundle, registry-linked postcondition, or version/fence was superseded while it was being read, the consumer discards the entire attempt and retries from a new registry lookup; a second change or any reachable mismatch denies. Timeouts and unavailable owners return retryable `AUTH_UNAVAILABLE`. No consumer rereads unrelated fields, combines evidence from different attempts, or claims a cross-store atomic snapshot. diff --git a/design/architecture/decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md b/design/architecture/decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md new file mode 100644 index 0000000000..22dde447ae --- /dev/null +++ b/design/architecture/decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md @@ -0,0 +1,58 @@ +# ADR 0185: Account-Owned Global-Role Administration and Bootstrap + +## Status + +Accepted + +## Implementation Status + +The approved authority boundary is target state only. Global-role grant/revoke production, the protected initial-administrator bootstrap, its Account source/event/readback implementation, and Gateway β†’ Logging & Admin ingress are not implemented or proved. The V55 explicit-empty source is fresh-Account birth evidence only; it does not authorize mutation or retained-account enrollment. Existing activation gates remain closed. + +## Decision Record + +- Human review status: Completed +- Human review date: 2026-10-04 +- Human review disposition: Accepted +- Review source: `AUTH-GLOBAL-ROLE-WRITER-01` +- Decision owner: FireMUD human product and architecture owner +- Consultation: Ben explicitly selected β€œApprove this boundary (Recommended)” on 2026-10-04, relayed by the Overseer through inbox `0f5ec31e-db81-4b31-ab9c-7e94b257cd62` + +## Context + +Global roles authorize only the control-plane route classes declared by Authentication and the Authorization Route Matrix. Account's V55 birth source records an explicit empty role set for eligible fresh Accounts, but retained role history, mutation authority, and authenticated recipient evidence are not supplied by that source. A present-day legacy scalar, first registrant, token claim, tenant identifier, or ordinary automated workload cannot safely establish the first global administrator or authorize subsequent role changes. + +## Decision + +Account is the sole authority for granting and revoking global roles and for the current role state used in authorization. Ordinary grant and revoke requests enter through the Gateway to Logging & Admin as human operator actions. The human operator must have a live `platformAdmin` role and current `privileged_control` step-up evidence. Account issues the currentness authorization used at the authoritative owner commit and revalidates it there; the committed operation has durable audit evidence. Logging & Admin is the external ingress and audit/forwarding boundary, not a second role authority. + +The first `platformAdmin` is established only through a separate, one-time protected deployment bootstrap. It is not assigned by public registration, first-account status, a legacy scalar, an asserted or signed token role, or ordinary automation. The bootstrap is a distinct operational authority from ordinary grants and revocations. + +Global-role actions are account-global actions with an explicit global-account target scope. They cannot use the existing non-moderation `tenant_scope` branch or treat a tenant ID, tenant role, or target-tenant generation as a substitute. Unattended automation cannot grant or revoke global roles. + +This decision selects the authority and ingress boundary only. It does not select an HTTP route, protobuf method, action-family schema, mutation identity or digest grammar, exact bootstrap artifact or recovery protocol, durable event schema, source-counter composition, or deployment activation procedure. Those details require canonical owner contracts and focused proof before a route or mutation becomes available. Until then, global-role mutation is target-only and fail closed. + +## Consequences + +- Authentication owns the normative role-administration policy and its authorization consequences. +- Account owns role persistence, the mutation/currentness decision at commit, durable audit evidence, and authoritative readback. Role-source version, Account authority generation, issuance fence, and event-stream checkpoint remain distinct evidence and must not be inferred from each other. +- Logging & Admin owns only the human external ingress and its local durable intent/audit and forwarding consequences under ADRs 0047 and 0048. +- The Authorization Route Matrix records target-only denial and an explicit global-account action scope. It does not create a runtime route or enable global-role administration. +- The protected first-administrator bootstrap, source/event contract, authenticated capture/readback, retry/recovery behavior, migration/enrollment policy for retained Accounts, and end-to-end proof remain implementation prerequisites. + +## Alternatives Considered + +### Allow the first registrant or an existing scalar to become administrator + +Rejected because public registration and historical role fields do not prove an authorized administrative designation or a trustworthy retained grant history. + +### Permit tenant-scoped or ordinary automated role assignment + +Rejected because tenant authority does not imply platform-global authority, and the current automation authorization path is tenant-scoped without a human operator or global-role step-up. + +### Enable mutations before owner-currentness and audit are committed + +Rejected because an ingress decision or preflight read cannot remain authoritative through Account's mutation commit or provide durable attribution. + +## Reversibility and Revisit Triggers + +The route and storage details remain intentionally unselected and can be specified under this accepted authority boundary. Revisit this decision only if the human owner changes who may administer global roles, the initial-administrator trust boundary, or the required human-only step-up policy. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d4352dc091..1da976e417 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -8,6 +8,14 @@ The authoritative REST schema source lives in [../../../../services/account-serv Account is the API boundary for platform identity, durable membership, entitlement authority, and Account-owned authentication mutations. This document retains endpoint and transport consequences; gameplay admission and JOIN identity binding are defined by [Authentication](../../system-architecture-authentication.md), while token refresh, replacement, generation, revocation, fencing, and logout are defined by [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). +### Account-Owned Global Role Administration + +Account is the sole writer and read authority for `platformAdmin`, `support`, and `billingAdmin` grants and revocations. The target human mutation enters through Gateway β†’ Logging & Admin and requires a live `platformAdmin` actor with current `privileged_control` step-up evidence under [ADR 0045](../../decisions/adr-0045-ordinary-login-factors-and-https-sensitive-action-step-up.md). Account-issued currentness authorization must be checked again at the Account-owned mutation commit; durable audit evidence is part of the committed operation. The human actor, target Account, selected role, action, and audit attribution must be bound by the eventual typed request and authorization evidence. Logging & Admin carries operator intent and does not write role state or become an authority source; ingress and owner execution follow [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md). Unattended automation cannot grant or revoke these roles. + +The initial `platformAdmin` is established only by a separate one-time protected deployment bootstrap. Public registration, first-account status, the legacy `accounts.role` scalar, a caller-supplied or signed token role, or tenant-scoped authority cannot establish initial or retained global-role authority. Existing retained role state requires explicit trusted provenance; V55's empty source is created only for qualifying fresh Account births and is not a retained-row backfill or role-mutation writer. + +Role mutation remains target-only: no route, RPC, published action-family schema, or current runtime writer is selected here. Before enablement, Account must own the source mutation, an independent positive role-source version, immutable event/audit evidence, and exact same-snapshot authorization readback. The role-source version is distinct from Account authority generations, issuance fences, event-stream checkpoints, and other source versions. Exact event fields, mutation identity/digest grammar, bootstrap artifact, retained-account enrollment, and retry/recovery protocol remain open owner-contract work under [ADR 0185](../../decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md). + ### Account-Owned Hosted Terms and Creator Party Account is the sole target authority for the identified hosted Creator Party, operator/legal-party and terms-version catalog, and acceptance/currentness evidence under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md). Acceptance is an explicit party-level decision for an identified operator and hosted-terms scope; tenant roles, billing ownership, payment, caller-supplied fields, or a copied Game Design flag do not establish party, signer, or acceptance authority. Organization and other unsupported party/signer paths remain disabled until their target contract is implemented and reviewed. @@ -30,6 +38,8 @@ Account is the sole writer and read authority for non-public realm grants under The grant `scopeId`, `outboxStreamKey`, and event `sourceScope` use the shared [canonical grant authority-stream scope codec](../../system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). This API contract owns the five-field semantic identity and lifecycle rules; it does not define a second stream encoding or permit a legacy scope fallback. +Before a grant write, Account validates the current exact lifecycle identity and `forkExpiresAt` from [Game Session's authenticated pointer-bound readback of World proof](../game-session-service/api-contracts.md#playtest-lifecycle-proof-on-the-admission-pointer), and satisfies the existing Account commit-gate freshness requirement at the write boundary. Missing, stale, mismatched, or unavailable World proof fails closed; neither a missing grant row nor a discovery snapshot supplies a source-version baseline or substitutes for current owner evidence. Account alone writes the closed five-field `grant/v1` scope and atomically commits the grant mutation receipt, retained tombstone when applicable, and authority outbox/checkpoint with their counters. `grantRevision` orders domain grant mutations; Account's independent per-grant `sourceVersion` and checkpoint order authority-source changes. They are never aliases or reconstructed from one another. The existing ADR 0047 `mutationDigest/v1` and request/revision retry rules remain unchanged. + Every grant has an explicit expiry no later than the fork's current `forkExpiresAt`; effective access is `min(grantExpiresAt, forkExpiresAt)`. The existing target tenant-admin `POST /tenant-admin/tenants/{tenantId}/realm-access-grants/{worldSlug}/{realmSlug}/{playtestLifecycleId}` is the duplicate-safe create-or-extend command: it carries the exact account/lifecycle target, `operation`, requested `grantExpiresAt`, stable `requestId`, and conditional `expectedGrantRevision`. `expectedGrantRevision` is absent for `CREATE`, which is an explicit absent-grant-and-tombstone precondition, and is required for `EXTEND` against the current active-grant revision. Its action-family schema maps that revision presence/value to ADR 0047's typed `expectedVersion`, maps normalized operation and requested-expiry presence/value into typed `mutation`, and uses the exact seven-field `mutationDigest/v1` grammar; an exact request identity with the same digest replays that stored outcome, while changed operation, target, lifecycle, expiry, expected revision, or normalized payload returns `IDEMPOTENCY_CONFLICT` before mutation. Fork extension does not extend grants implicitly, and each grant extension revalidates the current fork expiry and advances the revision. Create, extend, revoke, and deliberate re-grant operations are ordered by the grant revision. Reordered or conflicting requests return the stored outcome or `IDEMPOTENCY_CONFLICT`; revocation retains a tombstone so delayed create/extend retries cannot resurrect access. A later intentional re-grant observes that tombstone and advances beyond it. Account atomically compares the expected revision with the current grant or retained tombstone, then commits the next revision, any tombstone, the durable request result, and the authority event. A mismatched existing revision, or a failed absent-grant precondition for `CREATE`, returns deterministic `GRANT_REVISION_CONFLICT` with no grant, tombstone, result, or event mutation. Concurrent operations with different request IDs and the same expected revision therefore have exactly one winner; an exact retry is resolved by request identity and `mutationDigest/v1` and replays the stored result without another revision or event. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index dafadd99c9..c89e281c6e 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +Global-role grant/revoke production and the protected first-administrator bootstrap are not implemented. V55 remains fresh-Account explicit-empty birth evidence only; there is no retained-row enrollment or versioned role writer. Account must not source current global roles or grant authority from the legacy scalar or token claims. The target owner contract and required source/readback boundary are defined in [Account API Contracts](./api-contracts.md#account-owned-global-role-administration) under [ADR 0185](../../decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md). + Canonical UUID membership, scope, journal, receipt, audit and event components widen the existing Account-owned families without rewriting retained history or inventing numeric aliases. Their readback-only reconciliation is not a public JOIN producer or fresh caller authorization. Complete authenticated current-target/entitlement composition and positive JOIN proof remain required; runtime paths stay denied. The [canonical JOIN contract](./api-contracts.md#canonical-uuid-join-evidence) belongs to the API owner, and component capability, executed proof and remaining gaps belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). Profile mapping receives the exact provenance-checked Account UUID explicitly rather than treating an ID-only profile relation as identity evidence. Numeric foreign keys stay private and retained rows are unchanged; reads, updates and local export verify exact Account/profile ownership. Proof and the separate tenant-qualified/delegated and Social Groups gaps remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). @@ -58,7 +60,7 @@ The unwired current-recipient membership producer now composes issuer, Account, The credential-granting gRPC `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` methods require the verified exact Game Session peer before invoking Account credential/challenge operations. Legacy profile GET/PUT require the exact Social Groups peer and matching non-internal caller-account subject; presence-policy reads require that peer. Direct account-ID export, external-link, and verification methods deny before reads or mutation. Runtime membership, grant, and entitlement reads still deny before owner data access. For membership, a held-back handler and client now enforce the typed caller/target, mTLS peer, and closed-carrier checks, but neither is wired into the active RPC; grant and entitlement paths remain separately gated. Focused negative tests cover local guards, while live composed certificate/consumer proof remains open; REST guards alone do not protect direct gRPC calls. -The target realm-grant mutation boundary remains the Account API's tenant-admin or separately authorized platform-admin operator path ([Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract)). The live legacy `POST`/`DELETE /internal/runtime/realm-access-grants` routes instead admit the broad shared global-privileged-role helper (including `moderator`), accept caller-supplied `grantedBy`/`grantReason`, and do not apply the target lifecycle identity, revision, digest, or request-replay contract. They must be removed or fail closed until the canonical owner transport and its authenticated attribution and replay proof are implemented; this route is not an additional grant authority. +The target realm-grant mutation boundary remains the Account API's tenant-admin or separately authorized platform-admin operator path ([Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract)). The legacy `POST`/`DELETE /internal/runtime/realm-access-grants` routes retain their old request shape and broad ingress guard, but now reject otherwise-valid requests with `AUTH_UNAVAILABLE` before service dispatch; direct grant/revoke service calls also fail before repository mutation. They are not an enabled grant authority or an implementation of the target lifecycle, revision, digest and replay contract. Canonical mutation and its authenticated attribution, current-lifecycle evidence and replay proof remain open in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Recovery/verification foundations are live. Password-reset and email-verification completion now claim the exact token row with a conditional SQL delete inside the account transaction before changing Account state; a failed or concurrent losing claim cannot mutate the account, and rollback restores the token. Focused local tests execute the single-use and rollback behavior; PostgreSQL concurrent-reuse cases compile but have not executed without Docker. Session revocation, token registry, distributed abuse controls, and end-to-end email-link reachability remain separate gaps under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md). @@ -186,6 +188,8 @@ Candidates come internally from the existing-only reader above, never from a cal **Target state:** Authentication generates a `control-ui`, player-bootstrap, or receiver-specific private player-delegation JWT and establishes exactly one server-side `session:auth:token:` registry record before returning it, following [ADR 0035](../../decisions/adr-0035-single-record-issued-token-registry.md). The record proves exact issuance and active state; signed claims plus Account-owned revocation/version state determine tenant and global authority without scope-duplicated token keys. **Current runtime:** it still uses the legacy Account session key and does not yet provide this registry proof. +**Target state:** Account persists and exactly reads back the immutable capture reference under [ADR 0035's bundle linearization contract](../../decisions/adr-0035-single-record-issued-token-registry.md#versioned-account-evidence-bundle-and-linearization), retaining each applicable source's independent version and checkpoint alongside the captured values. A later source advance does not rewrite that capture or make its reference current authorization; owner-side current-source and issuance-fence checks remain separate. The connect-source fence capture below is partial provenance, not this complete bundle. Detailed implementation and executed-proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). + **Target state:** `tokenHash` is a fixed-length digest (a hex-encoded SHA-256 of the complete compact JWT), and the one registry record's TTL is derived from that token's own `exp` claim, not from a global session lifetime: - `registry_ttl_ms = max(0, token_exp_ms - now_ms) + FIREMUD_AUTH_SESSION_SAFETY_MARGIN_MS` @@ -206,7 +210,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - It establishes account identity for first-party gameplay bootstrap only. The target creates public-game membership only through explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` require existing membership and the selected target's grants, entitlements, and admission checks. Current Account connect-token issuance and character discovery return non-actionable `JOIN_REQUIRED` only for missing or explicit `INACTIVE` membership on an eligible public-production target; an existing non-admitting membership is rejected. These paths do not create or restore membership. Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only fresh `MISSING`/`INACTIVE` membership can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account runtime readers still fail closed before reads, so this local classification does not prove a composed outcome; canonical eligibility and remaining outcome mapping belong to [Authentication](../../system-architecture-authentication.md). World and realm discovery remain available before membership. The Account JOIN writer/controller and direct text `JOIN` dispatch exist locally, but the Gateway guard blocks external route exposure and first-party `Join & Play` remains unavailable. Durable recovery after an unknown database commit outcome remains open. Non-public targets remain subject to their realm-access and grant checks rather than public onboarding semantics. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. -- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The V37.1 storage candidate binds an exchange to a committed V35 connect operation and stores an immutable purpose-bound terminal envelope, but neither operation is wired to credential issuance or recovery. The selected expired-context terminal-recovery contract is owned by [Authentication](../../system-architecture-authentication.md#terminal-bare-login-result-recovery-normative); it is unimplemented and unproved. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish the complete proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. +- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The V37 storage candidate binds an exchange to a committed V35 connect operation and stores an immutable purpose-bound terminal envelope. Forward V53 permits the non-authorizing pending claim and write-once evidence to survive separate Account transactions for recovery; terminal success still commits atomically with its exact bound envelope. This is a storage prerequisite for [ADR 0014's ordered crash-safe issuance](../../decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md#crash-safe-issuance-and-registry-projection), not a complete pre-sign authority bundle or signing/registry path. Neither operation is wired to credential issuance or recovery. The selected expired-context terminal-recovery contract is owned by [Authentication](../../system-architecture-authentication.md#terminal-bare-login-result-recovery-normative); it is unimplemented and unproved. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish the complete proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. - It is backed by one `session:auth:token:` record so per-token logout and account-level revocation semantics remain consistent. - `POST /auth/logout` and `POST /auth/logout-all` must accept this profile so first-party gameplay UIs can explicitly revoke bootstrap capability on sign-out rather than waiting for expiry. @@ -291,6 +295,8 @@ The exact tenant identity in connect issuance, bare-`LOGIN` exchange, operation The target Account persistence shape is not current implementation: one Account-schema `connect_token_issuance_operation` record owns the exact `(accountId, tenantId, connectScopeId, requestId)` identity, Account-computed versioned request digest, lifecycle (`PENDING`, `COMMITTED`, deterministic `FAILED`, or `ABORTED`), token identity/hash and authority/postcondition evidence, and reconciliation metadata; it never stores a raw JWT. A separate bounded `connect_token_response_envelope` record is keyed to that operation and stores the exact success credential or deterministic failure only as an Account-encrypted envelope with its key/version and authenticated binding to the operation identity, digest, authority tuple, Account-local issuance CAS fence, and applicable postconditions. That Account-local fence serializes the durable operation; it is not an `issuanceFence` claim in the `gameplay-connect` token or a substitute for Gateway's distinct `replayAdmissionFence`. Both records are Account-owned service-schema objects introduced and accessed through the service-local Flyway/jOOQ lineage; Redis remains only the reset-sensitive exact-result projection/cache. +Account captures the positive local issuance-fence value and its positive source version from its durable authority row while the complete applicable authority snapshot is fenced, and binds them write-once to the existing issuance operation. The versioned internal `account-connect-issuance-fence/v1` digest is SHA-256 over ADR 0047-style UTF-8 byte-length framing of, in fixed order, the schema name, exact operation UUID, canonical Account UUID, canonical tenant UUID, stored connect-scope hash, request ID, lowercase hexadecimal request digest, captured issuance-fence value and captured fence source version. Counters use canonical positive decimal strings. The capture and the source operation's authority, terminal outcome and envelope belong to the same Account transaction; a capture alone is not successful issuance. Its exact durable readback must reproduce both the stored digest and the envelope's authenticated fence binding. An absent capture is unproved provenance, never a value inferred from a current row, a token field, a numeric association or a retained digest. Existing operation and envelope bytes are not backfilled or rewritten to manufacture that proof. A current-authority comparison verifies every applicable tuple member and independent membership version as well as this captured Account fence; matching the scalar alone does not establish issuer or tenant currentness. This internal evidence neither changes the closed `gameplay-connect`/Gateway schemas nor makes their distinct replay fence interchangeable with Account authority. + Account owns one versioned, mounted-secret key ring and rotation procedure for both connect-token issuance and bare first-party `LOGIN` response envelopes. The ring contains distinct AEAD keys for the two purposes; an envelope records its purpose and key ID, and a key for one purpose must never decrypt the other. These encryption keys are separate from JWT signing and request-digest keys. New envelopes use the current write key for their purpose. Rotation makes older keys decrypt-only, and Account retains each old key until no retained envelope requiring exact-result recovery references it; removal is an evidence-backed cleanup decision, not a fixed timer. Decryption authenticates the exact durable operation identity, request digest and applicable authority/postcondition binding. Recovery first reads back that operation and its exact envelope, then checks the recorded purpose, key ID and binding before returning the original result. A missing key, failed authentication, missing or mismatched operation or envelope, or binding mismatch fails closed and never mints a replacement credential. Neither envelope purpose is enabled until rotation, wrong-purpose and wrong-operation rejection, and lost-response recovery are proved for its producer and consumer. The operation identity is claimed by a serializable transaction or equivalent Account-owned CAS: one matching digest wins, a concurrent matching request waits for and reads the same operation, and any changed digest returns `IDEMPOTENCY_CONFLICT` without minting or mutating. Account records the durable operation before exposing a result, accepts and reads back the required registry/admission postconditions before `COMMITTED`, and exact retries revalidate current authority and all applicable registry/admission postconditions before decrypting and returning a successful credential envelope. If that revalidation fails, the retry returns the applicable canonical denial and leaves the committed operation and envelope unchanged; it does not remint or replace the credential. A deterministic `FAILED` result, such as `JOIN_REQUIRED`, replays its stored failure envelope directly after the exact operation identity and digest match, without rerunning authority or membership checks, while that failure envelope remains retained. If the matching compact receipt remains after its response envelope has been removed at the declared response-recovery horizon, an exact digest match returns `RESPONSE_RECOVERY_EXPIRED`; a changed digest still returns `IDEMPOTENCY_CONFLICT`. That outcome is terminal for the original issuance attempt and callers must use a new `requestId` for a fresh authorized request. Missing, ambiguous, or unreconciled durable state fails closed; no retry reconstructs or silently remints a JWT. The response envelope must not be removed while the operation is pending, ambiguous, or otherwise blocked on reconciliation. This target persistence/CAS/readback path is unimplemented and must not be inferred from the current Redis map. @@ -335,15 +341,15 @@ Entitlement producer contract: ### Playtest Grant Persistence and Authority Consequences -The complete Account-owned grant mutation and replay contract is defined in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract). This runtime document owns only its data and projection consequences: persist one grant scope `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}` with active/revoked state, `grantRevision`, explicit `grantExpiresAt`, fork-expiry reference, grantor/audit metadata, request outcome, and a retained revocation tombstone. The grant row must never be hard-deleted while delayed request replay could still arrive. Each mutation also persists a separate durable grant-mutation operation/replay recordβ€”not a second grant rowβ€”with `requestId`, ADR 0047's exact seven-field `mutationDigest/v1`, normalized operation, complete lifecycle-bound target, requested expiry, conditional `expectedGrantRevision` mapped to typed `expectedVersion` (absent only for the initial `CREATE` precondition), pending or terminal outcome, and the configured retention/deduplication horizon. Exact request/digest retries replay that operation result and changed inputs conflict before grant mutation; the operation record is distinct from both the current grant row and its retained revocation tombstone. +The complete Account-owned grant mutation and replay contract is defined in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract). This runtime document owns only its data and projection consequences: persist one grant scope `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}` with active/revoked state, `grantRevision`, explicit `grantExpiresAt`, the exact World-owned fork-expiry reference, grantor/audit metadata, request outcome, and a retained revocation tombstone. The grant row must never be hard-deleted while delayed request replay could still arrive. Each mutation also persists a separate durable grant-mutation operation/replay recordβ€”not a second grant rowβ€”with `requestId`, ADR 0047's exact seven-field `mutationDigest/v1`, normalized operation, complete lifecycle-bound target, requested expiry, conditional `expectedGrantRevision` mapped to typed `expectedVersion` (absent only for the initial `CREATE` precondition), pending or terminal outcome, and the configured retention/deduplication horizon. Exact request/digest retries replay that operation result and changed inputs conflict before grant mutation; the operation record is distinct from both the current grant row and its retained revocation tombstone. -Account's grant write transaction compares `expectedGrantRevision` against the current active grant for `EXTEND`/`REVOKE`, against the current grant or retained tombstone for `REGRANT`, or verifies the absent-grant-and-tombstone precondition for `CREATE`; on success it commits the next revision, grant/tombstone projection, durable result, and authority event atomically. A stale or failed precondition is a deterministic `GRANT_REVISION_CONFLICT` with no grant, tombstone, result, or event mutation. Concurrent operations sharing one expected revision have exactly one commit; an exact request retry replays its stored result without another revision or event. +The Account-owned commit atomically records the applicable `grantRevision`, independent per-grant `sourceVersion` and checkpoint, grant/tombstone projection, mutation receipt, and outbox evidence. These counters have separate meanings and must never be aliased. A missing grant row or copied snapshot is not proof of an initial source-version baseline: proved Account-owned source enrollment establishes that baseline, while the current source snapshot never substitutes for the required commit-gate owner fence. The complete mutation/CAS and retry semantics remain owned by [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract). Account evaluates effective access as `min(grantExpiresAt, forkExpiresAt)` and emits a monotonic grant authority event on create, extension, revocation, expiry, and deliberate re-grant as part of the successful mutation commit. The stream is scoped to the exact grant, with the same per-stream sequence, event identity/digest, checkpoint, and gap/conflict fail-closed rules as other Account authority streams. Consumers do not reconstruct grant state from a JWT, realm slug, cached discovery result, or a separate fork read. A missing, stale, contradictory, or unavailable grant projection denies non-public discovery/admission and requires exact Account reconciliation. Grant `scopeId`, `outboxStreamKey`, and event `sourceScope` are produced and parsed through the [canonical grant authority-stream scope codec](../../system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). This document owns only the persistence and projection consequences; it does not define another stream grammar or fallback identity. -Current `AccountRealmAccessGrant` persistence is limited to the legacy four-field identity; current Game Session grant gRPC reads fail with `FAILED_PRECONDITION` before data access, so downstream text `PLAY` does not reach grant evaluation. The unsupported legacy grant and revoke HTTP entries and direct service mutators now deny before grant reads or writes. Existing rows, versions and history remain unchanged; hard-deleting a legacy row is not a substitute for a lifecycle-bound revocation tombstone. No lifecycle-bound read, expiry, fork-expiry evaluation, tenant-admin mutation surface, expected-revision CAS, request-replay record, durable tombstone, revocation propagation, consumer reconciliation, active-binding ejection, or complete grant event proof exists. During the direct pre-v1 cutover, records lacking `playtestLifecycleId` are invalidated or denied and must be regranted under the exact lifecycle; this local status does not add an alias or compatibility path. The gap statement is intentionally local; endpoint ownership and mutation outcomes remain in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). +Current `AccountRealmAccessGrant` persistence is limited to the legacy four-field identity; current Game Session grant gRPC reads fail with `FAILED_PRECONDITION` before data access, so downstream text `PLAY` does not reach grant evaluation. The unsupported legacy grant and revoke HTTP entries and direct service mutators now deny before grant reads or writes. Existing rows, versions and history remain unchanged; hard-deleting a legacy row is not a substitute for a lifecycle-bound revocation tombstone. World playtest lifecycle allocation and authenticated Game Session pointer-bound readback, Account lifecycle-bound grant reads and writes, independent grant `sourceVersion`/checkpoint persistence, expiry evaluation, tenant-admin mutation, request-replay receipt, durable tombstone, revocation propagation, consumer reconciliation, active-binding ejection, and complete grant event proof remain unimplemented. Runtime grant reads continue to deny before data access; legacy rows and snapshots cannot stand in for current owner proof. During the direct pre-v1 cutover, records lacking `playtestLifecycleId` are invalidated or denied and must be regranted under the exact lifecycle; this local status does not add an alias or compatibility path. The gap statement is intentionally local; endpoint ownership and mutation outcomes remain in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). ### Runtime Implementation Status and Drift diff --git a/design/architecture/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index 3e3376aaea..03f9d6759d 100644 --- a/design/architecture/microservices/account-service/subscription-management.md +++ b/design/architecture/microservices/account-service/subscription-management.md @@ -15,6 +15,8 @@ Payment-instrument ownership, explicit per-subscription binding, and billing-own The plan-change timing, over-quota behavior, pending-plan metadata, and full quota-bearing runtime entitlement response described below are canonical target-state behavior. Current implementation has the first runtime availability surface, but quota fields, pending plan metadata, downgrade/cancellation enforcement, strict capacity admission, and the target separation between create and existing-subscription update APIs still need implementation follow-through. The current `CreateSubscriptionRequest` carries only tenant/account/plan fields: it lacks the caller-supplied stable `requestId`, exact instrument-selection input, and immutable creation-operation identities. Account computes the versioned `requestDigest` from normalized request fields; that digest is not a caller-supplied request field. Account must also resolve the authoritative billing owner, which is not supplied as a request field. Account therefore rejects this incomplete create method with `FAILED_PRECONDITION` before any membership, account, subscription, or provider mutation; it must not be treated as proof of the target contract. Expected row-version/CAS is not a creation precondition and is required for every supported existing-subscription mutation through `UpdateSubscription`. The durable authority/usage ledger and reservation lifecycle for strict capacity admission are also not implemented. +Initial billing enrollment is also unimplemented: the fresh tenant identity association records canonical tenant provenance but no authenticated initiator or billing-enrollment authority, and the Account-side payer-consent/owner-CAS producer and proof are absent. `CreateSubscription` remains denied until its prerequisites are implemented. The fresh tenant source contract is [owned by Game Design](../game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback); current capability and proof status belongs in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + The target `CreateSubscription` request accepts a high-entropy stable caller-supplied `requestId` as the sole logical create-operation key, along with the normalized tenant, plan, and instrument-selection inputs. Account resolves the authoritative billing owner and computes a versioned `requestDigest` from those normalized inputs and the resolved owner; neither the digest nor billing-owner resolution is supplied as a request field. Account captures the resolved owner's authority version/generation and validates that exact fence in the same local intent/outbox transaction before persisting the pair or creating provider work; an owner change or generation/version mismatch fails closed. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same `subscriptionId`, durable operation, and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`. The provider `subscription_provisioning_request_id` and cleanup identity remain separate provider-operation keys and must not replace the caller identity. Hosted-terms acceptance and the tenant's Creator Party are separate from subscription and billing ownership. Current V1 subscription behavior remains the hosting-billing boundary in [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md). [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) is accepted and defines the target changed-terms boundary: decline or missing reacceptance blocks new covered creator-content mutations but does not itself cancel a subscription, delete content, or decide a refund; those mutations still require the Account-owned currentness outcome. Only the detailed renewal, paid-through continuity, exit, refund, and service-credit choreography across a material terms change remains candidate pre-launch policy pending complete terms and New Zealand legal review. No current route or implementation proves these changed-term behaviors. @@ -56,6 +58,14 @@ Saved payment instruments are account-owned and managed only by the authenticate Every existing-subscription mutation, including plan change, cancellation, instrument rebinding, and billing-owner transfer, must use the exact HTTPS `control-ui` route class and recent ordinary reauthentication. The owner path requires the route's required assurance and binds the authenticated subject to `subscription.accountId`; the only cross-tenant alternative is the explicit audited billing-owner handoff, which retains the exact HTTPS `control-ui` and recent-reauthentication requirements and additionally requires `privileged_control` assurance and explicit target binding. Creation has no subscription row or `subscription.accountId` yet: Account must first resolve the authoritative billing owner for the target tenant and authorize the actor against that resolved owner, or require the explicit audited handoff authority, before persisting any subscription intent or row. The actor must remain distinct from the billing-owner subject. Payment selection is never inferred from an account, Stripe customer, or provider default: creation and any mutation that changes payment binding must carry an explicit instrument or deterministic selection that resolves to exactly one instrument owned by the authorized billing owner. +### Initial Billing Enrollment + +For a newly provisioned tenant, only Account may begin initial billing enrollment after verifying the exact canonical tenant and immutable Game Design creation receipt in Account's tenant-provisioning transaction. Account binds the authenticated initiator to that verified initiating Account provisioning operation; an arbitrary authenticated caller presenting a Game Design identity receipt is insufficient. Account then issues one operation-specific, one-time enrollment authority bound to that Account operation, tenant, creation receipt, initiator, and expected `UNASSIGNED` owner state. That authority permits nomination of a payer only; it does not assign an owner, authorize billing, or grant a role. The tenant-creation receipt establishes tenant identity and does not itself establish payer or billing authority. See the [Game Design fresh-tenant source contract](../game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback). + +The nominated payer must directly authenticate and explicitly consent to the exact tenant and enrollment operation/digest. Account accepts consent only for that scope, then atomically consumes the enrollment authority, compare-and-sets the initial owner from `UNASSIGNED` using durable owner evidence, advances the independent owner version, and records the immutable consent/replay receipt. `UNASSIGNED` must be proved by durable owner evidence; a missing owner row is not evidence of that state. Exact retries return the original result; a changed scope or competing owner assignment is denied. The initiator, nominator, payer, and resulting owner are distinct identities unless independently proven equal. Neither `tenantAdmin`, Creator Party membership, a payment instrument, nor a caller-supplied account identifier supplies or implies enrollment authority. `tenantAdmin` remains view-only for billing. + +Retained tenants use the existing audited privileged `control-ui` bootstrap for initial owner binding; fresh-tenant enrollment authority must not be reconstructed from a retained association. This enrollment does not authorize `CreateSubscription` or select an instrument: subscription creation still requires the caller authorization, explicit instrument selection, stable operation identity, owner fence, and local intent/outbox transaction defined below. Payment-instrument ownership and binding remain governed by [ADR 0044](../../decisions/adr-0044-account-owned-payment-instruments-with-explicit-subscription-binding.md), and V1 remains limited to hosting billing under [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md). + Current support-safe allowlist in this domain: - `GetTenantEntitlementsCrossTenantSupportSafe(tenantId)` diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index b8f4cef2de..4247471204 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -42,6 +42,8 @@ The readback request binds a distinct canonical non-nil read `requestId` to the ### Authored-source-bound launch descriptor and exact readback +The descriptor's `publishedReleaseBundleRef` uses the exact persisted [Game Design release identity](version-control.md#launch-and-attestation-read-authorization-target-state), not a reference reconstructed from its source tenant or private row identifiers. A new source-bound resolution rejects a bundle without that owner reference. This storage prerequisite does not complete the separately required release-attestation response or authorize launch. + Game Design's existing immutable launch-descriptor boundary binds selector provenance to a resolved release; it does not turn selector registration into publication. Game Session remains the launch orchestrator. A canonical launch request names the exact authored-source operation and evidence digest, canonical tenant UUID and tenant-scoped `worldSlug`, together with its stable request identity and requested template/version inputs. Game Design reads and verifies its actual persisted source and template/version ownership before resolving. A private Game Design source key is usable only inside that proved owner association, never as a World or Game Session tenant alias. The committed descriptor retains those source fields and the exact resolved template, version, release bundle reference and Game Design version-state epoch, plus every other resolved launch field and the original request identity/digest. New canonical request and result digests use distinct versioned domains, fixed exhaustive field order, strict UTF-8 byte-length framing and explicit optional presence/value encoding as in [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). A digest excludes only its own derived value, not an applicable source, request or result field. Source identity, release attestation and the launch result remain independently verified evidence; none substitutes for another. @@ -123,7 +125,7 @@ Concrete RPC names, message fields, enums, pagination, and transport exposure re For every creator-intent `SaveRevision`, including revision-only requests, the exact Account party, acceptance-evidence, and material-acceptance-generation authorization must remain valid through Game Design's authoritative commit boundary. A preflight Account read alone is insufficient. If the authority is stale, mismatched, unavailable, or uncertain at that boundary, Game Design aborts the local transaction; no creator mutation or staged artifact becomes authoritative or externally reachable, and any staged artifact is cleanup/quarantine state, not success. The implementation must use commit-bound Account authorization/fence or equivalent validation without this contract selecting its mechanism. -For a `SaveRevision` request carrying `worldDesignMutation`, the same authorization invariant additionally applies to every participating authoritative mutation. Participating owners may use prepare or other non-authoritative staging before the authoritative commit boundary, but this contract selects no transaction, lease, fence, saga, route, or schema mechanism. If the boundary cannot be satisfied, no participating owner commits, and SaveRevision must not report success for a partial cross-owner commit. +For a `SaveRevision` request carrying `worldDesignMutation`, the same authorization invariant applies to every participating authoritative mutation. Game Design carries the current Account authorization with the exact mutation descriptor to World, whose owner contract defines the [canonical Draft commit authorization boundary](../world-management-service/api-contracts.md#canonical-draft-commit-authorization). Until World can verify that authorization at its commit boundary, no participating owner commits and `SaveRevision` must not report success for a partial cross-owner commit; any staging remains non-authoritative. A source receipt, forwarded JWT, workload identity, or preflight-only check does not satisfy this producer obligation. ## Implementation Status diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index c4cfb7d116..9d2411a8b2 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -149,7 +149,7 @@ In addition to domain-service digests, publish safety requires a Game Design con - `participantDigests[] { serviceName, appliedCommitId, contentDigest, digestSchemaVersion }` - `artifactDigests[] { usageKey, artifactKind, immutableObjectKey, contentDigest, contentType, artifactSchemaVersion }` for every exported binary or derived artifact; these entries are mandatory in the initial slice for world navmesh/path graph bundles - `requiredManifestAssetKeys[]` listing the stable manifest usage keys required for launch or cutover validation of that release - - `publishedReleaseBundleRef` β€” target-state owner-generated opaque identity for the immutable release bundle; the current implementation may expose only its internal bundle row identifier, so this field is not yet live + - `publishedReleaseBundleRef` β€” Game Design-generated opaque identity durably bound to the immutable release bundle, never reconstructed from tenant, version or private bundle-row identifiers. The owner repository assigns and reads back this identity for new bundle rows; retained rows remain unbound rather than receiving inferred identities. The source-bound descriptor and bundle read carry the exact stored value; a retained row's missing reference remains absent, never replaced by a synthetic alias. The complete commit, artifact, manifest and ability-schema evidence still remains incomplete, so this identity's persistence and transport are not proof of a complete launch attestation. - `manifestHash`, `manifestSchemaVersion` - `abilitySchemaDigest` β€” the dedicated Game Logic-owned ability-schema digest for the same target commit, carried with the existing Game Logic participant `digestSchemaVersion` and canonicalization evidence; aggregate participant digests are not substitutes - `generationConfigRevision` diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 137f8e7c0c..0ea25d084c 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -44,6 +44,10 @@ It also communicates game lifecycle changes to other microservices over gRPC so Game Session consumes the exact authenticated authored-world receipt defined by [Game Design's source contract](../game-design-service/api-contracts.md#authored-world-source-registration-and-game-session-readback) before its own runtime catalog intake. The source client validates the separate read identity, complete tenant/world scope and both immutable digests; it does not create or update a catalog, select a runtime, or grant admission. Game Session alone persists the runtime association and must prove exact owner readback. A retained numeric Game Session tenant key requires its separately audited source association and current retained-row evidence, never Account's migration manifest or a guessed selector. Normal fresh intake is an automated owner handoff, while this candidate stays unwired until producer, receiver, creator authorization and catalog proof exist. Remaining implementation and execution limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +### Playtest lifecycle proof on the admission pointer + +For a private/playtest target, Game Session consumes World Management's exact current `{playtestLifecycleId, forkExpiresAt}` proof together with its existing lifecycle version/epoch evidence. It records the proof with the admission-pointer CAS and audit, and its authenticated pointer-bound readback returns that same World evidence for Account's grant validation. `pointerVersion` is Game Session's independent routing fence; it does not allocate or replace the World lifecycle identity, version/epoch, or expiry. Public-production pointers omit playtest lifecycle evidence. World remains the only lifecycle and expiry producer under the [World playtest lifecycle contract](../world-management-service/operations.md#playtest-fork-lifecycle-authority); Game Session does not define a competing producer or derive `forkExpiresAt`. World allocation/readback and this authenticated pointer-bound carrier are not implemented. + ### Authored-world source intake and durable readback The separate [audited retained-tenant association](../game-design-service/api-contracts.md#audited-retained-game-session-tenant-association) uses this same Game Design-authenticated client channel but a distinct closed manifest and read method. The client checks the independent request echo, exact namespace/operation/tenant/key binding, complete evidence, canonical signature shape and recomputed digest. It does not persist a local retained association or prove the captured Game Session rows; that owner-fenced snapshot and durable receiver remain required before catalog use. The source digest and historical approval are never gameplay authorization. @@ -54,6 +58,8 @@ Game Session's source intake binds its own stable non-nil UUID `intakeRequestId` Reject an ambient transaction before the authenticated source call; no Game Session owner transaction or row lock spans that network read. After validating the immutable source, a short writable READ COMMITTED owner transaction atomically persists the local non-nil UUID operation, immutable source evidence and tenant selector claim. Within a namespace, one tenant UUID has one `tenantSlug`, one `tenantSlug` has one tenant UUID, and each `(tenantId, worldSlug)` has one exact consumed source. Compatible additional worlds reuse the same tenant source claim; a conflicting tenant/world/source or changed request fails without partial claims. After the write commits, independently read and compare the complete original local request, operation, source and digests before returning success; missing, changed or unavailable readback denies success without repairing or replacing committed evidence. Exact retries first read the original committed request and return its original local operation and receipt without changing rows or repeating the upstream source call; changed tenant, source operation or world scope conflicts. The transient read-attempt ID is an authenticated response echo, not a replacement intake request or persisted registration field. Committed readback is non-mutating and checks the complete stored source and selector binding; it cannot allocate missing state or choose another candidate. +An owner-local read by exact `(targetNamespace, canonicalTenantId, worldSlug)` may recover that selector's one committed intake receipt and its original Game Design source operation and evidence digest. It validates the complete stored receipt and tenant binding, returns absence without enrollment, and cannot infer an authored source from a numeric row, published-policy digest or retained-association approval. A retained tenant's minimal audited association proves its distinct local key; that association and the authored-world intake are separate evidence families. Launch orchestration compares their shared canonical identity and source provenance with the selected catalog before using the source receipt. The lookup itself neither authorizes launch nor supplies release attestation. + `game-session-authored-world-intake-request/v1` hashes, in order, the domain, canonical `intakeRequestId` and Game Design `evidenceDigest`. `game-session-authored-world-intake-receipt/v1` hashes the domain, canonical local operation UUID, exact local request digest and exact Game Design evidence digest. Each value is encoded in UTF-8 as its decimal byte length, a colon, then those bytes; results are lowercase `sha256:` SHA-256 values. Game Design's closed source codec independently verifies all source fields and both owner digests before either local digest is calculated. A local digest never replaces the authenticated source read or its exact scope checks. 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. @@ -80,6 +86,20 @@ Exact retries and lost-response recovery read back the original routing tuple, t 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). +### Source-qualified launch preparation and durable readback + +Game Session consumes Game Design's exact [authored-source-bound descriptor](../game-design-service/api-contracts.md#authored-source-bound-launch-descriptor-and-exact-readback) against its committed canonical catalog and source intake before preparing a canonical runtime. Its local preparation binds the stable control-plane request, acting Account UUID, exact namespace/tenant/realm/catalog identity and the complete original descriptor request and result. The acting Account value is an identity binding, not creator/terms authorization; that current Account authorization remains required before an authorized creation workflow invokes the primitive. A preparation neither allocates a runtime instance nor creates World lifecycle, membership or admission authority. + +Reject an ambient owner transaction before contacting Game Design. Read and verify the exact committed catalog/source, resolve through the exact same-namespace Game Design workload, then independently read and compare the complete immutable descriptor. No Game Session transaction or row lock spans those network calls. In a short writable READ COMMITTED transaction, lock and revalidate the same catalog/source and atomically retain the original request, descriptor and local operation/digests. After commit, independently read and compare the complete durable result before returning success; missing, changed or unavailable readback denies success without repairing or replacing evidence. + +An exact committed retry returns its original operation and descriptor without upstream re-resolution or new allocation. Changed acting Account, catalog/source, requested launch field or descriptor binding conflicts under the same request identity. Historical preparation readback is not current launch permission: canonical World preparation must independently verify and retain the source/descriptor association, complete release attestation and required current Account authorization through its own commit boundary. World lifecycle epochs remain distinct from Game Design version-state epochs. The initial pointer/World hold contracts still govern any later first OPEN; the current `StartSession` denial cannot be removed merely because preparation readback succeeds. + +The local request digest is SHA-256 over the following fixed-order UTF-8 segments, each framed as its canonical decimal byte length, a colon, then its exact bytes: `game-session-canonical-launch-preparation-request/v1`, schema version `1`, `controlPlaneRequestId`, acting Account UUID, target namespace, canonical tenant UUID, realm UUID, catalog creation request UUID, catalog revision, source intake operation UUID, Game Design template ID, requested script-patch presence/value, source-version presence/value, target-version presence/value, runtime-flags presence/value, the complete catalog segment below, source intake operation/request UUIDs and request/receipt digests, authored-source schema version, registration request UUID, source operation UUID, source request digest, canonical tenant UUID, tenant slug, world slug, display name, private source game-row ID, private source tenant key, provenance kind, source evidence digest, and descriptor request/result digests. The catalog segment is its exact target namespace, tenant UUID, tenant slug, world slug, realm UUID, realm slug, realm display name, visibility, public-production flag, state scope, playable-state namespace UUID, character-creation policy, catalog revision, creation request UUID, request digest and receipt digest, in that order. UUIDs use canonical lowercase spelling, counters use canonical decimal strings, and booleans use `true` or `false`; an absent optional value contributes an empty segment, while a present value retains its exact bytes. Presence/value contradictions, malformed Unicode and unsupported evidence fail closed. The private source identifiers are owner-qualified evidence, never public identity or runtime selectors. Valid runtime-flags text is not reserialized for this digest. + +The receipt digest uses the same framing over `game-session-canonical-launch-preparation-receipt/v1`, schema version `1`, the fresh local preparation operation UUID, request digest, target namespace, control-plane request ID, acting Account UUID, canonical tenant UUID, realm UUID, catalog creation request UUID, catalog revision, catalog request/receipt digests, source intake operation/request UUIDs and request/receipt digests, source evidence digest, and descriptor request/result digests. Both digests are lowercase `sha256:` plus 64 hexadecimal digits. Persist the complete closed request/catalog/source/descriptor evidence and redundant identity/digest columns atomically; committed readback must decode, validate their exact joins, recompute both digests and compare every stored identity/digest before returning evidence. JSON storage formatting is not the digest preimage and cannot change the bound values. + +This local consumer and persistence remain an unwired candidate until their focused producer/consumer proof is complete; implementation and execution limits belong to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). Preparation survivor evidence has no invented TTL or automatic release; cleanup requires its owning retention proof. + ### 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/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index e10fcbdb3f..62e69884ea 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -34,6 +34,10 @@ Target state only: for script and plugin operations, Logging & Admin is a compos Routine rollback is expected to leave ordinary gameplay available while scoped Automation admission drains and reconciles; operator views must not describe cleanup or projection lag as a gameplay pause. Dead-letter recovery and purge remain separate, explicit, per-row owner operations. These read and audit consequences follow the [scripting contracts](../../system-architecture-scripting-contracts.md), [scripting control-plane API](../../system-architecture-scripting-control-plane-api.md), and [scripting rollout and rollback](../../system-architecture-scripting-rollout-and-rollback.md) owners. +## Global Role Administration Ingress + +Global-role grant/revoke ingress is target-only and no route or action schema is currently selected. If implemented, requests must enter through the canonical Gateway β†’ Logging & Admin human operator path, with a live `platformAdmin` actor, current `privileged_control` step-up, durable local operator intent/audit, and Account-issued currentness authorization validated again by Account at the owner commit. Logging & Admin must not write role state, authorize from asserted roles, substitute tenant scope for a global-account target, or forward unattended automation requests. The initial administrator uses the separate protected deployment bootstrap and does not pass through this ordinary ingress. Apply the human step-up and operator delegation boundaries in [ADR 0045](../../decisions/adr-0045-ordinary-login-factors-and-https-sensitive-action-step-up.md), [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md). See [Authentication](../../system-architecture-authentication.md#role-model), [Account's owner contract](../account-service/api-contracts.md#account-owned-global-role-administration), and [ADR 0185](../../decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md); no runtime route is thereby enabled. + ## Implementation Status - Offline producer and receiver fixtures retain the typed `CreateLogEvent` response checks and receipt/projection behavior; this is not a live delivery capability. In the live boundary, `CreateLogEvent` authenticates the exact Account mTLS workload and then returns `UNAVAILABLE` before envelope conversion or storage, while Account automatic delivery scheduling is disabled and pending outbox rows remain pending. Account does not yet invoke `ReadLogEventReceipt`; exact receiver readback and guarded recording of retained historical delivery evidence remain Account-owned activation gates. Focused unit proof is authored, but PostgreSQL migration/transaction runtime proof and direct text-client-to-Logging end-to-end proof are not claimed. The full receiver retention horizon, safe-watermark, hold, and payload-minimization lifecycle remains governed by the owner contract above and [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index a682f35fc6..25481624eb 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -8,7 +8,7 @@ This API contract is target-state canonical; implementation coverage is partial - The bridge, cross-service callers, examples, and focused proof have not migrated together to the scoped decimal `roomInstanceId` contract. The checked-in proof still exercises the legacy encoding. - The typed `ApplyRoomAmbientStatePatch` contract below is target-state: the current service has no complete handler or durable operation/digest-bound guard, so player-significant ambient mutations remain on the fenced Game Session admission/reconciliation path and are not direct table writes. - `GetDraftDesignDigest` requires the verified same-namespace Game Design workload peer and validates the complete typed publication-read request/workflow/digest binding before reading owner content. Wrong-workload and changed-binding unit denial proof exists. Its current content resolver still uses numeric tenant/version storage, and this read supplies neither canonical-source-qualified write authorization nor a publication-freeze acknowledgement or terminal result. The target owner-to-owner read contract remains canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); current capability and proof limits belong in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). -- The current typed `ApplyWorldDesignMutation` owner-write boundary also has no method/workload or tenant authorization beyond shared JWT parsing: its gRPC handler forwards any authenticated bearer to the mutation service, whose current checks cover request shape and Draft state but not caller identity or tenant access. This is separate from the digest-read gap and the legacy REST generation-rule gap; the target authenticated Game Design caller and tenant authorization remain defined by the design-time contract below, and wrong-workload/cross-tenant denial is not implemented or proved. +- The current typed `ApplyWorldDesignMutation` owner-write boundary has no commit-time creator authorization: its gRPC handler forwards any authenticated bearer to the mutation service, whose checks cover request shape and Draft state but not the acting account, current tenant role, or applicable Account terms authority. V24 SQL guards deny canonical-key mutations across all 16 tenant-bearing tables. The source-qualified Game Design Draft/version read is non-mutating precondition evidence, not write authorization. Current wrong-workload, cross-tenant, and commit-time authorization denial proof remains absent; see the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status). - Required executable migration/proof gate: `./gradlew :world-management-service:test :game-logic-service:test :game-session-service:test :tcp-proxy-service:crossServiceTest`. This gate must update the bridge, callers, examples, and checked-in proof together and pass before the target examples below may be treated as current. This document does not claim that the gate exists or passes. ## gRPC APIs @@ -62,7 +62,7 @@ Runtime/gameplay-facing requests to this service come from other internal servic World Management exposes design-time APIs used by Game Design to write Draft template rows keyed by `(tenantId, versionId)`, such as creating or updating `room_template` rows and version-scoped topology bindings. -- Auth: design-time APIs must validate JWTs and enforce designer/admin authorization for the target `tenantId`, consistent with Game Design control-plane auth. +- Auth: external design-time entrypoints validate JWTs, while Game Design-to-World canonical writes require the authenticated producer and current Account authorization through the [owner commit boundary](#canonical-draft-commit-authorization); an entrypoint JWT is not that owner authorization. - Mutability: design-time writes are allowed only for Draft versions. Attempts to write templates for Published, Active, or Failed versions must fail fast. - Publication handoff: the owner-local freeze protocol below is the only WMS publication boundary. A digest or preflight `GetVersionState` read without its acknowledgement is not publication proof. Game Design owns lifecycle state and final release attestation; WMS owns this freeze, its Draft write fence, and the terminal owner handoff. - Scope integrity: scoped `ApplyWorldDesignMutation` requests must prove the changed topology belongs to the declared `REGION_SUBTREE` or `ZONE_SUBTREE` before advancing a scope epoch. Room exits must keep both endpoints inside the declared scope. Unsupported `NEW_EMPTY_REGION` combinations must return a normal application error instead of applying a partial topology mutation. @@ -70,6 +70,12 @@ World Management exposes design-time APIs used by Game Design to write Draft tem - Scoped `WORLD_GENERATION_SUBTREE` mutations are the canonical multi-row generation write path. They apply generated rooms, room exits, generation rules, and spawn bindings under one declared `REGION_SUBTREE` or `ZONE_SUBTREE`; `REPLACE_SCOPE` removes prior room, exit, spawn-binding, and generation-rule rows inside the scope before applying the replacement, while `SEED_APPEND_ONLY` rejects rewrites of existing same-scope generation rules or spawn bindings. - Runtime isolation: runtime gameplay flows and the world-lifecycle workflow must never call design APIs. +### Canonical Draft commit authorization + +For a canonical Draft write, Account supplies the current tenant-scoped designer/admin authorization for the acting account; where official-hosted creator terms apply, the applicable Account-owned party and terms currentness authority is required independently of the tenant role. Game Design carries that authorization with the exact World mutation descriptor. The descriptor and authorization must bind the acting account, canonical tenant, stable operation identity and digest, expected Draft/version, and the applicable role/terms authority. Account remains the owner of current authority and its fence under the [canonical authority contract](../../system-architecture-authentication.md#canonical-authority-tuple) and [hosted-terms contract](../account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party); consumers reuse the Account authority/fence protocol where supported. No new route, RPC, lease, envelope, schema, or field encoding is selected by this contract. + +World verifies both the authenticated Game Design producer and the Account authorization against the exact descriptor at the owner commit boundary. A source receipt, source-qualified Draft/version read, forwarded JWT, workload identity, copied role/terms state, or preflight-only check cannot authorize the mutation or replace commit-time currentness verification. The path remains automatic through Account, Game Design, and World; it has no manual authorization or migration step. Missing, stale, mismatched, unavailable, or uncertain authorization denies or aborts the owner commit, and Game Design must not report a successful cross-owner commit. Any staged data remains non-authoritative cleanup/quarantine state. Canonical World writes remain denied until this commit-time verification is implemented and proved. + ### Publication freeze and terminal handoff (target state) The publication-freeze operations remain unavailable target contract surfaces. The internal owner-lock persistence prerequisite is not an authenticated freeze producer or terminal handoff; the [World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records its current code and proof limits. No current caller may infer a freeze, publication, or terminal owner result from a digest, a remote `GetVersionState` read, or a Temporal run identity. diff --git a/design/architecture/microservices/world-management-service/operations.md b/design/architecture/microservices/world-management-service/operations.md index 3e2be566f3..48068fd037 100644 --- a/design/architecture/microservices/world-management-service/operations.md +++ b/design/architecture/microservices/world-management-service/operations.md @@ -13,6 +13,12 @@ - When temporary content remains a zone-scoped child of a parent game instance, it requires a separate scoped, idempotent cleanup contract. Expiring the child must not transition or terminate the parent `world_instance`. - Direct periodic deletion is not a valid target cleanup path for either boundary. +## Playtest Fork Lifecycle Authority + +World Management owns allocation, lifecycle, and expiry for each playtest fork under [ADR 0137](../../decisions/adr-0137-isolated-playtest-state-modes-and-reset.md) and [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). A new fork receives a fresh immutable canonical `playtestLifecycleId` and its exact `forkExpiresAt`, bound to the World-owned lifecycle/version/epoch proof. World is the sole producer of this identity and deadline; fork extension changes World lifecycle authority and never silently extends Account grants. + +World supplies the exact current proof to Game Session for its admission-pointer transaction and authenticated readback. Game Session and Account consume that proof without allocating an ID, deriving an expiry, or creating a competing lifecycle record. Allocation and authenticated owner readback are not implemented; current legacy runtime rows do not prove the target lifecycle or expiry. + ## Implementation Status The current `instance` table models legacy temporary zone copies for dungeons or housing, with `expires_at` derived from `world.instance.expiration-hours`. The live scheduled cleanup still deletes those rows directly. That is explicit implementation drift, not evidence that the legacy row participates in the [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) lifecycle. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index a2fde92bd6..31d88459ea 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -166,6 +166,10 @@ FireMUD standardizes a small, explicit role set so tenant authorization and cros - `tenantAdmin` – Owns the tenant in day-to-day operations: can manage game instances, configure runtime settings, and view the tenant's high-level subscription state. Subscription and billing mutation is separately subject-bound to the authenticated billing owner recorded as `subscription.accountId`, or to the explicit audited cross-tenant billing-owner handoff; the tenant role alone cannot mutate subscriptions or payment instruments. - `moderator` – Performs tenant-scoped moderation actions (for example, muting or banning players) but cannot alter billing or platform-wide configuration. +Account is the sole authority for global-role grants, revocations, and current role evidence. Ordinary global-role changes are human operator actions entering through Gateway β†’ Logging & Admin; the actor must have a live `platformAdmin` role and current `privileged_control` step-up evidence under [ADR 0045](./decisions/adr-0045-ordinary-login-factors-and-https-sensitive-action-step-up.md). Account provides the currentness authorization and revalidates it at the owner commit, where durable audit evidence accompanies the role change. The operator ingress and owner execution follow [ADR 0047](./decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) and [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md). Unattended automation cannot grant or revoke global roles. The first `platformAdmin` requires a separate one-time protected deployment bootstrap; registration order, a legacy scalar, a token claim, or tenant authority never establishes it. See [ADR 0185](./decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md), [Account's owner contract](./microservices/account-service/api-contracts.md#account-owned-global-role-administration), and [Logging & Admin's ingress consequence](./microservices/logging-admin-service/api-contracts.md#global-role-administration-ingress). + +Global-role mutation is target-only and unavailable until the Account commit-time authorization, independent role-source evidence, durable event/audit, exact same-snapshot readback, protected bootstrap, and focused proof are implemented. The global-account action scope is distinct from `tenant_scope`; a tenant ID or tenant-role branch cannot represent a global-role target. Exact API route, action schema, event schema, bootstrap artifact, and retry/recovery mechanics remain unselected by ADR 0185. + Services must not introduce ad-hoc roles without updating this model and the Tenant Authorization Contract. Where finer-grained behavior is required, services should prefer additional capabilities/flags derived from these core roles rather than inventing new top-level roles. Official-hosted creator-party and signer authority under [ADR 0180](./decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) is Account-owned evidence, not a global or tenant role and must not be embedded as a broad JWT role. Account evaluates the party, authenticated signer authority, current terms acceptance, and requested legal action at the acceptance boundary. `tenantAdmin`, `designer`, organization administration, billing ownership, payment, or a company email domain do not establish signer authority. Game Design separately requires current tenant authorization and current party acceptance; neither substitutes for the other. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 73f17225f3..feef98bb7b 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -29,6 +29,7 @@ Hosted creator-terms acceptance is an explicit current inventory gap. [ADR 0180] - `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` remain target `internal_workload` routes requiring the exact Game Session or World Management caller policy declared in rows 260-261 and the normative [machine-readable route matrix](./system-architecture-authz-route-matrix.yaml). Current Account development and production configuration no longer lists these methods as public gRPC bypasses. Their handlers deny before data access, including for the exact Game Session peer, until the typed caller/target contract is implemented. Missing-token, wrong-workload, and cross-tenant denial proof establish containment, not a working admission path or target snapshot. - The current `IssueConnectToken` route requires existing caller-bound membership for every realm and never creates it; its required membership-authority-generation reread is missing. A realm grant never substitutes for membership. - `privileged_control` is target-only and currently unavailable; route branches that authorize through a global `platformAdmin` or cross-tenant `billingAdmin` role therefore fail closed, while the `support` branch of `cross_tenant_support_safe` does not require `privileged_control`. Operator mutation rows that require an Account-issued authorization reference or this privileged-control window are normative target rows, not current availability claims. +- Global-role grant/revoke administration is a target-only Account owner action, not a current route. Its human ingress must use Gateway β†’ Logging & Admin, require live `platformAdmin` and `privileged_control`, and obtain Account currentness authorization that Account revalidates at commit with durable audit. The first administrator is a separate protected deployment bootstrap; automation, registration order, token claims, legacy scalar roles, and tenant scope cannot establish or mutate global roles. `operator_delegation.global_role_administration` records the target-only global-account action boundary separately from the closed authorization-reference branches; no action schema or route is published or routable. See [ADR 0185](./decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md). - The `platformAdmin` privileged-control predicate applies to the exact internal-workload `account-service/IssueHumanOperatorAuthorizationReference` issuance route in addition to its declared route-class allowlist. This exact route identity does not add `internal_workload` to the support or billing-safe classification scopes; the separate automation issuance path prohibits privileged control. - `LinkExternalAccount` is target-only and currently unavailable. The current tenant-scoped caller-asserted scaffold must not be exposed or advertised; the target global-account route is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md) and remains unavailable until server-verified provider authorization and recent ordinary reauthentication exist. - The current Account implementation of `ExportTenantData` remains account-targeted while the canonical target is a tenant-wide, tenant-owned export; this is recorded as known drift while the target route remains a distinct `billing_safe_tenant` exception. diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 963363302b..f5201d00dd 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -690,6 +690,17 @@ operator_delegation: bindings: [workload_identity, automation_policy_id, automation_policy_version, tenant_scope, action_family, action_family_schema_id, action_family_schema_version, mutation_digest, membership_version_when_applicable, issuance_fence, authority_evidence_bundle, control_plane_request_id, issued_at, expires_at] user_impersonation_forbidden: true + global_role_administration: + status: target_not_currently_routable + ingress: gateway_to_logging_admin_human_operator + owner: account-service + actions: [grant, revoke] + target_scope: global_account + required_target: target_account_id + forbidden_authority: [tenant_scope, tenant_id, target_tenant_generation, membership, membership_version_when_applicable] + required_authority: [live_platformAdmin, current_privileged_control, account_owner_commit_currentness] + unattended_automation: forbidden + first_platform_admin: separate_one_time_protected_deployment_bootstrap typed_mutation_contract: schema_pair: [action_family_schema_id, action_family_schema_version] digest: mutationDigest/v1 diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 6a2a21cb9a..c576e6c89f 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -80,6 +80,10 @@ for conventions on schema evolution and error handling. See each service's - [AccountService](#account-v1-AccountService) - [account/v1/issuer_authority_service.proto](#account_v1_issuer_authority_service-proto) + - [AcknowledgeIssuerProjectionForRuntimeRequest](#account-v1-AcknowledgeIssuerProjectionForRuntimeRequest) + - [AcknowledgeIssuerProjectionForRuntimeResponse](#account-v1-AcknowledgeIssuerProjectionForRuntimeResponse) + - [CaptureIssuerProjectionForRuntimeRequest](#account-v1-CaptureIssuerProjectionForRuntimeRequest) + - [CaptureIssuerProjectionForRuntimeResponse](#account-v1-CaptureIssuerProjectionForRuntimeResponse) - [IssuerAuthoritySourceSnapshot](#account-v1-IssuerAuthoritySourceSnapshot) - [ReadIssuerAuthorityForRuntimeRequest](#account-v1-ReadIssuerAuthorityForRuntimeRequest) - [ReadIssuerAuthorityForRuntimeResponse](#account-v1-ReadIssuerAuthorityForRuntimeResponse) @@ -272,6 +276,9 @@ for conventions on schema evolution and error handling. See each service's - [AppliedWorldDesignMutation](#gamedesign-v1-AppliedWorldDesignMutation) - [ApproveTemplateRemapSetRequest](#gamedesign-v1-ApproveTemplateRemapSetRequest) - [ApproveTemplateRemapSetResponse](#gamedesign-v1-ApproveTemplateRemapSetResponse) + - [AuthoredWorldLaunchDescriptorEvidence](#gamedesign-v1-AuthoredWorldLaunchDescriptorEvidence) + - [AuthoredWorldSourceReceipt](#gamedesign-v1-AuthoredWorldSourceReceipt) + - [AuthoredWorldVersionStateEvidence](#gamedesign-v1-AuthoredWorldVersionStateEvidence) - [BeginPurgeVersionAssetsRequest](#gamedesign-v1-BeginPurgeVersionAssetsRequest) - [BeginPurgeVersionAssetsResponse](#gamedesign-v1-BeginPurgeVersionAssetsResponse) - [CanDeleteVersionAssetsRequest](#gamedesign-v1-CanDeleteVersionAssetsRequest) @@ -290,8 +297,12 @@ for conventions on schema evolution and error handling. See each service's - [DesignControlPlaneDigest](#gamedesign-v1-DesignControlPlaneDigest) - [FinalizePurgeVersionAssetsRequest](#gamedesign-v1-FinalizePurgeVersionAssetsRequest) - [FinalizePurgeVersionAssetsResponse](#gamedesign-v1-FinalizePurgeVersionAssetsResponse) + - [GetAuthoredWorldVersionStateRequest](#gamedesign-v1-GetAuthoredWorldVersionStateRequest) + - [GetAuthoredWorldVersionStateResponse](#gamedesign-v1-GetAuthoredWorldVersionStateResponse) - [GetDesignControlPlaneDigestRequest](#gamedesign-v1-GetDesignControlPlaneDigestRequest) - [GetDesignControlPlaneDigestResponse](#gamedesign-v1-GetDesignControlPlaneDigestResponse) + - [GetLaunchDescriptorRequest](#gamedesign-v1-GetLaunchDescriptorRequest) + - [GetLaunchDescriptorResponse](#gamedesign-v1-GetLaunchDescriptorResponse) - [GetPublishedPluginVersionRequest](#gamedesign-v1-GetPublishedPluginVersionRequest) - [GetPublishedPluginVersionResponse](#gamedesign-v1-GetPublishedPluginVersionResponse) - [GetPublishedReleaseBundleRequest](#gamedesign-v1-GetPublishedReleaseBundleRequest) @@ -663,12 +674,16 @@ for conventions on schema evolution and error handling. See each service's - [GetWorldInstanceLifecycleResponse](#world_management-v1-GetWorldInstanceLifecycleResponse) - [HazardAmbientState](#world_management-v1-HazardAmbientState) - [InitialAdmissionBindHold](#world_management-v1-InitialAdmissionBindHold) + - [IntakeAuthoredWorldSourceRequest](#world_management-v1-IntakeAuthoredWorldSourceRequest) + - [IntakeAuthoredWorldSourceResponse](#world_management-v1-IntakeAuthoredWorldSourceResponse) - [ListRoomOccupantsRequest](#world_management-v1-ListRoomOccupantsRequest) - [ListRoomOccupantsResponse](#world_management-v1-ListRoomOccupantsResponse) - [PingRequest](#world_management-v1-PingRequest) - [PingResponse](#world_management-v1-PingResponse) - [PrepareWorldInstanceRequest](#world_management-v1-PrepareWorldInstanceRequest) - [PrepareWorldInstanceResponse](#world_management-v1-PrepareWorldInstanceResponse) + - [ReadAuthoredWorldSourceIntakeRequest](#world_management-v1-ReadAuthoredWorldSourceIntakeRequest) + - [ReadAuthoredWorldSourceIntakeResponse](#world_management-v1-ReadAuthoredWorldSourceIntakeResponse) - [RegionDesignMutation](#world_management-v1-RegionDesignMutation) - [RoomAmbientState](#world_management-v1-RoomAmbientState) - [RoomAmbientStatePatch](#world_management-v1-RoomAmbientStatePatch) @@ -700,6 +715,7 @@ for conventions on schema evolution and error handling. See each service's - [WorldDesignScopeType](#world_management-v1-WorldDesignScopeType) - [WorldInstanceLifecycleStatus](#world_management-v1-WorldInstanceLifecycleStatus) + - [WorldAuthoredSourceIntakeService](#world_management-v1-WorldAuthoredSourceIntakeService) - [WorldManagementService](#world_management-v1-WorldManagementService) - [Scalar Value Types](#scalar-value-types) @@ -1700,6 +1716,95 @@ Basic ping response containing a greeting and optional error details. + + +### AcknowledgeIssuerProjectionForRuntimeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| issuer_id | [string](#string) | | | +| capture_operation_id | [string](#string) | | | +| capture_request_id | [string](#string) | | | +| capture_request_digest_version | [uint32](#uint32) | | | +| capture_request_digest | [string](#string) | | | +| projection_key | [string](#string) | | | +| installed_projection_json | [string](#string) | | | + + + + + + + + +### AcknowledgeIssuerProjectionForRuntimeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [string](#string) | | | +| target_namespace | [string](#string) | | | +| acknowledgment_id | [string](#string) | | | +| issuer_id | [string](#string) | | | +| caller_workload_identity | [string](#string) | | | +| projection_key | [string](#string) | | | +| capture_operation_id | [string](#string) | | | +| capture_request_id | [string](#string) | | | +| capture_request_digest_version | [uint32](#uint32) | | | +| capture_request_digest | [string](#string) | | | +| request_digest_version | [uint32](#uint32) | | | +| request_digest | [string](#string) | | | +| installed_projection_json | [string](#string) | | | +| installed_projection_sha256 | [string](#string) | | | + + + + + + + + +### CaptureIssuerProjectionForRuntimeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| issuer_id | [string](#string) | | | +| request_id | [string](#string) | | | + + + + + + + + +### CaptureIssuerProjectionForRuntimeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [string](#string) | | | +| target_namespace | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_id | [string](#string) | | | +| issuer_id | [string](#string) | | | +| caller_workload_identity | [string](#string) | | | +| projection_key | [string](#string) | | | +| request_digest_version | [uint32](#uint32) | | | +| request_digest | [string](#string) | | | +| captured_source_snapshot | [IssuerAuthoritySourceSnapshot](#account-v1-IssuerAuthoritySourceSnapshot) | | | + + + + + + ### IssuerAuthoritySourceSnapshot @@ -1766,12 +1871,14 @@ Basic ping response containing a greeting and optional error details. ### IssuerAuthorityService -Owner-local source evidence only; this service is not wired for runtime use. +Owner-local issuer evidence handoffs only; this service is not wired for runtime use. Caller and response workload identities must both be verified from mTLS. | Method Name | Request Type | Response Type | Description | | ----------- | ------------ | ------------- | ------------| | ReadIssuerAuthorityForRuntime | [ReadIssuerAuthorityForRuntimeRequest](#account-v1-ReadIssuerAuthorityForRuntimeRequest) | [ReadIssuerAuthorityForRuntimeResponse](#account-v1-ReadIssuerAuthorityForRuntimeResponse) | | +| CaptureIssuerProjectionForRuntime | [CaptureIssuerProjectionForRuntimeRequest](#account-v1-CaptureIssuerProjectionForRuntimeRequest) | [CaptureIssuerProjectionForRuntimeResponse](#account-v1-CaptureIssuerProjectionForRuntimeResponse) | | +| AcknowledgeIssuerProjectionForRuntime | [AcknowledgeIssuerProjectionForRuntimeRequest](#account-v1-AcknowledgeIssuerProjectionForRuntimeRequest) | [AcknowledgeIssuerProjectionForRuntimeResponse](#account-v1-AcknowledgeIssuerProjectionForRuntimeResponse) | | @@ -5215,6 +5322,96 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo + + +### AuthoredWorldLaunchDescriptorEvidence + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| authored_world_source_operation_id | [string](#string) | | | +| authored_world_source_evidence_digest | [string](#string) | | | +| game_template_id | [int64](#int64) | | | +| requested_script_patch_version | [string](#string) | optional | | +| source_version_id | [int64](#int64) | optional | | +| target_version_id | [int64](#int64) | optional | | +| requested_runtime_flags_json | [string](#string) | optional | | +| request_digest | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| script_patch_version | [string](#string) | optional | | +| runtime_flags_json | [string](#string) | | | +| generation_config_revision | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| release_bundle_id | [int64](#int64) | | | +| published_release_bundle_ref | [string](#string) | | | +| remap_set_id | [string](#string) | optional | | +| result_digest | [string](#string) | | | + + + + + + + + +### AuthoredWorldSourceReceipt +Complete immutable registration receipt, without another RPC's transient read request ID. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| registration_request_id | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| tenant_slug | [string](#string) | | | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| source_game_row_id | [int64](#int64) | | | +| source_game_tenant_key | [string](#string) | | | +| provenance_kind | [string](#string) | | | +| evidence_digest | [string](#string) | | | + + + + + + + + +### AuthoredWorldVersionStateEvidence + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| read_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | +| version_id | [int64](#int64) | | | +| source_evidence | [AuthoredWorldSourceReceipt](#gamedesign-v1-AuthoredWorldSourceReceipt) | | | +| version_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| version_state_epoch | [int64](#int64) | | | +| evidence_digest | [string](#string) | | | + + + + + + ### BeginPurgeVersionAssetsRequest @@ -5518,6 +5715,43 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo + + +### GetAuthoredWorldVersionStateRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| read_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | +| version_id | [int64](#int64) | | | + + + + + + + + +### GetAuthoredWorldVersionStateResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| evidence | [AuthoredWorldVersionStateEvidence](#gamedesign-v1-AuthoredWorldVersionStateEvidence) | | | + + + + + + ### GetDesignControlPlaneDigestRequest @@ -5552,6 +5786,43 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo + + +### GetLaunchDescriptorRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| expected_request_digest | [string](#string) | | | +| expected_result_digest | [string](#string) | | | + + + + + + + + +### GetLaunchDescriptorResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| request_id | [string](#string) | | | +| launch_descriptor | [LaunchDescriptor](#gamedesign-v1-LaunchDescriptor) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + ### GetPublishedPluginVersionRequest @@ -5857,7 +6128,7 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | launch_descriptor_id | [string](#string) | | | -| tenant_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | | game_template_id | [int64](#int64) | | | | control_plane_request_id | [string](#string) | | | | version_id | [int64](#int64) | | | @@ -5868,6 +6139,7 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | release_bundle_id | [int64](#int64) | | | | published_release_bundle_ref | [string](#string) | | | | remap_set_id | [string](#string) | | | +| authored_world_binding | [AuthoredWorldLaunchDescriptorEvidence](#gamedesign-v1-AuthoredWorldLaunchDescriptorEvidence) | | | @@ -6291,6 +6563,7 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | workflow_status | [string](#string) | | | | workflow_family | [string](#string) | | | | command_definitions | [string](#string) | repeated | | +| published_release_bundle_ref | [string](#string) | | | @@ -6510,13 +6783,16 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | | game_template_id | [int64](#int64) | | | | control_plane_request_id | [string](#string) | | | | requested_script_patch_version | [string](#string) | optional | | | source_version_id | [int64](#int64) | optional | | | target_version_id | [int64](#int64) | optional | | | requested_runtime_flags_json | [string](#string) | optional | | +| world_slug | [string](#string) | | | +| authored_world_source_operation_id | [string](#string) | | | +| expected_authored_world_source_evidence_digest | [string](#string) | | | @@ -7036,8 +7312,10 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | GetDesignControlPlaneDigest | [GetDesignControlPlaneDigestRequest](#gamedesign-v1-GetDesignControlPlaneDigestRequest) | [GetDesignControlPlaneDigestResponse](#gamedesign-v1-GetDesignControlPlaneDigestResponse) | | | GetPublishedReleaseBundle | [GetPublishedReleaseBundleRequest](#gamedesign-v1-GetPublishedReleaseBundleRequest) | [GetPublishedReleaseBundleResponse](#gamedesign-v1-GetPublishedReleaseBundleResponse) | | | GetVersionState | [GetVersionStateRequest](#gamedesign-v1-GetVersionStateRequest) | [GetVersionStateResponse](#gamedesign-v1-GetVersionStateResponse) | | +| GetAuthoredWorldVersionState | [GetAuthoredWorldVersionStateRequest](#gamedesign-v1-GetAuthoredWorldVersionStateRequest) | [GetAuthoredWorldVersionStateResponse](#gamedesign-v1-GetAuthoredWorldVersionStateResponse) | Exact current version state for one already-registered authored-world source. | | CompareAndSetVersionState | [CompareAndSetVersionStateRequest](#gamedesign-v1-CompareAndSetVersionStateRequest) | [CompareAndSetVersionStateResponse](#gamedesign-v1-CompareAndSetVersionStateResponse) | | | ResolveLaunchDescriptor | [ResolveLaunchDescriptorRequest](#gamedesign-v1-ResolveLaunchDescriptorRequest) | [ResolveLaunchDescriptorResponse](#gamedesign-v1-ResolveLaunchDescriptorResponse) | | +| GetLaunchDescriptor | [GetLaunchDescriptorRequest](#gamedesign-v1-GetLaunchDescriptorRequest) | [GetLaunchDescriptorResponse](#gamedesign-v1-GetLaunchDescriptorResponse) | | | CreateTemplateRemapSet | [CreateTemplateRemapSetRequest](#gamedesign-v1-CreateTemplateRemapSetRequest) | [CreateTemplateRemapSetResponse](#gamedesign-v1-CreateTemplateRemapSetResponse) | | | ApproveTemplateRemapSet | [ApproveTemplateRemapSetRequest](#gamedesign-v1-ApproveTemplateRemapSetRequest) | [ApproveTemplateRemapSetResponse](#gamedesign-v1-ApproveTemplateRemapSetResponse) | | | GetTemplateRemapSet | [GetTemplateRemapSetRequest](#gamedesign-v1-GetTemplateRemapSetRequest) | [GetTemplateRemapSetResponse](#gamedesign-v1-GetTemplateRemapSetResponse) | | @@ -10457,6 +10735,8 @@ plus scoped tick pause/resume used for rollback safety. | payload | [bytes](#bytes) | | | | payload_digest_version | [int32](#int32) | | | | payload_digest | [string](#string) | | | +| tenant_identity_version | [int32](#int32) | | Version 1 carries the retained numeric tenant identity; version 2 carries tenant_uuid. | +| tenant_uuid | [string](#string) | | | @@ -10483,6 +10763,8 @@ plus scoped tick pause/resume used for rollback safety. | status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | | outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | | audit_projection_version | [int32](#int32) | | 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. | +| tenant_identity_version | [int32](#int32) | | | +| tenant_uuid | [string](#string) | | | @@ -10601,6 +10883,8 @@ plus scoped tick pause/resume used for rollback safety. | payload | [bytes](#bytes) | | | | payload_digest_version | [int32](#int32) | | | | payload_digest | [string](#string) | | | +| tenant_identity_version | [int32](#int32) | | | +| tenant_uuid | [string](#string) | | | @@ -10627,6 +10911,8 @@ plus scoped tick pause/resume used for rollback safety. | outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | | audit_projection_version | [int32](#int32) | | Same receipt/projection attestation as CreateLogEventResponse; never payload replay proof. Zero or unsupported versions cannot verify delivery or historical producer provenance. | +| tenant_identity_version | [int32](#int32) | | | +| tenant_uuid | [string](#string) | | | @@ -12299,6 +12585,51 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### IntakeAuthoredWorldSourceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| intake_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | + + + + + + + + +### IntakeAuthoredWorldSourceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| intake_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_digest | [string](#string) | | Recomputable from the echoed intake binding using the World request digest contract. | +| receipt_digest | [string](#string) | | Opaque authenticated World attestation; it binds private World state and is not client-recomputable. | + + + + + + ### ListRoomOccupantsRequest @@ -12402,6 +12733,53 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### ReadAuthoredWorldSourceIntakeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| request_id | [string](#string) | | A distinct nonnil identity for this read; intake_request_id remains the stored receipt key. | +| intake_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | + + + + + + + + +### ReadAuthoredWorldSourceIntakeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| request_id | [string](#string) | | | +| intake_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_digest | [string](#string) | | Recomputable from the echoed intake binding using the World request digest contract. | +| receipt_digest | [string](#string) | | Opaque authenticated World attestation; it binds private World state and is not client-recomputable. | + + + + + + ### RegionDesignMutation @@ -12912,6 +13290,18 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### WorldAuthoredSourceIntakeService +Explicitly unwired authenticated authored-source intake boundary. This service remains separate +from the runtime WorldManagementService until its caller and deployment path are authorized. + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| IntakeAuthoredWorldSource | [IntakeAuthoredWorldSourceRequest](#world_management-v1-IntakeAuthoredWorldSourceRequest) | [IntakeAuthoredWorldSourceResponse](#world_management-v1-IntakeAuthoredWorldSourceResponse) | | +| ReadAuthoredWorldSourceIntake | [ReadAuthoredWorldSourceIntakeRequest](#world_management-v1-ReadAuthoredWorldSourceIntakeRequest) | [ReadAuthoredWorldSourceIntakeResponse](#world_management-v1-ReadAuthoredWorldSourceIntakeResponse) | | + + ### WorldManagementService diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 7cd8accd21..8de0b809db 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -396,3 +396,28 @@ Entry format: - Context: the existing gRPC server-peer response interceptor validates the certificate only when response headers or content arrive. Integration inspection of the World intake client and its initial socket fixture found that the wrong authenticated server could receive the mutation before its response was rejected; that initial fixture was not executed. This response guard is not pre-send receiver authorization. - Outcome: the unregistered World intake client now also checks the negotiated TLS peer through call credentials before releasing request metadata/body, retaining the response guard. All seven focused socket cases execute cleanly locally, including both wrong-server intake/read rejection with no owner interaction. The receiver service is mocked in that suite; it does not prove database composition, delivery or runtime activation. - Expected pattern: for owner mutations, prove both denial of wrong-peer responses and that the wrong receiver never sees the owner request. Do not treat response rejection as evidence that no mutation was attempted. + +- `2026-10-04`: Tie scoped source inventory to the same verified working directory + - Context: a bounded read-only helper reported that login-shell behavior had redirected its source inspection to the default checkout, then repeated negative inventory claims about files the orchestrator verified existed in the pinned worktree. Its initial identity check did not establish the location of those later reads. The cause of the remaining contradictory inventory is unproved. + - Outcome: the orchestrator rejected that source inventory and commissioned a bounded recheck with explicit working directory, disabled login-shell behavior and contemporaneous source-path verification. The helper made no edits; build diagnostics independently identified the intended worktree. No absent-file or architecture decision is inferred from the rejected map. + - Expected pattern: for revision-sensitive worktree evidence, verify the directory, branch and head together with the actual scoped source paths, and use absolute paths or an explicit directory change when shell behavior is uncertain. Treat contradictory source presence as an attribution problem before inferring a missing capability. + +- `2026-10-04`: Paginate CI artifact inventory before reporting missing proof + - Context: the exact CI37141351309 observer initially reported the bare-LOGIN XML artifact missing from an unpaginated artifact response, although its upload succeeded and it existed on the second page. + - Outcome: the complete paginated inventory recovered the artifact; independent raw-XML parsing and hashing proved all fourteen storage cases executed cleanly. The initial missing-artifact statement supplied no evidence of a skipped test or broken upload. + - Expected pattern: inspect every artifact page and the exact upload outcome before classifying evidence as absent. Preserve the exact run/head and distinguish unavailable capture from execution failure. + +- `2026-10-04`: Cross-check CI aggregate labels against exact required job evidence + - Context: installed controller writer build 8 returned `aggregate.state=SUCCESS` for #2966 head `bb7fb28ea9fa9c194a3e9418e3f61ee95f149d25` while the same inventory contained six failed jobs, including Validation Gate and Account, and exact workflow run37167089744 concluded failure. Its separate `NOT READY` verdict still prevented a readiness claim; the cause of the aggregate mismatch is unproved. + - Outcome: Document reported the discrepancy through FireController inbox981f7fcc-67b9-4c30-8740-128070090dca and retained the actual failed-job and absent-test evidence. The Account fixture correction does not establish that the controller presentation issue is repaired. + - Expected pattern: use exact-head required job outcomes and raw test evidence for proof; do not convert an aggregate label into green CI when its own inventory disagrees. Report the command, version and contradictory evidence without changing private review state to bypass the discrepancy. + +- `2026-10-04`: Await PR retarget completion before generating LOC metadata + - Context: Document started the #2932 LOC refresh while its authorized base edit was still in flight. The generator initially compared the new head against the old merge-base and reported 178 files instead of the verified 122-file child delta; its final base-consistency guard refused the body update. + - Outcome: no stale LOC section was published. Document read back the completed exact base/head edit, then repeated the canonical generation against that stable pair. Final marked metadata and the retained handoff body exactly match the published 122-file child, its head and #2969 base. + - Expected pattern: serialize PR base/body mutation and LOC generation, and verify the final marked metadata against the exact published pair. A generated report from a superseded merge-base is not current scope evidence. + +- `2026-10-04`: Verify a CI sentinel's queried run against its assigned identity + - Context: the #2966 watcher was assigned run `37182915940`, but returned a 404 result for the unrelated run `371546092`. The intended workflow had already been dispatched and its exact head verified; the wrong-target error was not evidence that the assigned run was unavailable. + - Outcome: Document rejected the unavailable-run conclusion and resumed the same sole watcher with the literal run URL and a separate workflow ID. The corrected watcher verified the assigned workflow/head and returned raw XML proving the required Account cases executed cleanly; the overall run completed with failures outside the Account job. No second watcher or duplicate parent polling was started. + - Expected pattern: require the executed request identity to match the assignment before classifying an external failure. Distinguish a workflow ID from a run ID and retain any mismatched query as a delegation error, not provider evidence. diff --git a/design/project-management/design-alignment/consequential-decision-inventory.md b/design/project-management/design-alignment/consequential-decision-inventory.md index 0fee2e6a3f..709ba78a52 100644 --- a/design/project-management/design-alignment/consequential-decision-inventory.md +++ b/design/project-management/design-alignment/consequential-decision-inventory.md @@ -379,11 +379,14 @@ Packet 2 historical-alias rule: `MS-AA-TOKEN-REVOCATION` is a superseded service ### Post-Archive Direct Human Decisions +`AUTH-GLOBAL-ROLE-WRITER-01` is the sixth post-archive direct human decision recorded in this unmerged candidate. It records approval of the authority boundary only; it does not claim merged application, runtime implementation, or proof completion. + - [x] `COMMERCE-02` β€” `accepted` on 2026-08-25; initial human approval on 2026-08-23 and final refinement/application on 2026-08-25; [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md) - [x] `HOSTED-TERMS-01` β€” `accepted` on 2026-08-25; initial human approval on 2026-08-24 and final refinement/application on 2026-08-25; [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) - [x] `HOSTED-TERMS-02` β€” `accepted` on 2026-08-25; initial human approval on 2026-08-24 and final refinement/application on 2026-08-25; [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) - [x] `OPS-07` β€” `revised` on 2026-09-06; [ADR 0182](../../architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) - [x] `EDGE-WITHDRAWAL-01` β€” `accepted` on 2026-09-24; human-approved emergency cutoff despite possible service interruption; [ADR 0184](../../architecture/decisions/adr-0184-emergency-tcp-proxy-identity-withdrawal.md) +- [x] `AUTH-GLOBAL-ROLE-WRITER-01` β€” `accepted` on 2026-10-04; Ben explicitly selected β€œApprove this boundary (Recommended),” relayed through Overseer inbox `0f5ec31e-db81-4b31-ab9c-7e94b257cd62`; [ADR 0185](../../architecture/decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md) ### Allocation Notes diff --git a/design/project-management/design-alignment/design-capability-allocation.md b/design/project-management/design-alignment/design-capability-allocation.md index 9b6eb9efad..9e2eaa4265 100644 --- a/design/project-management/design-alignment/design-capability-allocation.md +++ b/design/project-management/design-alignment/design-capability-allocation.md @@ -24,7 +24,8 @@ This file intentionally owns the detailed allocation-validation history; the des - Final combined Packet 5 tail and Packet 6 P0 validation record on 2026-08-25 Pacific/Auckland (2026-08-24 UTC): all active ADRs 0146-0159 are allocated; `linkCheck` checked `6,039` total links (`6,002` OK, `37` excluded, `0` errors); `lintMarkdown` checked `509` files (`0` issues); allocation reported `332` sources (`329` allocated, `3` explicit exemptions); ADR review status was `146` reviewed / `11` pre-formal; architecture doc contracts, allocation regression `28` tests, ADR review regression `141` tests, and authorization-route regression `216` tests passed; the focused preflight, player-experience evidence, player-experience runner, and observability-validator contract tests passed; and Ruff, ShellCheck, Python syntax, and `git diff --check` were clean. No environment-backed runtime proof is required for validating this allocation ledger itself. That ledger-only exemption does not waive runtime-proof requirements for the allocated architecture documents or operational validation tooling; changes requiring canonical fresh-image rebuild-and-boot proof must retain and report that requirement separately. - Packet 6 P1-P3 allocation state: ADRs 0160-0167 add 8 reviewed records, bringing the canonical source set to `340` discovered sources (`337` allocated, `3` explicit exemptions) and the ADR registry to `165` records. The final reviewed import through Packet 7 ADRs 0168-0178 adds 11 more ADR records (19 reviewed records across both parcels), yielding `351` discovered sources (`348` allocated, `3` explicit exemptions) and `176` ADR records. Those review categories overlap where accepted legacy pre-formal records now carry exact review metadata. This structural state does not upgrade implementation or runtime proof for the allocated decisions; final parcel validation is reported by the design-alignment workstream rather than inferred from allocation arithmetic. - The four post-archive direct human decisions `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, and `OPS-07` add ADRs 0179-0182 without changing the completed historical Packet 1-7 archive. They bring the canonical source set to `355` discovered sources (`352` allocated, `3` explicit exemptions) and the ADR registry to `180` records. The marketplace, hosted-terms, signer, and billing-lifecycle boundaries remain future or pre-launch target state. This allocation entry records allocation authority and target-state boundaries only; for ADR 0182, only local/static prerequisite evidence exists, while live activation, certificate issuance, and consumer convergence remain unproved. It does not establish broader implementation status, focused proof, or environment-backed runtime proof. -- The pending AI-authored ADR 0183 proposal and the later direct human `EDGE-WITHDRAWAL-01` decision in accepted ADR 0184 add two allocated ADR sources to the four post-archive decisions above. The current canonical source set is `357` discovered sources (`354` allocated, `3` explicit exemptions), including `182` ADR records plus the registry/index exemption. ADR 0183 remains `Proposed - Pending Human Review` with `AI-AUTHORED-PENDING` provenance; its mechanical renumbering preserves the proposal but does not accept it. ADR 0184's emergency withdrawal remains unproved in a live hosted environment; this allocation is not runtime proof. +- At the prior candidate checkpoint, the pending AI-authored ADR 0183 proposal and the later direct human `EDGE-WITHDRAWAL-01` decision in accepted ADR 0184 brought the canonical source set to `357` discovered sources (`354` allocated, `3` explicit exemptions), including `182` ADR records plus the registry/index exemption. ADR 0183 remains `Proposed - Pending Human Review` with `AI-AUTHORED-PENDING` provenance; its mechanical renumbering preserves the proposal but does not accept it. ADR 0184's emergency withdrawal remains unproved in a live hosted environment; this allocation is not runtime proof. +- `AUTH-GLOBAL-ROLE-WRITER-01` in the current unmerged candidate adds allocated ADR 0185, bringing the source set to `358` discovered sources (`355` allocated, `3` explicit exemptions), including `183` ADR records plus the registry/index exemption. This preserves the completed historical Packet 1-7 archive count; the accepted authority boundary is not merged implementation or runtime proof. - Historical baseline allocation-validator run on 2026-08-27 Pacific/Auckland: `python3 dev-tools/validation/check-design-capability-allocation.py` passed with `340` discovered sources (`337` allocated, `3` explicit exemptions). This records the Packet 6 baseline allocation coverage only and does not claim implementation or runtime proof. - Pre-licensing-integration allocation and ADR review-status baseline on 2026-08-28 Pacific/Auckland: allocation validation passed with `351` discovered sources (`348` allocated, `3` explicit exemptions), and ADR review-status validation passed with `168` reviewed ADRs and `11` pre-formal records. ADRs 0002, 0007, and 0008 are overlapping records present in both the reviewed count and the 11 pre-formal records, so the deduplicated registry total is `168 + 11 - 3 = 176` before licensing integration. These are historical baseline/provenance facts, separate from implementation or runtime proof. - Licensing-integration validation on 2026-08-28 Pacific/Auckland: allocation validation passed with `354` discovered sources (`351` allocated, `3` explicit exemptions); ADR review-status validation passed with `171` reviewed ADRs and `11` pre-formal records; implementation tracking passed with `79` leaves across `10` trackers; the authorization-route matrix and full architecture-document contract suite passed; `linkCheck` checked `6,537` links (`6,489` OK, `0` errors, `48` excluded); `lintMarkdown` checked `535` files (`0` issues); and `git diff --check` was clean. ADRs 0002, 0007, and 0008 are overlapping records present in both the reviewed count and the 11 pre-formal records, so the deduplicated registry total is `171 + 11 - 3 = 179` after licensing integration. These checks establish documentation and structural consistency for the integration only; they do not claim commit, PR, CI, or runtime proof. @@ -46,16 +47,16 @@ This file intentionally owns the detailed allocation-validation history; the des | Infrastructure | 6 | 6 | 0 | 100% classified | | Generated references | 2 | 2 | 0 | 100% classified | | Microservice architecture | 76 | 74 | 0; 2 explicit governance/template exemptions | 100% classified | -| Architecture decisions | 183 | 182 | 0; 1 registry exemption | 100% classified | +| Architecture decisions | 184 | 183 | 0; 1 registry exemption | 100% classified | | Product documentation | 7 | 7 | 0 | 100% classified | -| **Total** | **357** | **354** | **0; 3 explicit exemptions** | **100% classified** | +| **Total** | **358** | **355** | **0; 3 explicit exemptions** | **100% classified** | ## Allocation Ledger | Design source | Heading or scope | Primary capability | Secondary handoffs | Source class | Notes or gap | | --- | --- | --- | --- | --- | --- | | [Microservice architecture allocation](./design-capability-allocation-microservices.md) | All 76 files under `design/architecture/microservices/**` | Per-source allocation | Per-source handoffs | Service design, contract, runtime/data, configuration, operations, and reference sources | All 76 files are accounted for as 74 allocated sources plus 2 exempt governance/template files: `service-documentation-structure.md` and `service-template.md`; complete path-set coverage | -| [Architecture decision registry](../../architecture/decisions/README.md) | Registry plus 182 ADRs | Per-record allocation | Per-record affected capabilities | Decision record | The registry is an index; reviewed, accepted, superseded, withdrawn, and pending records remain distinguishable | +| [Architecture decision registry](../../architecture/decisions/README.md) | Registry plus 183 ADRs | Per-record allocation | Per-record affected capabilities | Decision record | The registry is an index; reviewed, accepted, superseded, withdrawn, and pending records remain distinguishable | | [System architecture allocation](./design-capability-allocation-system.md) | All 83 direct architecture, 6 infrastructure, and 2 generated sources | Per-source allocation | Per-source handoffs | Normative design, runbook, reference, index, and generated sources | Complete path-set coverage | | [Product documentation](../../product/README.md#canonical-sources) | All 7 files under `design/product/**` | Per-source allocation | Per-source product behavior scope | Requirements, taxonomy, index, and observable product behavior | Complete path-set coverage | @@ -246,6 +247,7 @@ This file intentionally owns the detailed allocation-validation history; the des | `design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md` | `PO-3` | `PO-1`, `PO-4`, `SF-1` | Accepted | | `design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md` | `GR-1` | `GR-4`, `AS-1`, `SF-1`, `SF-2`, `PO-4` | Proposed - Pending Human Review | | `design/architecture/decisions/adr-0184-emergency-tcp-proxy-identity-withdrawal.md` | `SF-1` | `PO-2`, `PO-3`, `PO-4` | Accepted | +| `design/architecture/decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md` | `AA-1` | `SF-1`, `PO-1` | Accepted | ADR 0121 is superseded by [ADR 0114](../../architecture/decisions/adr-0114-command-plan-preview-dry-run-isolation.md); its historical capability allocation remains recorded above. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 07ef045c43..414e2606ef 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The source-aware Unit 1B launch integration still depends on the complete Game Design release producer under `AR-1.4`, `AR-1.5` and `AR-3.2`. The prepared owner-reference prerequisite adds a fresh persisted opaque identity to new release-bundle rows and preserves retained rows as unbound; the source-bound descriptor uses that exact reference rather than deriving it from private identifiers. Its focused validation and executed PostgreSQL proof must be recorded separately. The existing generic release read still lacks the complete target commit, actual-byte artifact digests/manifest schema and dedicated Game Logic ability-schema evidence. Tenant-wide mutable asset export and the process-local frozen-content cache do not supply version-scoped durable attestation. Game Logic's required full-version manifest/provenance remains unavailable, so no complete source-qualified release response or successful launch can be manufactured from these seams. Separately proved source-qualified version-state reads below do not close this release gate. Retained World content additionally needs its owner-approved audited canonical association; neither Game Session's private tenant key nor Account's migration manifest can substitute for World evidence. Initial launch and admission remain denied until the corresponding owner producers and authenticated exact readback/consumer proof execute. + Three PostgreSQL-through-physical-mTLS methods compose the source-qualified version read using the actual persisted repositories, transaction manager, owner producer, handler, peer interceptor and World client. They cover complete non-mutating readback, changed-source/foreign-version denial and a fresh lifecycle/epoch snapshot for a repeated read identity. Their authored-source fixtures are synthetic. At exact `cd7751371e999360091e6ed70c99d45acee88d76`, [CI37130036974](https://github.com/benhook1013/FireMUD/actions/runs/37130036974) was terminal `FAILURE`; independent raw-XML parsing and rehashing nevertheless verified all 11 focused suites clean, including these three methods, with 75 executed, 75 passed, and zero skips/errors/failures. The full local Game Design/World PostgreSQL suites still skip without Docker; this is a local limitation, not a runner skip. Automatic delivery, publication, canonical World writes and runtime activation remain separate open boundaries. The fresh Version identity prerequisite now allocates and reads back a persisted non-nil UUID with the exact canonical tenant and source-game provenance for normal owner repository inserts. V35.1 leaves retained Version rows unchanged and unmapped; the focused PostgreSQL fixture and strict CI cases cover retained denial, exact fresh read/update, tenant/source mismatch, nil identity and immutability. The cumulative seven-module checks, five boot JARs, schema generation and documentation gate passed at `12d6cf5cfab437c0d69583566a6aa0738a644986`, with reused task results disclosed in the PR evidence. All six new PostgreSQL methods skipped locally without Docker. Exact-head [CI37218116041](https://github.com/benhook1013/FireMUD/actions/runs/37218116041) is terminal `FAILURE`: `newVersionIdentityUsesExactRetainedGameSourceProvenance` failed during forward migration, and the raw report was unavailable after later test selectors replaced the files. The other five methods are not individually established by that summary. The corrected workflow captures the complete component XML and HTML immediately, including failures, before later selectors; failed SQL and complete migration execution remain required proof, not guessed fixture or production disposition. The closed numeric descriptor/API representation, full release attestation, and runtime activation remain separate open work; no UUID is inferred for retained rows. @@ -28,7 +30,7 @@ The opt-in migration Jobs require separately provisioned, mode-specific database Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. -Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These links do not change current capability ratings or imply an operative hosted service. +Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). The current creator path has no authenticated, commit-bound Account authorization for the acting account's current tenant designer/admin role and applicable terms authority. For `worldDesignMutation`, Game Design cannot yet carry and establish this authorization at World's commit boundary; the canonical contract and World denial status are recorded in the [World tracker](world-runtime-and-movement.md#current-status). These links do not change current capability ratings or imply an operative hosted service. The Gateway Java catalog now omits external Game Design asset and template writes, containing the previously reachable service-local controllers at that edge. Those controllers still lack Account currentness/evidence binding, and direct service-local or future creator ingress is not ready for official-hosted use. The route restriction is not Game Design gate proof. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index fe8e58e422..f6f004b057 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,58 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +Exact cumulative `12d6cf5cfab437c0d69583566a6aa0738a644986` [CI37218116041](https://github.com/benhook1013/FireMUD/actions/runs/37218116041) is terminal `FAILURE`. Independently parsed raw XML proves four Account canonical reconciliation, ten Game Session source and five canonical catalog methods executed cleanly without skips. The Account scope suite executed four methods with one failure: its deliberate missing-source injection was blocked by the actual scope-reference foreign key, then its `finally` statement masked that rejection in an aborted transaction. The fixture correction separately proves the normal FK rejection without mutation and simulates corrupt retained storage only inside its private schema with transactional guard restoration. Game Session preparation executed three methods with one failure because the assertion guessed a source operation ID instead of reading the actual committed intake receipt; its correction uses the stored ID. These corrections preserve the production guards and original retry/rollback/concurrency obligations. Corrected-head PostgreSQL execution remains required; local compilation or Docker-free skips do not close either proof gap. The Game Design release identity/immutability and immediate raw-report capture corrections are recorded in the [publishing tracker](./game-authoring-publishing-and-activation.md); shared Python/TCP failures remain separately owned. None of this enables membership, credentials, launch or the response-envelope mount. + +The source-qualified launch-preparation candidate is an unwired Game Session consumer of the committed canonical catalog/source intake and exact Game Design descriptor. It resolves and independently reads back the descriptor outside an owner transaction, then locks/revalidates the catalog/source in a short writable READ COMMITTED transaction and independently recovers the immutable local result after commit. Its preparation binds the acting Account UUID as identity only; no creator/terms authorization, runtime instance allocation, World preparation, first OPEN or admission is implemented by this primitive. The corrected local Game Session full check, boot JAR, schema generation, formatting, analyzers, coverage and documentation gate passes in 2m1s (255 tasks: 41 executed, 214 up-to-date). All nine new unit cases execute cleanly; the module executes 1,895 unit, 18 integration and 26 cross-service cases with no failures/errors. Another 17 unit, 177 integration and 54 cross-service cases skip, including all three new PostgreSQL methods without Docker. Those three cases define V13β†’V14 preservation with no preparation backfill, retained-row isolation, exact committed retry, rollback/immutability, stored catalog-payload tamper rejection and concurrent recovery of one operation; Game Design responses are synthetic, so even their later database execution will not prove authenticated transport or complete release authority. The first gate failed on two test compilation defects and an unused production local; those were corrected without weakening guards before the passing run. CI requires the three exact PostgreSQL methods and uploads raw XML; corrected-head execution remains open. Complete authenticated source/descriptor composition, current Account authorization, full release attestation, canonical World lifecycle and positive JOIN/LOGIN remain open. The [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#source-qualified-launch-preparation-and-durable-readback) owns the binding, digest, transaction and retry rules; existing runtime and ring-mount activation gates remain closed. + +The human-approved authority boundary for global-role grant/revoke and first-administrator bootstrap is recorded in [ADR 0185](../../architecture/decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md) and its canonical owner contracts. This is a design decision, not implementation evidence: no authenticated global-role mutation producer, protected bootstrap, source event, complete recipient capture, credential wiring, or runtime activation exists. Preserve V55's fresh-only explicit-empty birth source and the existing denied activation gates until those prerequisites and focused proof are complete. + +At exact `4b7e4f149e8b7892a797dff989abd0fb72ac9117`, [CI37184606397](https://github.com/benhook1013/FireMUD/actions/runs/37184606397) completed with aggregate failure while the Account job passed. Independently parsed and rehashed raw XML proves 78 distinct clean executions, with no skips/errors/failures: current-source 17, initial token-fence 10, bare-LOGIN storage 14, fresh role-source 5, Account repository 17 and fresh UUID membership 15. All three composition methods executed, including actual PostgreSQL blocking of the tenant-authority writer by the capture transaction, single advancement after release and preservation of independent captured sources. Duplicated artifact copies are counted once. This closes the earlier concurrency component execution gap, not complete authenticated capture, credential release, fresh-image/live proof or activation. Other-area Python, dev-demo, Automation and Game Design fixture failures remain independently owned; aggregate green is not claimed. + +The owner-source prerequisite persists an opaque Game Design bundle identity on new V36 rows, reads and transports the exact stored reference, and leaves retained rows unbound without inferred backfill. Game Session's owner-local selector read recovers the original committed authored-world intake by exact namespace, tenant UUID and world slug without enrollment; an actual Spring proxy rejects an ambient owner transaction rather than suspending it. The corrected composed Game Design/Game Session full checks, both boot JARs, formatting, analyzers, coverage and documentation passed in 4m46s (167 tasks: 102 executed, 65 up-to-date). Both unit suites newly executed cleanly: Game Design 362 and Game Session 1,886, with 17 Game Session skips; Game Session additionally executed 18 integration and 26 cross-service cases cleanly. All 61 Game Design integration cases, 174 Game Session integration cases and 54 cross-service cases skipped locally without Docker, including both new selector cases and the release-reference/retained-migration proof. Earlier Account raw-XML execution above proves its own parent components, not these new owner-source cases. Corrected-head PostgreSQL, authenticated complete release/source-room, retained World association and positive consumer proof remain required; no primitive lookup or opaque locator authorizes launch, initial OPEN or activation. + +At exact composition checkpoint `c2b4f6d2b05e0d6f5fa7dd643c6b354cd2b85280`, [CI37182915940](https://github.com/benhook1013/FireMUD/actions/runs/37182915940) supplies raw XML proving six distinct suites executed cleanly without skips: current-source 17, initial token-fence 10, bare-LOGIN storage 14, fresh role-source 5, Account repository 17 and fresh UUID membership 14 (77 executions total, with duplicated artifact copies counted once). Both new composition methods executed successfully; the Account job passed. Aggregate validation failed on the separately owned Python lint, dev-demo summary contract, Automation formatting and Game Design duplicate-key fixture failures documented below. This is database component proof, not a complete authenticated capture or enabled flow. A new concurrency method additionally specifies a real tenant authority writer blocked by the capture transaction's source lock, an exact single advance after release, preservation of the original captured vector/checkpoint and unchanged Account/pair/membership/role sources. CI requires that exact method; its execution is not supplied by the earlier checkpoint. The corrected local full Account check/JAR/format/analyzers/coverage and documentation gate passes in 23s (72 tasks: 15 executed, 57 up-to-date). Its 770 unit results are reused from the unchanged production/unit batch; all 314 integration cases compile but skip without Docker, including the new concurrency method. + +The unwired `AccountFreshCaptureSourceReader` now composes the existing membership-source vector with a fresh Account's immutable explicit-empty global-role birth source in one caller-owned writable READ COMMITTED transaction. The result preserves each authority source version, checkpoint and issuance fence independently from the role source version, binds both components to the exact canonical Account/tenant request, and denies retained Accounts without enrolling a role source. The initial full Account check, boot JAR, formatting, analyzers, coverage and documentation gate passes in 2m34s (72 tasks: 20 executed, 52 up-to-date); 770 unit tests execute cleanly, including six composition methods. All 313 integrations compile but skip without local Docker. Two PostgreSQL cases specify independent tenant advancement, exact retry/readback, cross-Account substitution denial and unchanged retained state; their clean execution at exact `c2b4f6d2b05e0d6f5fa7dd643c6b354cd2b85280` is recorded above, separately from the newer concurrency case. Workflow lint, all 25 CI scope contracts, Flyway sanity (12 sets/151 files) and diff hygiene pass. This is partial source composition, not a persisted or authenticated complete authorization bundle: applicable billing, grant, current token-fence, signer, registry and recovery proof remain open, and all activation gates remain unchanged. + +At exact Account checkpoint `46b0e1fa8e4b3bf7ebd426dcacedfd05e612039d`, [CI37177519324](https://github.com/benhook1013/FireMUD/actions/runs/37177519324) passed the Account job. Independently parsed raw XML proves all seventeen current-source, ten initial token-fence, fourteen LOGIN storage and five fresh global-role-source cases executed without skips, failures or errors. All seventeen Account repository cases also passed, including the qualified-schema registration regression. This closes both preceding V55 defects; aggregate CI still failed on separately owned tooling, Automation formatting and Game Design fixture checks. Database component proof does not establish live authentication or activation. + +The settled source prerequisites are now explicit at their canonical owners: [initial billing enrollment and payer consent](../../architecture/microservices/account-service/subscription-management.md#initial-billing-enrollment), [World playtest lifecycle allocation](../../architecture/microservices/world-management-service/operations.md#playtest-fork-lifecycle-authority), [Game Session pointer-bound proof](../../architecture/microservices/game-session-service/api-contracts.md#playtest-lifecycle-proof-on-the-admission-pointer), and [Account grant mutation](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract). Their authenticated producers, independent source persistence and end-to-end proof remain unimplemented. Fresh tenant identity association alone proves neither provisioning-initiator authorization nor billing authority; retained role enrollment still requires exact trusted provenance. Complete authority capture and activation of grant creation, initial billing enrollment, first-party credential paths and the membership RPC remain denied. The older checkpoint paragraphs below retain their historical proof state, not current pending defects. + +Exact published head `2bf280141ce61a35a47ccee9caf3b45319a88f7c` [CI37175502792](https://github.com/benhook1013/FireMUD/actions/runs/37175502792) completed with aggregate failure. Independently parsed and rehashed raw XML proves all seventeen current-source, ten initial token-fence and fourteen bare-LOGIN storage cases executed cleanly without skips, closing the preceding source-export failure at this head. The five fresh global-role-source cases executed: four passed and the direct-write case failed because its assertion expected constraint metadata rather than the trigger's actual rendered error message. The separate `AccountRepositoryIntegrationTest.globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows` failed at its fresh Account insert: V55's unqualified cross-table trigger operations used the connection's default schema rather than the schema owning the qualified Account row. The correction binds all three operations to `TG_TABLE_SCHEMA`, preserves retained rows and source guards, and adds exact owning-schema fresh-source and legacy-role-update denial readback. The direct-write assertions now match the actual guard messages. These owned corrections require new exact-head PostgreSQL execution; neither failure is declared flaky. Other failing jobs remain the separately owned shared dev-demo summary, Python lint, Automation formatting and Game Design duplicate-key checks, plus the dependent gate. No runtime activation or aggregate-green claim follows. + +Exact published head `13ea49adce1de2f06f3e0e587b4ad069d14799df` [CI37172935822](https://github.com/benhook1013/FireMUD/actions/runs/37172935822) completed with failure. Independently parsed raw XML proves all ten initial token-identity fence cases and fourteen bare-LOGIN storage cases executed cleanly, with zero skips. All seventeen current-source cases executed: the existing fourteen passed, but three new export cases failed. Two failures incorrectly require canonical tenant metadata in a retained numeric role header rather than binding its unchanged stored header to the separate audited tenant association; the absence case omitted explicit fixture authority enrollment. Their corrections preserve existing-only read semantics and require new exact-head database execution. These failures are owned Account corrections, not flakes or evidence that the runtime is enabled. Other aggregate failures remain separately owned Python lint, dev-demo summary validation, Automation formatting and Game Design duplicate-key proof; none is declared fixed. + +The V55 prerequisite prepares a fresh Account's explicit empty global-role source at insertion, with its own positive source version and exact persisted UUID/private-row provenance. It does not backfill retained rows or even preexisting rows labeled with fresh provenance: a present-day null scalar is not evidence of historical absence. Existing-only readback requires a real writable READ COMMITTED owner transaction and locks the Account and source rows. Birth-only insert, mutation, truncate and legacy-scalar guards preserve that evidence. Five PostgreSQL cases specify fresh repository/database insertion, independent generation advances, V54-to-V55 no-backfill, direct-write denial and rollback/transaction checks; their clean execution at exact `46b0e1fa8e4b3bf7ebd426dcacedfd05e612039d` and the later composition execution at `c2b4f6d2b05e0d6f5fa7dd643c6b354cd2b85280` are recorded above. The newer lock-ordering case still requires execution. Global-role grant/revoke production, retained enrollment, authenticated bundle composition and credential wiring remain open. This preparation is not a complete authority capture or activation proof. + +The corrected source export preserves nullable canonical metadata in the actual retained numeric role header and carries the exact audited tenant association separately. It rejects missing/substituted association scope, wrong legacy identity, contradictory canonical metadata and mixed header evidence without rewriting retained rows. The absence fixture explicitly enrolls its baseline through the owning preparation path before taking its no-mutation fingerprint; the production reader remains existing-only. The consolidated Account full check, boot JAR, formatting, Checkstyle, SpotBugs, coverage and documentation gate passes in 1m56s (72 tasks: 24 executed, 48 up-to-date). Parsed XML proves 761 clean unit executions, including five source-vector and five fresh-role-source methods; all 311 integrations compile and skip locally without Docker. Schema generation, workflow lint, 25 CI scope contracts, Flyway sanity (12 sets/151 migrations) and diff hygiene pass. Corrected-head database execution remains required for the source17, token-fence10, storage14 and fresh-role5 cases. The constructor-only analyzer annotation covers injected collaborator validation, not a runtime check; all guards and assertions remain intact. The 18 protobuf configuration-cache problems remain an unavailable cache gate, not a test failure or cache-support claim. Runtime paths and ring-mount activation remain unchanged. + +The next unwired bare-LOGIN storage prerequisite adds V54's immutable initial outgoing private-token identity capture, bound to an already hash-bound `PENDING` exchange, exact request and source operation, canonical Account UUID provenance and the actual current Account issuance fence. Its stored token hash is the canonical lowercase hexadecimal SHA-256 representation. The initial token-identity fence and its source version are separately recorded as one for that newly captured identity, never inferred from the incoming gameplay-connect replay evidence or aliased to the Account fence. Exact retry/readback requires unchanged evidence, missing reads do not enroll or backfill, and terminal operations cannot acquire a missing capture. Update, delete and bulk-truncate protections preserve the capture pending a separate safe-cleanup proof. This is initial storage evidence only: monotonic logout/rotation transitions, a complete current token-fence source, signing, registry postconditions and runtime activation remain open. + +Exact V54 head `bb7fb28ea9fa9c194a3e9418e3f61ee95f149d25` [CI37167089744](https://github.com/benhook1013/FireMUD/actions/runs/37167089744) completed with failure. `AccountRepositoryIntegrationTest` cascaded its old per-test account truncate into the new immutable capture table; the targeted current-source and initial-token-fence suites did not execute and their raw proof artifacts are absent. The owned fixture repair gives the two plain repository fixtures a fresh fully migrated schema per case and preserves unique Account rows plus exact account-bound audit lookup in the Spring fixture. Production retention guards, migrations and assertions remain intact. Corrected-head PostgreSQL execution is still required; missing execution is not a pass. + +The unwired existing-only `readExistingRuntimeMembershipCaptureSources` export now retains the original locked composite authority rows, each independent source version/checkpoint and actual Account issuance-fence value/version, together with the unchanged current membership snapshot and exact retained role-header identity/version/provenance. It reads under one writable owner transaction without enrolling a pair or recreating membership. Its immutable value rejects mixed request, scope, tuple, source, event, checkpoint, role-header and fence evidence. Three new PostgreSQL methods specify independently advancing issuer/tenant/Account sources, preservation of historical membership evidence through LEFT, and existing non-admitting sequence-zero absence with mixed-evidence denial; they extend the existing fourteen current-source methods. This is source material, not an authenticated complete evidence bundle, durable bundle reference, signer, registry postcondition or credential release. Applicable global-role, billing and grant source production remains open. + +The corrected Account full check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass in 1m21s (72 tasks: 19 executed, 53 up-to-date). Parsed XML records 755 unit cases executed cleanly, including all four new source-vector cases; all 306 integration cases compile and skip locally without Docker, including all seventeen current-source and ten initial-token-fence methods. Synthetic upstream envelopes, events and token identities are not signed issuance or authenticated transport proof. CI requires every exact method and uploads raw XML; corrected-head database execution remains open. Workflow lint, all 25 CI scope contracts, Flyway sanity (12 sets/150 migrations) and diff hygiene pass. The narrowly scoped constructor annotation covers only retaining injected transaction collaborators, not a runtime guard or global analyzer rule. Configuration-cache storage still discards 18 protobuf serialization problems rather than proving cache support. No activation or ring-mount gate changes. + +Overseer approved the [ADR 0035 capture-reference interpretation](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md#versioned-account-evidence-bundle-and-linearization): the durable capture has its own identifying source version and capture fence, with every applicable authority source's version and checkpoint retained independently. The existing partial source/capture components do not yet materialize that complete bundle; no Account issuance fence, incoming replay fence, latest checkpoint or maximum of source counters is relabeled as the bundle reference. Complete same-snapshot capture, exact immutable readback, independently advancing source and mixed-evidence rejection proof remain assigned Account work, not an activation decision. + +Exact preceding head `473f9ca8b3492288b87c075bacc96ac345692ccc` [CI37164983556](https://github.com/benhook1013/FireMUD/actions/runs/37164983556) is terminal aggregate failure, with the Account job successful. Independently parsed and rehashed raw XML proves all fourteen current-recipient source and fourteen bare-LOGIN storage cases executed cleanly, zero failures, errors or skips. This includes the corrected post-rollback baseline, both actual PostgreSQL lock-ordering cases, durable pending recovery and concurrent exact claims. It closes those component proof gaps at that exact head, not the new V54 database execution, immutable full-bundle producer, network delivery or enabled credential flow. The raw XML hashes are `9d439005fd2700401463ea92066ba1780be0c6f26711a6f60d48b93e2e4463ce` (current source) and `4f2929380db73fa397cb0f262726a5c8e281aef48a15dfcdbf22e12094cc6b91` (storage). Other failing jobs remain the concrete shared validator/Python, Game Design fixture and Automation formatting failures recorded below; none is declared fixed or flaky. The observer is finished, and activation and ring-mount gates are unchanged. + +Account's connect-issuance authority preparation now adds an immutable, versioned positive issuance-fence capture to the existing V35 operation family through V52, with exact request, scope and persisted Account UUID provenance checks. The capture service uses the real existing-only membership snapshot and durable Account fence in a writable READ COMMITTED owner transaction; it does not enroll a pair, create membership, commit a credential or establish admission. Missing historical capture remains unproved and is never backfilled from present authority. The [Account runtime contract](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) owns its digest and persistence boundary. + +The unwired bare-LOGIN current-authority reader composes the strict signed committed-source read, original durable capture, existing full membership snapshot and current Account authority/fence. It compares the complete applicable tuple and the separate exact one-tenant membership-version map, then repeats the strict current source read after owner-fence waits to reject expiry or source substitution. Its redacted result is inspection evidence, not credential release, registry/postcondition proof, terminal recovery beyond expiry, or gameplay admission. Six new PostgreSQL storage cases use explicitly synthetic V35 result bytes; four further composition cases use signed fixture JWT/context bytes, the real encrypted committed-source reader and current owner repositories. Their upstream catalog/policy/route evidence, keys and peer context remain fixtures, not an authenticated network producer. The actual bare-LOGIN issuer, committed-connect success producer, JWT signing/registry wiring, authenticated delivery and runtime activation remain open; all existing denial and unpublished ring-mount gates remain in force. + +The unwired `AccountTokenProfileCatalog` prepares the mandatory finite ordinary-token profile checks from [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md#profile-boundaries) and the [canonical byte-measurement owner](../../architecture/system-architecture-jwt-and-token-contracts.md#canonical-profile-catalog-byte-measurements). It requires an explicit complete three-profile configuration and validated deployment ceilings, checks exact profile/audience, finite cardinalities, checked UTC-second lifetime and canonical UTF-8 tuple/compact-JWT/registry-record sizes, and rejects malformed Unicode without normalizing valid text. Supported serialized authority-tuple scope keys, optional cutoff presence and exact lifecycle-qualified grant identity/version must match the supplied typed candidate; a private target and grant must belong to the delegated tenant. The pre-sign API now also receives defensive immutable copies of the actual separate `membershipVersion` and `scopedRoles` maps, preserving arbitrary-precision positive counters and required-empty versus optional-omitted presence. Exact canonical tenant keys, cardinalities and canonical role vocabulary must match the typed profile scope; membership versions remain independent from authority generations. This is structural candidate proof only, not source currentness, role authorization, signature validation, complete signed-claim or registry-schema validation, or a registry postcondition. No production callers are wired. Complete immutable claim construction, deployment configuration/startup integration, current Account bundle, signer/registry/lifecycle wiring and activation proof remain open. No production defaults or activation are introduced. + +The actual-map catalog and V55 owning-schema corrections pass the consolidated Account full check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, schema generation, links and Markdown in 1m30s (72 tasks: 24 executed, 48 up-to-date). Independently parsed XML records 764 clean unit executions, including all 17 catalog methods; all 311 integration cases still skip locally without Docker. The added assertions cover arbitrary-precision membership counters, exact map scope and presence, defensive copies, canonical role vocabulary, duplicate rejection and preservation of valid supplied role order. The membership-event schema's sorted-array requirement is not imposed on JWT role lists. Parent diff review caught duplicate detection being lost while removing that overbroad order check; the existing negative assertion failed in the first gate and passed after the narrow correction. No assertion, authorization guard or analyzer rule was weakened. CI now requires the exact qualified-schema registration method alongside all five V55 cases and uploads both raw suites. Workflow lint, all 25 CI scope contracts, Flyway sanity (12 sets/151 migrations) and diff hygiene pass. Schema generation uses H2's static DDL emulation, not execution of the PostgreSQL trigger bodies. Gradle discards its configuration-cache entry with 18 protobuf serialization problems; this does not establish working configuration-cache support or negate the completed check. Corrected-head PostgreSQL, complete claim/issuer/registry, fresh-image and live activation proof remain open. + +At published #2966 head `03086915bdc99e3237c8d1e15e68d3450aaa980e`, the consolidated Account full check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown passed locally in 1m11s (72 tasks: 15 executed, 57 up-to-date). Parsed XML contained 733 clean unit executions, including all 18 capture-vector, transaction-guard and current-authority-reader cases. All 286 integration cases skipped without Docker. Exact-head [CI37138277809](https://github.com/benhook1013/FireMUD/actions/runs/37138277809) then executed all 12 current-recipient source PostgreSQL methods: eight passed, four failed, none skipped. The foreign-Account fixture exceeded its username column bound; an older negative source check left deliberate issuer-generation corruption committed, contaminating three later JOIN fixtures. The scoped corrections shorten the fixture username and prove source mismatch inside a rollback-only transaction, retaining post-rollback exact source and membership readback. The expanded suite also defines two actual PostgreSQL-blocking cases for capture/current read against the real Account logout-all owner transition. These corrected-state and concurrency cases still require executed runner proof; compiling or skipping them locally is not that proof. The narrow test-only Mockito resource-analysis annotation does not weaken production guards or global analysis. Other aggregate failures are inherited source defects: ten Ruff errors in hosted-preview helpers/tests, unsupported dev-demo summary syntax, Game Design's `EntityDigestBaselineMigrationIntegrationTest` duplicate tenant `9301`, and Automation's `NpcFormationGrpcServiceTest` formatting. Their offending source blobs match both exact parent `46a06286ace53ab1b82d235a25be95bb0def6ea1` and ancestor `ab0b055a5c25b418cf5b29ab127e2f806118fea6`; they are not newly introduced, flaky or proved resolved here. No aggregate-green, fresh-image, live or activation claim follows. The runtime paths stay denied and the Account-ring mount stays unpublished. + +Forward V53 removes only V37's transaction-local pending-commit prohibition so a non-authorizing bare-LOGIN operation can survive separately committed evidence and exact retry after response loss. Terminal success and its exact purpose-bound envelope remain atomic; original identity/digest, fresh readback, write-once evidence, CAS and deletion guards remain enforced. The expanded storage suite defines committed pending recovery, changed identity/evidence conflicts, rollback, concurrent first-writer and conflicting-evidence behavior, and rejection of terminal success without its bound envelope. This is storage preparation for the existing ordered issuance contract, not the complete pre-sign evidence bundle, signer, registry, terminal recovery or credential release. Corrected-state Account full check and boot JAR pass in 1m9s (72 tasks: 17 executed, 55 up-to-date), with 733 clean unit cases and all 293 integration cases skipped without Docker. Each expanded PostgreSQL suite has 14 compiled but skipped methods. Links, Markdown, workflow lint, 25 CI scope contracts, Flyway sanity (12 sets/149 migrations) and diff hygiene pass. + +Exact published `658d80da33d45e25ff7faee288847433691b9248` [CI37141351309](https://github.com/benhook1013/FireMUD/actions/runs/37141351309) completed with aggregate failure and its sole observer finished. Independently parsed and rehashed raw XML proves all 14 bare-LOGIN storage methods executed cleanly without skips, including durable pending recovery, concurrent exact claims, changed-evidence conflict, rollback, terminal-envelope atomicity and retained deletion guards. All 14 current-recipient source methods executed: 13 passed and one failed, with no errors or skips. Both real PostgreSQL lock-ordering cases passed. The remaining owned failure is a post-rollback fixture assertion comparing the current source against its original generation-one snapshot even though that method had deliberately committed generation-two advances earlier. Its correction compares the complete same-snapshot tuple, map, roles, fence, checkpoints, source evidence and unchanged event bytes to the immediately preceding authority read; executed corrected-head proof remains required. These are component/database tests with fixture keys and source evidence, not authenticated delivery, registry activation, an enabled LOGIN flow, fresh-image or live proof. Other aggregate failures retain their separately owned dispositions above. Runtime activation remains denied and the Account-ring mount stays unpublished. + Exact `202c58f1605018f6bf51277ac4f431497eca9a34` [CI37121026340](https://github.com/benhook1013/FireMUD/actions/runs/37121026340) completed with aggregate failure and its sole observer finished. Independently parsed/rehashed raw XML proves all34 focused Account/World/Game Session methods executed cleanly with zero skips: canonical journal4, reconciliation4, World physical socket7, owner-local PostgreSQL8, real World PostgreSQL/socket3 and Game Session source intake8. The V51 diagnostic-preserving recovery, corrected World source fixture and all three real Game Session service/transaction/readback methods are now executed component proof. Upstream source/policy fixtures remain synthetic; this is not public JOIN or normal creation/delivery. The Game Session job exhausted its exact20-minute budget after focused proof passed and while packaging the runtime JAR, as its check annotation confirms; the bounded job allowance is now30minutes for Game Session only, leaving other modules at20 and retaining all proof/check/failure propagation. Its later whole-job success still needs execution. Game Design's duplicate-key fixture, Automation formatting, Python lint and the dev-demo workflow validator remain concrete other-owner failures. No aggregate-green, fresh-image/live or activation claim follows, and the Account ring mount remains unpublished. The explicitly unwired Game Session authored-source intake now rejects an ambient transaction or synchronization before reading Game Design, fetches fresh immutable evidence outside its owner transaction, and opens a short writable READ COMMITTED transaction only for local registration. It independently reads and compares the complete committed result before success. Exact retries first read the original immutable local request, source and tenant binding, without another source call or write; changed tenant, source operation or world scope conflicts. Missing or contradictory post-commit readback denies success without replacing committed evidence. This corrects the former mandatory outer-transaction prerequisite; it does not add a creator API, automatic handoff, runtime catalog activation or admission. The [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#authored-world-source-intake-and-durable-readback) owns the transaction and retry boundary. @@ -368,6 +420,8 @@ The #2880 local Account check separately recorded 389 unit cases executed and al The #2876 `account-auth-authority-event/v1` correction uses the exact one-tenant `membershipVersion` map, strict shared codec, canonical digest vectors, immutable evidence, and exact Account retry/readback comparisons. Local codec and Account/Game Session vectors execute; PostgreSQL JOIN/reconciliation tests compile but skip without Docker. V31–V36 authority, role, event, enrollment, issuance-envelope, and pair-authority migrations remain distinct from the current V40 transition-receipt migration. The V40 receipt is not a complete authority tuple or a replacement for event/source evidence. Runtime event delivery/projection and Game Session consumption remain open. The local AES-GCM envelope and ring materializer remain offline candidates: per-access principal checks and receipt shape validation do not authenticate target-cluster identity, and local receipts do not prove Secret delivery. Normal Kubernetes operations remain denied pending the [canonical target-cluster binding gate](../../architecture/infrastructure/environment-and-secrets-overview.md#account-ring-materializer-target-cluster-binding), protected custody, trusted writer, deployment readback, and readiness proof. +Historical V37 storage proof rejected a transaction that would commit `PENDING` without its terminal envelope; its seven PostgreSQL cases passed on #2881 head `25626210c` in CI run `36289042648`. That transaction-local pending restriction did not implement ADR 0014's durable pre-sign intent and separately fenced registry postconditions. Forward V53 removes only the obsolete deferred pending-commit prohibition: a non-authorizing pending claim and write-once evidence may survive separate Account transactions, while terminal success and its exact bound envelope still commit together. An exact replay may resume writes only while its observed operation is pending and the fresh identity/digest/readback/CAS checks still hold; committed replay cannot become a new writer. This is pending-storage/recovery preparation, not the complete pre-sign authority bundle, signer, registry, credential-release or reconciliation path. Deletion remains denied until Account proves receipt/envelope retention and safe cleanup; no fixed TTL, timeout, absent row or persisted pending claim is authority or a terminal result. Current producer/consumer and executed corrected-head proof remain activation gates. + Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, owner-local audit outbox, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Account's bounded JOIN worker is readback-only: expired scopes, attempt limits, absent evidence, and uncertainty do not terminalize or trigger resubmission. JOINED requires exact positive operation, scope, membership, transition-receipt, authority-event, and version-1 COMMITTED audit receipt/projection evidence, including the explicit marker and nonblank receiver identities read from the locked scoped outbox row; ALREADY_ACTIVE requires matching positive retained receipt history with no new event. Legacy rows without that marker remain unresolved and are never promoted by deploying the receiver. Incomplete evidence remains pending with capped diagnostics. PostgreSQL lost-acknowledgement/concurrency and direct text-client-to-Logging end-to-end proof remain open. Gateway blocks external exposure of Account JOIN, so first-party browser `Join & Play` remains unavailable. Account's live membership, entitlement, and realm-grant handlers fail closed before data reads, including for Game Session. Supplied-authority local `PLAY` classification is not composed admission proof; text `PLAY` checks entitlement before membership and maps the denied Account entitlement read's `FAILED_PRECONDITION` to retryable `ENTITLEMENT_UNAVAILABLE`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. The current Game Session presence classifier has no fresh Account-authenticated gameplay-grant carrier and records `PLAYER` for new presence; JWT role claims do not confer gameplay elevation. Existing Redis presence reads project `PLAYER` without writes or TTL refresh, and activity updates demote cached elevated roles without changing identity or activity fields. The catalog and `GetAdmissionPointer` fail closed unless a tenant has exactly one visible public-production realm; direct-text Account scope issuance checks current entitlement and denies missing, ambiguous, unavailable, or gameplay-blocked authority before retaining scope. Reconnect and continuity remain partial: private retained-context replay is suppressed fail-closed, safe eligible first-party replay remains incomplete, and accepted `PLAY` renders a fresh `LOOK`; namespace-aware binding, effective resume-window enforcement, exactly-one-prompt proof, and durable post-logout episode fencing are incomplete. Authenticated text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, does not clear the active binding, and does not prove the generation fence. TCP Proxy's bounded ordered input remains connection-local and is not durable replay. Broader manual end-to-end and continuity proof remain open; canonical target behavior is linked below rather than restated. @@ -435,7 +489,7 @@ Unit 1A's 29-source broad discovery closed by Overseer judgment after Cycle 23, | Profile tenant qualification; membership lifecycle/generation, grants, roles, delegation and JOIN abuse limits | Account `AA-1.1`/`AA-1.2` authority successor, then Unit 1B consumer | Current profile route is self-bound and membership-checked; no tenant-qualified or delegated route activates until live generation/role/grant authority, caller binding and audit proof. Unit 1B must consume the exact snapshot and prove stale-generation/private-grant/character negatives before admission readiness. | | Issued-token registry, deterministic replay, reset/logout revocation and authentication abuse controls | Account `AA-1.3` issuer/recovery successor; Game Session `AA-2.2`/`AA-3.3` consumer in Unit 1B | Current password/email-OTP login remains available but is not registry, replay, reset-revocation or graduated-throttle complete. Before claiming those properties, implement the single-record registry, atomic issuance/replay, revocation and Account-owned limiter/outage proof; Unit 1B handles logout/reconnect consumption. Do not infer safety from OTP challenge caps or a prior binding. | | Login-factor changes, provider linking, TOTP, safety/appeal, account switching and signing-key rotation | Account `AA-1.3` security successors | Login-factor `PUT` and unverified linking are denied; other unimplemented features are not offered as supported authority. Each activates only after its Account-owned recent-reauth/provider/security-state or validator-convergence contract and negative proof, not because this corpus section was reviewed. | -| Hosting billing owner, provider lifecycle, current-row entitlement snapshot and strict new-binding rules | Account `AA-1.4`/`AA-1.5` billing-and-entitlement successor; Unit 1B consumer | Subscription creation is disabled and zero/ambiguous rows fail retryably. Select the initial billing-owner source/consent, then prove durable provider reconciliation, one current row and complete freshness/evidence before paid hosting or new commitments activate. Exact-binding last-known-good reconnect stays undecided; no fallback is authorized. | +| Hosting billing owner, provider lifecycle, current-row entitlement snapshot and strict new-binding rules | Account `AA-1.4`/`AA-1.5` billing-and-entitlement successor; Unit 1B consumer | Subscription creation is disabled and zero/ambiguous rows fail retryably. Implement the accepted [initial billing enrollment and direct payer-consent producer](../../architecture/microservices/account-service/subscription-management.md#initial-billing-enrollment), then prove durable provider reconciliation, one current row and complete freshness/evidence before paid hosting or new commitments activate. Exact-binding last-known-good reconnect stays undecided; no fallback is authorized. | | Official-hosted creator terms and future creator commerce | Account acceptance authority, Game Design mutation/readback gate, Platform `PO-2.1` edge; separate accepted product successor for commerce | Gateway exposes only safe GETs for now. Official hosted writes stay unavailable until current acceptance/changed-terms negative owner-side proof; creator purchases, tips, payouts and entitlement issuance remain unsupported pending separate product/authority acceptance. | | Audit producer/receiver retention, migration, certificates and live proof | Account `AA-1.1`/`AA-1.2` producer, Logging receiver, #2847/#2848 readiness | Execute PostgreSQL receipt/projection and retained-row tests, verify exact workload certificate/render and direct text-to-Logging delivery, and define safe-watermark/hold/reference cleanup for committed payloads before long-running activation. Skipped local tests and green documentation checks do not close these gates. | @@ -469,7 +523,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. Local producer proof covers minimizing payload after a verified terminal receiver receipt while retaining audit identity and digest; live `CreateLogEvent` currently returns `UNAVAILABLE` and Account delivery is unscheduled, so this is not live delivery proof and new/outstanding rows remain `PENDING`. Historical rows with unknown projection provenance are not promoted, and safe-watermark, hold, reference, finite-retention, PostgreSQL runtime, and retained-row disposition/readback proof remain open. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. V29 adds immutable account UUIDs while retaining numeric primary keys and explicit migration/repository provenance; its 13 PostgreSQL migration/immutability cases compiled but were all skipped because Docker was unavailable, and it neither changes numeric external identity nor maps tenant UUIDs. Lifecycle-state retention is tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. Fresh and cached-success connect-token attempts recheck current pointer/visibility, membership lifecycle/admission, and entitlement; when complete selected-target evidence is unavailable, the cached-success attempt returns retryable `AUTH_UNAVAILABLE` rather than the cached token. Independent same-snapshot membership-version/generation and issuance-fence proof, durable registry/postcondition revalidation, and end-to-end issuance remain unproved. The explicit JOIN operation validates a server-issued scope and caller, rereads Game Session routing/catalog/pointer evidence before its Account transaction, and binds a version-1 digest to caller/scope and policy evidence; membership, stored outcome, and tenant audit outbox row persist atomically, but exact target/catalog/pointer validity is not guaranteed through commit and the strict ADR 0025 commit fence remains incomplete. The subscription authority query locks the subscription row but not its joined billing-owner Account; JOIN locks the caller Account and operation row. Terminal replay's remote scope/target/entitlement reads occur outside the lock-holding transaction; unit proof covers replay after commit or rollback without rewriting stored outcome, while the PostgreSQL row-lock regression was Docker-skipped. Global-only registration creates no admitting membership. Expired unreferenced connect scopes are swept, and V27's restrictive FK preserves scopes referenced by PENDING or terminal JOIN records and fences racing intent inserts. The bounded worker is readback-only: it terminalizes only exact positive operation/scope/membership/audit evidence; an expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, and the worker does not resubmit the bearer-bound request or terminalize from expiry, attempt limit, absent evidence, or uncertainty. Exact replay remains fenced to caller, target, intent, and retained policy digest. New/outstanding audit rows remain `PENDING` because live `CreateLogEvent` is `UNAVAILABLE` and delivery scheduling is disabled; positive delivery/receipt handling is offline fixture proof, and historical unknown provenance is not promoted. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Runtime membership authority-generation evidence, issuance grant validation, independent issuance-snapshot/fence and durable postcondition proof, and the target five-field grant codec remain incomplete. Game Session omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); fresh caller-bound prior snapshots for the exact current private target receive retryable `AUTH_UNAVAILABLE`, while unbound selectors remain hidden. Account's runtime membership, entitlement, and grant handlers fail closed before reads; text `PLAY` and namespace-qualified `CHARS` remain unavailable, not positive admission proof. Other transactional outboxes, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses; unknown addresses create no token or delivery attempt, and known-account post-commit SMTP exceptions are contained and logged. Delivery remains synchronous after commit, so timing resistance and durable asynchronous delivery remain unproved; current tests prove error containment only. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Every current `DeleteAccount` entry now fails with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation, including terminal subscriptions. The named pre-v1 Account `AA-1.3`/`DATA-01` successor must implement the full ADR 0043 pending-deletion, provider/transfer clearance, cross-service erasure, retained-data registry, finite approved schedules, restore/replay and proof before deletion is enabled. Password-reset and email-verification tokens now use conditional single-use consumption in the Account transaction; PostgreSQL concurrent-reuse proof is compiled but not locally executed. Reset-driven revocation remains a separate issuer successor. The legacy account/profile export is explicitly partial, the account-targeted tenant export is disabled before data reads, and JWKS foundations remain live; complete ADR 0050 export is a separate pre-v1 Account successor. | -| `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Focused repeated-call tests prove the three methods create no `PaymentService` or provider interaction. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | +| `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. The accepted [initial billing enrollment contract](../../architecture/microservices/account-service/subscription-management.md#initial-billing-enrollment) selects Account-owned operation-bound nomination, direct payer consent and an atomic owner CAS from positively proved durable `UNASSIGNED` state, with an independent owner version and immutable receipt. Its authenticated provisioning-initiator producer, owner-source persistence, consent/assignment implementation and focused proof remain absent; Game Design identity evidence, caller-supplied account ID, tenant role, Creator Party or payment-instrument ownership cannot supply that authority. Generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` gRPC handlers now deny with `FAILED_PRECONDITION` before service/provider calls, with focused repeated-call no-interaction proof; the underlying provider-mutating service and non-exposed purchase-workflow substrate remain unsupported. Exact authenticated workload/method authorization for any future internal generic call remains unproved. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto); [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.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); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and text `PLAY` exist with supplied-authority unit proof for local public-production admission classification. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context, and Game Session player identity is separate from game-instance control-plane ownership. Reauthentication as a different account clears prior gameplay context; same-account/same-tenant login may preserve only a candidate binding for fresh checks, while tenant switching clears the old gameplay presence. Text `PLAY` validates exact account/tenant identity and fresh membership lifecycle, admission, version, authority-generation, and evaluation-time evidence before binding. `ACTIVE` is required for admission; only public-target `MISSING` or `INACTIVE` membership may receive `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks; an active non-admitting member is denied and unavailable evidence remains retryable. Strict persisted actor selection distinguishes an actor-selection-required outcome from authority/evidence failures; focused service proof also covers the Game Session-to-Entity peer allowlist. `PLAY` roster loading has focused proof for authenticated account, tenant, selected instance, and playable-state scope, but not namespace-aware actor revalidation or target binding-generation fencing; no synthetic account/name/hash actor fallback is permitted. Live Account runtime membership/grant/entitlement readers still fail closed before data access, so supplied-authority local PLAY checks do not establish composed live admission; valid-route live text `PLAY` maps Account `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`. Account connect-token issuance requires existing membership. Cached-success attempts recheck current eligibility but fail `AUTH_UNAVAILABLE` rather than returning the token when complete selected-target evidence is unavailable; the independent issuance membership-version/authority-generation baseline reread and registry proof remain gaps. The Account public-production JOIN writer and Game Session direct text `JOIN` dispatch exist locally, but first-party `Join & Play` remains unavailable; the Gateway guard blocks external exposure of the Account HTTP route. The bounded Account-owned JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; scopes are never reissued, and only exact positive prior-commit evidence terminalizes. Expiry, attempt limit, absent evidence, and uncertainty do not terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unexecuted under ADR 0025. Generic prompt-mode login and account-bound Entity actor lookup remain gaps. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; malformed actor rows and normalized-duplicate IDs remain unvalidated response cases because the current handler stops before those responses. Focused unit proof is linked above; PostgreSQL runtime proof, direct text-client end-to-end proof, deployment/mTLS proof, and fresh-image proof remain incomplete. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior remain gaps. The current player child rejects text `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. The first-party private-transcript fence is a fail-closed boundary and does not establish durable post-`LOGOUT` replay suppression. This fail-closed behavior is partial progress, not durable logout/replay completion: the durable namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. | 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 52be2cd1bc..b0b11e9e05 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,9 +6,10 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The legacy World lifecycle adapter now exact-compares Game Design's persisted opaque release-bundle reference instead of reconstructing it from private numeric keys. Focused unit cases prove acceptance, substituted/missing-reference denial before persistence, and stable exact retry; the full World check and boot JAR pass with 153 clean unit results. All 25 World integration cases skip locally without Docker. This is reference-binding proof only, not complete release attestation, authenticated canonical launch composition, source-room delivery or activation. The current normal reconciliation preserves the incoming V23 initial-admission hold and mechanically places fresh-source intake at V23.1 with byte-identical SQL. The original intake SHA-256 remains `a7ac30d48da1911eb3395716e827ac0f0ec612970d4f40b5a27530d634430445`; its PostgreSQL fixture now explicitly requires the hold-before-intake applied script order. This is an unapplied candidate, not authority to rename applied migrations or invoke repair/out-of-order execution. Exact environment history/checksums and retained-row readback remain rollout gates; the historical V23 source proof below does not execute the newly composed sequence. -The owner-local source-qualified receipt lookup is implemented as a read-only prerequisite and is not yet called by the lifecycle path. Its four new PostgreSQL cases are required by the focused suite selector but remain unexecuted. The earlier eight-case intake proof and subsequent V24 guard proof predate the composed V23 hold β†’ V23.1 intake β†’ V24 sequence and do not prove the four lookup cases; the V24 fixture now seeds after V23.1 and applies V24 explicitly. No activation or source-qualified lifecycle composition is claimed. +The owner-local source-qualified receipt lookup is implemented as a read-only prerequisite and is not yet called by the lifecycle path. Exact cumulative `12d6cf5cfab437c0d69583566a6aa0738a644986` [CI37218116041](https://github.com/benhook1013/FireMUD/actions/runs/37218116041) is terminal `FAILURE`, but independently parsed and hashed raw XML proves all 29 focused World cases executed cleanly with zero skips, failures or errors: thirteen intake/isolation/lookup cases, six fence cases, three actual PostgreSQL-through-physical-mTLS composition cases and seven physical socket cases. This supersedes the earlier unused initial-bind client fixture setup failure for those methods and proves the four new lookup cases under the composed V23 hold β†’ V23.1 intake β†’ V24 guard β†’ V25 fence sequence. The composition's upstream authored-source evidence remains synthetic; this is not automatic delivery, full authenticated release evidence, a canonical writer, live deployment, activation or source-qualified lifecycle composition. Local PostgreSQL skips and pending revalidation of later changes remain separate limitations. **Canonical launch prerequisite:** Current World design/materialization rows and `PrepareWorldInstance` still use World's private numeric tenant key. V23 and the explicitly unwired owner-local fresh-source intake service/repository persist complete authenticated Game Design `NEW_GAME_ROW` evidence, a private World tenant association, numeric-key reservation and immutable intake receipt together, with exact independent readback. Legacy numeric writes cannot take a reserved canonical selector; existing legacy keys are reserved without inventing UUID associations. Exact [CI37111727823](https://github.com/benhook1013/FireMUD/actions/runs/37111727823) at `73ab357d694618a56c65129394fd324b38ad652e` proves all eight intake PostgreSQL cases and nine Game Design source-read socket cases executed cleanly without skips. Independent raw-XML verification confirms the reservation rejection, SQL state `23514`, unchanged legacy row and no-region assertions. That prior checkpoint does not prove the newer World receiver. @@ -24,6 +25,8 @@ Exact corrected `ab0b055a5c25b418cf5b29ab127e2f806118fea6` [CI37122999109](https V24 closes V23's legacy mutation bypasses: all16 tenant-bearing tables reject canonical reserved-key inserts, payload-only updates, movement away from the canonical key, deletes and unqualified table truncation. Legacy row updates/deletes remain available; the immutable reservation is not removed by deletion. Its PostgreSQL case, including all16 table guards and truncation assertions, executed cleanly in CI37130036974. The fixture uses synthetic retained canonical rows to test isolation, not a completed canonical writer or retained migration. Local Docker unavailability still skips the 61 Game Design and 25 World PostgreSQL tests; those are local skips, not skips in the runner evidence. The authenticated source-qualified writer, transaction-bound mutation authorization and shared mutation/publication fence remain required before canonical content or lifecycle preparation is admitted. +The source-qualified Game Design current-version read is implemented and read-only; it verifies source/version/lifecycle identity but does not authorize writes. V24's deny guard means canonical World mutations remain unavailable. The current `ApplyWorldDesignMutation` path does not authenticate Game Design workload/tenant access or verify current Account designer/admin and applicable terms authority at commit. The synthetic V25 freeze checkpoint remains persistence-only and does not prove an authenticated authorization or mutation commit. See the [World commit authorization contract](../../architecture/microservices/world-management-service/api-contracts.md#canonical-draft-commit-authorization); no canonical World write or lifecycle preparation is admitted. + An earlier runner attempt executed all nine World intake cases: eight passed, while the all-table case failed during setup because its isolated Flyway configuration omitted the common-saga `serviceSchema` placeholder. The fixture correction is now exercised: all nine World intake PostgreSQL cases passed in CI37130036974, including the complete16-table guard and truncation assertions. The same exact-head run passed World socket7, World PostgreSQL/socket3, Game Design source socket9 and descriptor socket13/PostgreSQL7. Aggregate CI remains `FAILURE` on concrete shared Ruff, dev-demo validator, Automation formatting and unchanged Game Design `EntityDigestBaselineMigrationIntegrationTest` duplicate-key fixture failures. Those failures are not relabeled flaky or resolved. V25 adds the internal shared tenant/version owner row and immutable freeze attempts. Ordinary locks and freeze claims use that same row; checkpoints are captured after lock acquisition, while exact retries return the stored fence/checkpoint without recapturing server-derived output. Multiple exact source receipts may use the same global tenant/version row. The full publication-attempt digest remains distinct from the separate publication-read binding used for workflow identity. Four evidence unit methods passed locally; all six PostgreSQL rollback, concurrency, lock-order and immutable-readback methods executed cleanly in CI37130036974. The freeze-checkpoint fixture is synthetic: it does not exercise a real content writer, complete-commit/digest producer, authenticated freeze acknowledgement, terminal producer/handoff or activation. The store remains unconnected to a public handler or RPC route. Canonical payload guards and runtime denial gates remain unchanged. 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/dev-tools/validation/check-design-capability-allocation.py b/dev-tools/validation/check-design-capability-allocation.py index 9c543175a1..8e2b471299 100644 --- a/dev-tools/validation/check-design-capability-allocation.py +++ b/dev-tools/validation/check-design-capability-allocation.py @@ -696,6 +696,9 @@ def adr_allocation(primary: str, classification: str, *secondary: str) -> tuple[ "design/architecture/decisions/adr-0184-emergency-tcp-proxy-identity-withdrawal.md": adr_allocation( "SF-1", "Accepted", "PO-2", "PO-3", "PO-4" ), + "design/architecture/decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md": adr_allocation( + "AA-1", "Accepted", "SF-1", "PO-1" + ), } MICROSERVICE_STANDARD_CLASSIFICATIONS = { "README.md": "Service overview", diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index c7e5d50ded..8d50710d63 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -560,6 +560,7 @@ message PublishedReleaseBundle { string workflow_status = 14; string workflow_family = 15; repeated string command_definitions = 16; + string published_release_bundle_ref = 17; string canonical_tenant_id = 18; string canonical_version_id = 19; } diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index d5172d7680..79153fc623 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -17,6 +17,8 @@ dependencies { implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) + // Test-only JDBC mocks need narrowly scoped resource-analysis annotations. + testCompileOnly(libs.spotbugs.annotations) // Integration analysis follows the real producer's annotated Account collaborators. add("integrationTestImplementation", "com.github.spotbugs:spotbugs-annotations:4.9.8") } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountFreshCaptureSources.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountFreshCaptureSources.java new file mode 100644 index 0000000000..5c8d6020ee --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountFreshCaptureSources.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourceRepository.FreshEmptySource; + +/** + * Partial fresh-Account capture material from one existing-only Account owner transaction. + * + *

This composes the existing membership source vector with the fresh Account's immutable + * explicit-empty global-role birth source. It is source evidence only, not an authorization bundle, + * credential decision, or admission result. + */ +public record AccountFreshCaptureSources( + UUID requestedAccountUuid, + UUID requestedTenantUuid, + AccountMembershipCaptureSources membershipSources, + FreshEmptySource freshGlobalRoleSource) { + public AccountFreshCaptureSources { + requireCanonicalUuid(requestedAccountUuid, "requested Account UUID"); + requireCanonicalUuid(requestedTenantUuid, "requested tenant UUID"); + Objects.requireNonNull(membershipSources, "existing membership sources are required"); + Objects.requireNonNull(freshGlobalRoleSource, "fresh global-role source is required"); + + if (!requestedAccountUuid.equals(membershipSources.requestedAccountUuid()) + || !requestedTenantUuid.equals(membershipSources.requestedTenantUuid())) { + throw new IllegalArgumentException( + "Fresh capture membership sources differ from the exact canonical request"); + } + + if (!requestedAccountUuid.equals(freshGlobalRoleSource.accountUuid()) + || freshGlobalRoleSource.accountRowId() <= 0L + || freshGlobalRoleSource.accountUuidSourceNumericId() + != freshGlobalRoleSource.accountRowId() + || !isFreshInsertProvenance(freshGlobalRoleSource.accountUuidProvenance()) + || !freshGlobalRoleSource.globalRoles().isEmpty() + || freshGlobalRoleSource.globalRoleSourceVersion() <= 0L) { + throw new IllegalArgumentException( + "Fresh global-role source differs from its exact fresh Account identity"); + } + } + + private static void requireCanonicalUuid(UUID value, String field) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + } + + private static boolean isFreshInsertProvenance(AccountIdentityProvenance provenance) { + return provenance == AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + || provenance == AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSources.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSources.java new file mode 100644 index 0000000000..27556073a2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSources.java @@ -0,0 +1,388 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +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.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec; + +/** + * Immutable source material retained from one owner-local existing-membership read. + * + *

This value is not authorization. It preserves the exact locked authority rows, their + * independent source versions and Account fence, alongside the membership projection that carries + * the corresponding source checkpoints and events. A raw retained role header remains unchanged; + * its audited tenant association is carried separately for identity binding. + */ +public record AccountMembershipCaptureSources( + UUID requestedAccountUuid, + UUID requestedTenantUuid, + CompositeSnapshot authoritySnapshot, + RuntimeMembershipSnapshotDto membershipSnapshot, + Optional roleSource, + Optional retainedTenantAssociation) { + private static final String AUTHORITY_STREAM_PREFIX = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + + public AccountMembershipCaptureSources { + requireCanonicalUuid(requestedAccountUuid, "requested Account UUID"); + requireCanonicalUuid(requestedTenantUuid, "requested tenant UUID"); + Objects.requireNonNull(authoritySnapshot, "locked Account authority snapshot is required"); + Objects.requireNonNull(membershipSnapshot, "existing runtime membership snapshot is required"); + roleSource = Objects.requireNonNull(roleSource, "role source presence is required"); + retainedTenantAssociation = + Objects.requireNonNull( + retainedTenantAssociation, "retained tenant association presence is required"); + + String accountId = requestedAccountUuid.toString(); + String tenantId = requestedTenantUuid.toString(); + if (!accountId.equals(membershipSnapshot.requestAccountUuid()) + || !tenantId.equals(membershipSnapshot.requestTenantUuid()) + || !accountId.equals(membershipSnapshot.accountUuid()) + || !tenantId.equals(membershipSnapshot.tenantUuid())) { + throw new IllegalArgumentException( + "Account membership sources differ from the exact canonical request"); + } + + ScopeState issuer = authoritySnapshot.issuer(); + ScopeState account = authoritySnapshot.account(); + ScopeState tenant = only(authoritySnapshot.tenants(), "tenant"); + ScopeState membership = only(authoritySnapshot.memberships(), "membership"); + var fence = authoritySnapshot.issuanceFence(); + if (!AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER).equals(issuer.scope()) + || !AuthorityScope.account(requestedAccountUuid).equals(account.scope()) + || !AuthorityScope.tenant(requestedTenantUuid).equals(tenant.scope()) + || !AuthorityScope.membership(requestedAccountUuid, requestedTenantUuid) + .equals(membership.scope()) + || !requestedAccountUuid.equals(fence.accountId()) + || !fence.equals(account.issuanceFence()) + || !fence.equals(membership.issuanceFence())) { + throw new IllegalArgumentException( + "Account authority sources do not retain the exact issuer, account, tenant and pair"); + } + + var tuple = membershipSnapshot.authorityTuple(); + var baseline = membershipSnapshot.membershipBaseline(); + String version = baseline.membershipVersion().get(tenantId); + if (version == null + || baseline.membershipVersion().size() != 1 + || !Long.toString(issuer.generation()).equals(tuple.issuerAuthGeneration()) + || !Long.toString(account.generation()).equals(tuple.accountAuthorityGeneration()) + || !Map.of(tenantId, Long.toString(tenant.generation())) + .equals(tuple.tenantAuthorityGeneration()) + || !Map.of(tenantId, Long.toString(membership.generation())) + .equals(tuple.membershipAuthorityGeneration()) + || !Long.toString(membership.generation()).equals(baseline.membershipAuthorityGeneration()) + || !Long.toString(fence.value()).equals(membershipSnapshot.issuanceFence())) { + throw new IllegalArgumentException( + "Membership projection differs from its exact captured authority generations or fence"); + } + + requireExactCheckpoints( + requestedAccountUuid, + requestedTenantUuid, + membershipSnapshot, + issuer, + account, + tenant, + membership); + requireSourceEvents( + requestedAccountUuid, + requestedTenantUuid, + membershipSnapshot, + issuer, + account, + tenant, + membership); + VerifiedTenantProvenance retainedProvenance = + retainedTenantAssociation + .map(association -> requireRetainedAssociation(requestedTenantUuid, association)) + .orElse(null); + requireRoleSource( + requestedAccountUuid, + requestedTenantUuid, + membershipSnapshot, + roleSource.orElse(null), + retainedProvenance, + version); + } + + private static void requireExactCheckpoints( + UUID accountUuid, + UUID tenantUuid, + RuntimeMembershipSnapshotDto snapshot, + ScopeState issuer, + ScopeState account, + ScopeState tenant, + ScopeState membership) { + Map actual = new HashMap<>(); + for (OutboxCheckpointEntry checkpoint : snapshot.outboxCheckpoints()) { + if (actual.put(checkpoint.outboxStreamKey(), checkpoint.outboxSequence()) != null) { + throw new IllegalArgumentException("Account source checkpoints must be unique"); + } + } + if (!actual + .keySet() + .equals( + new HashSet<>( + List.of( + issuerStreamKey(), + accountStreamKey(accountUuid), + tenantStreamKey(tenantUuid), + membershipStreamKey(accountUuid, tenantUuid)))) + || !scopeCheckpointMatches(actual.get(issuerStreamKey()), issuer) + || !scopeCheckpointMatches(actual.get(accountStreamKey(accountUuid)), account) + || !scopeCheckpointMatches(actual.get(tenantStreamKey(tenantUuid)), tenant) + || !actual + .get(membershipStreamKey(accountUuid, tenantUuid)) + .equals(membershipSequence(snapshot))) { + throw new IllegalArgumentException( + "Account membership checkpoints differ from their exact source scopes"); + } + + String membershipSequence = membershipSequence(snapshot); + if ("0".equals(membershipSequence) + && (membership.generation() != 1L + || membership.sourceVersion() != 1L + || !"MISSING".equals(snapshot.membershipBaseline().membershipLifecycleState()) + || snapshot.membershipExists() + || snapshot.gameplayAdmissionAllowed())) { + throw new IllegalArgumentException( + "Sequence-zero membership is not the original non-admitting pair baseline"); + } + } + + private static void requireSourceEvents( + UUID accountUuid, + UUID tenantUuid, + RuntimeMembershipSnapshotDto snapshot, + ScopeState issuer, + ScopeState account, + ScopeState tenant, + ScopeState membership) { + Map events = new HashMap<>(); + for (OutboxSourceEvidence source : snapshot.outboxSourceEvidence()) { + if (events.put(source.outboxStreamKey(), source) != null) { + throw new IllegalArgumentException("Account source events must be unique by stream"); + } + } + var expectedPositiveStreams = + snapshot.outboxCheckpoints().stream() + .filter(checkpoint -> !"0".equals(checkpoint.outboxSequence())) + .map(OutboxCheckpointEntry::outboxStreamKey) + .collect(java.util.stream.Collectors.toSet()); + if (!events.keySet().equals(expectedPositiveStreams)) { + throw new IllegalArgumentException( + "Account source events differ from the positive source checkpoint inventory"); + } + requireSourceEventPresence( + issuerStreamKey(), checkpointSequence(snapshot, issuerStreamKey()), events); + requireSourceEventPresence( + accountStreamKey(accountUuid), + checkpointSequence(snapshot, accountStreamKey(accountUuid)), + events); + requireSourceEventPresence( + tenantStreamKey(tenantUuid), + checkpointSequence(snapshot, tenantStreamKey(tenantUuid)), + events); + String membershipStream = membershipStreamKey(accountUuid, tenantUuid); + requireSourceEventPresence( + membershipStream, checkpointSequence(snapshot, membershipStream), events); + + OutboxSourceEvidence issuerEvent = events.get(issuerStreamKey()); + if (issuerEvent != null + && !Long.toString(issuer.sourceVersion()) + .equals( + IssuerGenerationAuthorityEventV1Codec.verify(issuerEvent.canonicalEventJson()) + .sourceVersion())) { + throw new IllegalArgumentException("Issuer source version differs from its exact event"); + } + + OutboxSourceEvidence accountEvent = events.get(accountStreamKey(accountUuid)); + if (accountEvent != null + && !Long.toString(account.sourceVersion()) + .equals(sourceVersionForAccountEvent(accountEvent))) { + throw new IllegalArgumentException("Account source version differs from its exact event"); + } + + OutboxSourceEvidence tenantEvent = events.get(tenantStreamKey(tenantUuid)); + if (tenantEvent != null + && !Long.toString(tenant.sourceVersion()) + .equals( + TenantGenerationAuthorityEventV1Codec.verify(tenantEvent.canonicalEventJson()) + .sourceVersion())) { + throw new IllegalArgumentException("Tenant source version differs from its exact event"); + } + + OutboxSourceEvidence membershipEvent = events.get(membershipStream); + if (membershipEvent != null) { + var event = MembershipAuthorityEventV1Codec.verify(membershipEvent.canonicalEventJson()); + if (!accountUuid.toString().equals(event.accountId()) + || !tenantUuid.toString().equals(event.tenantId()) + || !Long.toString(membership.generation()).equals(event.membershipAuthorityGeneration()) + || snapshot.sourceEvent() == null + || !event.canonicalJson().equals(snapshot.sourceEvent().canonicalJson())) { + throw new IllegalArgumentException( + "Membership source event differs from its exact locked membership scope"); + } + } else if (snapshot.sourceEvent() != null) { + throw new IllegalArgumentException("Membership event is missing from its source evidence"); + } + } + + private static String sourceVersionForAccountEvent(OutboxSourceEvidence source) { + try { + return PasswordResetAuthorityEventV1Codec.verify(source.canonicalEventJson()).sourceVersion(); + } catch (IllegalArgumentException resetSchemaMismatch) { + return AccountLogoutAllAuthorityEventV1Codec.verify(source.canonicalEventJson()) + .sourceVersion(); + } + } + + private static void requireSourceEventPresence( + String streamKey, String sequence, Map events) { + OutboxSourceEvidence event = events.get(streamKey); + if ("0".equals(sequence) != (event == null) + || (event != null && !sequence.equals(event.outboxSequence()))) { + throw new IllegalArgumentException("Account source event differs from its exact checkpoint"); + } + } + + private static void requireRoleSource( + UUID accountUuid, + UUID tenantUuid, + RuntimeMembershipSnapshotDto snapshot, + RoleSnapshot roleSource, + VerifiedTenantProvenance retainedProvenance, + String membershipVersion) { + if (!snapshot.membershipExists()) { + if (roleSource != null || !snapshot.roles().isEmpty()) { + throw new IllegalArgumentException( + "An absent membership cannot contain role source evidence or grants"); + } + return; + } + + boolean canonicalTenantUuidPresent = roleSource != null && roleSource.tenantUuid() != null; + boolean canonicalProvenancePresent = + roleSource != null && roleSource.tenantProvenance() != null; + if (roleSource == null + || retainedProvenance == null + || roleSource.accountUuid() == null + || !accountUuid.equals(roleSource.accountUuid()) + || roleSource.accountId() <= 0L + || !Objects.equals(roleSource.tenantId(), retainedProvenance.legacyTenantId()) + || roleSource.membershipId() <= 0L + || roleSource.snapshotVersion() != Long.parseLong(membershipVersion) + || !roleSource.roles().equals(snapshot.roles()) + || canonicalTenantUuidPresent != canonicalProvenancePresent + || (canonicalTenantUuidPresent + && (!tenantUuid.equals(roleSource.tenantUuid()) + || !retainedProvenance.equals(roleSource.tenantProvenance())))) { + throw new IllegalArgumentException( + "Current membership roles lack the exact existing role header and identity"); + } + } + + private static VerifiedTenantProvenance requireRetainedAssociation( + UUID tenantUuid, ApprovedAssociation association) { + if (association.legacyTenantId() <= 0L + || association.canonicalTenantId() == null + || !tenantUuid.equals(association.canonicalTenantId())) { + throw new IllegalArgumentException( + "Retained tenant association differs from the exact canonical request"); + } + return new VerifiedTenantProvenance( + association.legacyTenantId(), + TenantProvenanceKind.APPROVED_RETAINED, + association.operationId(), + association.manifestDigest()); + } + + private static String membershipSequence(RuntimeMembershipSnapshotDto snapshot) { + UUID accountUuid = requireCanonicalSnapshotUuid(snapshot.accountUuid(), "Account UUID"); + UUID tenantUuid = requireCanonicalSnapshotUuid(snapshot.tenantUuid(), "tenant UUID"); + return checkpointSequence(snapshot, membershipStreamKey(accountUuid, tenantUuid)); + } + + private static UUID requireCanonicalSnapshotUuid(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalidUuid) { + throw new IllegalArgumentException(field + " must be a canonical UUID", invalidUuid); + } + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical lowercase UUID"); + } + return requireCanonicalUuid(parsed, field); + } + + private static String checkpointSequence( + RuntimeMembershipSnapshotDto snapshot, String streamKey) { + return snapshot.outboxCheckpoints().stream() + .filter(checkpoint -> streamKey.equals(checkpoint.outboxStreamKey())) + .map(OutboxCheckpointEntry::outboxSequence) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Membership source checkpoint is missing")); + } + + private static boolean scopeCheckpointMatches(String sequence, ScopeState scope) { + if (sequence == null) { + return false; + } + if (scope.generation() == 1L && scope.sourceVersion() == 1L) { + return "0".equals(sequence); + } + return !"0".equals(sequence); + } + + private static String issuerStreamKey() { + return AUTHORITY_STREAM_PREFIX + "issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER; + } + + private static String accountStreamKey(UUID accountUuid) { + return AUTHORITY_STREAM_PREFIX + "account/" + accountUuid; + } + + private static String tenantStreamKey(UUID tenantUuid) { + return AUTHORITY_STREAM_PREFIX + "tenant/" + tenantUuid; + } + + private static String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { + return AUTHORITY_STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; + } + + private static ScopeState only(List scopes, String label) { + if (scopes.size() != 1) { + throw new IllegalArgumentException("Exactly one captured " + label + " scope is required"); + } + return scopes.getFirst(); + } + + private static UUID requireCanonicalUuid(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must be a non-nil canonical UUID"); + } + return value; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java index 2e032ad8d0..7f0d4a4333 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginExchangeRepository.java @@ -20,10 +20,11 @@ import org.springframework.transaction.annotation.Transactional; /** - * Account-owned first-writer storage and exact readback for bare first-party LOGIN exchange. Claim, - * pending evidence, terminal success, and its exact envelope must share one Account transaction; - * V37.1 permits {@code PENDING} only as an in-transaction intermediate and rejects a still-pending - * exchange at transaction commit. + * Account-owned first-writer storage and exact readback for bare first-party LOGIN exchange. A + * non-authorizing {@code PENDING} claim and its write-once evidence may survive separate Account + * transactions for crash recovery. The transition to terminal success and its exact purpose-bound + * envelope must share one Account transaction. This storage primitive is not the complete pre-sign + * issuance evidence bundle, signer, registry, credential exchange, or activation path. */ @Repository @SuppressFBWarnings( @@ -46,9 +47,10 @@ public AccountBareLoginExchangeRepository(DSLContext dsl) { /** * Claims one source connect-operation identity without replacing a prior writer's request * identity or digest. A source connect operation must already be a committed V35 issuance; a - * pending or absent source is not Account authentication and cannot start an exchange. The caller - * must keep this claim in the same Account transaction as pending evidence and terminal envelope - * completion; committing the claim alone is rejected. + * pending or absent source is not Account authentication and cannot start an exchange. A durable + * {@code PENDING} claim is non-authorizing and may commit alone; an exact retry recovers the + * original operation ID and request digest and may resume its evidence or completion while the + * operation remains pending. */ @Transactional(propagation = Propagation.MANDATORY) public ClaimResult claim(AccountBareLoginExchangeIdentity identity, byte[] requestDigest) { @@ -126,9 +128,9 @@ public Optional find( /** * Adds write-once source/token/authority evidence to a still-pending exchange. It never marks a - * transient or ambiguous result terminal; the claim, this evidence binding, and the later - * terminal call must share one transaction, which must store the exact purpose-bound envelope - * before commit. + * transient or ambiguous result terminal. The pending evidence may commit for crash recovery; + * terminal completion must separately commit the transition and exact purpose-bound envelope + * together. */ @Transactional(propagation = Propagation.MANDATORY) public AccountBareLoginExchangeOperation recordPendingEvidence( @@ -236,8 +238,9 @@ public AccountBareLoginExchangeOperation recordPendingEvidence( /** * Stores one terminal successful result and its authenticated ciphertext in the caller's - * transaction. The claim and any pending evidence must have occurred in this same transaction; - * this repository never creates or decrypts the delegation JWT. + * transaction. The still-pending operation and exact envelope become durable together; the + * original claim and any write-once pending evidence may have committed in earlier transactions. + * This repository never creates or decrypts the delegation JWT. */ @Transactional(propagation = Propagation.MANDATORY) public AccountBareLoginResponseEnvelope completeWithEnvelope( @@ -629,9 +632,11 @@ private static void validateTokenEvidence(String tokenIdentity, byte[] tokenHash private AccountBareLoginExchangeIdentity requireClaimIdentity(ClaimResult claim) { Objects.requireNonNull(claim, "claim"); - if (claim.disposition() != ClaimDisposition.CLAIMED) { + if (claim.disposition() != ClaimDisposition.CLAIMED + && !(claim.disposition() == ClaimDisposition.REPLAYED + && claim.operation().lifecycle() == Lifecycle.PENDING)) { throw new IllegalStateException( - "Only the first bare LOGIN exchange claimant may record evidence or an outcome"); + "Only an exact pending bare LOGIN exchange claim may record evidence or an outcome"); } return claim.identity(); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginTokenIdentityFence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginTokenIdentityFence.java new file mode 100644 index 0000000000..cd59a79c93 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginTokenIdentityFence.java @@ -0,0 +1,189 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * Immutable initial Account source capture for one exact bare-LOGIN private delegation identity. + * + *

The identity fence and its source version describe this new identity's initial durable row; + * both are 1 and are distinct from the captured Account issuance-fence value and source version. + * This capture does not implement later monotonic logout or rotation transitions, registry proof, + * token issuance, or admission authority. Row deletion and truncation remain denied pending + * separate safe-retention proof. + */ +public record AccountBareLoginTokenIdentityFence( + String schemaName, + UUID operationId, + UUID sourceConnectOperationId, + long accountId, + UUID accountUuid, + UUID tenantId, + String connectScopeHash, + String requestId, + int requestDigestVersion, + byte[] requestDigest, + String profile, + String tokenIdentity, + byte[] tokenHash, + long tokenIdentityFence, + long tokenIdentityFenceSourceVersion, + long accountIssuanceFence, + long accountIssuanceFenceSourceVersion, + Instant capturedAt) { + + public static final String SCHEMA_NAME = "account-bare-login-token-identity-fence/v1"; + public static final String PROFILE_NAME = "game-session-account-delegation"; + private static final Pattern SCOPE_HASH = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final int DIGEST_LENGTH_BYTES = 32; + private static final int MAX_TEXT_LENGTH = 128; + + public AccountBareLoginTokenIdentityFence { + if (!SCHEMA_NAME.equals(schemaName) + || isNil(operationId) + || isNil(sourceConnectOperationId) + || accountId <= 0L + || isNil(accountUuid) + || isNil(tenantId) + || connectScopeHash == null + || !SCOPE_HASH.matcher(connectScopeHash).matches() + || !validText(requestId) + || requestDigestVersion != 1 + || !PROFILE_NAME.equals(profile) + || !validText(tokenIdentity) + || tokenIdentityFence != 1L + || tokenIdentityFenceSourceVersion != 1L + || accountIssuanceFence <= 0L + || accountIssuanceFenceSourceVersion <= 0L + || capturedAt == null) { + throw new IllegalArgumentException("Stored bare LOGIN token identity fence is malformed"); + } + requestDigest = requireDigest(requestDigest, "request digest"); + tokenHash = requireDigest(tokenHash, "token hash"); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] tokenHash() { + return tokenHash.clone(); + } + + /** Compares immutable capture contents while excluding the database-assigned capture time. */ + public boolean sameInitialCapture(AccountBareLoginTokenIdentityFence other) { + return other != null + && operationId.equals(other.operationId) + && sourceConnectOperationId.equals(other.sourceConnectOperationId) + && accountId == other.accountId + && accountUuid.equals(other.accountUuid) + && tenantId.equals(other.tenantId) + && connectScopeHash.equals(other.connectScopeHash) + && requestId.equals(other.requestId) + && requestDigestVersion == other.requestDigestVersion + && Arrays.equals(requestDigest, other.requestDigest) + && profile.equals(other.profile) + && tokenIdentity.equals(other.tokenIdentity) + && Arrays.equals(tokenHash, other.tokenHash) + && tokenIdentityFence == other.tokenIdentityFence + && tokenIdentityFenceSourceVersion == other.tokenIdentityFenceSourceVersion + && accountIssuanceFence == other.accountIssuanceFence + && accountIssuanceFenceSourceVersion == other.accountIssuanceFenceSourceVersion; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AccountBareLoginTokenIdentityFence that)) { + return false; + } + return sameInitialCapture(that) + && schemaName.equals(that.schemaName) + && capturedAt.equals(that.capturedAt); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + schemaName, + operationId, + sourceConnectOperationId, + accountId, + accountUuid, + tenantId, + connectScopeHash, + requestId, + requestDigestVersion, + profile, + tokenIdentity, + tokenIdentityFence, + tokenIdentityFenceSourceVersion, + accountIssuanceFence, + accountIssuanceFenceSourceVersion, + capturedAt); + result = 31 * result + Arrays.hashCode(requestDigest); + result = 31 * result + Arrays.hashCode(tokenHash); + return result; + } + + @Override + public String toString() { + return "AccountBareLoginTokenIdentityFence{operationId=" + + operationId + + ", accountUuid=" + + accountUuid + + ", profile='" + + profile + + "', tokenEvidence=, tokenIdentityFence=" + + tokenIdentityFence + + ", tokenIdentityFenceSourceVersion=" + + tokenIdentityFenceSourceVersion + + ", accountIssuanceFence=" + + accountIssuanceFence + + ", accountIssuanceFenceSourceVersion=" + + accountIssuanceFenceSourceVersion + + "}"; + } + + private static boolean validText(String value) { + return value != null + && !value.isBlank() + && value.length() <= MAX_TEXT_LENGTH + && value.indexOf('\0') < 0 + && !hasUnpairedSurrogate(value); + } + + private static boolean hasUnpairedSurrogate(String value) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + return true; + } + index++; + } else if (Character.isLowSurrogate(current)) { + return true; + } + } + return false; + } + + private static boolean isNil(UUID value) { + return value == null || value.equals(new UUID(0L, 0L)); + } + + private static byte[] requireDigest(byte[] value, String label) { + if (value == null || value.length != DIGEST_LENGTH_BYTES) { + throw new IllegalArgumentException(label + " must be 32 bytes"); + } + return value.clone(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginTokenIdentityFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginTokenIdentityFenceRepository.java new file mode 100644 index 0000000000..4c271e0f61 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBareLoginTokenIdentityFenceRepository.java @@ -0,0 +1,544 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import javax.sql.DataSource; +import net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.jdbc.datasource.DataSourceUtils; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account-owned immutable initial token-identity fence capture for the bare first-party LOGIN + * source. It never issues or signs a token, changes authority, touches a registry, or authorizes + * admission. Storage captures only the initial positive identity fence; complete monotonic logout + * and rotation transitions and producer/registry proof remain open. UPDATE, DELETE, and TRUNCATE + * remain denied until a separate safe-retention proof justifies removal. + */ +@Repository +public class AccountBareLoginTokenIdentityFenceRepository { + private static final String CAPTURE_TABLE = "account_bare_login_token_identity_fence_captures"; + private static final String OPERATION_TABLE = "account_bare_login_exchange_operations"; + private static final int REQUEST_DIGEST_VERSION = 1; + private static final long INITIAL_IDENTITY_FENCE = 1L; + private static final long INITIAL_IDENTITY_SOURCE_VERSION = 1L; + private static final int DIGEST_LENGTH_BYTES = 32; + private static final int MAX_TOKEN_IDENTITY_LENGTH = 128; + private static final Pattern TOKEN_HASH_HEX = Pattern.compile("[0-9a-f]{64}"); + + private final DSLContext dsl; + private final DataSource dataSource; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Spring-injected DSLContext and DataSource must retain the same owner transaction.") + public AccountBareLoginTokenIdentityFenceRepository(DSLContext dsl, DataSource dataSource) { + this.dsl = dsl; + this.dataSource = dataSource; + } + + /** + * Captures the exact outgoing private-delegation identity while its owning bare-LOGIN operation + * remains PENDING. The canonical Account row is locked first, followed by that operation and its + * current Account issuance-fence row. An exact retry returns the original immutable capture only + * while every bound value, including current Account issuance-fence evidence, is unchanged. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public AccountBareLoginTokenIdentityFence captureInitial( + AccountBareLoginExchangeIdentity exchangeIdentity, + UUID exchangeOperationId, + UUID accountUuid, + byte[] requestDigest, + String tokenIdentity, + byte[] tokenHash) { + CaptureInput input = + validateInput( + exchangeIdentity, + exchangeOperationId, + accountUuid, + requestDigest, + tokenIdentity, + tokenHash); + requireWritableReadCommittedOwnerTransaction(); + long persistedAccountId = lockAndVerifyCanonicalAccount(input); + lockAndVerifyPendingOperation(input, persistedAccountId); + CurrentAccountFence currentFence = readCurrentAccountIssuanceFence(input.accountUuid(), true); + AccountBareLoginTokenIdentityFence expected = expectedCapture(input, currentFence); + + AccountBareLoginTokenIdentityFence prior = readByOperation(input.exchangeOperationId()); + if (prior != null) { + requireExactCapture(prior, expected); + return prior; + } + AccountBareLoginTokenIdentityFence conflictingIdentity = + readByTokenIdentity(input.tokenHash(), input.tokenIdentity()); + if (conflictingIdentity != null) { + throw new IllegalStateException( + "Bare LOGIN token identity is already captured by another exact operation"); + } + + Record inserted = + dsl.fetchOne( + "INSERT INTO " + + CAPTURE_TABLE + + " (token_hash, schema_name, operation_id, source_connect_operation_id, account_id, " + + "account_uuid, tenant_id, connect_scope_hash, request_id, " + + "request_digest_version, request_digest, token_identity, profile, " + + "token_identity_fence, token_identity_fence_source_version, " + + "account_issuance_fence, account_issuance_fence_source_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT DO NOTHING RETURNING operation_id", + encodeTokenHash(input.tokenHash()), + AccountBareLoginTokenIdentityFence.SCHEMA_NAME, + input.exchangeOperationId(), + input.exchangeIdentity().sourceConnectOperationId(), + input.exchangeIdentity().accountId(), + input.accountUuid(), + input.exchangeIdentity().tenantId(), + input.exchangeIdentity().connectScopeHash(), + input.exchangeIdentity().requestId(), + REQUEST_DIGEST_VERSION, + input.requestDigest(), + input.tokenIdentity(), + AccountBareLoginTokenIdentityFence.PROFILE_NAME, + INITIAL_IDENTITY_FENCE, + INITIAL_IDENTITY_SOURCE_VERSION, + currentFence.issuanceFence(), + currentFence.sourceVersion()); + if (inserted != null + && !input.exchangeOperationId().equals(inserted.get("operation_id", UUID.class))) { + throw new IllegalStateException( + "Bare LOGIN token identity insert returned another operation"); + } + + AccountBareLoginTokenIdentityFence stored = readByOperation(input.exchangeOperationId()); + if (stored == null) { + if (readByTokenIdentity(input.tokenHash(), input.tokenIdentity()) != null) { + throw new IllegalStateException( + "Bare LOGIN token identity conflicts with another immutable capture"); + } + throw new IllegalStateException( + "Bare LOGIN token identity fence capture has no exact durable readback"); + } + requireExactCapture(stored, expected); + CurrentAccountFence readbackFence = readCurrentAccountIssuanceFence(input.accountUuid(), true); + if (!currentFence.equals(readbackFence)) { + throw new IllegalStateException( + "Account issuance-fence evidence changed during bare LOGIN identity capture"); + } + return stored; + } + + /** + * Requires existing exact initial evidence and never creates a row. It applies the same account, + * pending-operation, transaction, and current-fence checks as capture so absent, terminal, or + * stale evidence cannot be mistaken for proof. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public AccountBareLoginTokenIdentityFence requireInitial( + AccountBareLoginExchangeIdentity exchangeIdentity, + UUID exchangeOperationId, + UUID accountUuid, + byte[] requestDigest, + String tokenIdentity, + byte[] tokenHash) { + CaptureInput input = + validateInput( + exchangeIdentity, + exchangeOperationId, + accountUuid, + requestDigest, + tokenIdentity, + tokenHash); + requireWritableReadCommittedOwnerTransaction(); + long persistedAccountId = lockAndVerifyCanonicalAccount(input); + lockAndVerifyPendingOperation(input, persistedAccountId); + CurrentAccountFence currentFence = readCurrentAccountIssuanceFence(input.accountUuid(), true); + AccountBareLoginTokenIdentityFence stored = readByOperation(input.exchangeOperationId()); + if (stored == null) { + throw new IllegalStateException( + "Bare LOGIN token identity fence capture is absent and cannot be inferred"); + } + requireExactCapture(stored, expectedCapture(input, currentFence)); + return stored; + } + + private CaptureInput validateInput( + AccountBareLoginExchangeIdentity exchangeIdentity, + UUID exchangeOperationId, + UUID accountUuid, + byte[] requestDigest, + String tokenIdentity, + byte[] tokenHash) { + Objects.requireNonNull(exchangeIdentity, "exchangeIdentity"); + if (isNil(exchangeOperationId) || isNil(accountUuid)) { + throw new IllegalArgumentException( + "Bare LOGIN operation and canonical Account UUID are required"); + } + byte[] checkedDigest = requireDigest(requestDigest, "request digest"); + byte[] checkedTokenHash = requireDigest(tokenHash, "token hash"); + if (!validTokenIdentity(tokenIdentity)) { + throw new IllegalArgumentException("Bare LOGIN token identity is malformed"); + } + return new CaptureInput( + exchangeIdentity, + exchangeOperationId, + accountUuid, + checkedDigest, + tokenIdentity, + checkedTokenHash); + } + + private long lockAndVerifyCanonicalAccount(CaptureInput input) { + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id " + + "FROM accounts WHERE account_uuid = ? FOR UPDATE", + input.accountUuid()); + if (account == null) { + throw new IllegalStateException("Bare LOGIN canonical Account row is absent"); + } + Long id = account.get("id", Long.class); + Long sourceId = account.get("account_uuid_source_numeric_id", Long.class); + String provenance = account.get("account_uuid_provenance", String.class); + if (id == null + || id <= 0L + || id.longValue() != input.exchangeIdentity().accountId() + || !input.accountUuid().equals(account.get("account_uuid", UUID.class)) + || sourceId == null + || sourceId.longValue() != id + || !validAccountUuidProvenance(provenance)) { + throw new IllegalStateException( + "Bare LOGIN canonical Account UUID provenance does not match its private row"); + } + return id; + } + + private void lockAndVerifyPendingOperation(CaptureInput input, long persistedAccountId) { + Record operation = + dsl.fetchOne( + "SELECT operation_id, source_connect_operation_id, account_id, tenant_id, " + + "connect_scope_hash, request_id, request_digest_version, request_digest, " + + "status, token_identity, token_hash FROM " + + OPERATION_TABLE + + " WHERE operation_id = ? FOR UPDATE", + input.exchangeOperationId()); + if (operation == null + || !input.exchangeOperationId().equals(operation.get("operation_id", UUID.class)) + || !input + .exchangeIdentity() + .sourceConnectOperationId() + .equals(operation.get("source_connect_operation_id", UUID.class)) + || !Objects.equals(operation.get("account_id", Long.class), persistedAccountId) + || !input.exchangeIdentity().tenantId().equals(operation.get("tenant_id", UUID.class)) + || !input + .exchangeIdentity() + .connectScopeHash() + .equals(operation.get("connect_scope_hash", String.class)) + || !input.exchangeIdentity().requestId().equals(operation.get("request_id", String.class)) + || !Integer.valueOf(REQUEST_DIGEST_VERSION) + .equals(operation.get("request_digest_version", Integer.class)) + || !MessageDigest.isEqual(input.requestDigest(), requiredBytes(operation, "request_digest")) + || !"PENDING".equals(operation.get("status", String.class)) + || !input.tokenIdentity().equals(operation.get("token_identity", String.class)) + || !MessageDigest.isEqual(input.tokenHash(), requiredBytes(operation, "token_hash"))) { + throw new IllegalStateException( + "Bare LOGIN token identity does not match its exact pending operation"); + } + } + + private CurrentAccountFence readCurrentAccountIssuanceFence(UUID accountUuid, boolean lock) { + Record fence = + dsl.fetchOne( + "SELECT issuance_fence, source_version FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?" + + (lock ? " FOR UPDATE" : ""), + accountUuid); + if (fence == null) { + throw new IllegalStateException("Current Account issuance fence is absent"); + } + return new CurrentAccountFence( + requiredPositive(fence.get("issuance_fence", Long.class), "Account issuance fence"), + requiredPositive( + fence.get("source_version", Long.class), "Account issuance-fence source version")); + } + + private AccountBareLoginTokenIdentityFence expectedCapture( + CaptureInput input, CurrentAccountFence currentFence) { + return new AccountBareLoginTokenIdentityFence( + AccountBareLoginTokenIdentityFence.SCHEMA_NAME, + input.exchangeOperationId(), + input.exchangeIdentity().sourceConnectOperationId(), + input.exchangeIdentity().accountId(), + input.accountUuid(), + input.exchangeIdentity().tenantId(), + input.exchangeIdentity().connectScopeHash(), + input.exchangeIdentity().requestId(), + REQUEST_DIGEST_VERSION, + input.requestDigest(), + AccountBareLoginTokenIdentityFence.PROFILE_NAME, + input.tokenIdentity(), + input.tokenHash(), + INITIAL_IDENTITY_FENCE, + INITIAL_IDENTITY_SOURCE_VERSION, + currentFence.issuanceFence(), + currentFence.sourceVersion(), + Instant.EPOCH); + } + + private AccountBareLoginTokenIdentityFence readByOperation(UUID operationId) { + Record row = + dsl.fetchOne( + "SELECT token_hash, schema_name, operation_id, source_connect_operation_id, account_id, " + + "account_uuid, tenant_id, connect_scope_hash, request_id, " + + "request_digest_version, request_digest, " + + "token_identity, profile, token_identity_fence, " + + "token_identity_fence_source_version, account_issuance_fence, " + + "account_issuance_fence_source_version, captured_at FROM " + + CAPTURE_TABLE + + " WHERE operation_id = ?", + operationId); + return row == null ? null : decode(row); + } + + private AccountBareLoginTokenIdentityFence readByTokenIdentity( + byte[] tokenHash, String tokenIdentity) { + Record row = + dsl.fetchOne( + "SELECT token_hash, schema_name, operation_id, source_connect_operation_id, account_id, " + + "account_uuid, tenant_id, connect_scope_hash, request_id, " + + "request_digest_version, request_digest, " + + "token_identity, profile, token_identity_fence, " + + "token_identity_fence_source_version, account_issuance_fence, " + + "account_issuance_fence_source_version, captured_at FROM " + + CAPTURE_TABLE + + " WHERE token_hash = ? OR (profile = ? AND token_identity = ?) LIMIT 1", + encodeTokenHash(tokenHash), + AccountBareLoginTokenIdentityFence.PROFILE_NAME, + tokenIdentity); + return row == null ? null : decode(row); + } + + private AccountBareLoginTokenIdentityFence decode(Record row) { + OffsetDateTime capturedAt = row.get("captured_at", OffsetDateTime.class); + if (capturedAt == null) { + throw new IllegalStateException("Stored bare LOGIN identity fence capture time is absent"); + } + return new AccountBareLoginTokenIdentityFence( + row.get("schema_name", String.class), + requiredUuid(row.get("operation_id", UUID.class), "operation ID"), + requiredUuid(row.get("source_connect_operation_id", UUID.class), "source operation ID"), + requiredPositive(row.get("account_id", Long.class), "Account ID"), + requiredUuid(row.get("account_uuid", UUID.class), "Account UUID"), + requiredUuid(row.get("tenant_id", UUID.class), "tenant UUID"), + row.get("connect_scope_hash", String.class), + row.get("request_id", String.class), + requiredVersion(row.get("request_digest_version", Integer.class)), + requiredBytes(row, "request_digest"), + row.get("profile", String.class), + row.get("token_identity", String.class), + decodeTokenHash(row.get("token_hash", String.class)), + requiredPositive(row.get("token_identity_fence", Long.class), "token identity fence"), + requiredPositive( + row.get("token_identity_fence_source_version", Long.class), + "token identity-fence source version"), + requiredPositive(row.get("account_issuance_fence", Long.class), "Account issuance fence"), + requiredPositive( + row.get("account_issuance_fence_source_version", Long.class), + "Account issuance-fence source version"), + JooqPersistenceSupport.toInstant(capturedAt)); + } + + private static void requireExactCapture( + AccountBareLoginTokenIdentityFence stored, AccountBareLoginTokenIdentityFence expected) { + if (!stored.sameInitialCapture(expected)) { + throw new IllegalStateException( + "Stored bare LOGIN token identity capture differs from its current exact evidence"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Bare LOGIN token identity capture requires a writable Account owner transaction"); + } + Connection connection = DataSourceUtils.getConnection(dataSource); + try { + if (!DataSourceUtils.isConnectionTransactional(connection, dataSource) + || connection.getAutoCommit()) { + throw new IllegalStateException( + "Bare LOGIN token identity capture requires the transaction-bound JDBC connection"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Bare LOGIN token identity capture requires READ COMMITTED isolation"); + } + if (connection.isReadOnly() + || !"off".equalsIgnoreCase(readPostgresSetting(connection, "transaction_read_only"))) { + throw new IllegalStateException( + "Bare LOGIN token identity capture requires a writable owner transaction"); + } + if (!"read committed" + .equalsIgnoreCase(readPostgresSetting(connection, "transaction_isolation"))) { + throw new IllegalStateException( + "Bare LOGIN token identity capture requires READ COMMITTED isolation"); + } + } catch (SQLException exception) { + throw new IllegalStateException( + "Bare LOGIN token identity capture could not prove its owner transaction", exception); + } finally { + DataSourceUtils.releaseConnection(connection, dataSource); + } + } + + private static String readPostgresSetting(Connection connection, String setting) + throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery("SHOW " + setting)) { + if (!result.next()) { + throw new IllegalStateException( + "PostgreSQL transaction setting is unavailable: " + setting); + } + String value = result.getString(1); + if (value == null || result.next()) { + throw new IllegalStateException("PostgreSQL transaction setting is malformed: " + setting); + } + return value.trim(); + } + } + + private static boolean validAccountUuidProvenance(String provenance) { + return "ACCOUNT_V29_MIGRATION".equals(provenance) + || "ACCOUNT_REPOSITORY_INSERT".equals(provenance) + || "ACCOUNT_DATABASE_INSERT".equals(provenance); + } + + private static boolean validTokenIdentity(String tokenIdentity) { + return tokenIdentity != null + && !tokenIdentity.isBlank() + && tokenIdentity.length() <= MAX_TOKEN_IDENTITY_LENGTH + && tokenIdentity.indexOf('\0') < 0 + && !hasUnpairedSurrogate(tokenIdentity); + } + + private static boolean hasUnpairedSurrogate(String value) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + return true; + } + index++; + } else if (Character.isLowSurrogate(current)) { + return true; + } + } + return false; + } + + private static boolean isNil(UUID value) { + return value == null || value.equals(new UUID(0L, 0L)); + } + + private static byte[] requireDigest(byte[] value, String label) { + if (value == null || value.length != DIGEST_LENGTH_BYTES) { + throw new IllegalArgumentException(label + " must be 32 bytes"); + } + return value.clone(); + } + + private static byte[] requiredBytes(Record record, String column) { + byte[] value = record.get(column, byte[].class); + if (value == null) { + throw new IllegalStateException("Stored bare LOGIN evidence is missing " + column); + } + return value; + } + + private static String encodeTokenHash(byte[] tokenHash) { + if (tokenHash == null || tokenHash.length != DIGEST_LENGTH_BYTES) { + throw new IllegalArgumentException("Token hash must be 32 bytes"); + } + return HexFormat.of().formatHex(tokenHash); + } + + private static byte[] decodeTokenHash(String tokenHash) { + if (tokenHash == null || !TOKEN_HASH_HEX.matcher(tokenHash).matches()) { + throw new IllegalStateException( + "Stored bare LOGIN token hash is not canonical lowercase SHA-256 hex"); + } + try { + byte[] decoded = HexFormat.of().parseHex(tokenHash); + if (decoded.length != DIGEST_LENGTH_BYTES) { + throw new IllegalStateException("Stored bare LOGIN token hash has the wrong length"); + } + return decoded; + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Stored bare LOGIN token hash is not canonical lowercase SHA-256 hex", exception); + } + } + + private static long requiredPositive(Long value, String label) { + if (value == null || value <= 0L) { + throw new IllegalStateException("Stored " + label + " is not positive"); + } + return value; + } + + private static int requiredVersion(Integer value) { + if (value == null || value != REQUEST_DIGEST_VERSION) { + throw new IllegalStateException("Stored bare LOGIN request digest version is unsupported"); + } + return value; + } + + private static UUID requiredUuid(UUID value, String label) { + if (isNil(value)) { + throw new IllegalStateException("Stored " + label + " is absent or nil"); + } + return value; + } + + private record CaptureInput( + AccountBareLoginExchangeIdentity exchangeIdentity, + UUID exchangeOperationId, + UUID accountUuid, + byte[] requestDigest, + String tokenIdentity, + byte[] tokenHash) { + private CaptureInput { + requestDigest = requestDigest.clone(); + tokenHash = tokenHash.clone(); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] tokenHash() { + return tokenHash.clone(); + } + } + + private record CurrentAccountFence(long issuanceFence, long sourceVersion) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceEvidence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceEvidence.java new file mode 100644 index 0000000000..d728757795 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceEvidence.java @@ -0,0 +1,243 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Immutable proof of the positive Account-local issuance fence for one pending operation. */ +public record AccountConnectIssuanceFenceEvidence( + String schemaName, + UUID operationId, + UUID accountUuid, + UUID tenantUuid, + String connectScopeHash, + String requestId, + byte[] requestDigest, + long issuanceFence, + long fenceSourceVersion, + byte[] digest) { + + public static final String SCHEMA_NAME = "account-connect-issuance-fence/v1"; + private static final Pattern SCOPE_HASH = Pattern.compile("sha256:[0-9a-f]{64}"); + + public AccountConnectIssuanceFenceEvidence { + if (!SCHEMA_NAME.equals(schemaName) + || isNil(operationId) + || isNil(accountUuid) + || isNil(tenantUuid) + || connectScopeHash == null + || !SCOPE_HASH.matcher(connectScopeHash).matches() + || requestId == null + || requestId.isBlank() + || requestId.indexOf('\0') >= 0 + || requestId.length() > 128 + || hasUnpairedSurrogate(requestId) + || issuanceFence <= 0L + || fenceSourceVersion <= 0L) { + throw new IllegalArgumentException("Account issuance-fence capture identity is malformed"); + } + requestDigest = requireDigest(requestDigest, "request digest"); + digest = requireDigest(digest, "capture digest"); + byte[] expected = + calculateDigest( + schemaName, + operationId, + accountUuid, + tenantUuid, + connectScopeHash, + requestId, + requestDigest, + issuanceFence, + fenceSourceVersion); + if (!MessageDigest.isEqual(expected, digest)) { + throw new IllegalArgumentException("Account issuance-fence capture digest does not match"); + } + } + + public static AccountConnectIssuanceFenceEvidence capture( + UUID operationId, + UUID accountUuid, + UUID tenantUuid, + String connectScopeHash, + String requestId, + byte[] requestDigest, + long issuanceFence, + long fenceSourceVersion) { + String schemaName = SCHEMA_NAME; + byte[] checkedRequestDigest = requireDigest(requestDigest, "request digest"); + byte[] digest = + calculateDigest( + schemaName, + operationId, + accountUuid, + tenantUuid, + connectScopeHash, + requestId, + checkedRequestDigest, + issuanceFence, + fenceSourceVersion); + return new AccountConnectIssuanceFenceEvidence( + schemaName, + operationId, + accountUuid, + tenantUuid, + connectScopeHash, + requestId, + checkedRequestDigest, + issuanceFence, + fenceSourceVersion, + digest); + } + + /** Reproduces the fixed-order ADR 0047 UTF-8 byte-length-framed digest preimage. */ + public static byte[] calculateDigest( + String schemaName, + UUID operationId, + UUID accountUuid, + UUID tenantUuid, + String connectScopeHash, + String requestId, + byte[] requestDigest, + long issuanceFence, + long fenceSourceVersion) { + if (!SCHEMA_NAME.equals(schemaName) + || isNil(operationId) + || isNil(accountUuid) + || isNil(tenantUuid) + || connectScopeHash == null + || !SCOPE_HASH.matcher(connectScopeHash).matches() + || requestId == null + || requestId.isBlank() + || requestId.indexOf('\0') >= 0 + || requestId.length() > 128 + || hasUnpairedSurrogate(requestId) + || issuanceFence <= 0L + || fenceSourceVersion <= 0L) { + throw new IllegalArgumentException("Account issuance-fence capture preimage is malformed"); + } + byte[] checkedRequestDigest = requireDigest(requestDigest, "request digest"); + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + appendSegment(preimage, schemaName); + appendSegment(preimage, operationId.toString()); + appendSegment(preimage, accountUuid.toString()); + appendSegment(preimage, tenantUuid.toString()); + appendSegment(preimage, connectScopeHash); + appendSegment(preimage, requestId); + appendSegment(preimage, HexFormat.of().formatHex(checkedRequestDigest)); + appendSegment(preimage, Long.toString(issuanceFence)); + appendSegment(preimage, Long.toString(fenceSourceVersion)); + try { + return MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] digest() { + return digest.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AccountConnectIssuanceFenceEvidence that)) { + return false; + } + return issuanceFence == that.issuanceFence + && fenceSourceVersion == that.fenceSourceVersion + && Objects.equals(schemaName, that.schemaName) + && Objects.equals(operationId, that.operationId) + && Objects.equals(accountUuid, that.accountUuid) + && Objects.equals(tenantUuid, that.tenantUuid) + && Objects.equals(connectScopeHash, that.connectScopeHash) + && Objects.equals(requestId, that.requestId) + && Arrays.equals(requestDigest, that.requestDigest) + && Arrays.equals(digest, that.digest); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + schemaName, + operationId, + accountUuid, + tenantUuid, + connectScopeHash, + requestId, + issuanceFence, + fenceSourceVersion); + result = 31 * result + Arrays.hashCode(requestDigest); + result = 31 * result + Arrays.hashCode(digest); + return result; + } + + private static void appendSegment(ByteArrayOutputStream output, String value) { + byte[] encoded = strictUtf8(value); + output.writeBytes(Integer.toString(encoded.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(encoded); + } + + private static byte[] strictUtf8(String 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( + "Account issuance-fence field is not well-formed UTF-8", exception); + } + } + + private static byte[] requireDigest(byte[] value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.length != 32) { + throw new IllegalArgumentException(fieldName + " must be 32 bytes"); + } + return value.clone(); + } + + private static boolean isNil(UUID value) { + return value == null || value.equals(new UUID(0L, 0L)); + } + + private static boolean hasUnpairedSurrogate(String value) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + return true; + } + index++; + } else if (Character.isLowSurrogate(current)) { + return true; + } + } + return false; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java index 8fc49f0433..559a1d6e81 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectTokenIssuanceRepository.java @@ -10,6 +10,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation.Lifecycle; import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; @@ -102,6 +103,182 @@ public Optional find( return operation; } + /** + * Reads the separately persisted positive Account issuance-fence capture for one exact operation. + * A legacy issuance-fence digest without the complete capture group remains unproved. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readIssuanceFenceCapture( + AccountConnectTokenIssuanceIdentity identity, byte[] requestDigest) { + validateIdentity(identity); + byte[] digest = requireDigest(requestDigest, "request digest"); + Optional operation = readOperation(identity); + if (operation.isEmpty()) { + return Optional.empty(); + } + AccountConnectTokenIssuanceOperation stored = operation.orElseThrow(); + requireDigestMatch(stored, digest); + + Record row = + dsl.fetchOne( + "SELECT issuance_fence_capture_schema, issuance_fence_capture_account_uuid, " + + "issuance_fence_capture_value, issuance_fence_capture_source_version, " + + "issuance_fence_capture_digest FROM " + + OPERATION_TABLE + + " WHERE operation_id = ? AND account_id = ? AND tenant_id = ? " + + "AND connect_scope_hash = ? AND request_id = ? " + + "AND request_digest_version = ? AND request_digest = ?", + stored.operationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest); + if (row == null) { + throw new IllegalStateException("Connect-token issuance capture owner row disappeared"); + } + + String schemaName = row.get("issuance_fence_capture_schema", String.class); + UUID accountUuid = row.get("issuance_fence_capture_account_uuid", UUID.class); + Long value = row.get("issuance_fence_capture_value", Long.class); + Long sourceVersion = row.get("issuance_fence_capture_source_version", Long.class); + byte[] captureDigest = row.get("issuance_fence_capture_digest", byte[].class); + boolean allAbsent = + schemaName == null + && accountUuid == null + && value == null + && sourceVersion == null + && captureDigest == null; + if (allAbsent) { + return Optional.empty(); + } + if (schemaName == null + || accountUuid == null + || value == null + || sourceVersion == null + || captureDigest == null) { + throw new IllegalStateException("Stored Account issuance-fence capture is incomplete"); + } + + AccountConnectIssuanceFenceEvidence evidence = + new AccountConnectIssuanceFenceEvidence( + schemaName, + stored.operationId(), + accountUuid, + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + stored.requestDigest(), + value, + sourceVersion, + captureDigest); + if (stored.issuanceFenceDigest() == null + || !MessageDigest.isEqual(stored.issuanceFenceDigest(), evidence.digest())) { + throw new IllegalStateException( + "Captured Account issuance fence differs from operation fence digest evidence"); + } + requirePersistedAccountIdentity(stored.accountId(), evidence.accountUuid()); + return Optional.of(evidence); + } + + /** + * Binds one positive Account issuance-fence capture to the exact first-writer PENDING claim. + * Existing evidence is read back unchanged; a different preexisting fence digest is a conflict. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountConnectIssuanceFenceEvidence captureIssuanceFence( + ClaimResult claim, byte[] requestDigest, AccountConnectIssuanceFenceEvidence evidence) { + AccountConnectTokenIssuanceIdentity identity = requireClaimIdentity(claim); + byte[] digest = requireDigest(requestDigest, "request digest"); + Objects.requireNonNull(evidence, "Account issuance-fence evidence is required"); + AccountConnectTokenIssuanceOperation operation = requireClaimedOperation(claim, digest); + requireCaptureIdentity(operation, identity, digest, evidence); + if (operation.lifecycle() != Lifecycle.PENDING) { + throw new IllegalStateException( + "Only a pending connect-token operation can capture its issuance fence"); + } + byte[] existingFenceDigest = operation.issuanceFenceDigest(); + if (existingFenceDigest != null + && !MessageDigest.isEqual(existingFenceDigest, evidence.digest())) { + throw new EvidenceMismatchException( + "Connect-token operation already has a different issuance-fence digest"); + } + + Optional existingCapture = + readIssuanceFenceCapture(identity, digest); + if (existingCapture.isPresent()) { + if (!existingCapture.orElseThrow().equals(evidence)) { + throw new EvidenceMismatchException( + "Connect-token issuance fence is already captured with different evidence"); + } + return existingCapture.orElseThrow(); + } + + Record changed = + dsl.fetchOne( + "UPDATE " + + OPERATION_TABLE + + " SET issuance_fence_capture_schema = COALESCE(issuance_fence_capture_schema, ?), " + + "issuance_fence_capture_account_uuid = " + + "COALESCE(issuance_fence_capture_account_uuid, ?), " + + "issuance_fence_capture_value = COALESCE(issuance_fence_capture_value, ?), " + + "issuance_fence_capture_source_version = " + + "COALESCE(issuance_fence_capture_source_version, ?), " + + "issuance_fence_capture_digest = COALESCE(issuance_fence_capture_digest, ?), " + + "issuance_fence_digest = COALESCE(issuance_fence_digest, ?) " + + "WHERE operation_id = ? AND account_id = ? AND tenant_id = ? " + + "AND connect_scope_hash = ? AND request_id = ? " + + "AND request_digest_version = ? AND request_digest = ? AND status = 'PENDING' " + + "AND (issuance_fence_capture_schema IS NULL " + + "OR issuance_fence_capture_schema = ?) " + + "AND (issuance_fence_capture_account_uuid IS NULL " + + "OR issuance_fence_capture_account_uuid = ?) " + + "AND (issuance_fence_capture_value IS NULL " + + "OR issuance_fence_capture_value = ?) " + + "AND (issuance_fence_capture_source_version IS NULL " + + "OR issuance_fence_capture_source_version = ?) " + + "AND (issuance_fence_capture_digest IS NULL " + + "OR issuance_fence_capture_digest = ?) " + + "AND (issuance_fence_digest IS NULL OR issuance_fence_digest = ?) " + + "RETURNING operation_id", + evidence.schemaName(), + evidence.accountUuid(), + evidence.issuanceFence(), + evidence.fenceSourceVersion(), + evidence.digest(), + evidence.digest(), + operation.operationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeHash(), + identity.requestId(), + REQUEST_DIGEST_VERSION, + digest, + evidence.schemaName(), + evidence.accountUuid(), + evidence.issuanceFence(), + evidence.fenceSourceVersion(), + evidence.digest(), + evidence.digest()); + if (changed == null + || !operation.operationId().equals(changed.get("operation_id", UUID.class))) { + throw new EvidenceMismatchException( + "Connect-token issuance capture could not bind to the exact pending operation"); + } + AccountConnectIssuanceFenceEvidence captured = + readIssuanceFenceCapture(identity, digest) + .orElseThrow( + () -> + new IllegalStateException( + "Account issuance-fence capture has no exact durable readback")); + if (!captured.equals(evidence)) { + throw new EvidenceMismatchException( + "Account issuance-fence capture readback differs from its candidate"); + } + return captured; + } + /** * Reads a successful committed source result using only its exact caller identity. The request * digest and all AEAD evidence are recovered from the immutable winning operation row; callers @@ -151,6 +328,15 @@ public Optional readCommittedResponseEnvelope( () -> new IllegalStateException( "Committed connect-token source has no exact response envelope")); + Optional capture = + readIssuanceFenceCapture(identity, operation.requestDigest()); + if (capture.isPresent() + && (!MessageDigest.isEqual(operation.issuanceFenceDigest(), capture.orElseThrow().digest()) + || !MessageDigest.isEqual( + envelope.binding().issuanceFenceDigest(), capture.orElseThrow().digest()))) { + throw new IllegalStateException( + "Committed connect-token envelope differs from its captured Account issuance fence"); + } return Optional.of(new AccountCommittedConnectSource(operation, envelope)); } @@ -798,6 +984,61 @@ private AccountConnectTokenIssuanceIdentity requireClaimIdentity(ClaimResult cla return claim.identity(); } + private void requireCaptureIdentity( + AccountConnectTokenIssuanceOperation operation, + AccountConnectTokenIssuanceIdentity identity, + byte[] requestDigest, + AccountConnectIssuanceFenceEvidence evidence) { + if (!operation.operationId().equals(evidence.operationId()) + || operation.accountId() != identity.accountId() + || !operation.tenantId().equals(identity.tenantId()) + || !operation.connectScopeHash().equals(identity.connectScopeHash()) + || !operation.requestId().equals(identity.requestId()) + || !evidence.tenantUuid().equals(identity.tenantId()) + || !evidence.connectScopeHash().equals(identity.connectScopeHash()) + || !evidence.requestId().equals(identity.requestId()) + || !MessageDigest.isEqual(evidence.requestDigest(), requestDigest)) { + throw new EvidenceMismatchException( + "Account issuance-fence capture differs from its operation identity or request digest"); + } + requirePersistedAccountIdentity(operation.accountId(), evidence.accountUuid()); + } + + private void requirePersistedAccountIdentity(long accountId, UUID expectedAccountUuid) { + if (accountId <= 0L + || expectedAccountUuid == null + || expectedAccountUuid.equals(new UUID(0L, 0L))) { + throw new EvidenceMismatchException( + "Account issuance-fence capture requires a canonical persisted Account identity"); + } + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id " + + "FROM accounts WHERE id = ?", + accountId); + if (account == null) { + throw new EvidenceMismatchException( + "Account issuance-fence operation has no exact persisted Account row"); + } + Long persistedAccountId = account.get("id", Long.class); + UUID persistedAccountUuid = account.get("account_uuid", UUID.class); + String provenanceValue = account.get("account_uuid_provenance", String.class); + Long sourceNumericId = account.get("account_uuid_source_numeric_id", Long.class); + AccountIdentityProvenance provenance = + AccountIdentityProvenance.fromStorageValue(provenanceValue); + if (persistedAccountId == null + || persistedAccountId != accountId + || persistedAccountUuid == null + || persistedAccountUuid.equals(new UUID(0L, 0L)) + || !persistedAccountUuid.equals(expectedAccountUuid) + || sourceNumericId == null + || sourceNumericId.longValue() != persistedAccountId.longValue() + || !provenance.name().equals(provenanceValue)) { + throw new EvidenceMismatchException( + "Account issuance-fence capture differs from exact Account UUID provenance"); + } + } + private AccountConnectTokenIssuanceOperation requireClaimedOperation( ClaimResult claim, byte[] digest) { AccountConnectTokenIssuanceIdentity identity = requireClaimIdentity(claim); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGlobalRoleSourceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGlobalRoleSourceRepository.java new file mode 100644 index 0000000000..7927e04315 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGlobalRoleSourceRepository.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.jdbc.datasource.DataSourceUtils; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Existing-only, owner-fenced readback of the fresh Account explicit-empty global-role source. */ +@Repository +public class AccountGlobalRoleSourceRepository { + private static final UUID NIL_ACCOUNT_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final DataSource dataSource; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring collaborator validation acquires no resources; the repository has no finalizer.") + public AccountGlobalRoleSourceRepository(DSLContext dsl, DataSource dataSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl is required"); + this.dataSource = Objects.requireNonNull(dataSource, "dataSource is required"); + } + + /** + * Locks and reads the exact fresh Account row and its immutable explicit-empty role source. + * Missing source state is never initialized by a read. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public FreshEmptySource readFreshEmptySourceForUpdate(UUID accountUuid) { + requireCanonicalAccountUuid(accountUuid); + requireWritableReadCommittedOwnerTransaction(); + + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_source_numeric_id, " + + "account_uuid_provenance, role FROM accounts " + + "WHERE account_uuid = ? FOR UPDATE", + accountUuid); + if (account == null) { + throw new IllegalStateException("Persisted Account row is missing"); + } + + Long accountRowId = account.get("id", Long.class); + UUID persistedAccountUuid = account.get("account_uuid", UUID.class); + Long accountUuidSourceNumericId = account.get("account_uuid_source_numeric_id", Long.class); + AccountIdentityProvenance provenance = + AccountIdentityProvenance.fromStorageValue( + account.get("account_uuid_provenance", String.class)); + String legacyRole = account.get("role", String.class); + requireFreshAccountIdentity( + accountUuid, + accountRowId, + persistedAccountUuid, + accountUuidSourceNumericId, + provenance, + legacyRole); + + Record source = + dsl.fetchOne( + "SELECT account_uuid, account_uuid_source_numeric_id, account_uuid_provenance, " + + "cardinality(global_roles) AS global_role_count, " + + "global_role_source_version FROM account_global_role_sources " + + "WHERE account_uuid = ? FOR UPDATE", + accountUuid); + if (source == null) { + throw new IllegalStateException("Fresh Account global-role source is missing"); + } + + UUID sourceAccountUuid = source.get("account_uuid", UUID.class); + Long sourceNumericId = source.get("account_uuid_source_numeric_id", Long.class); + AccountIdentityProvenance sourceProvenance = + AccountIdentityProvenance.fromStorageValue( + source.get("account_uuid_provenance", String.class)); + Integer globalRoleCount = source.get("global_role_count", Integer.class); + Long sourceVersion = source.get("global_role_source_version", Long.class); + requireExactSourceReadback( + accountUuid, + accountRowId, + accountUuidSourceNumericId, + provenance, + sourceAccountUuid, + sourceNumericId, + sourceProvenance, + globalRoleCount, + sourceVersion); + + return new FreshEmptySource( + accountUuid, + accountRowId, + accountUuidSourceNumericId, + provenance, + List.of(), + sourceVersion); + } + + private static void requireCanonicalAccountUuid(UUID accountUuid) { + if (accountUuid == null || NIL_ACCOUNT_UUID.equals(accountUuid)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account global-role source readback requires a writable Account owner transaction"); + } + Connection connection = DataSourceUtils.getConnection(dataSource); + try { + if (!DataSourceUtils.isConnectionTransactional(connection, dataSource) + || connection.getAutoCommit()) { + throw new IllegalStateException( + "Account global-role source readback requires the transaction-bound JDBC connection"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Account global-role source readback requires READ COMMITTED isolation"); + } + if (connection.isReadOnly() + || !"off".equalsIgnoreCase(readPostgresSetting(connection, "transaction_read_only"))) { + throw new IllegalStateException( + "Account global-role source readback requires a writable owner transaction"); + } + if (!"read committed" + .equalsIgnoreCase(readPostgresSetting(connection, "transaction_isolation"))) { + throw new IllegalStateException( + "Account global-role source readback requires READ COMMITTED isolation"); + } + } catch (SQLException exception) { + throw new IllegalStateException( + "Account global-role source readback could not prove its owner transaction", exception); + } finally { + DataSourceUtils.releaseConnection(connection, dataSource); + } + } + + private static String readPostgresSetting(Connection connection, String setting) + throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery("SHOW " + setting)) { + if (!result.next()) { + throw new IllegalStateException( + "PostgreSQL transaction setting is unavailable: " + setting); + } + String value = result.getString(1); + if (value == null || result.next()) { + throw new IllegalStateException("PostgreSQL transaction setting is malformed: " + setting); + } + return value.trim(); + } + } + + private static void requireFreshAccountIdentity( + UUID expectedAccountUuid, + Long accountRowId, + UUID persistedAccountUuid, + Long accountUuidSourceNumericId, + AccountIdentityProvenance provenance, + String legacyRole) { + if (accountRowId == null + || accountRowId <= 0L + || !expectedAccountUuid.equals(persistedAccountUuid) + || accountUuidSourceNumericId == null + || !accountRowId.equals(accountUuidSourceNumericId) + || !isFreshInsertProvenance(provenance)) { + throw new IllegalStateException("Fresh canonical Account identity readback is invalid"); + } + if (legacyRole != null) { + throw new IllegalStateException( + "Legacy Account role contradicts the explicit-empty global-role source"); + } + } + + private static void requireExactSourceReadback( + UUID expectedAccountUuid, + Long accountRowId, + Long expectedSourceNumericId, + AccountIdentityProvenance expectedProvenance, + UUID sourceAccountUuid, + Long sourceNumericId, + AccountIdentityProvenance sourceProvenance, + Integer globalRoleCount, + Long sourceVersion) { + if (!expectedAccountUuid.equals(sourceAccountUuid) + || accountRowId == null + || sourceNumericId == null + || !accountRowId.equals(sourceNumericId) + || !Objects.equals(expectedSourceNumericId, sourceNumericId) + || sourceProvenance != expectedProvenance + || !isFreshInsertProvenance(sourceProvenance) + || globalRoleCount == null + || globalRoleCount != 0 + || sourceVersion == null + || sourceVersion != 1L) { + throw new IllegalStateException( + "Fresh Account global-role source readback is missing, malformed, or mismatched"); + } + } + + private static boolean isFreshInsertProvenance(AccountIdentityProvenance provenance) { + return provenance == AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + || provenance == AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT; + } + + /** Exact fresh identity and source revision returned by the owner-fenced read. */ + public record FreshEmptySource( + UUID accountUuid, + long accountRowId, + long accountUuidSourceNumericId, + AccountIdentityProvenance accountUuidProvenance, + List globalRoles, + long globalRoleSourceVersion) { + public FreshEmptySource { + Objects.requireNonNull(accountUuid, "canonical Account UUID is required"); + Objects.requireNonNull(accountUuidProvenance, "Account UUID provenance is required"); + globalRoles = List.copyOf(Objects.requireNonNull(globalRoles, "globalRoles is required")); + if (NIL_ACCOUNT_UUID.equals(accountUuid) + || accountRowId <= 0L + || accountUuidSourceNumericId != accountRowId + || !isFreshInsertProvenance(accountUuidProvenance) + || !globalRoles.isEmpty() + || globalRoleSourceVersion != 1L) { + throw new IllegalArgumentException("Fresh explicit-empty global-role source is invalid"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalog.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalog.java new file mode 100644 index 0000000000..fdeb9b68a2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalog.java @@ -0,0 +1,1304 @@ +package net.firedevops.firemud.accountservice.security; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +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.time.DateTimeException; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** + * Immutable, explicit Account registry-backed token-profile limits and candidate-bound checks. + * + *

This catalog is an unwired issuance prerequisite. It checks the finite profile limits, the + * caller-supplied typed shape evidence against the supported authority-tuple scope fields, exact + * membershipVersion and scopedRoles claim-map structure and scope, exact UTC-second lifetime + * arithmetic, and canonical UTF-8 byte lengths at the pre-sign and post-sign boundaries. It does + * not establish current Account authority, prove role authorization, validate a signature, perform + * registry I/O, or authorize a token. Issuers and lifecycle handlers must continue to prove those + * separate contracts before mutation or exposure. This unwired catalog does not prove runtime + * issuance or activation. + */ +public final class AccountTokenProfileCatalog { + public static final String VERSION = "account-token-profile-catalog/v1"; + + public static final String CONTROL_UI = "control-ui"; + public static final String PLAYER_BOOTSTRAP = "player-bootstrap"; + public static final String GAME_SESSION_ACCOUNT_DELEGATION = "game-session-account-delegation"; + + private static final String CATALOG_INVALID = "Account token profile catalog is invalid"; + private static final String CANDIDATE_INVALID = "Account token profile candidate is invalid"; + private static final String CANDIDATE_OVER_LIMIT = + "Account token profile candidate exceeds configured limits"; + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final Set AUTHORITY_TUPLE_REQUIRED_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set AUTHORITY_TUPLE_ALLOWED_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions", + "accountSecurityCutoff", + "tenantBillingCutoff"); + private static final Set ACCOUNT_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Set TENANT_CUTOFF_FIELDS = + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence"); + private static final Set PRIVATE_REALM_GRANT_FIELDS = + Set.of("tenantId", "worldSlug", "realmSlug", "playtestLifecycleId", "grantVersion"); + // Canonical tenant-role vocabulary from Authentication & Authorization. + private static final Set TENANT_ROLE_VALUES = + Set.of("player", "designer", "tenantAdmin", "moderator"); + private static final List PROFILE_ORDER = + List.of(CONTROL_UI, PLAYER_BOOTSTRAP, GAME_SESSION_ACCOUNT_DELEGATION); + private static final Set REQUIRED_PROFILES = Set.copyOf(PROFILE_ORDER); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final String version; + private final Map profiles; + private final DeploymentCeilings deploymentCeilings; + + /** + * Creates a catalog only from an explicitly supplied version, complete profile map, and + * deployment ceilings that have already passed the owning deployment validator. + * + *

No limits are defaulted or inferred from current token contents, membership counts, + * transport acceptance, or Redis acceptance. + * + * @param version exact supported catalog schema version + * @param profileLimits all three ordinary registry-backed profiles and no other profile + * @param deploymentCeilings already validated transport and Coordination Redis ceilings + * @throws IllegalArgumentException if the catalog is missing, inconsistent, or over deployment + */ + public AccountTokenProfileCatalog( + String version, + Map profileLimits, + DeploymentCeilings deploymentCeilings) { + if (!VERSION.equals(version) + || profileLimits == null + || deploymentCeilings == null + || !REQUIRED_PROFILES.equals(profileLimits.keySet())) { + throw invalidCatalog(); + } + + Map copied = new LinkedHashMap<>(); + for (String profileId : PROFILE_ORDER) { + ProfileLimits limits = profileLimits.get(profileId); + if (limits == null) { + throw invalidCatalog(); + } + validateLimits(profileId, limits, deploymentCeilings); + copied.put(profileId, limits); + } + + this.version = version; + this.profiles = Collections.unmodifiableMap(copied); + this.deploymentCeilings = deploymentCeilings; + } + + public String version() { + return version; + } + + /** Returns the immutable complete profile map supplied to this catalog. */ + public Map profiles() { + return profiles; + } + + public DeploymentCeilings deploymentCeilings() { + return deploymentCeilings; + } + + /** Returns the validated immutable limits for one supported registry-backed profile. */ + public ProfileLimits requireProfile(String profileId) { + ProfileLimits limits = profiles.get(profileId); + if (limits == null) { + throw invalidCatalog(); + } + return limits; + } + + /** + * Validates exact UTC epoch-second representability and checked {@code exp - iat} lifetime. + * + *

The caller must use this check before mutation for issuance, refresh, and lifecycle + * operations that accept token identity. This method does not compare the timestamps with a clock + * or establish token freshness. + * + * @return the positive checked lifetime in seconds + * @throws IllegalArgumentException for impossible timestamps, arithmetic overflow, or an + * over-limit lifetime + */ + public long validateTokenLifetime( + String profileId, long issuedAtEpochSecond, long expiresAtEpochSecond) { + ProfileLimits limits = requireProfile(profileId); + final long lifetime; + try { + lifetime = Math.subtractExact(expiresAtEpochSecond, issuedAtEpochSecond); + Instant.ofEpochSecond(issuedAtEpochSecond); + Instant.ofEpochSecond(expiresAtEpochSecond); + } catch (ArithmeticException | DateTimeException exception) { + throw invalidCandidate(); + } + if (lifetime <= 0 || lifetime > limits.maxTokenLifetimeSeconds()) { + throw invalidCandidate(); + } + return lifetime; + } + + /** + * Applies profile shape, actual membership/role claim structure, cardinality, checked lifetime, + * and canonical tuple byte limits before the one permitted signing operation. + * + *

{@code canonicalAuthorityTupleJson} must be the exact RFC 8785 serialization already + * constructed by the owning Account claim builder. The input is rejected unless it is already + * canonical; this method does not silently replace it with canonical bytes. + * + *

{@code actualClaims} carries the separate {@code membershipVersion} and {@code scopedRoles} + * maps from the same candidate. Their exact presence, tenant keys, positive counters, and role + * values are checked against the typed profile shape. This is structural proof only; current + * Account sources, role authorization, JWT signature, and registry postconditions remain outside + * this unwired API. + */ + public void validatePreSignCandidate( + String profileId, + ProfileShape shape, + ActualClaimMaps actualClaims, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + String canonicalAuthorityTupleJson) { + ProfileLimits limits = requireProfile(profileId); + validateTokenLifetime(profileId, issuedAtEpochSecond, expiresAtEpochSecond); + validateActualClaimPresence(shape, actualClaims); + validateShape(profileId, limits, shape); + validateActualClaimMaps(shape, actualClaims); + + CanonicalJsonObject authorityTuple = + requireCanonicalJsonObject(canonicalAuthorityTupleJson, limits.maxAuthorityTupleBytes()); + validateAuthorityTupleMatchesShape(authorityTuple.object(), shape); + } + + /** + * Applies post-sign complete compact-JWT and canonical registry-record byte ceilings. + * + *

The compact JWT is checked as three non-empty base64url segments and measured as UTF-8 bytes + * after signing. {@code canonicalRegistryRecordJson} must be the exact RFC 8785 serialization of + * the complete state-specific logical record; it must already be canonical. The JWT and record + * contents are never retained, placed in an exception, or included in this catalog's diagnostic + * representation. + * + *

This size check does not verify the token signature, its claims, the registry postcondition, + * or successful activation. + */ + public void validatePostSignCandidate( + String profileId, String compactJwt, String canonicalRegistryRecordJson) { + ProfileLimits limits = requireProfile(profileId); + compactJwtUtf8Length(compactJwt, limits.maxCompactJwtBytes()); + canonicalJsonObjectUtf8Length(canonicalRegistryRecordJson, limits.maxRegistryRecordBytes()); + } + + private static void validateLimits( + String profileId, ProfileLimits limits, DeploymentCeilings deploymentCeilings) { + String expectedAudience = expectedAudience(profileId); + if (expectedAudience == null + || !expectedAudience.equals(limits.audience()) + || limits.maxTokenLifetimeSeconds() <= 0 + || limits.maxTokenLifetimeSeconds() > deploymentCeilings.maxRegistryTokenLifetimeSeconds() + || limits.maxAuthorityTupleBytes() <= 0 + || limits.maxAuthorityTupleBytes() > deploymentCeilings.maxCoordinationAuthorityTupleBytes() + || limits.maxCompactJwtBytes() <= 0 + || limits.maxCompactJwtBytes() > deploymentCeilings.maxTransportCompactJwtBytes() + || limits.maxRegistryRecordBytes() <= 0 + || limits.maxRegistryRecordBytes() > deploymentCeilings.maxCoordinationRegistryRecordBytes() + || limits.maxAuthorityTupleBytes() > limits.maxRegistryRecordBytes()) { + throw invalidCatalog(); + } + + int[] cardinalityCaps = { + limits.maxTenantAuthorityEntries(), + limits.maxMembershipAuthorityEntries(), + limits.maxMembershipVersionEntries(), + limits.maxTenantBillingCutoffEntries(), + limits.maxPrivateRealmGrantEntries() + }; + for (int cap : cardinalityCaps) { + if (cap < 0) { + throw invalidCatalog(); + } + } + + Optional sharedUiCap = limits.maxControlUiTenantScopes(); + switch (profileId) { + case CONTROL_UI -> { + if (sharedUiCap.isEmpty() || sharedUiCap.orElseThrow() <= 0) { + throw invalidCatalog(); + } + int cap = sharedUiCap.orElseThrow(); + if (limits.maxTenantAuthorityEntries() <= 0 + || limits.maxTenantAuthorityEntries() > cap + || limits.maxMembershipAuthorityEntries() <= 0 + || limits.maxMembershipAuthorityEntries() > cap + || limits.maxMembershipVersionEntries() <= 0 + || limits.maxMembershipVersionEntries() > cap + || limits.maxTenantBillingCutoffEntries() <= 0 + || limits.maxTenantBillingCutoffEntries() > cap + || limits.maxPrivateRealmGrantEntries() != 0) { + throw invalidCatalog(); + } + } + case PLAYER_BOOTSTRAP -> { + if (sharedUiCap.isPresent() + || limits.maxTenantAuthorityEntries() != 0 + || limits.maxMembershipAuthorityEntries() != 0 + || limits.maxMembershipVersionEntries() != 0 + || limits.maxTenantBillingCutoffEntries() != 0 + || limits.maxPrivateRealmGrantEntries() != 0) { + throw invalidCatalog(); + } + } + case GAME_SESSION_ACCOUNT_DELEGATION -> { + if (sharedUiCap.isPresent() + || limits.maxTenantAuthorityEntries() != 1 + || limits.maxMembershipAuthorityEntries() != 1 + || limits.maxMembershipVersionEntries() != 1 + || limits.maxTenantBillingCutoffEntries() != 1 + || limits.maxPrivateRealmGrantEntries() != 1) { + throw invalidCatalog(); + } + } + default -> throw invalidCatalog(); + } + } + + private static String expectedAudience(String profileId) { + return switch (profileId) { + case CONTROL_UI -> CONTROL_UI; + case PLAYER_BOOTSTRAP -> PLAYER_BOOTSTRAP; + case GAME_SESSION_ACCOUNT_DELEGATION -> "account-service"; + default -> null; + }; + } + + private static void validateShape(String profileId, ProfileLimits limits, ProfileShape shape) { + if (shape == null) { + throw invalidCandidate(); + } + ClaimFieldPresence claims = shape.claims(); + AuthorityMapShape authority = shape.authority(); + validateCommonClaimPresence(claims, limits); + + if (claims.tenantBillingCutoffPresent() != !authority.tenantBillingCutoffKeys().isEmpty()) { + throw invalidCandidate(); + } + + switch (profileId) { + case CONTROL_UI -> { + if (!(shape instanceof ControlUiShape controlUi)) { + throw invalidCandidate(); + } + validateControlUiShape(limits, controlUi); + } + case PLAYER_BOOTSTRAP -> { + if (!(shape instanceof PlayerBootstrapShape bootstrap)) { + throw invalidCandidate(); + } + validateBootstrapShape(bootstrap); + } + case GAME_SESSION_ACCOUNT_DELEGATION -> { + if (shape instanceof TenantBoundDelegationShape tenantBound) { + validateTenantBoundDelegationShape(limits, tenantBound); + } else if (shape instanceof NonTenantDelegationShape nonTenant) { + validateNonTenantDelegationShape(nonTenant); + } else { + throw invalidCandidate(); + } + } + default -> throw invalidCatalog(); + } + } + + private static void validateCommonClaimPresence(ClaimFieldPresence claims, ProfileLimits limits) { + if (claims == null + || !claims.issuerPresent() + || !claims.subjectPresent() + || !claims.tokenIdPresent() + || !claims.accountIdPresent() + || !limits.audience().equals(claims.audience()) + || !claims.issuedAtPresent() + || !claims.expiresAtPresent() + || !claims.authorityTuplePresent() + || !claims.issuerAuthGenerationPresent() + || !claims.accountAuthorityGenerationPresent() + || !claims.tenantAuthorityGenerationPresent() + || !claims.membershipAuthorityGenerationPresent() + || !claims.membershipVersionPresent() + || !claims.privateRealmGrantVersionsPresent() + || !claims.tokenGenerationPresent() + || !claims.issuanceFencePresent()) { + throw invalidCandidate(); + } + } + + private static void validateActualClaimPresence( + ProfileShape shape, ActualClaimMaps actualClaims) { + if (shape == null || shape.claims() == null || actualClaims == null) { + throw invalidCandidate(); + } + ClaimFieldPresence presence = shape.claims(); + if (presence.membershipVersionPresent() != actualClaims.membershipVersion().isPresent() + || presence.scopedRolesPresent() != actualClaims.scopedRoles().isPresent()) { + throw invalidCandidate(); + } + } + + private static void validateActualClaimMaps(ProfileShape shape, ActualClaimMaps actualClaims) { + Map membershipVersion = + actualClaims.membershipVersion().orElseThrow(AccountTokenProfileCatalog::invalidCandidate); + Set membershipVersionKeys = requirePositiveTenantCounterMap(membershipVersion); + if (!membershipVersionKeys.equals( + canonicalTenantKeys(shape.authority().membershipVersionKeys()))) { + throw invalidCandidate(); + } + + if (actualClaims.scopedRoles().isPresent()) { + Map> scopedRoles = actualClaims.scopedRoles().orElseThrow(); + Set scopedRoleKeys = requireCanonicalScopedRoles(scopedRoles); + if (!scopedRoleKeys.equals(canonicalTenantKeys(shape.scopedRoleKeys()))) { + throw invalidCandidate(); + } + } else if (!shape.scopedRoleKeys().isEmpty()) { + throw invalidCandidate(); + } + } + + private static Set requirePositiveTenantCounterMap(Map values) { + Set keys = new HashSet<>(); + for (Map.Entry entry : values.entrySet()) { + String key = entry.getKey(); + BigInteger value = entry.getValue(); + requireCanonicalTenantKey(key); + if (value == null || value.signum() <= 0) { + throw invalidCandidate(); + } + keys.add(key); + } + return Set.copyOf(keys); + } + + private static Set requireCanonicalScopedRoles(Map> values) { + Set keys = new HashSet<>(); + for (Map.Entry> entry : values.entrySet()) { + String tenantKey = entry.getKey(); + requireCanonicalTenantKey(tenantKey); + List roles = entry.getValue(); + if (roles == null || roles.isEmpty()) { + throw invalidCandidate(); + } + Set seenRoles = new HashSet<>(); + for (String role : roles) { + if (!TENANT_ROLE_VALUES.contains(role) || !seenRoles.add(role)) { + throw invalidCandidate(); + } + } + keys.add(tenantKey); + } + return Set.copyOf(keys); + } + + private static void validateControlUiShape(ProfileLimits limits, ControlUiShape shape) { + AuthorityMapShape authority = shape.authority(); + int sharedLimit = limits.maxControlUiTenantScopes().orElseThrow(); + if (!shape.claims().scopedRolesPresent() + || !shape.scopedTenantKeys().containsAll(shape.scopedRoleKeys()) + || !shape.scopedRoleKeys().containsAll(shape.tenantAuthorityRouteKeys()) + || !shape.scopedTenantKeys().containsAll(shape.requiredCallerMembershipKeys()) + || !shape.scopedTenantKeys().containsAll(shape.billingSafeTenantKeys()) + || !shape.scopedTenantKeys().containsAll(shape.applicableBillingCutoffKeys()) + || !Collections.disjoint(shape.billingSafeTenantKeys(), shape.tenantAuthorityRouteKeys()) + || !shape.requiredCallerMembershipKeys().containsAll(shape.billingSafeTenantKeys()) + || !authority.tenantAuthorityKeys().equals(shape.tenantAuthorityRouteKeys()) + || !authority.membershipAuthorityKeys().equals(shape.requiredCallerMembershipKeys()) + || !authority.membershipVersionKeys().equals(shape.requiredCallerMembershipKeys()) + || !authority.tenantBillingCutoffKeys().equals(shape.applicableBillingCutoffKeys()) + || !authority.privateRealmGrants().isEmpty()) { + throw invalidCandidate(); + } + + requireCount(shape.scopedRoleKeys().size(), sharedLimit); + requireCount(authority.tenantAuthorityKeys().size(), limits.maxTenantAuthorityEntries()); + requireCount(authority.tenantAuthorityKeys().size(), sharedLimit); + requireCount( + authority.membershipAuthorityKeys().size(), limits.maxMembershipAuthorityEntries()); + requireCount(authority.membershipAuthorityKeys().size(), sharedLimit); + requireCount(authority.membershipVersionKeys().size(), limits.maxMembershipVersionEntries()); + requireCount(authority.membershipVersionKeys().size(), sharedLimit); + requireCount( + authority.tenantBillingCutoffKeys().size(), limits.maxTenantBillingCutoffEntries()); + requireCount(authority.tenantBillingCutoffKeys().size(), sharedLimit); + requireCount(authority.privateRealmGrants().size(), limits.maxPrivateRealmGrantEntries()); + } + + private static void validateBootstrapShape(PlayerBootstrapShape shape) { + if (!shape.claims().scopedRolesPresent() + || !shape.scopedRoleKeys().isEmpty() + || !isEmpty(shape.authority())) { + throw invalidCandidate(); + } + } + + private static void validateTenantBoundDelegationShape( + ProfileLimits limits, TenantBoundDelegationShape shape) { + AuthorityMapShape authority = shape.authority(); + UUID tenantId = shape.tenantId(); + Set soleTenant = Set.of(tenantId); + if (!authority.tenantAuthorityKeys().equals(soleTenant) + || !authority.membershipAuthorityKeys().equals(soleTenant) + || !authority.membershipVersionKeys().equals(soleTenant) + || !(authority.tenantBillingCutoffKeys().isEmpty() + || authority.tenantBillingCutoffKeys().equals(soleTenant)) + || !(shape.scopedRoleKeys().isEmpty() || shape.scopedRoleKeys().equals(soleTenant))) { + throw invalidCandidate(); + } + + if (!shape.claims().scopedRolesPresent() && !shape.scopedRoleKeys().isEmpty()) { + throw invalidCandidate(); + } + + if (shape.publicProduction()) { + if (shape.selectedPrivateRealm().isPresent() || !authority.privateRealmGrants().isEmpty()) { + throw invalidCandidate(); + } + } else { + if (shape.selectedPrivateRealm().isEmpty() || authority.privateRealmGrants().size() != 1) { + throw invalidCandidate(); + } + PrivateRealmTarget target = shape.selectedPrivateRealm().orElseThrow(); + PrivateRealmGrantShape grant = authority.privateRealmGrants().getFirst(); + if (grant.grantVersionDecimal().length() > limits.maxAuthorityTupleBytes() + || !grant.tenantId().equals(tenantId) + || !target.tenantId().equals(tenantId) + || !grant.matches(target)) { + throw invalidCandidate(); + } + } + + if (authority.privateRealmGrants().size() > 1) { + throw invalidCandidate(); + } + } + + private static void validateNonTenantDelegationShape(NonTenantDelegationShape shape) { + if (!isEmpty(shape.authority()) || !shape.scopedRoleKeys().isEmpty()) { + throw invalidCandidate(); + } + if (!shape.claims().scopedRolesPresent() && !shape.scopedRoleKeys().isEmpty()) { + throw invalidCandidate(); + } + } + + private static boolean isEmpty(AuthorityMapShape authority) { + return authority.tenantAuthorityKeys().isEmpty() + && authority.membershipAuthorityKeys().isEmpty() + && authority.membershipVersionKeys().isEmpty() + && authority.tenantBillingCutoffKeys().isEmpty() + && authority.privateRealmGrants().isEmpty(); + } + + private static void requireCount(int count, int limit) { + if (count > limit) { + throw overLimitCandidate(); + } + } + + private static long canonicalJsonObjectUtf8Length(String json, long maximumBytes) { + return requireCanonicalJsonObject(json, maximumBytes).utf8Length(); + } + + private static CanonicalJsonObject requireCanonicalJsonObject(String json, long maximumBytes) { + if (json == null || json.isEmpty()) { + throw invalidCandidate(); + } + if (json.length() > maximumBytes) { + throw overLimitCandidate(); + } + byte[] exactUtf8 = strictUtf8(json); + if (exactUtf8.length > maximumBytes) { + throw overLimitCandidate(); + } + + final JsonNode parsed; + try { + parsed = JSON.readTree(json); + } catch (IOException | RuntimeException exception) { + throw invalidCandidate(); + } + if (!(parsed instanceof ObjectNode object)) { + throw invalidCandidate(); + } + requireWellFormedJsonUnicode(object); + + final byte[] canonicalUtf8; + try { + canonicalUtf8 = Rfc8785CanonicalJson.canonicalizeUtf8(json); + } catch (IOException | RuntimeException exception) { + throw invalidCandidate(); + } + if (!Arrays.equals(exactUtf8, canonicalUtf8) + || exactUtf8[0] != (byte) '{' + || exactUtf8[exactUtf8.length - 1] != (byte) '}') { + throw invalidCandidate(); + } + return new CanonicalJsonObject(object, exactUtf8.length); + } + + private static void validateAuthorityTupleMatchesShape(ObjectNode tuple, ProfileShape shape) { + // The typed model contains scope keys and grant versions, but not the source values needed to + // prove that generation/cutoff counters are current. Those values receive schema checks only. + requireExactFields(tuple, AUTHORITY_TUPLE_REQUIRED_FIELDS, AUTHORITY_TUPLE_ALLOWED_FIELDS); + requirePositiveDecimal(tuple.get("issuerAuthGeneration")); + requirePositiveDecimal(tuple.get("accountAuthorityGeneration")); + + AuthorityMapShape authority = shape.authority(); + Set tenantAuthorityKeys = + requirePositiveDecimalMap(tuple.get("tenantAuthorityGeneration")); + Set membershipAuthorityKeys = + requirePositiveDecimalMap(tuple.get("membershipAuthorityGeneration")); + if (!tenantAuthorityKeys.equals(canonicalTenantKeys(authority.tenantAuthorityKeys())) + || !membershipAuthorityKeys.equals( + canonicalTenantKeys(authority.membershipAuthorityKeys()))) { + throw invalidCandidate(); + } + + JsonNode billingCutoff = tuple.get("tenantBillingCutoff"); + if (tuple.has("tenantBillingCutoff") != shape.claims().tenantBillingCutoffPresent()) { + throw invalidCandidate(); + } + if (tuple.has("tenantBillingCutoff")) { + Set billingKeys = requireTenantBillingCutoff(billingCutoff); + if (!billingKeys.equals(canonicalTenantKeys(authority.tenantBillingCutoffKeys()))) { + throw invalidCandidate(); + } + } + + JsonNode accountCutoff = tuple.get("accountSecurityCutoff"); + if (tuple.has("accountSecurityCutoff") != shape.claims().accountSecurityCutoffPresent()) { + throw invalidCandidate(); + } + if (tuple.has("accountSecurityCutoff")) { + requireAccountSecurityCutoff(accountCutoff); + } + + requirePrivateRealmGrants( + tuple.get("privateRealmGrantVersions"), authority.privateRealmGrants()); + } + + private static Set requirePositiveDecimalMap(JsonNode value) { + if (!(value instanceof ObjectNode map)) { + throw invalidCandidate(); + } + Set keys = new HashSet<>(); + Iterator> entries = map.fields(); + while (entries.hasNext()) { + Map.Entry entry = entries.next(); + requireCanonicalTenantKey(entry.getKey()); + requirePositiveDecimal(entry.getValue()); + keys.add(entry.getKey()); + } + return Set.copyOf(keys); + } + + private static Set requireTenantBillingCutoff(JsonNode value) { + if (!(value instanceof ObjectNode cutoffs) || cutoffs.isEmpty()) { + throw invalidCandidate(); + } + Set keys = new HashSet<>(); + Iterator> entries = cutoffs.fields(); + while (entries.hasNext()) { + Map.Entry entry = entries.next(); + String tenantKey = entry.getKey(); + requireCanonicalTenantKey(tenantKey); + if (!(entry.getValue() instanceof ObjectNode cutoff)) { + throw invalidCandidate(); + } + requireExactFields(cutoff, TENANT_CUTOFF_FIELDS, TENANT_CUTOFF_FIELDS); + requirePositiveDecimal(cutoff.get("tenantAuthorityGeneration")); + requirePositiveDecimal(cutoff.get("tenantBillingSequence")); + requirePositiveDecimal(cutoff.get("outboxSequence")); + requireNonEmptyText(cutoff.get("outboxStreamKey")); + keys.add(tenantKey); + } + return Set.copyOf(keys); + } + + private static void requireAccountSecurityCutoff(JsonNode value) { + if (!(value instanceof ObjectNode cutoff)) { + throw invalidCandidate(); + } + requireExactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, ACCOUNT_CUTOFF_FIELDS); + requirePositiveDecimal(cutoff.get("accountAuthorityGeneration")); + requirePositiveDecimal(cutoff.get("outboxSequence")); + requireNonEmptyText(cutoff.get("outboxStreamKey")); + } + + private static void requirePrivateRealmGrants( + JsonNode value, List expected) { + if (value == null || !value.isArray() || value.size() != expected.size()) { + throw invalidCandidate(); + } + for (int index = 0; index < expected.size(); index++) { + JsonNode entry = value.get(index); + if (!(entry instanceof ObjectNode grant)) { + throw invalidCandidate(); + } + requireExactFields(grant, PRIVATE_REALM_GRANT_FIELDS, PRIVATE_REALM_GRANT_FIELDS); + PrivateRealmGrantShape expectedGrant = expected.get(index); + String tenantId = requireText(grant.get("tenantId")); + String worldSlug = requireNonEmptyText(grant.get("worldSlug")); + String realmSlug = requireNonEmptyText(grant.get("realmSlug")); + String lifecycleId = requireText(grant.get("playtestLifecycleId")); + String grantVersion = requirePositiveDecimal(grant.get("grantVersion")); + if (!expectedGrant.tenantId().toString().equals(tenantId) + || !expectedGrant.worldSlug().equals(worldSlug) + || !expectedGrant.realmSlug().equals(realmSlug) + || !expectedGrant.playtestLifecycleId().toString().equals(lifecycleId) + || !expectedGrant.grantVersionDecimal().equals(grantVersion)) { + throw invalidCandidate(); + } + } + } + + private static void requireExactFields( + ObjectNode object, Set required, Set allowed) { + Set actual = new HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.containsAll(required) || !allowed.containsAll(actual)) { + throw invalidCandidate(); + } + } + + private static String requirePositiveDecimal(JsonNode value) { + String text = requireText(value); + if (text.isEmpty() || text.charAt(0) < '1' || text.charAt(0) > '9') { + throw invalidCandidate(); + } + for (int index = 1; index < text.length(); index++) { + char character = text.charAt(index); + if (character < '0' || character > '9') { + throw invalidCandidate(); + } + } + return text; + } + + private static String requireNonEmptyText(JsonNode value) { + String text = requireText(value); + if (text.isBlank()) { + throw invalidCandidate(); + } + return text; + } + + private static String requireText(JsonNode value) { + if (value == null || !value.isTextual()) { + throw invalidCandidate(); + } + return value.textValue(); + } + + private static void requireCanonicalTenantKey(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw invalidCandidate(); + } + } catch (IllegalArgumentException exception) { + throw invalidCandidate(); + } + } + + private static Set canonicalTenantKeys(Set tenantIds) { + Set keys = new HashSet<>(); + tenantIds.forEach(tenantId -> keys.add(tenantId.toString())); + return Set.copyOf(keys); + } + + private static Map immutableMembershipVersion( + Map values) { + if (values == null || values.entrySet().stream().anyMatch(entry -> entry.getKey() == null)) { + throw invalidCandidate(); + } + return Collections.unmodifiableMap(new LinkedHashMap<>(values)); + } + + private static Map> immutableScopedRoles(Map> values) { + if (values == null) { + throw invalidCandidate(); + } + Map> copied = new LinkedHashMap<>(); + for (Map.Entry> entry : values.entrySet()) { + if (entry.getKey() == null + || entry.getValue() == null + || entry.getValue().stream().anyMatch(Objects::isNull)) { + throw invalidCandidate(); + } + copied.put(entry.getKey(), List.copyOf(entry.getValue())); + } + return Collections.unmodifiableMap(copied); + } + + private static void requireWellFormedJsonUnicode(JsonNode node) { + if (node.isTextual()) { + requireWellFormedUtf16(node.textValue()); + } else if (node.isObject()) { + Iterator> fields = node.fields(); + while (fields.hasNext()) { + Map.Entry field = fields.next(); + requireWellFormedUtf16(field.getKey()); + requireWellFormedJsonUnicode(field.getValue()); + } + } else if (node.isArray()) { + for (JsonNode element : node) { + requireWellFormedJsonUnicode(element); + } + } + } + + private static byte[] strictUtf8(String 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 invalidCandidate(); + } + } + + private static void requireWellFormedUtf16(String value) { + for (int index = 0; index < value.length(); index++) { + char character = value.charAt(index); + if (Character.isHighSurrogate(character)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalidCandidate(); + } + index++; + } else if (Character.isLowSurrogate(character)) { + throw invalidCandidate(); + } + } + } + + private static int compactJwtUtf8Length(String compactJwt, long maximumBytes) { + if (compactJwt == null || compactJwt.isEmpty()) { + throw invalidCandidate(); + } + if (compactJwt.length() > maximumBytes) { + throw overLimitCandidate(); + } + int firstDot = compactJwt.indexOf('.'); + int secondDot = firstDot < 0 ? -1 : compactJwt.indexOf('.', firstDot + 1); + if (firstDot <= 0 + || secondDot <= firstDot + 1 + || secondDot == compactJwt.length() - 1 + || compactJwt.indexOf('.', secondDot + 1) >= 0) { + throw invalidCandidate(); + } + for (int index = 0; index < compactJwt.length(); index++) { + char character = compactJwt.charAt(index); + if (character == '.') { + continue; + } + if (!isBase64UrlCharacter(character)) { + throw invalidCandidate(); + } + } + requireCanonicalBase64UrlSegment(compactJwt.substring(0, firstDot)); + requireCanonicalBase64UrlSegment(compactJwt.substring(firstDot + 1, secondDot)); + requireCanonicalBase64UrlSegment(compactJwt.substring(secondDot + 1)); + int utf8Length = compactJwt.getBytes(StandardCharsets.UTF_8).length; + if (utf8Length > maximumBytes) { + throw overLimitCandidate(); + } + return utf8Length; + } + + private static void requireCanonicalBase64UrlSegment(String segment) { + try { + String canonical = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(Base64.getUrlDecoder().decode(segment)); + if (!canonical.equals(segment)) { + throw invalidCandidate(); + } + } catch (IllegalArgumentException exception) { + throw invalidCandidate(); + } + } + + private static boolean isBase64UrlCharacter(char character) { + return (character >= 'A' && character <= 'Z') + || (character >= 'a' && character <= 'z') + || (character >= '0' && character <= '9') + || character == '-' + || character == '_'; + } + + private record CanonicalJsonObject(ObjectNode object, long utf8Length) {} + + private static Set immutableTenantKeys(Set keys) { + if (keys == null || keys.stream().anyMatch(key -> key == null || NIL_UUID.equals(key))) { + throw invalidCandidate(); + } + return Set.copyOf(keys); + } + + private static List immutableGrants(List grants) { + if (grants == null || grants.stream().anyMatch(Objects::isNull)) { + throw invalidCandidate(); + } + return List.copyOf(grants); + } + + private static IllegalArgumentException invalidCatalog() { + return new IllegalArgumentException(CATALOG_INVALID); + } + + private static IllegalArgumentException invalidCandidate() { + return new IllegalArgumentException(CANDIDATE_INVALID); + } + + private static IllegalArgumentException overLimitCandidate() { + return new IllegalArgumentException(CANDIDATE_OVER_LIMIT); + } + + @Override + public String toString() { + return "AccountTokenProfileCatalog[version=" + + version + + ", profiles=" + + profiles.keySet() + + "]"; + } + + /** The one required limit set for one exact ordinary registry-backed profile. */ + public record ProfileLimits( + String audience, + long maxTokenLifetimeSeconds, + int maxTenantAuthorityEntries, + int maxMembershipAuthorityEntries, + int maxMembershipVersionEntries, + int maxTenantBillingCutoffEntries, + int maxPrivateRealmGrantEntries, + long maxAuthorityTupleBytes, + long maxCompactJwtBytes, + long maxRegistryRecordBytes, + Optional maxControlUiTenantScopes) { + public ProfileLimits { + if (audience == null || maxControlUiTenantScopes == null) { + throw invalidCatalog(); + } + } + } + + /** Caller-supplied deployment ceilings already validated by transport and Redis owners. */ + public record DeploymentCeilings( + long maxTransportCompactJwtBytes, + long maxCoordinationAuthorityTupleBytes, + long maxCoordinationRegistryRecordBytes, + long maxRegistryTokenLifetimeSeconds) { + public DeploymentCeilings { + if (maxTransportCompactJwtBytes <= 0 + || maxCoordinationAuthorityTupleBytes <= 0 + || maxCoordinationRegistryRecordBytes <= 0 + || maxRegistryTokenLifetimeSeconds <= 0) { + throw invalidCatalog(); + } + } + } + + /** Typed evidence that required and optional claim fields have the canonical presence shape. */ + public record ClaimFieldPresence( + boolean issuerPresent, + boolean subjectPresent, + boolean tokenIdPresent, + boolean accountIdPresent, + String audience, + boolean issuedAtPresent, + boolean expiresAtPresent, + boolean authorityTuplePresent, + boolean issuerAuthGenerationPresent, + boolean accountAuthorityGenerationPresent, + boolean tenantAuthorityGenerationPresent, + boolean membershipAuthorityGenerationPresent, + boolean membershipVersionPresent, + boolean privateRealmGrantVersionsPresent, + boolean tokenGenerationPresent, + boolean issuanceFencePresent, + boolean scopedRolesPresent, + boolean tenantBillingCutoffPresent, + boolean accountSecurityCutoffPresent) { + public ClaimFieldPresence { + if (audience == null) { + throw invalidCandidate(); + } + } + } + + /** + * Actual separate JWT map claims, preserving omission and arbitrary-precision counters. + * + *

The optionals preserve claim absence separately from an empty object. Maps and nested role + * lists are copied defensively. + */ + public record ActualClaimMaps( + Optional> membershipVersion, + Optional>> scopedRoles) { + public ActualClaimMaps { + if (membershipVersion == null || scopedRoles == null) { + throw invalidCandidate(); + } + membershipVersion = + membershipVersion.map(AccountTokenProfileCatalog::immutableMembershipVersion); + scopedRoles = scopedRoles.map(AccountTokenProfileCatalog::immutableScopedRoles); + } + + @Override + public String toString() { + return "ActualClaimMaps[membershipVersionEntries=" + + membershipVersion.map(Map::size).orElse(0) + + ", scopedRoleTenants=" + + scopedRoles.map(Map::size).orElse(0) + + "]"; + } + } + + /** Exact map/list keys and grant identities represented in the canonical authority tuple. */ + public record AuthorityMapShape( + Set tenantAuthorityKeys, + Set membershipAuthorityKeys, + Set membershipVersionKeys, + Set tenantBillingCutoffKeys, + List privateRealmGrants) { + public AuthorityMapShape { + tenantAuthorityKeys = immutableTenantKeys(tenantAuthorityKeys); + membershipAuthorityKeys = immutableTenantKeys(membershipAuthorityKeys); + membershipVersionKeys = immutableTenantKeys(membershipVersionKeys); + tenantBillingCutoffKeys = immutableTenantKeys(tenantBillingCutoffKeys); + privateRealmGrants = immutableGrants(privateRealmGrants); + } + + @Override + public Set tenantAuthorityKeys() { + return Set.copyOf(this.tenantAuthorityKeys); + } + + @Override + public Set membershipAuthorityKeys() { + return Set.copyOf(this.membershipAuthorityKeys); + } + + @Override + public Set membershipVersionKeys() { + return Set.copyOf(this.membershipVersionKeys); + } + + @Override + public Set tenantBillingCutoffKeys() { + return Set.copyOf(this.tenantBillingCutoffKeys); + } + + @Override + public List privateRealmGrants() { + return List.copyOf(this.privateRealmGrants); + } + + @Override + public String toString() { + return "AuthorityMapShape[tenantAuthority=" + + tenantAuthorityKeys.size() + + ", membershipAuthority=" + + membershipAuthorityKeys.size() + + ", membershipVersion=" + + membershipVersionKeys.size() + + ", tenantBillingCutoff=" + + tenantBillingCutoffKeys.size() + + ", privateRealmGrants=" + + privateRealmGrants.size() + + "]"; + } + } + + /** Caller-supplied route-derived key sets for independent control-UI authority maps. */ + public record ControlUiShape( + ClaimFieldPresence claims, + AuthorityMapShape authority, + Set scopedTenantKeys, + Set scopedRoleKeys, + Set tenantAuthorityRouteKeys, + Set requiredCallerMembershipKeys, + Set billingSafeTenantKeys, + Set applicableBillingCutoffKeys) + implements ProfileShape { + public ControlUiShape { + if (claims == null || authority == null) { + throw invalidCandidate(); + } + scopedTenantKeys = immutableTenantKeys(scopedTenantKeys); + scopedRoleKeys = immutableTenantKeys(scopedRoleKeys); + tenantAuthorityRouteKeys = immutableTenantKeys(tenantAuthorityRouteKeys); + requiredCallerMembershipKeys = immutableTenantKeys(requiredCallerMembershipKeys); + billingSafeTenantKeys = immutableTenantKeys(billingSafeTenantKeys); + applicableBillingCutoffKeys = immutableTenantKeys(applicableBillingCutoffKeys); + } + + @Override + public Set scopedTenantKeys() { + return Set.copyOf(this.scopedTenantKeys); + } + + @Override + public Set scopedRoleKeys() { + return Set.copyOf(this.scopedRoleKeys); + } + + @Override + public Set tenantAuthorityRouteKeys() { + return Set.copyOf(this.tenantAuthorityRouteKeys); + } + + @Override + public Set requiredCallerMembershipKeys() { + return Set.copyOf(this.requiredCallerMembershipKeys); + } + + @Override + public Set billingSafeTenantKeys() { + return Set.copyOf(this.billingSafeTenantKeys); + } + + @Override + public Set applicableBillingCutoffKeys() { + return Set.copyOf(this.applicableBillingCutoffKeys); + } + + @Override + public String toString() { + return "ControlUiShape[scopedTenants=" + + scopedTenantKeys.size() + + ", scopedRoles=" + + scopedRoleKeys.size() + + ", membershipScopes=" + + requiredCallerMembershipKeys.size() + + "]"; + } + } + + /** The base pre-tenant profile, whose scope maps and lists must be present and empty. */ + public record PlayerBootstrapShape( + ClaimFieldPresence claims, AuthorityMapShape authority, Set scopedRoleKeys) + implements ProfileShape { + public PlayerBootstrapShape { + if (claims == null || authority == null) { + throw invalidCandidate(); + } + scopedRoleKeys = immutableTenantKeys(scopedRoleKeys); + } + + @Override + public Set scopedRoleKeys() { + return Set.copyOf(this.scopedRoleKeys); + } + + @Override + public String toString() { + return "PlayerBootstrapShape[scope=empty]"; + } + } + + /** One tenant-bound receiver delegation and its selected public or non-public target. */ + public record TenantBoundDelegationShape( + ClaimFieldPresence claims, + AuthorityMapShape authority, + UUID tenantId, + Set scopedRoleKeys, + boolean publicProduction, + Optional selectedPrivateRealm) + implements ProfileShape { + public TenantBoundDelegationShape { + if (claims == null + || authority == null + || tenantId == null + || NIL_UUID.equals(tenantId) + || selectedPrivateRealm == null) { + throw invalidCandidate(); + } + scopedRoleKeys = immutableTenantKeys(scopedRoleKeys); + } + + @Override + public Set scopedRoleKeys() { + return Set.copyOf(this.scopedRoleKeys); + } + + @Override + public String toString() { + return "TenantBoundDelegationShape[tenant-bound=true, publicProduction=" + + publicProduction + + ", scopeEntries=" + + authority.tenantAuthorityKeys().size() + + ", grants=" + + authority.privateRealmGrants().size() + + "]"; + } + } + + /** Explicitly non-tenant private delegation; all tenant and grant collections are empty. */ + public record NonTenantDelegationShape( + ClaimFieldPresence claims, AuthorityMapShape authority, Set scopedRoleKeys) + implements ProfileShape { + public NonTenantDelegationShape { + if (claims == null || authority == null) { + throw invalidCandidate(); + } + scopedRoleKeys = immutableTenantKeys(scopedRoleKeys); + } + + @Override + public Set scopedRoleKeys() { + return Set.copyOf(this.scopedRoleKeys); + } + + @Override + public String toString() { + return "NonTenantDelegationShape[scope=empty]"; + } + } + + /** Exact selected non-public realm identity required by a lifecycle-bound private grant. */ + public record PrivateRealmTarget( + UUID tenantId, String worldSlug, String realmSlug, UUID playtestLifecycleId) { + public PrivateRealmTarget { + if (tenantId == null + || NIL_UUID.equals(tenantId) + || worldSlug == null + || worldSlug.isBlank() + || realmSlug == null + || realmSlug.isBlank() + || playtestLifecycleId == null + || NIL_UUID.equals(playtestLifecycleId)) { + throw invalidCandidate(); + } + } + + @Override + public String toString() { + return "PrivateRealmTarget[identity=redacted]"; + } + } + + /** + * Typed identity evidence for the exact five-field non-public grant entry. The grant version is a + * canonical positive decimal string so the shape check never rounds a large counter. This is not + * an ordinary JWT encoder or a replacement for the owning authority codec. + */ + public record PrivateRealmGrantShape( + UUID tenantId, + String worldSlug, + String realmSlug, + UUID playtestLifecycleId, + String grantVersionDecimal) { + public PrivateRealmGrantShape { + if (tenantId == null + || NIL_UUID.equals(tenantId) + || worldSlug == null + || worldSlug.isBlank() + || realmSlug == null + || realmSlug.isBlank() + || playtestLifecycleId == null + || NIL_UUID.equals(playtestLifecycleId) + || !isCanonicalPositiveDecimal(grantVersionDecimal)) { + throw invalidCandidate(); + } + } + + private boolean matches(PrivateRealmTarget target) { + return tenantId.equals(target.tenantId()) + && worldSlug.equals(target.worldSlug()) + && realmSlug.equals(target.realmSlug()) + && playtestLifecycleId.equals(target.playtestLifecycleId()); + } + + private static boolean isCanonicalPositiveDecimal(String value) { + if (value == null || value.isEmpty() || value.charAt(0) < '1' || value.charAt(0) > '9') { + return false; + } + for (int index = 1; index < value.length(); index++) { + char digit = value.charAt(index); + if (digit < '0' || digit > '9') { + return false; + } + } + return true; + } + + @Override + public String toString() { + return "PrivateRealmGrantShape[identity=redacted, grantVersion=redacted]"; + } + } + + /** Profile-specific typed pre-sign shape evidence. */ + public sealed interface ProfileShape + permits ControlUiShape, + PlayerBootstrapShape, + TenantBoundDelegationShape, + NonTenantDelegationShape { + ClaimFieldPresence claims(); + + AuthorityMapShape authority(); + + Set scopedRoleKeys(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBareLoginCurrentAuthorityReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBareLoginCurrentAuthorityReader.java new file mode 100644 index 0000000000..3d0d09dd55 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBareLoginCurrentAuthorityReader.java @@ -0,0 +1,582 @@ +package net.firedevops.firemud.accountservice.service; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountConnectIssuanceFenceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader.OriginalSourceEvidence; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Unwired, non-authorizing composition of a current gameplay-connect source and Account authority + * readbacks. This candidate does not issue or recover credentials, establish registry or + * postcondition state, or admit gameplay. + */ +public final class AccountBareLoginCurrentAuthorityReader { + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + + private final AccountCommittedConnectSourceReader committedSourceReader; + private final AccountConnectTokenAuthorityCaptureService captureService; + private final AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; + + public AccountBareLoginCurrentAuthorityReader( + AccountCommittedConnectSourceReader committedSourceReader, + AccountConnectTokenAuthorityCaptureService captureService, + AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer, + AccountAuthorityGenerationRepository authorityGenerationRepository) { + this.committedSourceReader = + Objects.requireNonNull(committedSourceReader, "committedSourceReader"); + this.captureService = Objects.requireNonNull(captureService, "captureService"); + this.membershipAuthorityEventProducer = + Objects.requireNonNull( + membershipAuthorityEventProducer, "membershipAuthorityEventProducer"); + this.authorityGenerationRepository = + Objects.requireNonNull(authorityGenerationRepository, "authorityGenerationRepository"); + } + + /** + * Composes current-only Account evidence under the caller's existing writable Account + * transaction. The strict source read runs first so peer, signature, context, and deadline + * failures precede retained-capture and current-membership reads. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CurrentAuthorityReadback read( + AccountConnectTokenIssuanceIdentity identity, + byte[] exactOriginalRequestDigest, + String signedCurrentGatewayContext) { + Objects.requireNonNull(identity, "identity"); + + // This reader checks the exact peer before parsing the signed context or touching repositories. + OriginalSourceEvidence original = + committedSourceReader.read(identity, signedCurrentGatewayContext); + byte[] requestDigest = requireDigest(exactOriginalRequestDigest); + UUID accountUuid = requireSourceBinding(identity, original); + + AccountConnectIssuanceFenceEvidence capture = + captureService + .read(identity, requestDigest) + .orElseThrow( + () -> + new IllegalStateException( + "Exact Account issuance-fence capture is not proved")); + requireCaptureBinding(identity, requestDigest, accountUuid, original, capture); + + RuntimeMembershipSnapshotDto membershipSnapshot = + membershipAuthorityEventProducer.readExistingRuntimeMembershipSnapshot( + accountUuid, identity.tenantId()); + requireExactActiveMembership(membershipSnapshot, accountUuid, identity.tenantId()); + + ScopeState accountAuthority = + authorityGenerationRepository.read(AuthorityScope.account(accountUuid)); + IssuanceFence currentFence = requireCurrentAccountState(accountAuthority, accountUuid); + requireCurrentSnapshotMatchesSource( + original.originalSourceClaims(), membershipSnapshot, accountAuthority, currentFence); + requireCaptureMatchesCurrentFence(capture, currentFence, membershipSnapshot.issuanceFence()); + + // Authority reads may wait on Account's owner fence. Re-run the strict current source read so + // neither the original JWT nor Gateway context can expire while those reads are in progress. + OriginalSourceEvidence finalSource = + committedSourceReader.read(identity, signedCurrentGatewayContext); + requireUnchangedSource(original, finalSource); + + return CurrentAuthorityReadback.from( + identity, original, capture, membershipSnapshot, currentFence); + } + + private static UUID requireSourceBinding( + AccountConnectTokenIssuanceIdentity identity, OriginalSourceEvidence source) { + Objects.requireNonNull(source, "verified original source evidence is required"); + if (source.operationId() == null || source.operationId().equals(new UUID(0L, 0L))) { + throw invalidEvidence(); + } + Map claims = source.originalSourceClaims(); + String accountText = requireClaimText(claims, "accountId"); + UUID accountUuid = parseCanonicalUuid(accountText); + if (!identity.tenantId().toString().equals(requireClaimText(claims, "tenantId")) + || !identity.requestId().equals(requireClaimText(claims, "requestId")) + || !identity.connectScopeId().equals(requireClaimText(claims, "connectScopeId"))) { + throw invalidEvidence(); + } + Map context = source.gatewayContextClaims(); + if (!identity.tenantId().toString().equals(requireClaimText(context, "tenantId")) + || !accountUuid.toString().equals(requireClaimText(context, "accountId")) + || !identity.requestId().equals(requireClaimText(context, "connectRequestId")) + || !identity.connectScopeId().equals(requireClaimText(context, "connectScopeId"))) { + throw invalidEvidence(); + } + requireSha256(source.sourceTokenHash()); + requireNonBlank(source.responseEnvelopeKeyId()); + requireNonBlank(source.gatewayKeyId()); + return accountUuid; + } + + private static void requireCaptureBinding( + AccountConnectTokenIssuanceIdentity identity, + byte[] requestDigest, + UUID accountUuid, + OriginalSourceEvidence source, + AccountConnectIssuanceFenceEvidence capture) { + if (!AccountConnectIssuanceFenceEvidence.SCHEMA_NAME.equals(capture.schemaName()) + || !source.operationId().equals(capture.operationId()) + || !accountUuid.equals(capture.accountUuid()) + || !identity.tenantId().equals(capture.tenantUuid()) + || !AccountJoinDigest.tokenHash(identity.connectScopeId()) + .equals(capture.connectScopeHash()) + || !identity.requestId().equals(capture.requestId()) + || !MessageDigest.isEqual(requestDigest, capture.requestDigest()) + || capture.issuanceFence() <= 0L + || capture.fenceSourceVersion() <= 0L + || capture.digest().length != 32) { + throw invalidEvidence(); + } + } + + private static void requireExactActiveMembership( + RuntimeMembershipSnapshotDto snapshot, UUID accountUuid, UUID tenantUuid) { + if (snapshot == null + || !accountUuid.toString().equals(snapshot.requestAccountUuid()) + || !accountUuid.toString().equals(snapshot.accountUuid()) + || !tenantUuid.toString().equals(snapshot.requestTenantUuid()) + || !tenantUuid.toString().equals(snapshot.tenantUuid()) + || !snapshot.membershipExists() + || !snapshot.gameplayAdmissionAllowed() + || snapshot.membershipBaseline() == null + || !"ACTIVE".equals(snapshot.membershipBaseline().membershipLifecycleState()) + || snapshot.roles() == null + || !snapshot.roles().contains("player") + || snapshot.authorityTuple() == null + || snapshot.outboxCheckpoints() == null + || snapshot.outboxSourceEvidence() == null + || snapshot.evaluatedAt() == null) { + throw new IllegalStateException( + "Current selected-target Account membership is not exact and ACTIVE"); + } + } + + private static IssuanceFence requireCurrentAccountState(ScopeState state, UUID accountUuid) { + if (state == null + || !AuthorityScope.account(accountUuid).equals(state.scope()) + || state.generation() <= 0L + || state.sourceVersion() <= 0L) { + throw invalidEvidence(); + } + IssuanceFence fence = state.issuanceFence(); + if (fence == null + || !accountUuid.equals(fence.accountId()) + || fence.value() <= 0L + || fence.sourceVersion() <= 0L) { + throw invalidEvidence(); + } + return fence; + } + + private static void requireCurrentSnapshotMatchesSource( + Map sourceClaims, + RuntimeMembershipSnapshotDto snapshot, + ScopeState accountAuthority, + IssuanceFence currentFence) { + UUID accountUuid = parseCanonicalUuid(snapshot.accountUuid()); + UUID tenantUuid = parseCanonicalUuid(snapshot.tenantUuid()); + Map sourceTuple = requireObject(sourceClaims.get("authorityTuple")); + Map projectedCurrentTuple = + projectCurrentTuple(snapshot.authorityTuple(), tenantUuid); + if (!projectedCurrentTuple.equals(sourceTuple) + || !BigInteger.valueOf(accountAuthority.generation()) + .equals(positiveInteger(sourceTuple.get("accountAuthorityGeneration"))) + || !Map.of( + tenantUuid.toString(), + decimalInteger( + snapshot.membershipBaseline().membershipVersion().get(tenantUuid.toString()))) + .equals(projectMembershipVersion(sourceClaims.get("membershipVersion"), tenantUuid)) + || !BigInteger.valueOf(currentFence.value()) + .equals(decimalInteger(snapshot.issuanceFence()))) { + throw new IllegalStateException( + "Committed gameplay-connect source differs from current Account authority"); + } + + Map membershipVersions = snapshot.membershipBaseline().membershipVersion(); + Map membershipGenerations = + snapshot.authorityTuple().membershipAuthorityGeneration(); + if (!membershipVersions.keySet().equals(Set.of(tenantUuid.toString())) + || !membershipGenerations.keySet().equals(Set.of(tenantUuid.toString())) + || !decimalInteger(snapshot.membershipBaseline().membershipAuthorityGeneration()) + .equals(decimalInteger(membershipGenerations.get(tenantUuid.toString()))) + || !accountUuid.equals(currentFence.accountId())) { + throw invalidEvidence(); + } + } + + private static Map projectCurrentTuple(AuthorityTuple tuple, UUID tenantUuid) { + Objects.requireNonNull(tuple, "current authority tuple is required"); + requireExactTenantKeys( + tuple.tenantAuthorityGeneration(), tenantUuid, "tenant authority generation"); + requireExactTenantKeys( + tuple.membershipAuthorityGeneration(), tenantUuid, "membership authority generation"); + + Map projected = new LinkedHashMap<>(); + projected.put("issuerAuthGeneration", decimalInteger(tuple.issuerAuthGeneration())); + projected.put("accountAuthorityGeneration", decimalInteger(tuple.accountAuthorityGeneration())); + projected.put( + "tenantAuthorityGeneration", + projectDecimalMap(tuple.tenantAuthorityGeneration(), "tenant authority generation")); + projected.put( + "membershipAuthorityGeneration", + projectDecimalMap( + tuple.membershipAuthorityGeneration(), "membership authority generation")); + + List> grants = new ArrayList<>(); + tuple + .privateRealmGrantVersions() + .forEach( + grant -> { + if (grant == null || !tenantUuid.toString().equals(grant.tenantId())) { + throw invalidEvidence(); + } + Map projectedGrant = new LinkedHashMap<>(); + projectedGrant.put("tenantId", grant.tenantId()); + projectedGrant.put("worldSlug", requireNonBlank(grant.worldSlug())); + projectedGrant.put("realmSlug", requireNonBlank(grant.realmSlug())); + projectedGrant.put( + "playtestLifecycleId", requireNonBlank(grant.playtestLifecycleId())); + projectedGrant.put("grantVersion", decimalInteger(grant.grantVersion())); + grants.add(Map.copyOf(projectedGrant)); + }); + projected.put("privateRealmGrantVersions", List.copyOf(grants)); + + tuple + .accountSecurityCutoff() + .ifPresent(cutoff -> projected.put("accountSecurityCutoff", projectAccountCutoff(cutoff))); + tuple + .tenantBillingCutoff() + .ifPresent( + cutoffs -> { + requireExactTenantKeys(cutoffs, tenantUuid, "tenant billing cutoff"); + Map projectedCutoffs = new LinkedHashMap<>(); + cutoffs.forEach( + (tenantId, cutoff) -> + projectedCutoffs.put(tenantId, projectTenantCutoff(cutoff))); + projected.put("tenantBillingCutoff", Map.copyOf(projectedCutoffs)); + }); + return Map.copyOf(projected); + } + + private static Map projectAccountCutoff(AccountSecurityCutoff cutoff) { + Objects.requireNonNull(cutoff, "current Account security cutoff is required"); + return Map.of( + "accountAuthorityGeneration", decimalInteger(cutoff.accountAuthorityGeneration()), + "outboxStreamKey", requireNonBlank(cutoff.outboxStreamKey()), + "outboxSequence", decimalInteger(cutoff.outboxSequence())); + } + + private static Map projectTenantCutoff(TenantBillingCutoff cutoff) { + Objects.requireNonNull(cutoff, "current tenant billing cutoff is required"); + return Map.of( + "tenantAuthorityGeneration", decimalInteger(cutoff.tenantAuthorityGeneration()), + "tenantBillingSequence", decimalInteger(cutoff.tenantBillingSequence()), + "outboxStreamKey", requireNonBlank(cutoff.outboxStreamKey()), + "outboxSequence", decimalInteger(cutoff.outboxSequence())); + } + + private static Map projectDecimalMap(Map values, String field) { + Map projected = new LinkedHashMap<>(); + values.forEach((key, value) -> projected.put(key, decimalInteger(value))); + if (projected.isEmpty()) { + throw new IllegalStateException("Current " + field + " is incomplete"); + } + return Map.copyOf(projected); + } + + private static Map projectMembershipVersion( + Object supplied, UUID tenantUuid) { + Map versionMap = requireObject(supplied); + if (!versionMap.keySet().equals(Set.of(tenantUuid.toString()))) { + throw invalidEvidence(); + } + Object version = versionMap.get(tenantUuid.toString()); + if (!(version instanceof String decimalVersion)) { + throw invalidEvidence(); + } + return Map.of(tenantUuid.toString(), decimalInteger(decimalVersion)); + } + + private static void requireCaptureMatchesCurrentFence( + AccountConnectIssuanceFenceEvidence capture, + IssuanceFence currentFence, + String membershipSnapshotFence) { + if (capture.issuanceFence() != currentFence.value() + || capture.fenceSourceVersion() != currentFence.sourceVersion() + || !Long.toString(currentFence.value()).equals(membershipSnapshotFence)) { + throw new IllegalStateException( + "Captured Account issuance fence differs from current fenced authority"); + } + } + + private static void requireUnchangedSource( + OriginalSourceEvidence original, OriginalSourceEvidence current) { + if (current == null + || !original.operationId().equals(current.operationId()) + || !original.responseEnvelopeKeyId().equals(current.responseEnvelopeKeyId()) + || !original.gatewayKeyId().equals(current.gatewayKeyId()) + || !MessageDigest.isEqual(original.sourceTokenHash(), current.sourceTokenHash()) + || !original.originalSourceClaims().equals(current.originalSourceClaims()) + || !original.gatewayContextClaims().equals(current.gatewayContextClaims())) { + throw new IllegalStateException( + "Committed gameplay-connect source changed during current authority readback"); + } + } + + private static Map requireObject(Object value) { + if (!(value instanceof Map raw)) { + throw invalidEvidence(); + } + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : raw.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw invalidEvidence(); + } + result.put(key, entry.getValue()); + } + return result; + } + + private static String requireClaimText(Map claims, String name) { + Object value = claims.get(name); + if (!(value instanceof String text) || text.isBlank()) { + throw invalidEvidence(); + } + return text; + } + + private static BigInteger positiveInteger(Object value) { + if (!(value instanceof BigInteger integer) || integer.signum() <= 0) { + throw invalidEvidence(); + } + return integer; + } + + private static BigInteger decimalInteger(String value) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw invalidEvidence(); + } + return new BigInteger(value); + } + + private static void requireExactTenantKeys( + Map values, UUID tenantUuid, String description) { + if (values == null || !values.keySet().equals(Set.of(tenantUuid.toString()))) { + throw new IllegalStateException("Current " + description + " does not match selected tenant"); + } + } + + private static byte[] requireDigest(byte[] supplied) { + if (supplied == null || supplied.length != 32) { + throw new IllegalArgumentException("Exact original request digest must be 32 bytes"); + } + return supplied.clone(); + } + + private static byte[] requireSha256(byte[] value) { + if (value == null || value.length != 32) { + throw invalidEvidence(); + } + return value; + } + + private static UUID parseCanonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (parsed.equals(new UUID(0L, 0L)) || !parsed.toString().equals(value)) { + throw invalidEvidence(); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw invalidEvidence(); + } + } + + private static String requireNonBlank(String value) { + if (value == null || value.isBlank()) { + throw invalidEvidence(); + } + return value; + } + + private static IllegalStateException invalidEvidence() { + return new IllegalStateException( + "Current Account authority evidence is malformed or mismatched"); + } + + /** Redacted, immutable values sufficient to inspect this source/current-authority comparison. */ + public record CurrentAuthorityReadback( + UUID operationId, + UUID accountUuid, + UUID tenantUuid, + String requestId, + String connectScopeHash, + String responseEnvelopeKeyId, + String gatewayKeyId, + byte[] sourceTokenHash, + AuthorityTuple authorityTuple, + Map membershipVersion, + String membershipLifecycleState, + List roles, + Instant evaluatedAt, + long issuanceFence, + long fenceSourceVersion, + byte[] requestDigest, + byte[] captureDigest, + List checkpoints, + List sourceEvents) { + public CurrentAuthorityReadback { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(accountUuid, "accountUuid"); + Objects.requireNonNull(tenantUuid, "tenantUuid"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(connectScopeHash, "connectScopeHash"); + Objects.requireNonNull(responseEnvelopeKeyId, "responseEnvelopeKeyId"); + Objects.requireNonNull(gatewayKeyId, "gatewayKeyId"); + sourceTokenHash = requireReadbackDigest(sourceTokenHash, "source token hash"); + Objects.requireNonNull(authorityTuple, "authorityTuple"); + membershipVersion = Map.copyOf(membershipVersion); + Objects.requireNonNull(membershipLifecycleState, "membershipLifecycleState"); + roles = List.copyOf(roles); + Objects.requireNonNull(evaluatedAt, "evaluatedAt"); + if (issuanceFence <= 0L || fenceSourceVersion <= 0L) { + throw new IllegalArgumentException("Account issuance fence must be positive"); + } + requestDigest = requireReadbackDigest(requestDigest, "request digest"); + captureDigest = requireReadbackDigest(captureDigest, "capture digest"); + checkpoints = List.copyOf(checkpoints); + sourceEvents = List.copyOf(sourceEvents); + } + + @Override + public byte[] sourceTokenHash() { + return sourceTokenHash.clone(); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] captureDigest() { + return captureDigest.clone(); + } + + @Override + public String toString() { + return "CurrentAuthorityReadback[operationId=" + + operationId + + ", accountUuid=" + + accountUuid + + ", tenantUuid=" + + tenantUuid + + ", authorityTuple=" + + authorityTuple + + ", membershipVersion=" + + membershipVersion + + ", issuanceFence=" + + issuanceFence + + ", fenceSourceVersion=" + + fenceSourceVersion + + ", checkpointCount=" + + checkpoints.size() + + ", sourceEvents=" + + sourceEvents.size() + + ", source=]"; + } + + private static CurrentAuthorityReadback from( + AccountConnectTokenIssuanceIdentity identity, + OriginalSourceEvidence source, + AccountConnectIssuanceFenceEvidence capture, + RuntimeMembershipSnapshotDto snapshot, + IssuanceFence fence) { + List checkpoints = + snapshot.outboxCheckpoints().stream() + .map( + checkpoint -> + new CheckpointReadback( + checkpoint.outboxStreamKey(), checkpoint.outboxSequence())) + .toList(); + List sourceEvents = + snapshot.outboxSourceEvidence().stream() + .map( + evidence -> + new SourceEventReadback( + evidence.outboxStreamKey(), + evidence.outboxSequence(), + evidence.eventId(), + evidence.eventDigest())) + .toList(); + return new CurrentAuthorityReadback( + source.operationId(), + parseCanonicalUuid(source.originalSourceClaims().get("accountId").toString()), + identity.tenantId(), + identity.requestId(), + AccountJoinDigest.tokenHash(identity.connectScopeId()), + source.responseEnvelopeKeyId(), + source.gatewayKeyId(), + source.sourceTokenHash(), + snapshot.authorityTuple(), + snapshot.membershipBaseline().membershipVersion(), + snapshot.membershipBaseline().membershipLifecycleState(), + snapshot.roles(), + snapshot.evaluatedAt(), + fence.value(), + fence.sourceVersion(), + capture.requestDigest(), + capture.digest(), + checkpoints, + sourceEvents); + } + + private static byte[] requireReadbackDigest(byte[] value, String field) { + if (value == null || value.length != 32) { + throw new IllegalArgumentException(field + " must be 32 bytes"); + } + return value.clone(); + } + } + + /** Checkpoint identity only; canonical source-event payloads are deliberately omitted. */ + public record CheckpointReadback(String outboxStreamKey, String outboxSequence) { + public CheckpointReadback { + Objects.requireNonNull(outboxStreamKey, "outboxStreamKey"); + Objects.requireNonNull(outboxSequence, "outboxSequence"); + } + } + + /** Event identity and digest only; the source event's canonical JSON is deliberately omitted. */ + public record SourceEventReadback( + String outboxStreamKey, String outboxSequence, String eventId, String eventDigest) { + public SourceEventReadback { + Objects.requireNonNull(outboxStreamKey, "outboxStreamKey"); + Objects.requireNonNull(outboxSequence, "outboxSequence"); + Objects.requireNonNull(eventId, "eventId"); + Objects.requireNonNull(eventDigest, "eventDigest"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountConnectTokenAuthorityCaptureService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountConnectTokenAuthorityCaptureService.java new file mode 100644 index 0000000000..b3935d088f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountConnectTokenAuthorityCaptureService.java @@ -0,0 +1,254 @@ +package net.firedevops.firemud.accountservice.service; + +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountConnectIssuanceFenceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository.ClaimDisposition; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository.ClaimResult; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import org.springframework.jdbc.datasource.DataSourceUtils; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired preparation of the Account-owned authority fence for one gameplay-connect issuance. The + * Account fence is distinct from Gateway's replayAdmissionFence. This source capture creates no + * token, membership, terminal operation, or runtime authorization. + */ +public final class AccountConnectTokenAuthorityCaptureService { + private final AccountConnectTokenIssuanceRepository issuanceRepository; + private final AccountRepository accountRepository; + private final AccountJoinOperationRepository joinOperationRepository; + private final AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; + private final DataSource dataSource; + + public AccountConnectTokenAuthorityCaptureService( + AccountConnectTokenIssuanceRepository issuanceRepository, + AccountRepository accountRepository, + AccountJoinOperationRepository joinOperationRepository, + AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer, + AccountAuthorityGenerationRepository authorityGenerationRepository, + DataSource dataSource) { + this.issuanceRepository = Objects.requireNonNull(issuanceRepository, "issuanceRepository"); + this.accountRepository = Objects.requireNonNull(accountRepository, "accountRepository"); + this.joinOperationRepository = + Objects.requireNonNull(joinOperationRepository, "joinOperationRepository"); + this.membershipAuthorityEventProducer = + Objects.requireNonNull( + membershipAuthorityEventProducer, "membershipAuthorityEventProducer"); + this.authorityGenerationRepository = + Objects.requireNonNull(authorityGenerationRepository, "authorityGenerationRepository"); + this.dataSource = Objects.requireNonNull(dataSource, "dataSource"); + } + + /** + * Captures the current positive Account fence for an exact PENDING first-writer claim. The + * selected gameplay-connect issuance path requires the exact existing ACTIVE membership snapshot; + * generic credential LOGIN, explicit JOIN, and admission claims do not call this gate. An exact + * replay returns the original durable capture without replacing it. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public AccountConnectIssuanceFenceEvidence capture(ClaimResult claim, byte[] requestDigest) { + Objects.requireNonNull(claim, "claim"); + byte[] checkedRequestDigest = requireRequestDigest(requestDigest); + requireWritableReadCommittedOwnerTransaction(); + + AccountConnectTokenIssuanceIdentity identity = claim.identity(); + Optional priorCapture = + issuanceRepository.readIssuanceFenceCapture(identity, checkedRequestDigest); + if (priorCapture.isPresent()) { + AccountConnectIssuanceFenceEvidence captured = priorCapture.orElseThrow(); + if (!captured.operationId().equals(claim.operation().operationId())) { + throw new IllegalStateException( + "Connect-token replay capture belongs to another operation"); + } + return captured; + } + if (claim.disposition() != ClaimDisposition.CLAIMED) { + throw new IllegalStateException( + "Connect-token replay has no proved original Account issuance-fence capture"); + } + if (claim.operation().lifecycle() != AccountConnectTokenIssuanceOperation.Lifecycle.PENDING) { + throw new IllegalStateException( + "Only a pending connect-token operation can capture its Account issuance fence"); + } + if (!MessageDigest.isEqual(claim.operation().requestDigest(), checkedRequestDigest)) { + throw new AccountConnectTokenIssuanceRepository.IdempotencyConflictException( + "Connect-token request digest differs from its first-writer claim"); + } + + long accountId = identity.accountId(); + joinOperationRepository.lockAccount(accountId); + Account account = + accountRepository + .findById(accountId) + .orElseThrow(() -> new IllegalStateException("Connect-token Account row is absent")); + UUID accountUuid = requirePersistedAccountIdentity(account, accountId); + + RuntimeMembershipSnapshotDto membershipSnapshot = + membershipAuthorityEventProducer.readExistingRuntimeMembershipSnapshot( + accountUuid, identity.tenantId()); + requireExactActiveMembership(membershipSnapshot, accountUuid, identity.tenantId()); + long snapshotFence = + parsePositiveCanonicalDecimal( + membershipSnapshot.issuanceFence(), "snapshot issuance fence"); + + ScopeState accountAuthority = + authorityGenerationRepository.read(AuthorityScope.account(accountUuid)); + IssuanceFence durableFence = accountAuthority.issuanceFence(); + if (durableFence == null + || !accountUuid.equals(durableFence.accountId()) + || durableFence.value() != snapshotFence) { + throw new IllegalStateException( + "Account issuance fence differs from the exact runtime membership snapshot"); + } + + AccountConnectIssuanceFenceEvidence candidate = + AccountConnectIssuanceFenceEvidence.capture( + claim.operation().operationId(), + accountUuid, + identity.tenantId(), + AccountJoinDigest.tokenHash(identity.connectScopeId()), + identity.requestId(), + checkedRequestDigest, + durableFence.value(), + durableFence.sourceVersion()); + return issuanceRepository.captureIssuanceFence(claim, checkedRequestDigest, candidate); + } + + /** + * Reads back only a complete positive capture bound to this exact operation and request digest. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public Optional read( + AccountConnectTokenIssuanceIdentity identity, byte[] requestDigest) { + Objects.requireNonNull(identity, "identity"); + byte[] checkedRequestDigest = requireRequestDigest(requestDigest); + requireWritableReadCommittedOwnerTransaction(); + return issuanceRepository.readIssuanceFenceCapture(identity, checkedRequestDigest); + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account issuance-fence capture requires an active owner transaction"); + } + Connection connection = DataSourceUtils.getConnection(dataSource); + try { + if (!DataSourceUtils.isConnectionTransactional(connection, dataSource) + || connection.getAutoCommit()) { + throw new IllegalStateException( + "Account issuance-fence capture requires the transaction-bound JDBC connection"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Account issuance-fence capture requires READ COMMITTED isolation"); + } + if (connection.isReadOnly() + || !"off".equalsIgnoreCase(readPostgresSetting(connection, "transaction_read_only"))) { + throw new IllegalStateException( + "Account issuance-fence capture requires a writable owner transaction"); + } + if (!"read committed" + .equalsIgnoreCase(readPostgresSetting(connection, "transaction_isolation"))) { + throw new IllegalStateException( + "Account issuance-fence capture requires READ COMMITTED isolation"); + } + } catch (SQLException exception) { + throw new IllegalStateException( + "Account issuance-fence capture could not prove its owner transaction", exception); + } finally { + DataSourceUtils.releaseConnection(connection, dataSource); + } + } + + private static String readPostgresSetting(Connection connection, String setting) + throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery("SHOW " + setting)) { + if (!result.next()) { + throw new IllegalStateException( + "PostgreSQL transaction setting is unavailable: " + setting); + } + String value = result.getString(1); + if (value == null || result.next()) { + throw new IllegalStateException("PostgreSQL transaction setting is malformed: " + setting); + } + return value.trim(); + } + } + + private static UUID requirePersistedAccountIdentity(Account account, long accountId) { + if (account.getId() == null + || account.getId() != accountId + || account.getAccountUuid() == null + || account.getAccountUuid().equals(new UUID(0L, 0L)) + || account.getAccountUuidProvenance() == null + || account.getAccountUuidSourceNumericId() == null + || account.getAccountUuidSourceNumericId() != accountId) { + throw new IllegalStateException( + "Account canonical UUID does not match its exact private row identity"); + } + return account.getAccountUuid(); + } + + private static void requireExactActiveMembership( + RuntimeMembershipSnapshotDto snapshot, UUID accountUuid, UUID tenantUuid) { + if (!accountUuid.toString().equals(snapshot.requestAccountUuid()) + || !accountUuid.toString().equals(snapshot.accountUuid()) + || !tenantUuid.toString().equals(snapshot.requestTenantUuid()) + || !tenantUuid.toString().equals(snapshot.tenantUuid()) + || !snapshot.membershipExists() + || !snapshot.gameplayAdmissionAllowed() + || !"ACTIVE".equals(snapshot.membershipBaseline().membershipLifecycleState()) + || !snapshot.roles().contains("player")) { + throw new IllegalStateException( + "Gameplay-connect issuance requires the exact existing ACTIVE Account membership"); + } + } + + private static long parsePositiveCanonicalDecimal(String value, String fieldName) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalStateException(fieldName + " is not a positive canonical decimal"); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalStateException(fieldName + " is outside its positive integer range"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalStateException( + fieldName + " is outside its positive integer range", exception); + } + } + + private static byte[] requireRequestDigest(byte[] requestDigest) { + Objects.requireNonNull(requestDigest, "requestDigest"); + if (requestDigest.length != 32) { + throw new IllegalArgumentException("Connect-token request digest must be 32 bytes"); + } + return requestDigest.clone(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountFreshCaptureSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountFreshCaptureSourceReader.java new file mode 100644 index 0000000000..c57465cbb0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountFreshCaptureSourceReader.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountFreshCaptureSources; +import net.firedevops.firemud.accountservice.dto.AccountMembershipCaptureSources; +import net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourceRepository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired composition of existing fresh Account role-birth and membership source evidence. + * + *

The caller owns one writable READ_COMMITTED Account transaction. The membership producer + * obtains the Account and composite/pair source locks first; the global-role repository then + * verifies that same transaction and locks the exact birth source. This reader performs no + * enrollment, initialization, mutation, authorization, or admission. + */ +public final class AccountFreshCaptureSourceReader { + private final AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; + private final AccountGlobalRoleSourceRepository globalRoleSourceRepository; + + public AccountFreshCaptureSourceReader( + AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer, + AccountGlobalRoleSourceRepository globalRoleSourceRepository) { + this.membershipAuthorityEventProducer = + Objects.requireNonNull( + membershipAuthorityEventProducer, "membership authority producer is required"); + this.globalRoleSourceRepository = + Objects.requireNonNull( + globalRoleSourceRepository, "global-role source repository is required"); + } + + /** Reads the exact already-existing fresh Account source vector and role-birth source. */ + public AccountFreshCaptureSources readExisting(UUID accountUuid, UUID tenantUuid) { + requireCanonicalUuid(accountUuid, "Account UUID"); + requireCanonicalUuid(tenantUuid, "tenant UUID"); + requireWritableOwnerTransaction(); + + AccountMembershipCaptureSources membershipSources = + membershipAuthorityEventProducer.readExistingRuntimeMembershipCaptureSources( + accountUuid, tenantUuid); + AccountGlobalRoleSourceRepository.FreshEmptySource globalRoleSource = + globalRoleSourceRepository.readFreshEmptySourceForUpdate(accountUuid); + + return new AccountFreshCaptureSources( + accountUuid, tenantUuid, membershipSources, globalRoleSource); + } + + private static void requireCanonicalUuid(UUID value, String field) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + } + + private static void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Fresh Account capture requires a writable caller-owned Account transaction"); + } + } +} 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 2b8269d5a8..74964db5bb 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 @@ -15,6 +15,7 @@ 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.AccountMembershipCaptureSources; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceiptDigest; @@ -670,6 +671,227 @@ public RuntimeMembershipSnapshotDto readExistingRuntimeMembershipSnapshot( accountUuid, tenantUuid, MembershipSnapshotReadMode.EXISTING_ONLY); } + /** + * Reads the complete existing-only Account membership source vector inside the caller's owner + * transaction. This export is deliberately unwired and cannot authorize or admit a caller. + * + *

The exact composite authority rows are locked before any pair, membership, or role owner + * lock. Existing snapshot assembly then reuses the same owner-local verifiers while those source + * rows remain locked; no separately transactional source APIs or enrollment path is used. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountMembershipCaptureSources readExistingRuntimeMembershipCaptureSources( + UUID accountUuid, UUID tenantUuid) { + requireActiveOwnerTransaction(); + requireCanonicalUuidInput(accountUuid, "Account UUID"); + requireCanonicalUuidInput(tenantUuid, "tenant UUID"); + + Account initialAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Runtime snapshot Account row is absent")); + requirePersistedAccountIdentity(initialAccount, accountUuid); + joinOperationRepository.lockAccount(initialAccount.getId()); + Account fencedAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Runtime snapshot Account row disappeared at its fence")); + requirePersistedAccountIdentity(fencedAccount, accountUuid); + if (!Objects.equals(initialAccount.getId(), fencedAccount.getId()) + || initialAccount.getAccountUuidProvenance() != fencedAccount.getAccountUuidProvenance() + || !Objects.equals( + initialAccount.getAccountUuidSourceNumericId(), + fencedAccount.getAccountUuidSourceNumericId())) { + throw new IllegalStateException("Runtime snapshot Account identity changed at its row fence"); + } + + Optional freshAssociation = + freshTenantIdentityAssociationRepository.read(tenantUuid); + ApprovedAssociation retainedAssociation = null; + Identity retainedIdentity = null; + if (freshAssociation.isPresent()) { + if (!tenantUuid.equals(freshAssociation.orElseThrow().canonicalTenantId())) { + throw new IllegalStateException( + "Fresh Game Design tenant association differs from its canonical UUID scope"); + } + } else { + retainedAssociation = tenantIdentityResolver.resolve(tenantUuid); + if (retainedAssociation.legacyTenantId() <= 0L + || !tenantUuid.equals(retainedAssociation.canonicalTenantId())) { + throw new IllegalStateException( + "Retained tenant UUID has no exact private numeric association"); + } + retainedIdentity = + resolveIdentity(fencedAccount.getId(), retainedAssociation.legacyTenantId()); + VerifiedTenantProvenance retainedProvenance = + new VerifiedTenantProvenance( + retainedAssociation.legacyTenantId(), + TenantProvenanceKind.APPROVED_RETAINED, + retainedAssociation.operationId(), + retainedAssociation.manifestDigest()); + if (!tenantUuid.equals(retainedAssociation.canonicalTenantId()) + || !tenantUuid.equals(retainedIdentity.tenantUuid()) + || !retainedProvenance.equals(verifiedProvenance(retainedIdentity))) { + throw new IllegalStateException( + "Retained Account identity differs from its exact audited tenant association"); + } + } + + // Hold issuer, account/fence, tenant and membership source rows before the later pair, + // membership and role-header locks. Every returned scalar and event below is checked against + // this exact composite before it leaves the owner transaction. + CompositeSnapshot authoritySnapshot = readSnapshot(accountUuid, tenantUuid); + readCurrentUpstreamSourceEvidence(accountUuid, tenantUuid, authoritySnapshot); + if (retainedIdentity != null) { + PairAuthority pair = + pairAuthorityRepository + .readForUpdate(accountUuid, tenantUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Retained Account membership pair baseline is absent")); + if (!verifiedProvenance(retainedIdentity).equals(pair.provenance())) { + throw new IllegalStateException( + "Retained Account membership pair differs from its exact private identity"); + } + } + + RuntimeMembershipSnapshotDto membershipSnapshot = + readUuidRuntimeMembershipSnapshot( + accountUuid, tenantUuid, MembershipSnapshotReadMode.EXISTING_ONLY); + verifyExistingRuntimeSnapshotIdentity(membershipSnapshot, accountUuid, tenantUuid); + requireUnchangedAccountIdentity(initialAccount, accountUuid); + + Optional roleSource; + Optional finalFreshAssociation = + freshTenantIdentityAssociationRepository.read(tenantUuid); + if (freshAssociation.isPresent()) { + if (!freshAssociation.equals(finalFreshAssociation)) { + throw new IllegalStateException( + "Fresh Game Design tenant association changed during membership readback"); + } + if (membershipSnapshot.membershipExists() + || !membershipSnapshot.roles().isEmpty() + || membershipRepository + .findCanonicalMembershipForUpdate(accountUuid, tenantUuid) + .isPresent()) { + throw new IllegalStateException( + "Fresh tenant membership source contradicts its non-admitting baseline"); + } + roleSource = Optional.empty(); + } else { + if (finalFreshAssociation.isPresent() + || !retainedAssociation.equals(tenantIdentityResolver.resolve(tenantUuid))) { + throw new IllegalStateException( + "Retained tenant identity changed during membership readback"); + } + roleSource = + readExactExistingRoleSource( + fencedAccount.getId(), + retainedAssociation.legacyTenantId(), + membershipSnapshot, + retainedIdentity, + retainedAssociation); + } + + return new AccountMembershipCaptureSources( + accountUuid, + tenantUuid, + authoritySnapshot, + membershipSnapshot, + roleSource, + Optional.ofNullable(retainedAssociation)); + } + + private Optional readExactExistingRoleSource( + long accountId, + long legacyTenantId, + RuntimeMembershipSnapshotDto membershipSnapshot, + Identity identity, + ApprovedAssociation association) { + if (!membershipSnapshot.membershipExists()) { + if (!membershipSnapshot.roles().isEmpty()) { + throw new IllegalStateException("Absent Account membership cannot have role evidence"); + } + return Optional.empty(); + } + if (association == null) { + throw new IllegalStateException( + "Retained role source requires its exact audited tenant association"); + } + VerifiedTenantProvenance associationProvenance = + new VerifiedTenantProvenance( + association.legacyTenantId(), + TenantProvenanceKind.APPROVED_RETAINED, + association.operationId(), + association.manifestDigest()); + if (association.legacyTenantId() != legacyTenantId + || !identity.tenantUuid().equals(association.canonicalTenantId()) + || !verifiedProvenance(identity).equals(associationProvenance)) { + throw new IllegalStateException( + "Current role source is not bound to its exact audited tenant association"); + } + + JoinMembershipProof membership = + membershipRepository + .findJoinProofForUpdate(accountId, legacyTenantId) + .orElseThrow( + () -> new IllegalStateException("Current Account membership row is absent")); + if (membership.membershipId() <= 0L + || membership.membershipVersion() <= 0L + || !membership + .lifecycleState() + .equals(membershipSnapshot.membershipBaseline().membershipLifecycleState()) + || membership.gameplayAdmissionAllowed() != membershipSnapshot.gameplayAdmissionAllowed() + || !Long.toString(membership.membershipVersion()) + .equals( + membershipSnapshot + .membershipBaseline() + .membershipVersion() + .get(membershipSnapshot.tenantUuid()))) { + throw new IllegalStateException( + "Current Account membership row differs from its exact source projection"); + } + + RoleSnapshot roles = + roleSnapshotRepository + .findForUpdate( + accountId, + legacyTenantId, + membership.membershipId(), + membership.membershipVersion()) + .orElseThrow( + () -> new IllegalStateException("Current Account role snapshot header is absent")); + List canonicalRoles; + try { + canonicalRoles = + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet(roles.roles()); + } catch (RuntimeException exception) { + throw new IllegalStateException("Current Account role snapshot is not canonical", exception); + } + UUID accountUuid = UUID.fromString(membershipSnapshot.accountUuid()); + UUID tenantUuid = UUID.fromString(membershipSnapshot.tenantUuid()); + boolean canonicalTenantUuidPresent = roles.tenantUuid() != null; + boolean canonicalProvenancePresent = roles.tenantProvenance() != null; + if (roles.accountId() != accountId + || !Objects.equals(roles.tenantId(), association.legacyTenantId()) + || roles.membershipId() != membership.membershipId() + || roles.snapshotVersion() != membership.membershipVersion() + || !accountUuid.equals(roles.accountUuid()) + || canonicalTenantUuidPresent != canonicalProvenancePresent + || (canonicalTenantUuidPresent + && (!tenantUuid.equals(roles.tenantUuid()) + || !associationProvenance.equals(roles.tenantProvenance()))) + || !canonicalRoles.equals(membershipSnapshot.roles())) { + throw new IllegalStateException( + "Current Account role source differs from its exact membership header and identity"); + } + return Optional.of(roles); + } + private RuntimeMembershipSnapshotDto readUuidRuntimeMembershipSnapshot( UUID accountUuid, UUID tenantUuid, MembershipSnapshotReadMode readMode) { requireActiveOwnerTransaction(); diff --git a/services/account-service/src/main/resources/db/migration/V52__connect_issuance_authority_fence_capture.sql b/services/account-service/src/main/resources/db/migration/V52__connect_issuance_authority_fence_capture.sql new file mode 100644 index 0000000000..f7782a2e8f --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V52__connect_issuance_authority_fence_capture.sql @@ -0,0 +1,67 @@ +ALTER TABLE account_connect_token_issuance_operations + ADD COLUMN issuance_fence_capture_schema VARCHAR(64), + ADD COLUMN issuance_fence_capture_account_uuid UUID, + ADD COLUMN issuance_fence_capture_value BIGINT, + ADD COLUMN issuance_fence_capture_source_version BIGINT, + ADD COLUMN issuance_fence_capture_digest BYTEA, + ADD CONSTRAINT account_connect_token_issuance_fence_capture_check + CHECK ( + (issuance_fence_capture_schema IS NULL + AND issuance_fence_capture_account_uuid IS NULL + AND issuance_fence_capture_value IS NULL + AND issuance_fence_capture_source_version IS NULL + AND issuance_fence_capture_digest IS NULL) + OR + (issuance_fence_capture_schema IS NOT NULL + AND issuance_fence_capture_account_uuid IS NOT NULL + AND issuance_fence_capture_value IS NOT NULL + AND issuance_fence_capture_source_version IS NOT NULL + AND issuance_fence_capture_digest IS NOT NULL + AND issuance_fence_capture_schema = 'account-connect-issuance-fence/v1' + AND issuance_fence_capture_account_uuid + <> '00000000-0000-0000-0000-000000000000'::UUID + AND issuance_fence_capture_value > 0 + AND issuance_fence_capture_source_version > 0 + AND octet_length(issuance_fence_capture_digest) = 32)), + ADD CONSTRAINT account_connect_token_issuance_fence_capture_binding_check + CHECK (issuance_fence_capture_digest IS NULL + OR (issuance_fence_digest IS NOT NULL + AND issuance_fence_digest = issuance_fence_capture_digest)); + +-- [jooq ignore start] +CREATE FUNCTION account_connect_token_issuance_fence_capture_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF (OLD.issuance_fence_capture_schema IS NOT NULL + AND NEW.issuance_fence_capture_schema + IS DISTINCT FROM OLD.issuance_fence_capture_schema) + OR (OLD.issuance_fence_capture_account_uuid IS NOT NULL + AND NEW.issuance_fence_capture_account_uuid + IS DISTINCT FROM OLD.issuance_fence_capture_account_uuid) + OR (OLD.issuance_fence_capture_value IS NOT NULL + AND NEW.issuance_fence_capture_value IS DISTINCT FROM OLD.issuance_fence_capture_value) + OR (OLD.issuance_fence_capture_source_version IS NOT NULL + AND NEW.issuance_fence_capture_source_version + IS DISTINCT FROM OLD.issuance_fence_capture_source_version) + OR (OLD.issuance_fence_capture_digest IS NOT NULL + AND NEW.issuance_fence_capture_digest IS DISTINCT FROM OLD.issuance_fence_capture_digest) THEN + RAISE EXCEPTION 'Connect-token issuance fence capture cannot be replaced or removed' + USING ERRCODE = '23514', CONSTRAINT = 'account_connect_token_issuance_fence_capture_immutable'; + END IF; + IF OLD.issuance_fence_capture_schema IS NULL + AND NEW.issuance_fence_capture_schema IS NOT NULL + AND (OLD.status <> 'PENDING' OR NEW.status <> 'PENDING') THEN + RAISE EXCEPTION 'Connect-token issuance fence capture requires a pending operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_connect_token_issuance_fence_capture_pending'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_connect_token_issuance_fence_capture_update_guard_trigger + BEFORE UPDATE ON account_connect_token_issuance_operations + FOR EACH ROW + EXECUTE FUNCTION account_connect_token_issuance_fence_capture_update_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V53__bare_login_durable_pending_intent.sql b/services/account-service/src/main/resources/db/migration/V53__bare_login_durable_pending_intent.sql new file mode 100644 index 0000000000..92a746fbf4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V53__bare_login_durable_pending_intent.sql @@ -0,0 +1,8 @@ +-- V37 made PENDING bare-LOGIN exchange claims transaction-local, which prevents durable +-- pre-sign intent recovery. Keep the operation non-authorizing while PENDING; terminal success +-- still requires its exact response envelope in the same Account transaction. +-- [jooq ignore start] +DROP TRIGGER account_bare_login_pending_commit_check_trigger + ON account_bare_login_exchange_operations; +DROP FUNCTION account_bare_login_pending_commit_check(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V54__bare_login_token_identity_fence_capture.sql b/services/account-service/src/main/resources/db/migration/V54__bare_login_token_identity_fence_capture.sql new file mode 100644 index 0000000000..839772df19 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V54__bare_login_token_identity_fence_capture.sql @@ -0,0 +1,142 @@ +-- Immutable initial Account source evidence for one exact bare-LOGIN private delegation token. +-- This does not implement the later monotonic logout/rotation transitions or their registry proof. +CREATE TABLE account_bare_login_token_identity_fence_captures ( + token_hash VARCHAR(64) PRIMARY KEY, + schema_name VARCHAR(64) NOT NULL, + operation_id UUID NOT NULL UNIQUE + REFERENCES account_bare_login_exchange_operations(operation_id) ON DELETE RESTRICT, + source_connect_operation_id UUID NOT NULL + REFERENCES account_connect_token_issuance_operations(operation_id) ON DELETE RESTRICT, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + tenant_id UUID NOT NULL, + connect_scope_hash VARCHAR(71) NOT NULL, + request_id VARCHAR(128) NOT NULL, + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + token_identity VARCHAR(128) NOT NULL, + profile VARCHAR(64) NOT NULL, + token_identity_fence BIGINT NOT NULL, + token_identity_fence_source_version BIGINT NOT NULL, + account_issuance_fence BIGINT NOT NULL, + account_issuance_fence_source_version BIGINT NOT NULL, + captured_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_bare_login_token_identity_fence_identity_check + CHECK (account_id > 0 + AND schema_name = 'account-bare-login-token-identity-fence/v1' + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND length(connect_scope_hash) = 71 + AND connect_scope_hash ~ '^sha256:[0-9a-f]{64}$' + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND request_digest_version = 1 + AND octet_length(request_digest) = 32 + AND length(btrim(token_identity)) BETWEEN 1 AND 128 + AND profile = 'game-session-account-delegation' + AND length(token_hash) = 64 + AND token_hash ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_bare_login_token_identity_fence_initial_check + CHECK (token_identity_fence = 1 + AND token_identity_fence_source_version = 1 + AND account_issuance_fence > 0 + AND account_issuance_fence_source_version > 0), + CONSTRAINT account_bare_login_token_identity_fence_token_identity_uq + UNIQUE (profile, token_identity) +); + +-- The only producer in scope is bare first-party LOGIN. The row is initial capture evidence; later +-- logout/rotation work must add and prove its own complete monotonic transition protocol. +-- [jooq ignore start] +CREATE FUNCTION account_bare_login_token_identity_fence_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + account_row accounts%ROWTYPE; + operation_row account_bare_login_exchange_operations%ROWTYPE; + issuance_fence_row account_authority_issuance_fences%ROWTYPE; +BEGIN + SELECT * INTO account_row + FROM accounts + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + IF NOT FOUND + OR account_row.id IS DISTINCT FROM NEW.account_id + OR account_row.account_uuid_source_numeric_id IS DISTINCT FROM account_row.id + OR account_row.account_uuid_provenance IS NULL + OR account_row.account_uuid_provenance NOT IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT') THEN + RAISE EXCEPTION 'Bare LOGIN identity fence has no exact canonical Account provenance' + USING ERRCODE = '23514', + CONSTRAINT = 'account_bare_login_token_identity_fence_account_binding'; + END IF; + + SELECT * INTO operation_row + FROM account_bare_login_exchange_operations + WHERE operation_id = NEW.operation_id + FOR UPDATE; + IF NOT FOUND + OR operation_row.status IS DISTINCT FROM 'PENDING' + OR operation_row.operation_id IS DISTINCT FROM NEW.operation_id + OR operation_row.source_connect_operation_id IS DISTINCT FROM NEW.source_connect_operation_id + OR operation_row.account_id IS DISTINCT FROM NEW.account_id + OR operation_row.tenant_id IS DISTINCT FROM NEW.tenant_id + OR operation_row.connect_scope_hash IS DISTINCT FROM NEW.connect_scope_hash + OR operation_row.request_id IS DISTINCT FROM NEW.request_id + OR operation_row.request_digest_version IS DISTINCT FROM NEW.request_digest_version + OR operation_row.request_digest IS DISTINCT FROM NEW.request_digest + OR operation_row.token_identity IS DISTINCT FROM NEW.token_identity + OR encode(operation_row.token_hash, 'hex') IS DISTINCT FROM NEW.token_hash + OR NEW.schema_name IS DISTINCT FROM 'account-bare-login-token-identity-fence/v1' + OR NEW.profile IS DISTINCT FROM 'game-session-account-delegation' + OR NEW.token_identity_fence IS DISTINCT FROM 1 + OR NEW.token_identity_fence_source_version IS DISTINCT FROM 1 THEN + RAISE EXCEPTION 'Bare LOGIN identity fence does not match its exact pending operation' + USING ERRCODE = '23514', + CONSTRAINT = 'account_bare_login_token_identity_fence_operation_binding'; + END IF; + + SELECT * INTO issuance_fence_row + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + IF NOT FOUND + OR issuance_fence_row.issuance_fence IS DISTINCT FROM NEW.account_issuance_fence + OR issuance_fence_row.source_version + IS DISTINCT FROM NEW.account_issuance_fence_source_version THEN + RAISE EXCEPTION 'Bare LOGIN identity fence lacks the exact current Account issuance fence' + USING ERRCODE = '23514', + CONSTRAINT = 'account_bare_login_token_identity_fence_account_issuance_binding'; + END IF; + + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_bare_login_token_identity_fence_insert_guard_trigger + BEFORE INSERT ON account_bare_login_token_identity_fence_captures + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_token_identity_fence_insert_guard(); + +CREATE FUNCTION account_bare_login_token_identity_fence_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Bare LOGIN token identity fence capture is immutable and retained' + USING ERRCODE = '23514', + CONSTRAINT = 'account_bare_login_token_identity_fence_immutable'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_bare_login_token_identity_fence_immutable_trigger + BEFORE UPDATE OR DELETE ON account_bare_login_token_identity_fence_captures + FOR EACH ROW + EXECUTE FUNCTION account_bare_login_token_identity_fence_immutable_guard(); + +CREATE TRIGGER account_bare_login_token_identity_fence_no_truncate_trigger + BEFORE TRUNCATE ON account_bare_login_token_identity_fence_captures + FOR EACH STATEMENT + EXECUTE FUNCTION account_bare_login_token_identity_fence_immutable_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V55__account_global_role_source.sql b/services/account-service/src/main/resources/db/migration/V55__account_global_role_source.sql new file mode 100644 index 0000000000..6073c4ddef --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V55__account_global_role_source.sql @@ -0,0 +1,190 @@ +ALTER TABLE accounts + ADD CONSTRAINT accounts_global_role_source_identity_uq + UNIQUE (account_uuid, account_uuid_source_numeric_id, account_uuid_provenance); + +CREATE TABLE account_global_role_sources ( + account_uuid UUID PRIMARY KEY, + account_uuid_source_numeric_id BIGINT NOT NULL, + account_uuid_provenance VARCHAR(40) NOT NULL, + global_roles TEXT[] NOT NULL, + global_role_source_version BIGINT NOT NULL, + CONSTRAINT account_global_role_sources_account_identity_fk + FOREIGN KEY ( + account_uuid, + account_uuid_source_numeric_id, + account_uuid_provenance + ) + REFERENCES accounts ( + account_uuid, + account_uuid_source_numeric_id, + account_uuid_provenance + ) + ON DELETE RESTRICT, + CONSTRAINT account_global_role_sources_account_numeric_id_check + CHECK (account_uuid_source_numeric_id > 0), + CONSTRAINT account_global_role_sources_account_uuid_check + CHECK (account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_global_role_sources_fresh_provenance_check + CHECK (account_uuid_provenance IN ( + 'ACCOUNT_REPOSITORY_INSERT', + 'ACCOUNT_DATABASE_INSERT' + )), + CONSTRAINT account_global_role_sources_empty_roles_check + CHECK (global_roles = ARRAY[]::TEXT[]), + CONSTRAINT account_global_role_sources_positive_version_check + CHECK (global_role_source_version > 0) +); + +-- This prerequisite admits only the explicit-empty state. Role mutations need a +-- separately versioned, fenced producer before this immutable source can advance. +-- [jooq ignore start] +CREATE FUNCTION account_global_role_source_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Fresh Account global-role source is immutable until a versioned writer exists' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_global_role_source_immutable + BEFORE UPDATE OR DELETE ON account_global_role_sources + FOR EACH ROW EXECUTE FUNCTION account_global_role_source_immutable_guard(); + +CREATE FUNCTION account_global_role_source_truncate_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Fresh Account global-role source cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_truncate_denied'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_global_role_source_truncate_guard + BEFORE TRUNCATE ON account_global_role_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_global_role_source_truncate_guard(); + +CREATE FUNCTION account_global_role_source_birth_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + account_identity_exists BOOLEAN; +BEGIN + IF pg_trigger_depth() <> 2 THEN + RAISE EXCEPTION 'Account global-role source may only be inserted by its fresh Account birth path' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_birth_only'; + END IF; + + -- The source table and its Account owner may be written through a + -- schema-qualified relation while the connection search_path names another + -- schema. Resolve the paired Account row in the trigger table's own schema. + EXECUTE format( + 'SELECT EXISTS ( + SELECT 1 + FROM %I.accounts account_row + WHERE account_row.id = $1 + AND account_row.account_uuid = $2 + AND account_row.account_uuid_source_numeric_id = $3 + AND account_row.account_uuid_provenance = $4 + AND account_row.account_uuid_provenance IN ( + ''ACCOUNT_REPOSITORY_INSERT'', + ''ACCOUNT_DATABASE_INSERT'' + ) + AND account_row.role IS NULL + )', + TG_TABLE_SCHEMA + ) INTO account_identity_exists + USING NEW.account_uuid_source_numeric_id, + NEW.account_uuid, + NEW.account_uuid_source_numeric_id, + NEW.account_uuid_provenance; + + IF NOT account_identity_exists THEN + RAISE EXCEPTION 'Account global-role source may only be inserted by its fresh Account birth path' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_birth_only'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_global_role_source_birth_insert_guard + BEFORE INSERT ON account_global_role_sources + FOR EACH ROW EXECUTE FUNCTION account_global_role_source_birth_insert_guard(); + +CREATE FUNCTION account_global_role_source_birth() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.account_uuid_provenance IN ( + 'ACCOUNT_REPOSITORY_INSERT', + 'ACCOUNT_DATABASE_INSERT' + ) AND NEW.role IS NULL THEN + IF NEW.account_uuid IS NULL + OR NEW.account_uuid = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM NEW.id THEN + RAISE EXCEPTION 'Fresh Account has no exact canonical UUID source identity' + USING ERRCODE = '23514', + CONSTRAINT = 'account_global_role_source_birth_identity'; + END IF; + + -- Bind the fresh source row to the schema that owns this Account row, + -- even when the caller inserted through a qualified table name. + EXECUTE format( + 'INSERT INTO %I.account_global_role_sources ( + account_uuid, + account_uuid_source_numeric_id, + account_uuid_provenance, + global_roles, + global_role_source_version + ) VALUES ($1, $2, $3, ARRAY[]::TEXT[], 1)', + TG_TABLE_SCHEMA + ) USING NEW.account_uuid, + NEW.account_uuid_source_numeric_id, + NEW.account_uuid_provenance; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER accounts_global_role_source_birth + AFTER INSERT ON accounts + FOR EACH ROW EXECUTE FUNCTION account_global_role_source_birth(); + +CREATE FUNCTION account_global_role_source_legacy_scalar_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + has_global_role_source BOOLEAN; +BEGIN + IF NEW.role IS DISTINCT FROM OLD.role THEN + EXECUTE format( + 'SELECT EXISTS ( + SELECT 1 + FROM %I.account_global_role_sources source + WHERE source.account_uuid = $1 + )', + TG_TABLE_SCHEMA + ) INTO has_global_role_source + USING OLD.account_uuid; + + IF has_global_role_source THEN + RAISE EXCEPTION 'Account role change requires a versioned global-role source writer' + USING ERRCODE = '23514', + CONSTRAINT = 'account_global_role_source_legacy_scalar_guard'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER accounts_global_role_source_legacy_scalar_guard + BEFORE UPDATE OF role ON accounts + FOR EACH ROW EXECUTE FUNCTION account_global_role_source_legacy_scalar_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java index 8623e750a5..d8b2ad2826 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginExchangeRepositoryIntegrationTest.java @@ -52,22 +52,244 @@ class AccountBareLoginExchangeRepositoryIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @Test - void claimOnlyTransactionRollsBackPendingExchange() { + void durablePendingClaimRecoversExactOperationAfterLostAcknowledgementWithoutEnvelope() { TestContext context = newTestContext(); Source source = committedSource(context); AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); byte[] requestDigest = digest(0); + // The first response is intentionally discarded to model a committed claim with a lost ack. + inTransaction(context.transaction(), () -> context.repository().claim(identity, requestDigest)); + UUID originalOperationId = + context + .dsl() + .resultQuery( + "SELECT operation_id FROM account_bare_login_exchange_operations " + + "WHERE source_connect_operation_id = ?", + identity.sourceConnectOperationId()) + .fetchOne(0, UUID.class); + assertThat(originalOperationId).isNotNull(); + + var recovered = + inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + var persisted = + inTransaction( + context.transaction(), + () -> context.repository().find(identity, requestDigest).orElseThrow()); + AccountEnvelopeBinding binding = binding(originalOperationId, identity, requestDigest, 3); + + assertThat(recovered.disposition()) + .isEqualTo(AccountBareLoginExchangeRepository.ClaimDisposition.REPLAYED); + assertThat(recovered.operation().operationId()).isEqualTo(originalOperationId); + assertThat(recovered.operation().lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(persisted.operationId()).isEqualTo(originalOperationId); + assertThat(persisted.lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(persisted.requestDigest()).containsExactly(requestDigest); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readResponseEnvelope(identity, requestDigest, binding))) + .isEmpty(); + Long envelopeCount = + context + .dsl() + .resultQuery( + "SELECT COUNT(*) FROM account_bare_login_response_envelopes " + + "WHERE operation_id = ?", + originalOperationId) + .fetchOne(0, Long.class); + assertThat(envelopeCount).isEqualTo(0L); + + var evidenceReadback = + inTransaction( + context.transaction(), + () -> + context + .repository() + .recordPendingEvidence( + recovered, + requestDigest, + "delegation-jti-recovered", + digest(80), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest())); + assertThat(evidenceReadback.lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(evidenceReadback.operationId()).isEqualTo(originalOperationId); + assertThat(evidenceReadback.requestDigest()).containsExactly(requestDigest); + + AccountEnvelopeBinding changedBinding = + binding(originalOperationId, identity, requestDigest, 4); assertThatThrownBy( () -> inTransaction( context.transaction(), - () -> context.repository().claim(identity, requestDigest))) - .isInstanceOf(TransactionSystemException.class); + () -> + context + .repository() + .recordPendingEvidence( + recovered, + requestDigest, + "delegation-jti-changed", + digest(81), + changedBinding.contextEvidenceDigest(), + changedBinding.authorityTupleDigest(), + changedBinding.issuanceFenceDigest(), + changedBinding.postconditionDigest()))) + .isInstanceOf(AccountBareLoginExchangeRepository.EvidenceMismatchException.class); + + var exactPendingRetry = + inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + assertThat(exactPendingRetry.disposition()) + .isEqualTo(AccountBareLoginExchangeRepository.ClaimDisposition.REPLAYED); + assertThat(exactPendingRetry.operation().operationId()).isEqualTo(originalOperationId); + assertThat(exactPendingRetry.operation().lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readResponseEnvelope(identity, requestDigest, binding))) + .isEmpty(); + + AccountBareLoginResponseEnvelope stored = + inTransaction( + context.transaction(), + () -> + context + .repository() + .completeWithEnvelope( + exactPendingRetry, + requestDigest, + "delegation-jti-recovered", + digest(80), + binding, + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE))); + assertThat(stored.operationId()).isEqualTo(originalOperationId); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().find(identity, requestDigest).orElseThrow().lifecycle())) + .isEqualTo(Lifecycle.COMMITTED); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readResponseEnvelope(identity, requestDigest, binding))) + .contains(stored); + } + + @Test + void changedDigestRequestOrSourceCannotReplaceDurablePendingClaim() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(4); + var original = + inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> context.repository().claim(identity, digest(5)))) + .isInstanceOf(AccountBareLoginExchangeRepository.IdempotencyConflictException.class); + + AccountBareLoginExchangeIdentity changedRequest = + new AccountBareLoginExchangeIdentity( + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeId(), + identity.requestId() + "-changed"); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().claim(changedRequest, requestDigest))) + .isInstanceOf(AccountBareLoginExchangeRepository.IdentityConflictException.class); + + AccountBareLoginExchangeIdentity changedSourceBinding = + new AccountBareLoginExchangeIdentity( + identity.sourceConnectOperationId(), + identity.accountId() + 1, + identity.tenantId(), + identity.connectScopeId(), + identity.requestId()); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().claim(changedSourceBinding, requestDigest))) + .isInstanceOf(AccountBareLoginExchangeRepository.IdentityConflictException.class); + + AccountBareLoginExchangeIdentity changedSourceOperation = + new AccountBareLoginExchangeIdentity( + UUID.randomUUID(), + identity.accountId(), + identity.tenantId(), + identity.connectScopeId(), + identity.requestId()); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().claim(changedSourceOperation, requestDigest))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source connect operation is missing"); + + var unchanged = + inTransaction( + context.transaction(), + () -> context.repository().find(identity, requestDigest).orElseThrow()); + assertThat(unchanged.operationId()).isEqualTo(original.operation().operationId()); + assertThat(unchanged.lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(unchanged.requestDigest()).containsExactly(requestDigest); + assertThat(unchanged.tokenIdentity()).isNull(); + Long envelopeCount = + context + .dsl() + .resultQuery( + "SELECT COUNT(*) FROM account_bare_login_response_envelopes " + + "WHERE operation_id = ?", + unchanged.operationId()) + .fetchOne(0, Long.class); + assertThat(envelopeCount).isEqualTo(0L); + } + + @Test + void rollingBackPendingClaimLeavesNoPartialExchange() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(6); + + AccountBareLoginExchangeRepository.ClaimResult attempted = + context + .transaction() + .execute( + status -> { + var claim = context.repository().claim(identity, requestDigest); + status.setRollbackOnly(); + return claim; + }); + + assertThat(attempted).isNotNull(); + assertThat(attempted.disposition()) + .isEqualTo(AccountBareLoginExchangeRepository.ClaimDisposition.CLAIMED); assertThat( inTransaction( context.transaction(), () -> context.repository().find(identity, requestDigest))) .isEmpty(); + Long operationCount = + context + .dsl() + .resultQuery( + "SELECT COUNT(*) FROM account_bare_login_exchange_operations " + + "WHERE source_connect_operation_id = ?", + identity.sourceConnectOperationId()) + .fetchOne(0, Long.class); + assertThat(operationCount).isEqualTo(0L); } @Test @@ -117,6 +339,24 @@ void sourceMustBeCommittedAndFirstWriterOwnsTheExchangeIdentity() { .isEqualTo(AccountBareLoginExchangeRepository.ClaimDisposition.REPLAYED); assertThat(exactRetry.operation().operationId()).isEqualTo(claimed.operation().operationId()); assertThat(exactRetry.operation().lifecycle()).isEqualTo(Lifecycle.COMMITTED); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .recordPendingEvidence( + exactRetry, + digest, + "delegation-jti-source", + digest(80), + firstResult.binding().contextEvidenceDigest(), + firstResult.binding().authorityTupleDigest(), + firstResult.binding().issuanceFenceDigest(), + firstResult.binding().postconditionDigest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact pending bare LOGIN exchange claim"); assertThat( inTransaction( context.transaction(), @@ -157,6 +397,183 @@ void sourceMustBeCommittedAndFirstWriterOwnsTheExchangeIdentity() { .hasMessageContaining("not committed"); } + @Test + void concurrentExactPendingClaimsConvergeOnOneDurableOperation() throws Exception { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(7); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Callable claimExactPending = + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Pending exchange claim race did not start together"); + } + return inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + }; + Future first = + executor.submit(claimExactPending); + Future second = + executor.submit(claimExactPending); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + var results = List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); + assertThat(results) + .extracting(AccountBareLoginExchangeRepository.ClaimResult::disposition) + .containsExactlyInAnyOrder( + AccountBareLoginExchangeRepository.ClaimDisposition.CLAIMED, + AccountBareLoginExchangeRepository.ClaimDisposition.REPLAYED); + UUID operationId = results.get(0).operation().operationId(); + assertThat(results.get(1).operation().operationId()).isEqualTo(operationId); + assertThat(results) + .extracting(result -> result.operation().lifecycle()) + .containsOnly(Lifecycle.PENDING); + + var persisted = + inTransaction( + context.transaction(), + () -> context.repository().find(identity, requestDigest).orElseThrow()); + assertThat(persisted.operationId()).isEqualTo(operationId); + assertThat(persisted.lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(persisted.requestDigest()).containsExactly(requestDigest); + Long envelopeCount = + context + .dsl() + .resultQuery( + "SELECT COUNT(*) FROM account_bare_login_response_envelopes " + + "WHERE operation_id = ?", + operationId) + .fetchOne(0, Long.class); + assertThat(envelopeCount).isEqualTo(0L); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void concurrentChangedPendingEvidenceWritersKeepOneFirstWrite() throws Exception { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(8); + var originalClaim = + inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + var exactRetry = + inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + AccountEnvelopeBinding firstBinding = + binding(originalClaim.operation().operationId(), identity, requestDigest, 9); + AccountEnvelopeBinding secondBinding = + binding(originalClaim.operation().operationId(), identity, requestDigest, 19); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Callable firstWriter = + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Pending evidence race did not start together"); + } + try { + inTransaction( + context.transaction(), + () -> + context + .repository() + .recordPendingEvidence( + originalClaim, + requestDigest, + "delegation-jti-concurrent-first", + digest(90), + firstBinding.contextEvidenceDigest(), + firstBinding.authorityTupleDigest(), + firstBinding.issuanceFenceDigest(), + firstBinding.postconditionDigest())); + return true; + } catch (AccountBareLoginExchangeRepository.EvidenceMismatchException exception) { + return false; + } + }; + Callable secondWriter = + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Pending evidence race did not start together"); + } + try { + inTransaction( + context.transaction(), + () -> + context + .repository() + .recordPendingEvidence( + exactRetry, + requestDigest, + "delegation-jti-concurrent-second", + digest(91), + secondBinding.contextEvidenceDigest(), + secondBinding.authorityTupleDigest(), + secondBinding.issuanceFenceDigest(), + secondBinding.postconditionDigest())); + return true; + } catch (AccountBareLoginExchangeRepository.EvidenceMismatchException exception) { + return false; + } + }; + Future first = executor.submit(firstWriter); + Future second = executor.submit(secondWriter); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat(List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + var persisted = + inTransaction( + context.transaction(), + () -> context.repository().find(identity, requestDigest).orElseThrow()); + assertThat(persisted.operationId()).isEqualTo(originalClaim.operation().operationId()); + assertThat(persisted.lifecycle()).isEqualTo(Lifecycle.PENDING); + AccountEnvelopeBinding winningBinding; + if ("delegation-jti-concurrent-first".equals(persisted.tokenIdentity())) { + assertThat(persisted.tokenHash()).containsExactly(digest(90)); + winningBinding = firstBinding; + } else { + assertThat(persisted.tokenIdentity()).isEqualTo("delegation-jti-concurrent-second"); + assertThat(persisted.tokenHash()).containsExactly(digest(91)); + winningBinding = secondBinding; + } + assertThat(persisted.contextEvidenceDigest()) + .containsExactly(winningBinding.contextEvidenceDigest()); + assertThat(persisted.authorityTupleDigest()) + .containsExactly(winningBinding.authorityTupleDigest()); + assertThat(persisted.issuanceFenceDigest()) + .containsExactly(winningBinding.issuanceFenceDigest()); + assertThat(persisted.postconditionDigest()) + .containsExactly(winningBinding.postconditionDigest()); + Long envelopeCount = + context + .dsl() + .resultQuery( + "SELECT COUNT(*) FROM account_bare_login_response_envelopes " + + "WHERE operation_id = ?", + persisted.operationId()) + .fetchOne(0, Long.class); + assertThat(envelopeCount).isEqualTo(0L); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + @Test void concurrentExactExchangeClaimsHaveOneTerminalFirstWriter() throws Exception { TestContext context = newTestContext(); @@ -417,6 +834,81 @@ void pendingEvidenceThenTerminalSuccessReadBacksExactPurposeBoundEnvelope() { .isInstanceOf(AccountBareLoginExchangeRepository.IdempotencyConflictException.class); } + @Test + void terminalSuccessWithoutItsExactBoundEnvelopeCannotCommit() { + TestContext context = newTestContext(); + Source source = committedSource(context); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = digest(12); + var claim = + inTransaction( + context.transaction(), () -> context.repository().claim(identity, requestDigest)); + AccountEnvelopeBinding binding = + binding(claim.operation().operationId(), identity, requestDigest, 22); + inTransaction( + context.transaction(), + () -> + context + .repository() + .recordPendingEvidence( + claim, + requestDigest, + "delegation-jti-no-envelope", + digest(82), + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest())); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + int updated = + context + .dsl() + .execute( + "UPDATE account_bare_login_exchange_operations " + + "SET status = 'COMMITTED', outcome_code = 'SUCCESS' " + + "WHERE operation_id = ?", + claim.operation().operationId()); + assertThat(updated).isEqualTo(1); + return null; + })) + .isInstanceOf(TransactionSystemException.class) + .satisfies( + exception -> { + Throwable rootCause = ((TransactionSystemException) exception).getRootCause(); + assertThat(rootCause).isNotNull(); + assertThat(rootCause.getMessage()) + .contains("Terminal bare LOGIN exchange requires its exact response envelope"); + }); + + var unchanged = + inTransaction( + context.transaction(), + () -> context.repository().find(identity, requestDigest).orElseThrow()); + assertThat(unchanged.lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(unchanged.outcomeCode()).isNull(); + assertThat(unchanged.requestDigest()).containsExactly(requestDigest); + assertThat(unchanged.contextEvidenceDigest()).containsExactly(binding.contextEvidenceDigest()); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().readResponseEnvelope(identity, requestDigest, binding))) + .isEmpty(); + Long envelopeCount = + context + .dsl() + .resultQuery( + "SELECT COUNT(*) FROM account_bare_login_response_envelopes " + + "WHERE operation_id = ?", + claim.operation().operationId()) + .fetchOne(0, Long.class); + assertThat(envelopeCount).isEqualTo(0L); + } + @Test void wrongIdentityBindingOrPurposeCannotTerminalizeThePendingExchange() { TestContext context = newTestContext(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginTokenIdentityFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginTokenIdentityFencePostgresIntegrationTest.java new file mode 100644 index 0000000000..6b9f1fc48b --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountBareLoginTokenIdentityFencePostgresIntegrationTest.java @@ -0,0 +1,910 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.HexFormat; +import java.util.Map; +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 java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeRepository; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginResponseEnvelope; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginTokenIdentityFence; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +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.postgresql.util.PSQLException; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real PostgreSQL proof for immutable initial bare-LOGIN token identity capture. Connect source + * results, encrypted envelopes, token identity strings and digests in these fixtures are synthetic + * repository evidence, not signed issuer output, authenticated source delivery or runtime proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountBareLoginTokenIdentityFencePostgresIntegrationTest { + private static final String SCHEMA = "account_bare_login_token_identity_fence_proof"; + private static final String CAPTURE_TABLE = "account_bare_login_token_identity_fence_captures"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void initialCapturePersistsExactSyntheticEvidenceAndExactRetriesDoNotChurn() { + TestContext context = newTestContext(); + TokenFixture fixture = pendingFixture(context); + + AccountBareLoginTokenIdentityFence captured = + inTransaction(context.transaction(), () -> capture(context, fixture)); + AccountBareLoginTokenIdentityFence retry = + inTransaction(context.transaction(), () -> capture(context, fixture)); + AccountBareLoginTokenIdentityFence required = + inTransaction(context.transaction(), () -> requireInitial(context, fixture)); + + assertThat(captured.schemaName()).isEqualTo(AccountBareLoginTokenIdentityFence.SCHEMA_NAME); + assertThat(captured.operationId()).isEqualTo(fixture.operationId()); + assertThat(captured.sourceConnectOperationId()) + .isEqualTo(fixture.identity().sourceConnectOperationId()); + assertThat(captured.accountId()).isEqualTo(fixture.account().id()); + assertThat(captured.accountUuid()).isEqualTo(fixture.account().uuid()); + assertThat(captured.tenantId()).isEqualTo(fixture.identity().tenantId()); + assertThat(captured.connectScopeHash()) + .isEqualTo(AccountJoinDigest.tokenHash(fixture.identity().connectScopeId())); + assertThat(captured.requestId()).isEqualTo(fixture.identity().requestId()); + assertThat(captured.requestDigest()).containsExactly(fixture.requestDigest()); + assertThat(captured.profile()).isEqualTo(AccountBareLoginTokenIdentityFence.PROFILE_NAME); + assertThat(captured.tokenIdentity()).isEqualTo(fixture.tokenIdentity()); + assertThat(captured.tokenHash()).containsExactly(fixture.tokenHash()); + String persistedTokenHash = + context + .dsl() + .resultQuery( + "SELECT token_hash FROM " + CAPTURE_TABLE + " WHERE operation_id = ?", + fixture.operationId()) + .fetchOne(0, String.class); + assertThat(persistedTokenHash).isEqualTo(HexFormat.of().formatHex(fixture.tokenHash())); + assertThat(captured.tokenIdentityFence()).isEqualTo(1L); + assertThat(captured.tokenIdentityFenceSourceVersion()).isEqualTo(1L); + assertThat(captured.accountIssuanceFence()).isEqualTo(1L); + assertThat(captured.accountIssuanceFenceSourceVersion()).isEqualTo(1L); + assertThat(captured.capturedAt()).isNotNull(); + assertThat(retry.sameInitialCapture(captured)).isTrue(); + assertThat(required.sameInitialCapture(captured)).isTrue(); + assertThat(retry.capturedAt()).isEqualTo(captured.capturedAt()); + assertThat(required.capturedAt()).isEqualTo(captured.capturedAt()); + assertThat(captureCount(context, fixture.operationId())).isEqualTo(1L); + } + + @Test + void missingRequireInitialDoesNotCreateOrBackfillEvidence() { + TestContext context = newTestContext(); + TokenFixture fixture = pendingFixture(context); + + assertThatThrownBy( + () -> inTransaction(context.transaction(), () -> requireInitial(context, fixture))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("absent"); + assertThat(captureCount(context, fixture.operationId())).isZero(); + } + + @Test + void changedRequestOperationAccountOrTokenEvidenceCannotReplaceCapture() { + TestContext context = newTestContext(); + TokenFixture fixture = pendingFixture(context); + AccountBareLoginTokenIdentityFence captured = + inTransaction(context.transaction(), () -> capture(context, fixture)); + + assertCaptureRejected( + context, + fixture.identity(), + fixture.operationId(), + fixture.account().uuid(), + digest(22), + fixture.tokenIdentity(), + fixture.tokenHash()); + assertCaptureRejected( + context, + new AccountBareLoginExchangeIdentity( + UUID.randomUUID(), + fixture.identity().accountId(), + fixture.identity().tenantId(), + fixture.identity().connectScopeId(), + fixture.identity().requestId()), + fixture.operationId(), + fixture.account().uuid(), + fixture.requestDigest(), + fixture.tokenIdentity(), + fixture.tokenHash()); + assertCaptureRejected( + context, + fixture.identity(), + UUID.randomUUID(), + fixture.account().uuid(), + fixture.requestDigest(), + fixture.tokenIdentity(), + fixture.tokenHash()); + assertCaptureRejected( + context, + new AccountBareLoginExchangeIdentity( + fixture.identity().sourceConnectOperationId(), + fixture.identity().accountId(), + fixture.identity().tenantId(), + fixture.identity().connectScopeId(), + "changed-request-" + UUID.randomUUID()), + fixture.operationId(), + fixture.account().uuid(), + fixture.requestDigest(), + fixture.tokenIdentity(), + fixture.tokenHash()); + assertCaptureRejected( + context, + fixture.identity(), + fixture.operationId(), + fixture.account().uuid(), + fixture.requestDigest(), + "changed-delegation-jti-" + UUID.randomUUID(), + fixture.tokenHash()); + assertCaptureRejected( + context, + fixture.identity(), + fixture.operationId(), + fixture.account().uuid(), + fixture.requestDigest(), + fixture.tokenIdentity(), + digest(23)); + Account foreignAccount = newAccount(context); + initializeAccountAuthority(context, foreignAccount); + assertCaptureRejected( + context, + fixture.identity(), + fixture.operationId(), + foreignAccount.uuid(), + fixture.requestDigest(), + fixture.tokenIdentity(), + fixture.tokenHash()); + assertCaptureRejected( + context, + new AccountBareLoginExchangeIdentity( + fixture.identity().sourceConnectOperationId(), + foreignAccount.id(), + fixture.identity().tenantId(), + fixture.identity().connectScopeId(), + fixture.identity().requestId()), + fixture.operationId(), + foreignAccount.uuid(), + fixture.requestDigest(), + fixture.tokenIdentity(), + fixture.tokenHash()); + + AccountBareLoginTokenIdentityFence unchanged = + inTransaction(context.transaction(), () -> requireInitial(context, fixture)); + assertThat(unchanged.sameInitialCapture(captured)).isTrue(); + assertThat(unchanged.capturedAt()).isEqualTo(captured.capturedAt()); + assertThat(captureCount(context, fixture.operationId())).isEqualTo(1L); + } + + @Test + void captureRequiresOutgoingTokenBindingAndRejectsLateTerminalCapture() { + TestContext context = newTestContext(); + TokenFixture unbound = pendingFixture(context, newAccount(context), false); + + assertThatThrownBy(() -> inTransaction(context.transaction(), () -> capture(context, unbound))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("pending operation"); + assertThat(captureCount(context, unbound.operationId())).isZero(); + + TokenFixture missingAccountFence = pendingFixture(context, newAccount(context), true); + assertThatThrownBy( + () -> inTransaction(context.transaction(), () -> capture(context, missingAccountFence))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current Account issuance fence is absent"); + assertThat(captureCount(context, missingAccountFence.operationId())).isZero(); + + TokenFixture terminal = pendingFixture(context); + AccountBareLoginResponseEnvelope terminalEnvelope = + inTransaction( + context.transaction(), + () -> + context + .exchangeRepository() + .completeWithEnvelope( + terminal.claim(), + terminal.requestDigest(), + terminal.tokenIdentity(), + terminal.tokenHash(), + terminal.binding(), + encryptedEnvelope(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE))); + assertThat(terminalEnvelope.operationId()).isEqualTo(terminal.operationId()); + assertThat( + inTransaction( + context.transaction(), + () -> + context + .exchangeRepository() + .find(terminal.identity(), terminal.requestDigest()) + .orElseThrow() + .lifecycle())) + .isEqualTo( + net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeOperation + .Lifecycle.COMMITTED); + assertThatThrownBy(() -> inTransaction(context.transaction(), () -> capture(context, terminal))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("pending operation"); + assertThat(captureCount(context, terminal.operationId())).isZero(); + } + + @Test + void missingAccountAndMismatchedCanonicalAccountIdentityAreDenied() { + TestContext context = newTestContext(); + TokenFixture fixture = pendingFixture(context); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .captureInitial( + fixture.identity(), + fixture.operationId(), + UUID.randomUUID(), + fixture.requestDigest(), + fixture.tokenIdentity(), + fixture.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account row is absent"); + assertThat(captureCount(context, fixture.operationId())).isZero(); + + Account foreignAccount = newAccount(context); + initializeAccountAuthority(context, foreignAccount); + assertSqlConstraint( + () -> insertCaptureDirect(context, fixture, foreignAccount.uuid(), 1L, 1L), + "account_bare_login_token_identity_fence_account_binding"); + assertThat(captureCount(context, fixture.operationId())).isZero(); + } + + @Test + void rollbackLeavesNoPartialInitialCapture() { + TestContext context = newTestContext(); + TokenFixture fixture = pendingFixture(context); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + capture(context, fixture); + throw new IllegalStateException("test rollback after capture"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("test rollback"); + assertThat(captureCount(context, fixture.operationId())).isZero(); + + AccountBareLoginTokenIdentityFence committed = + inTransaction(context.transaction(), () -> capture(context, fixture)); + assertThat(committed.operationId()).isEqualTo(fixture.operationId()); + assertThat(captureCount(context, fixture.operationId())).isEqualTo(1L); + } + + @Test + void concurrentExactInitialCapturesConvergeOnOneImmutableRow() throws Exception { + TestContext context = newTestContext(); + TokenFixture fixture = pendingFixture(context); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Callable capture = + () -> { + ready.countDown(); + await(start, "exact capture race did not start"); + return inTransaction(context.transaction(), () -> capture(context, fixture)); + }; + Future first = executor.submit(capture); + Future second = executor.submit(capture); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + AccountBareLoginTokenIdentityFence firstResult = first.get(20, TimeUnit.SECONDS); + AccountBareLoginTokenIdentityFence secondResult = second.get(20, TimeUnit.SECONDS); + assertThat(firstResult.sameInitialCapture(secondResult)).isTrue(); + assertThat(firstResult.capturedAt()).isEqualTo(secondResult.capturedAt()); + assertThat(captureCount(context, fixture.operationId())).isEqualTo(1L); + } finally { + executor.shutdownNow(); + } + } + + @Test + void accountFenceAdvanceSerializesCaptureAndMakesHistoricalCurrentEvidenceStale() + throws Exception { + TestContext context = newTestContext(); + Account account = newAccount(context); + initializeAccountAuthority(context, account); + TokenFixture first = pendingFixture(context, account, true); + TokenFixture afterAdvance = pendingFixture(context, account, true); + AccountBareLoginTokenIdentityFence firstCapture = + inTransaction(context.transaction(), () -> capture(context, first)); + + CountDownLatch advanced = new CountDownLatch(1); + CountDownLatch releaseAdvance = new CountDownLatch(1); + CountDownLatch captureStarted = new CountDownLatch(1); + AtomicInteger blockerPid = new AtomicInteger(); + AtomicInteger waiterPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future advance = + executor.submit( + () -> + inTransaction( + context.transaction(), + () -> { + blockerPid.set(currentBackendPid(context)); + AuthorityScope scope = AuthorityScope.account(account.uuid()); + var current = context.authorityRepository().read(scope); + var next = + context.authorityRepository().advance(current, current.issuanceFence()); + advanced.countDown(); + await(releaseAdvance, "Account fence advance was not released"); + return next; + })); + assertThat(advanced.await(10, TimeUnit.SECONDS)).isTrue(); + + Future captureAfterAdvance = + executor.submit( + () -> + inTransaction( + context.transaction(), + () -> { + waiterPid.set(currentBackendPid(context)); + captureStarted.countDown(); + return capture(context, afterAdvance); + })); + assertThat(captureStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat( + awaitDatabaseBlock(context, waiterPid.get(), blockerPid.get(), Duration.ofSeconds(5))) + .isTrue(); + releaseAdvance.countDown(); + + var advancedState = advance.get(20, TimeUnit.SECONDS); + AccountBareLoginTokenIdentityFence secondCapture = + captureAfterAdvance.get(20, TimeUnit.SECONDS); + assertThat(advancedState.generation()).isEqualTo(2L); + assertThat(advancedState.sourceVersion()).isEqualTo(2L); + assertThat(secondCapture.accountIssuanceFence()).isEqualTo(2L); + assertThat(secondCapture.accountIssuanceFenceSourceVersion()).isEqualTo(2L); + assertThat(firstCapture.accountIssuanceFence()).isEqualTo(1L); + assertThatThrownBy( + () -> inTransaction(context.transaction(), () -> requireInitial(context, first))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from its current exact evidence"); + assertThat(captureCount(context, first.operationId())).isEqualTo(1L); + assertThat(captureCount(context, afterAdvance.operationId())).isEqualTo(1L); + } finally { + releaseAdvance.countDown(); + executor.shutdownNow(); + } + } + + @Test + void actualOwnerTransactionMustBeWritableReadCommittedAndConnectionBound() { + TestContext context = newTestContext(); + TokenFixture fixture = pendingFixture(context); + + assertThatThrownBy(() -> capture(context, fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owner transaction"); + + TransactionTemplate readOnly = + new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); + readOnly.setReadOnly(true); + assertThatThrownBy(() -> inTransaction(readOnly, () -> capture(context, fixture))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable"); + + TransactionTemplate repeatableRead = + new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); + repeatableRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy(() -> inTransaction(repeatableRead, () -> capture(context, fixture))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ COMMITTED"); + assertThat(captureCount(context, fixture.operationId())).isZero(); + } + + @Test + void directSqlMismatchedCurrentFenceInsertAndCaptureMutationAreDenied() { + TestContext context = newTestContext(); + Account account = newAccount(context); + initializeAccountAuthority(context, account); + TokenFixture retained = pendingFixture(context, account, true); + AccountBareLoginTokenIdentityFence stored = + inTransaction(context.transaction(), () -> capture(context, retained)); + + var state = + inTransaction( + context.transaction(), + () -> context.authorityRepository().read(AuthorityScope.account(account.uuid()))); + inTransaction( + context.transaction(), + () -> context.authorityRepository().advance(state, state.issuanceFence())); + TokenFixture staleDirectInsert = pendingFixture(context, account, true); + assertSqlConstraint( + () -> + insertCaptureDirect( + context, + staleDirectInsert, + account.uuid(), + stored.accountIssuanceFence(), + stored.accountIssuanceFenceSourceVersion()), + "account_bare_login_token_identity_fence_account_issuance_binding"); + assertThat(captureCount(context, staleDirectInsert.operationId())).isZero(); + + assertSqlConstraint( + () -> + context + .dsl() + .execute( + "UPDATE " + CAPTURE_TABLE + " SET request_id = ? WHERE operation_id = ?", + "rewritten-request", + retained.operationId()), + "account_bare_login_token_identity_fence_immutable"); + assertSqlConstraint( + () -> + context + .dsl() + .execute( + "DELETE FROM " + CAPTURE_TABLE + " WHERE operation_id = ?", + retained.operationId()), + "account_bare_login_token_identity_fence_immutable"); + assertSqlConstraint( + () -> context.dsl().execute("TRUNCATE TABLE " + CAPTURE_TABLE), + "account_bare_login_token_identity_fence_immutable"); + + assertThat(readCapture(context, retained.operationId())).isEqualTo(stored); + assertThat(captureCount(context, retained.operationId())).isEqualTo(1L); + } + + private TestContext newTestContext() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + SCHEMA); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(SCHEMA) + .defaultSchema(SCHEMA) + .placeholders(Map.of("serviceSchema", SCHEMA)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + dsl, + dataSource, + new AccountBareLoginExchangeRepository(dsl), + new AccountConnectTokenIssuanceRepository(dsl), + new AccountAuthorityGenerationRepository(dsl), + new AccountBareLoginTokenIdentityFenceRepository(dsl, dataSource), + new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + } + + private TokenFixture pendingFixture(TestContext context) { + Account account = newAccount(context); + initializeAccountAuthority(context, account); + return pendingFixture(context, account, true); + } + + private TokenFixture pendingFixture( + TestContext context, Account account, boolean recordOutgoingTokenEvidence) { + Source source = committedSource(context, account.id()); + AccountBareLoginExchangeIdentity identity = source.exchangeIdentity(); + byte[] requestDigest = uniqueDigest(); + var claim = + inTransaction( + context.transaction(), + () -> context.exchangeRepository().claim(identity, requestDigest)); + String tokenIdentity = "synthetic-delegation-jti-" + UUID.randomUUID(); + byte[] tokenHash = uniqueDigest(); + AccountEnvelopeBinding binding = + bareLoginBinding(claim.operation().operationId(), identity, requestDigest); + if (recordOutgoingTokenEvidence) { + inTransaction( + context.transaction(), + () -> { + context + .exchangeRepository() + .recordPendingEvidence( + claim, + requestDigest, + tokenIdentity, + tokenHash, + binding.contextEvidenceDigest(), + binding.authorityTupleDigest(), + binding.issuanceFenceDigest(), + binding.postconditionDigest()); + return null; + }); + } + return new TokenFixture( + account, + identity, + claim.operation().operationId(), + requestDigest, + tokenIdentity, + tokenHash, + claim, + binding); + } + + private Source committedSource(TestContext context, long accountId) { + AccountConnectTokenIssuanceIdentity sourceIdentity = + new AccountConnectTokenIssuanceIdentity( + accountId, + UUID.randomUUID(), + "synthetic-connect-scope-" + UUID.randomUUID(), + "synthetic-connect-request-" + UUID.randomUUID()); + byte[] requestDigest = uniqueDigest(); + var claim = + inTransaction( + context.transaction(), + () -> context.sourceRepository().claim(sourceIdentity, requestDigest)); + AccountEnvelopeBinding binding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + claim.operation().operationId().toString(), + sourceIdentity.requestId(), + Long.toString(sourceIdentity.accountId()), + sourceIdentity.tenantId().toString(), + sourceIdentity.connectScopeId(), + null, + requestDigest, + uniqueDigest(), + uniqueDigest(), + uniqueDigest(), + uniqueDigest()); + inTransaction( + context.transaction(), + () -> { + context + .sourceRepository() + .completeWithEnvelope( + claim, + requestDigest, + net.firedevops.firemud.accountservice.repository + .AccountConnectTokenIssuanceOperation.Lifecycle.COMMITTED, + "SUCCESS", + "synthetic-connect-jti-" + UUID.randomUUID(), + uniqueDigest(), + binding, + encryptedEnvelope(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE)); + return null; + }); + return new Source( + claim.operation().operationId(), + new AccountBareLoginExchangeIdentity( + claim.operation().operationId(), + accountId, + sourceIdentity.tenantId(), + sourceIdentity.connectScopeId(), + "synthetic-bare-login-request-" + UUID.randomUUID())); + } + + private Account newAccount(TestContext context) { + String unique = UUID.randomUUID().toString().replace("-", ""); + var row = + context + .dsl() + .resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) " + + "RETURNING id, account_uuid", + "bare_fence_" + unique.substring(0, 12), + unique + "@example.test", + "synthetic-test-hash") + .fetchOne(); + if (row == null) { + throw new IllegalStateException("Synthetic Account fixture was not inserted"); + } + return new Account(row.get("id", Long.class), row.get("account_uuid", UUID.class)); + } + + private void initializeAccountAuthority(TestContext context, Account account) { + inTransaction( + context.transaction(), + () -> context.authorityRepository().initialize(AuthorityScope.account(account.uuid()))); + } + + private AccountBareLoginTokenIdentityFence capture(TestContext context, TokenFixture fixture) { + return context + .repository() + .captureInitial( + fixture.identity(), + fixture.operationId(), + fixture.account().uuid(), + fixture.requestDigest(), + fixture.tokenIdentity(), + fixture.tokenHash()); + } + + private AccountBareLoginTokenIdentityFence requireInitial( + TestContext context, TokenFixture fixture) { + return context + .repository() + .requireInitial( + fixture.identity(), + fixture.operationId(), + fixture.account().uuid(), + fixture.requestDigest(), + fixture.tokenIdentity(), + fixture.tokenHash()); + } + + private void assertCaptureRejected( + TestContext context, + AccountBareLoginExchangeIdentity identity, + UUID operationId, + UUID accountUuid, + byte[] requestDigest, + String tokenIdentity, + byte[] tokenHash) { + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .captureInitial( + identity, + operationId, + accountUuid, + requestDigest, + tokenIdentity, + tokenHash))) + .isInstanceOf(IllegalStateException.class); + } + + private long captureCount(TestContext context, UUID operationId) { + Long count = + context + .dsl() + .resultQuery( + "SELECT COUNT(*) FROM " + CAPTURE_TABLE + " WHERE operation_id = ?", operationId) + .fetchOne(0, Long.class); + return count == null ? -1L : count; + } + + private void insertCaptureDirect( + TestContext context, + TokenFixture fixture, + UUID accountUuid, + long accountIssuanceFence, + long accountIssuanceFenceSourceVersion) { + context + .dsl() + .execute( + "INSERT INTO " + + CAPTURE_TABLE + + " (token_hash, schema_name, operation_id, source_connect_operation_id, account_id, " + + "account_uuid, tenant_id, connect_scope_hash, request_id, " + + "request_digest_version, request_digest, token_identity, profile, " + + "token_identity_fence, token_identity_fence_source_version, " + + "account_issuance_fence, account_issuance_fence_source_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, 1, 1, ?, ?)", + HexFormat.of().formatHex(fixture.tokenHash()), + AccountBareLoginTokenIdentityFence.SCHEMA_NAME, + fixture.operationId(), + fixture.identity().sourceConnectOperationId(), + fixture.identity().accountId(), + accountUuid, + fixture.identity().tenantId(), + AccountJoinDigest.tokenHash(fixture.identity().connectScopeId()), + fixture.identity().requestId(), + fixture.requestDigest(), + fixture.tokenIdentity(), + AccountBareLoginTokenIdentityFence.PROFILE_NAME, + accountIssuanceFence, + accountIssuanceFenceSourceVersion); + } + + private AccountEnvelopeBinding bareLoginBinding( + UUID operationId, AccountBareLoginExchangeIdentity identity, byte[] requestDigest) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + operationId.toString(), + identity.requestId(), + Long.toString(identity.accountId()), + identity.tenantId().toString(), + identity.connectScopeId(), + identity.sourceConnectOperationId().toString(), + requestDigest, + uniqueDigest(), + uniqueDigest(), + uniqueDigest(), + uniqueDigest()); + } + + private AccountBareLoginTokenIdentityFence readCapture(TestContext context, UUID operationId) { + var row = + context + .dsl() + .fetchOne( + "SELECT schema_name, token_hash, operation_id, source_connect_operation_id, " + + "account_id, account_uuid, tenant_id, connect_scope_hash, request_id, " + + "request_digest_version, request_digest, token_identity, profile, token_identity_fence, " + + "token_identity_fence_source_version, account_issuance_fence, " + + "account_issuance_fence_source_version, captured_at FROM " + + CAPTURE_TABLE + + " WHERE operation_id = ?", + operationId); + if (row == null) { + throw new IllegalStateException("Expected retained identity capture is absent"); + } + return new AccountBareLoginTokenIdentityFence( + row.get("schema_name", String.class), + row.get("operation_id", UUID.class), + row.get("source_connect_operation_id", UUID.class), + row.get("account_id", Long.class), + row.get("account_uuid", UUID.class), + row.get("tenant_id", UUID.class), + row.get("connect_scope_hash", String.class), + row.get("request_id", String.class), + row.get("request_digest_version", Integer.class), + row.get("request_digest", byte[].class), + row.get("profile", String.class), + row.get("token_identity", String.class), + HexFormat.of().parseHex(row.get("token_hash", String.class)), + row.get("token_identity_fence", Long.class), + row.get("token_identity_fence_source_version", Long.class), + row.get("account_issuance_fence", Long.class), + row.get("account_issuance_fence_source_version", Long.class), + row.get("captured_at", OffsetDateTime.class).toInstant()); + } + + private int currentBackendPid(TestContext context) { + Integer pid = context.dsl().resultQuery("SELECT pg_backend_pid()").fetchOne(0, Integer.class); + if (pid == null) { + throw new IllegalStateException("PostgreSQL did not return the transaction backend PID"); + } + return pid; + } + + private boolean awaitDatabaseBlock( + TestContext context, int waiterPid, int blockerPid, Duration timeout) + throws InterruptedException { + long deadline = System.nanoTime() + timeout.toNanos(); + while (System.nanoTime() < deadline) { + Boolean blocked = + context + .dsl() + .resultQuery( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity waiting " + + "WHERE waiting.pid = ? AND waiting.wait_event_type = 'Lock' " + + "AND ? = ANY(pg_blocking_pids(waiting.pid)))", + waiterPid, + blockerPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + + private void assertSqlConstraint(Runnable action, String constraint) { + assertThatThrownBy(action::run) + .isInstanceOf(DataAccessException.class) + .satisfies(failure -> assertPostgresConstraint(failure, constraint)); + } + + private void assertPostgresConstraint(Throwable failure, String expectedConstraint) { + Throwable cause = failure; + while (cause != null && !(cause instanceof PSQLException)) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(PSQLException.class); + PSQLException postgresFailure = (PSQLException) cause; + assertThat(postgresFailure.getServerErrorMessage().getConstraint()) + .isEqualTo(expectedConstraint); + } + + private AccountEncryptedEnvelope encryptedEnvelope(AccountEnvelopePurpose purpose) { + return new AccountEncryptedEnvelope( + AccountEncryptedEnvelope.CURRENT_FORMAT_VERSION, + "synthetic_key_1", + purpose, + new byte[AccountEncryptedEnvelope.NONCE_LENGTH_BYTES], + new byte[AccountEncryptedEnvelope.AUTHENTICATION_TAG_LENGTH_BYTES]); + } + + private static byte[] uniqueDigest() { + try { + return MessageDigest.getInstance("SHA-256") + .digest(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8)); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] digest(int seed) { + byte[] value = new byte[32]; + for (int index = 0; index < value.length; index++) { + value[index] = (byte) (seed + index); + } + return value; + } + + private static void await(CountDownLatch latch, String message) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException(message); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(message, exception); + } + } + + private T inTransaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record Account(long id, UUID uuid) {} + + private record Source(UUID operationId, AccountBareLoginExchangeIdentity exchangeIdentity) {} + + private record TokenFixture( + Account account, + AccountBareLoginExchangeIdentity identity, + UUID operationId, + byte[] requestDigest, + String tokenIdentity, + byte[] tokenHash, + AccountBareLoginExchangeRepository.ClaimResult claim, + AccountEnvelopeBinding binding) {} + + private record TestContext( + DSLContext dsl, + DataSource dataSource, + AccountBareLoginExchangeRepository exchangeRepository, + AccountConnectTokenIssuanceRepository sourceRepository, + AccountAuthorityGenerationRepository authorityRepository, + AccountBareLoginTokenIdentityFenceRepository repository, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java index 0c7bcb0e75..03a9f135c7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java @@ -4,16 +4,46 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; +import io.grpc.Context; +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.security.Signature; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import javax.sql.DataSource; 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.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.dto.AccountMembershipCaptureSources; import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; @@ -26,12 +56,30 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountCommittedConnectSource; +import net.firedevops.firemud.accountservice.repository.AccountConnectIssuanceFenceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation.Lifecycle; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository.ClaimResult; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; 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.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountBareLoginCurrentAuthorityReader; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader; +import net.firedevops.firemud.accountservice.service.AccountConnectTokenAuthorityCaptureService; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; @@ -41,6 +89,9 @@ import net.firedevops.firemud.accountservice.service.AccountTenantAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.GatewayConnectContextSignature; import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.v1.GameplayRealm; @@ -48,6 +99,7 @@ import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mail.javamail.JavaMailSender; @@ -60,6 +112,7 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -77,12 +130,17 @@ class AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest { private static final String WORKLOAD_NAMESPACE = "account-current-authority-test"; private static final String WORLD_SLUG = "current-authority-proof-world"; private static final String REALM_SLUG = "production"; - private static final String NAMESPACE_ID = "current-authority-proof-namespace"; + private static final String NAMESPACE_ID = "9f206856-6cf8-4cf6-8c0f-0b1af02c491a"; private static final UUID REALM_ID = UUID.fromString("7bda1169-a8a3-4b43-96a4-53f8579ac164"); private static final long GAME_INSTANCE_ID = 79L; private static final long CATALOG_REVISION = 31L; private static final long POINTER_VERSION = 13L; private static final String AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; + private static final String ACCOUNT_SOURCE_KEY_ID = "account-capture-proof-key"; + private static final String GATEWAY_CONTEXT_KEY_ID = "gateway-capture-proof-key"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Base64.Encoder BASE64_URL = Base64.getUrlEncoder().withoutPadding(); + private static final SecureRandom FIXTURE_RANDOM = new SecureRandom(); @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -91,6 +149,8 @@ class AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest { static GenericContainer redis = new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + @TempDir Path tempDir; + @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); @@ -104,11 +164,15 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private AccountAuthorityGenerationRepository authorityGenerationRepository; @Autowired private AccountAuthorityOutboxRepository authorityOutboxRepository; @Autowired private AccountRepository accountRepository; + @Autowired private AccountJoinOperationRepository joinOperationRepository; + @Autowired private AccountConnectTokenIssuanceRepository connectIssuanceRepository; @Autowired private AccountLogoutAllOperationRepository logoutAllOperationRepository; @Autowired private AccountPasswordResetOperationRepository passwordResetOperationRepository; @Autowired private ApprovedLegacyTenantAssociationRepository tenantAssociationRepository; + @Autowired private FreshTenantIdentityAssociationRepository freshTenantIdentityRepository; @Autowired private LegacyTenantSourceEvidence legacyTenantSourceEvidence; @Autowired private PlatformTransactionManager transactionManager; + @Autowired private DataSource dataSource; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @@ -391,16 +455,306 @@ void postJoinSnapshotCarriesCurrentCompositeSourcesWithoutRewritingMembershipEve assertThat(absentReadback.outboxCheckpoints()).isEqualTo(absent.outboxCheckpoints()); assertThat(absentReadback.outboxSourceEvidence()).isEqualTo(absent.outboxSourceEvidence()); - dsl.execute( - "UPDATE account_authority_generations SET generation = generation + 1, " - + "source_version = source_version + 1 WHERE scope_kind = 'ISSUER' AND issuer_id = ?", - AccountServiceImpl.ACCOUNT_JWT_ISSUER); - assertThatThrownBy(() -> readRuntimeMembershipSnapshot(fixture)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Current issuer source event differs from its generation"); + RuntimeMembershipSnapshotDto beforeIssuerCorruption = readRuntimeMembershipSnapshot(fixture); + new TransactionTemplate(transactionManager) + .execute( + status -> { + dsl.execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1 " + + "WHERE scope_kind = 'ISSUER' AND issuer_id = ?", + AccountServiceImpl.ACCOUNT_JWT_ISSUER); + assertThatThrownBy(() -> readRuntimeMembershipSnapshot(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current issuer source event differs from its generation"); + status.setRollbackOnly(); + return null; + }); + RuntimeMembershipSnapshotDto afterRollback = readRuntimeMembershipSnapshot(fixture); + assertThat(afterRollback.membershipBaseline()) + .isEqualTo(beforeIssuerCorruption.membershipBaseline()); + assertThat(afterRollback.roles()).isEqualTo(beforeIssuerCorruption.roles()); + assertThat(afterRollback.authorityTuple()).isEqualTo(beforeIssuerCorruption.authorityTuple()); + assertThat(afterRollback.issuanceFence()).isEqualTo(beforeIssuerCorruption.issuanceFence()); + assertThat(afterRollback.outboxCheckpoints()) + .isEqualTo(beforeIssuerCorruption.outboxCheckpoints()); + assertThat(afterRollback.outboxSourceEvidence()) + .isEqualTo(beforeIssuerCorruption.outboxSourceEvidence()); + assertThat(afterRollback.sourceEvent().canonicalJsonUtf8()) + .containsExactly(beforeIssuerCorruption.sourceEvent().canonicalJsonUtf8()); assertThat(membershipEventBytes(fixture)).containsExactly(immutableMembershipBytes); } + @Test + void captureSourcesPreserveIndependentlyAdvancedAuthorityVersionsAndCheckpoints() { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + byte[] immutableMembershipEvent = membershipEventBytes(fixture); + AccountMembershipCaptureSources beforeTransitions = readMembershipCaptureSources(fixture); + ScopeState initialIssuer = beforeTransitions.authoritySnapshot().issuer(); + ScopeState initialAccount = beforeTransitions.authoritySnapshot().account(); + ScopeState initialTenant = beforeTransitions.authoritySnapshot().tenants().getFirst(); + + UUID issuerRequestUuid = UUID.randomUUID(); + issuerProducer() + .advance( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + issuerRequestUuid, + initialIssuer.generation(), + initialIssuer.sourceVersion()); + long tenantGeneration = initialTenant.generation(); + long tenantSourceVersion = initialTenant.sourceVersion(); + for (int transition = 0; transition < 2; transition++) { + tenantProducer() + .advance(fixture.tenantUuid(), UUID.randomUUID(), tenantGeneration, tenantSourceVersion); + tenantGeneration++; + tenantSourceVersion++; + } + + AccountLogoutAllAuthorityEventProducer accountProducer = logoutProducer(); + for (int transition = 1; transition <= 3; transition++) { + String tokenHash = "f".repeat(63) + Integer.toHexString(transition); + String tokenProfile = "control-ui"; + String requestDigest = + AccountLogoutRequestDigest.accountLogoutAll( + fixture.accountUuid(), tokenProfile, tokenHash); + ScopeState expectedAccountState = readAccountAuthority(fixture.accountUuid()); + assertThat( + accountProducer.commit( + UUID.randomUUID(), + 1, + requestDigest, + tokenProfile, + tokenHash, + readAccount(fixture.accountId()), + expectedAccountState)) + .isEqualTo(AccountLogoutAllAuthorityEventProducer.LogoutAllResult.LOGOUT_ALL_COMMITTED); + } + + List> membershipBeforeRead = membershipAuthoritySourceFingerprint(fixture); + List> accountBeforeRead = accountSourceFingerprint(fixture); + long receiptCountBeforeRead = countMembershipTransitionReceipts(fixture); + long membershipEventsBeforeRead = countStreamEvents(membershipStreamKey(fixture)); + AccountMembershipCaptureSources sources = readMembershipCaptureSources(fixture); + + assertThat(sources.authoritySnapshot().issuer().generation()) + .isEqualTo(initialIssuer.generation() + 1L); + assertThat(sources.authoritySnapshot().issuer().sourceVersion()) + .isEqualTo(initialIssuer.sourceVersion() + 1L); + assertThat(sources.authoritySnapshot().account().generation()) + .isEqualTo(initialAccount.generation() + 3L); + assertThat(sources.authoritySnapshot().account().sourceVersion()) + .isEqualTo(initialAccount.sourceVersion() + 3L); + assertThat(sources.authoritySnapshot().tenants().getFirst().generation()) + .isEqualTo(initialTenant.generation() + 2L); + assertThat(sources.authoritySnapshot().tenants().getFirst().sourceVersion()) + .isEqualTo(initialTenant.sourceVersion() + 2L); + assertThat(sources.authoritySnapshot().memberships().getFirst().generation()).isEqualTo(1L); + assertThat(sources.authoritySnapshot().memberships().getFirst().sourceVersion()).isEqualTo(1L); + assertThat(sources.authoritySnapshot().issuanceFence().value()) + .isEqualTo(initialAccount.issuanceFence().value() + 3L); + assertThat(sources.authoritySnapshot().issuanceFence().sourceVersion()) + .isEqualTo(initialAccount.issuanceFence().sourceVersion() + 3L); + assertThat(sources.membershipSnapshot().authorityTuple().issuerAuthGeneration()) + .isEqualTo(Long.toString(initialIssuer.generation() + 1L)); + assertThat(sources.membershipSnapshot().authorityTuple().accountAuthorityGeneration()) + .isEqualTo(Long.toString(initialAccount.generation() + 3L)); + assertThat(sources.membershipSnapshot().authorityTuple().tenantAuthorityGeneration()) + .isEqualTo( + Map.of( + fixture.tenantUuid().toString(), Long.toString(initialTenant.generation() + 2L))); + assertThat(sources.membershipSnapshot().authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(sources.membershipSnapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(sources.membershipSnapshot().issuanceFence()) + .isEqualTo(Long.toString(initialAccount.issuanceFence().value() + 3L)); + long expectedAccountCheckpoint = + checkpoint(beforeTransitions, accountStreamKey(fixture.accountUuid())) + 3L; + long expectedIssuerCheckpoint = checkpoint(beforeTransitions, issuerStreamKey()) + 1L; + long expectedTenantCheckpoint = + checkpoint(beforeTransitions, tenantStreamKey(fixture.tenantUuid())) + 2L; + assertThat(sources.membershipSnapshot().outboxCheckpoints()) + .containsExactly( + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + accountStreamKey(fixture.accountUuid()), Long.toString(expectedAccountCheckpoint)), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + issuerStreamKey(), Long.toString(expectedIssuerCheckpoint)), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + membershipStreamKey(fixture), "1"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + tenantStreamKey(fixture.tenantUuid()), Long.toString(expectedTenantCheckpoint))); + assertThat(sources.membershipSnapshot().outboxSourceEvidence()) + .extracting(AccountMembershipAuthorityEventProducer.OutboxSourceEvidence::outboxStreamKey) + .containsExactly( + accountStreamKey(fixture.accountUuid()), + issuerStreamKey(), + membershipStreamKey(fixture), + tenantStreamKey(fixture.tenantUuid())); + assertThat(sources.membershipSnapshot().sourceEvent().canonicalJsonUtf8()) + .containsExactly(immutableMembershipEvent); + assertThat(membershipEventBytes(fixture)).containsExactly(immutableMembershipEvent); + + assertThat(membershipAuthoritySourceFingerprint(fixture)).isEqualTo(membershipBeforeRead); + assertThat(accountSourceFingerprint(fixture)).isEqualTo(accountBeforeRead); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(receiptCountBeforeRead); + assertThat(countStreamEvents(membershipStreamKey(fixture))) + .isEqualTo(membershipEventsBeforeRead); + } + + @Test + void historicalCaptureSourcesRemainUnchangedWhenCurrentMembershipAdvances() { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + AccountMembershipCaptureSources historical = readMembershipCaptureSources(fixture); + byte[] historicalEvent = historical.membershipSnapshot().sourceEvent().canonicalJsonUtf8(); + List> historicalFingerprint = membershipAuthoritySourceFingerprint(fixture); + + MembershipTransitionReceipt leave = + membershipLifecycleService.leave( + fixture.accountId(), fixture.tenantId(), "capture-history-leave-" + UUID.randomUUID()); + assertThat(leave.transitionType()).isEqualTo("MEMBERSHIP_LEFT"); + List> inactiveFingerprint = membershipAuthoritySourceFingerprint(fixture); + AccountMembershipCaptureSources current = readMembershipCaptureSources(fixture); + + assertThat(historical.membershipSnapshot().membershipBaseline().membershipLifecycleState()) + .isEqualTo("ACTIVE"); + assertThat(historical.membershipSnapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(historical.authoritySnapshot().memberships().getFirst().generation()).isEqualTo(1L); + assertThat(historical.authoritySnapshot().memberships().getFirst().sourceVersion()) + .isEqualTo(1L); + assertThat(historical.roleSource().orElseThrow().snapshotVersion()).isEqualTo(2L); + assertThat(historical.membershipSnapshot().sourceEvent().canonicalJsonUtf8()) + .containsExactly(historicalEvent); + + assertThat(current.membershipSnapshot().membershipBaseline().membershipLifecycleState()) + .isEqualTo("INACTIVE"); + assertThat(current.membershipSnapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "3")); + assertThat(current.authoritySnapshot().memberships().getFirst().generation()).isEqualTo(2L); + assertThat(current.authoritySnapshot().memberships().getFirst().sourceVersion()).isEqualTo(2L); + assertThat(current.roleSource().orElseThrow().snapshotVersion()).isEqualTo(3L); + assertThat(current.membershipSnapshot().sourceEvent().outboxSequence()).isEqualTo("2"); + assertThat(current.membershipSnapshot().sourceEvent().membershipLifecycleState()) + .isEqualTo("INACTIVE"); + assertThat(membershipEventBytes(fixture, 1L)).containsExactly(historicalEvent); + assertThat(membershipAuthoritySourceFingerprint(fixture)).isEqualTo(inactiveFingerprint); + assertThat(historical.membershipSnapshot().sourceEvent().canonicalJsonUtf8()) + .containsExactly(historicalEvent); + assertThat(historicalFingerprint).isNotEqualTo(inactiveFingerprint); + } + + @Test + void existingCaptureSourcesAuthenticateAbsenceAndRejectMixedSourceOrRoleEvidence() { + JoinFixture neverJoined = fixture(); + new TransactionTemplate(transactionManager) + .execute( + status -> { + membershipAuthorityEventProducer.preparePairAuthorityForJoin( + neverJoined.accountId(), neverJoined.tenantId()); + return null; + }); + List> absenceBeforeRead = membershipAuthoritySourceFingerprint(neverJoined); + AccountMembershipCaptureSources absence = readMembershipCaptureSources(neverJoined); + assertThat(absence.membershipSnapshot().membershipExists()).isFalse(); + assertThat(absence.membershipSnapshot().gameplayAdmissionAllowed()).isFalse(); + assertThat(absence.membershipSnapshot().membershipBaseline().membershipLifecycleState()) + .isEqualTo("MISSING"); + assertThat(absence.membershipSnapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(neverJoined.tenantUuid().toString(), "1")); + assertThat(absence.membershipSnapshot().sourceEvent()).isNull(); + assertThat(absence.roleSource()).isEmpty(); + assertThat(membershipAuthoritySourceFingerprint(neverJoined)).isEqualTo(absenceBeforeRead); + + var authority = absence.authoritySnapshot(); + var tenant = authority.tenants().getFirst(); + var mixedTenant = + new ScopeState(tenant.scope(), tenant.generation(), tenant.sourceVersion() + 1L, null); + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + neverJoined.accountUuid(), + neverJoined.tenantUuid(), + new AccountAuthorityGenerationRepository.CompositeSnapshot( + authority.issuer(), + authority.account(), + List.of(mixedTenant), + authority.memberships(), + authority.issuanceFence()), + absence.membershipSnapshot(), + absence.roleSource(), + absence.retainedTenantAssociation())) + .isInstanceOf(IllegalArgumentException.class); + + JoinFixture active = fixture(); + assertThat(join(active).success()).isTrue(); + List> activeBeforeRead = membershipAuthoritySourceFingerprint(active); + AccountMembershipCaptureSources existing = readMembershipCaptureSources(active); + assertThat(existing.roleSource().orElseThrow().accountUuid()).isEqualTo(active.accountUuid()); + assertThat(existing.roleSource().orElseThrow().tenantId()).isEqualTo(active.tenantId()); + assertThat(existing.roleSource().orElseThrow().tenantUuid()).isNull(); + assertThat(existing.roleSource().orElseThrow().tenantProvenance()).isNull(); + assertThat(existing.retainedTenantAssociation()) + .hasValueSatisfying( + association -> { + assertThat(association.canonicalTenantId()).isEqualTo(active.tenantUuid()); + assertThat(association.legacyTenantId()).isEqualTo(active.tenantId()); + }); + RuntimeMembershipSnapshotDto existingMembership = existing.membershipSnapshot(); + List mixedCheckpoints = + existingMembership.outboxCheckpoints().stream() + .map( + checkpoint -> + checkpoint.outboxStreamKey().equals(membershipStreamKey(active)) + ? new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + membershipStreamKey(active), + Long.toString(Long.parseLong(checkpoint.outboxSequence()) + 1L)) + : checkpoint) + .toList(); + assertThatThrownBy( + () -> + new RuntimeMembershipSnapshotDto( + existingMembership.requestAccountUuid(), + existingMembership.requestTenantUuid(), + existingMembership.accountUuid(), + existingMembership.tenantUuid(), + existingMembership.membershipExists(), + existingMembership.gameplayAdmissionAllowed(), + existingMembership.membershipBaseline(), + existingMembership.roles(), + existingMembership.authorityTuple(), + existingMembership.issuanceFence(), + existingMembership.evaluatedAt(), + mixedCheckpoints, + existingMembership.outboxSourceEvidence(), + existingMembership.sourceEvent())) + .isInstanceOf(IllegalArgumentException.class); + + RoleSnapshot role = existing.roleSource().orElseThrow(); + RoleSnapshot mixedRoleHeader = + new RoleSnapshot( + role.accountId(), + role.tenantId(), + role.membershipId(), + role.snapshotVersion() + 1L, + role.roles(), + role.accountUuid(), + role.tenantUuid(), + role.tenantProvenance()); + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + active.accountUuid(), + active.tenantUuid(), + existing.authoritySnapshot(), + existing.membershipSnapshot(), + Optional.of(mixedRoleHeader), + existing.retainedTenantAssociation())) + .isInstanceOf(IllegalArgumentException.class); + assertThat(membershipAuthoritySourceFingerprint(active)).isEqualTo(activeBeforeRead); + } + @Test void membershipSourceReaderReadsRetainedInactiveRetryAndReactivationWithoutMutation() { JoinFixture fixture = fixture(); @@ -524,6 +878,1507 @@ void membershipSourceReaderReadsRetainedInactiveRetryAndReactivationWithoutMutat assertThat(countStreamEvents(membershipStreamKey(fixture))).isEqualTo(activeEventCount); } + @Test + void activeMembershipCaptureCommitsBesideSyntheticV35SourceAndExactReadbackDoesNotRewriteIt() { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + RuntimeMembershipSnapshotDto membershipBefore = readRuntimeMembershipSnapshot(fixture); + List> accountSourceBefore = accountSourceFingerprint(fixture); + + ConnectSourceFixture source = createCommittedConnectSource(fixture, true); + assertThat(source.evidence().accountUuid()).isEqualTo(fixture.accountUuid()); + assertThat(source.evidence().tenantUuid()).isEqualTo(fixture.tenantUuid()); + assertThat(source.evidence().issuanceFence()).isEqualTo(accountIssuanceFence(fixture)); + assertThat(source.evidence().fenceSourceVersion()) + .isEqualTo(accountIssuanceFenceSourceVersion(fixture)); + assertThat(source.evidence().digest()) + .containsExactly(independentlyRehashCapture(source.evidence())); + assertThat(source.binding().issuanceFenceDigest()).containsExactly(source.evidence().digest()); + + String operationBeforeRead = operationFingerprint(source.claim().operation().operationId()); + String envelopeBeforeRead = envelopeFingerprint(source.claim().operation().operationId()); + CaptureReadback readback = + ownerTransaction( + () -> + new CaptureReadback( + captureService().read(source.identity(), source.requestDigest()).orElseThrow(), + connectIssuanceRepository + .readCommittedResponseEnvelope(source.identity()) + .orElseThrow())); + + assertThat(readback.evidence()).isEqualTo(source.evidence()); + assertThat(readback.source().operation().operationId()) + .isEqualTo(source.claim().operation().operationId()); + assertThat(readback.source().operation().issuanceFenceDigest()) + .containsExactly(source.evidence().digest()); + assertThat(readback.source().responseEnvelope().binding()).isEqualTo(source.binding()); + assertThat(readback.source().responseEnvelope().envelope()).isEqualTo(source.envelope()); + assertThat(operationFingerprint(source.claim().operation().operationId())) + .isEqualTo(operationBeforeRead); + assertThat(envelopeFingerprint(source.claim().operation().operationId())) + .isEqualTo(envelopeBeforeRead); + assertThat(accountSourceFingerprint(fixture)).isEqualTo(accountSourceBefore); + + RuntimeMembershipSnapshotDto membershipAfter = readRuntimeMembershipSnapshot(fixture); + assertThat(membershipAfter.membershipBaseline()) + .isEqualTo(membershipBefore.membershipBaseline()); + assertThat(membershipAfter.roles()).isEqualTo(membershipBefore.roles()); + assertThat(membershipAfter.authorityTuple()).isEqualTo(membershipBefore.authorityTuple()); + assertThat(membershipAfter.issuanceFence()).isEqualTo(membershipBefore.issuanceFence()); + assertThat(membershipAfter.sourceEvent().canonicalJsonUtf8()) + .containsExactly(membershipBefore.sourceEvent().canonicalJsonUtf8()); + assertThat(membershipAfter.outboxCheckpoints()).isEqualTo(membershipBefore.outboxCheckpoints()); + assertThat(membershipAfter.outboxSourceEvidence()) + .isEqualTo(membershipBefore.outboxSourceEvidence()); + } + + @Test + void bareLoginCurrentAuthorityReaderReturnsExactRedactedReadbackWithoutMutation() + throws Exception { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + ComposedConnectSourceFixture source = createCryptographicConnectSource(fixture, true); + String operationBefore = operationFingerprint(source.claim().operation().operationId()); + String envelopeBefore = envelopeFingerprint(source.claim().operation().operationId()); + List> accountSourceBefore = accountSourceFingerprint(fixture); + + AccountBareLoginCurrentAuthorityReader.CurrentAuthorityReadback readback = + readCurrentAuthority(source, source.requestDigest()); + + assertThat(readback.operationId()).isEqualTo(source.claim().operation().operationId()); + assertThat(readback.accountUuid()).isEqualTo(fixture.accountUuid()); + assertThat(readback.tenantUuid()).isEqualTo(fixture.tenantUuid()); + assertThat(readback.requestId()).isEqualTo(source.identity().requestId()); + assertThat(readback.connectScopeHash()) + .isEqualTo(AccountJoinDigest.tokenHash(source.identity().connectScopeId())); + assertThat(readback.responseEnvelopeKeyId()).isEqualTo(source.envelope().keyId()); + assertThat(readback.gatewayKeyId()).isEqualTo(GATEWAY_CONTEXT_KEY_ID); + assertThat(readback.sourceTokenHash()).containsExactly(sha256(source.compactJwt())); + assertThat(readback.authorityTuple()).isEqualTo(source.membershipSnapshot().authorityTuple()); + assertThat(readback.membershipVersion()) + .isEqualTo(source.membershipSnapshot().membershipBaseline().membershipVersion()); + assertThat(readback.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(readback.roles()).contains("player"); + assertThat(source.capture().accountUuid()).isEqualTo(fixture.accountUuid()); + assertThat(source.capture().tenantUuid()).isEqualTo(fixture.tenantUuid()); + assertThat(source.capture().issuanceFence()).isEqualTo(accountIssuanceFence(fixture)); + assertThat(source.capture().fenceSourceVersion()) + .isEqualTo(accountIssuanceFenceSourceVersion(fixture)); + assertThat(source.capture().digest()) + .containsExactly(independentlyRehashCapture(source.capture())); + assertThat(source.binding().issuanceFenceDigest()).containsExactly(source.capture().digest()); + assertThat(readback.issuanceFence()).isEqualTo(source.capture().issuanceFence()); + assertThat(readback.fenceSourceVersion()).isEqualTo(source.capture().fenceSourceVersion()); + assertThat(readback.requestDigest()).containsExactly(source.requestDigest()); + assertThat(readback.captureDigest()).containsExactly(source.capture().digest()); + assertThat(readback.checkpoints()) + .containsExactlyElementsOf( + source.membershipSnapshot().outboxCheckpoints().stream() + .map( + checkpoint -> + new AccountBareLoginCurrentAuthorityReader.CheckpointReadback( + checkpoint.outboxStreamKey(), checkpoint.outboxSequence())) + .toList()); + assertThat(readback.sourceEvents()) + .containsExactlyElementsOf( + source.membershipSnapshot().outboxSourceEvidence().stream() + .map( + evidence -> + new AccountBareLoginCurrentAuthorityReader.SourceEventReadback( + evidence.outboxStreamKey(), + evidence.outboxSequence(), + evidence.eventId(), + evidence.eventDigest())) + .toList()); + assertThat(source.sourceClaims()).doesNotContainKey("issuanceFence"); + assertThat((BigInteger) source.sourceClaims().get("replayAdmissionFence")) + .isNotEqualTo(BigInteger.valueOf(source.capture().issuanceFence())); + assertThat(readback.toString()) + .doesNotContain(source.identity().connectScopeId()) + .doesNotContain(source.identity().requestId()) + .doesNotContain(source.tokenIdentity()) + .doesNotContain(source.compactJwt()) + .doesNotContain(source.signedGatewayContext()); + + assertThatThrownBy(() -> readCurrentAuthority(source, digest(132))) + .isInstanceOf(AccountConnectTokenIssuanceRepository.IdempotencyConflictException.class); + assertThat(operationFingerprint(source.claim().operation().operationId())) + .isEqualTo(operationBefore); + assertThat(envelopeFingerprint(source.claim().operation().operationId())) + .isEqualTo(envelopeBefore); + assertThat(accountSourceFingerprint(fixture)).isEqualTo(accountSourceBefore); + } + + @Test + void bareLoginCurrentAuthorityReaderRejectsMissingCaptureForValidCommittedSource() + throws Exception { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + ComposedConnectSourceFixture source = createCryptographicConnectSource(fixture, false); + String operationBefore = operationFingerprint(source.claim().operation().operationId()); + String envelopeBefore = envelopeFingerprint(source.claim().operation().operationId()); + List> accountSourceBefore = accountSourceFingerprint(fixture); + + assertThatThrownBy(() -> readCurrentAuthority(source, source.requestDigest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact Account issuance-fence capture is not proved"); + + assertThat( + ownerTransaction( + () -> + connectIssuanceRepository.readIssuanceFenceCapture( + source.identity(), source.requestDigest()))) + .isEmpty(); + assertThat(operationFingerprint(source.claim().operation().operationId())) + .isEqualTo(operationBefore); + assertThat(envelopeFingerprint(source.claim().operation().operationId())) + .isEqualTo(envelopeBefore); + assertThat(accountSourceFingerprint(fixture)).isEqualTo(accountSourceBefore); + } + + @Test + void bareLoginCurrentAuthorityReaderRechecksDeadlineAfterAuthorityRead() throws Exception { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + ComposedConnectSourceFixture source = createCryptographicConnectSource(fixture, true); + UUID operationId = source.claim().operation().operationId(); + String operationBefore = operationFingerprint(operationId); + String envelopeBefore = envelopeFingerprint(operationId); + List> accountSourceBefore = accountSourceFingerprint(fixture); + // The first strict source read consumes four clock reads; the fifth forces its final reread + // past both signed deadlines after the current-authority reads have completed. + source.clock().expireAfterReads(5, Duration.ofSeconds(21)); + + assertThatThrownBy(() -> readCurrentAuthority(source, source.requestDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Gateway context is expired"); + + assertThat(operationFingerprint(operationId)).isEqualTo(operationBefore); + assertThat(envelopeFingerprint(operationId)).isEqualTo(envelopeBefore); + assertThat(accountSourceFingerprint(fixture)).isEqualTo(accountSourceBefore); + assertThat( + ownerTransaction( + () -> + connectIssuanceRepository + .readIssuanceFenceCapture(source.identity(), source.requestDigest()) + .orElseThrow())) + .isEqualTo(source.capture()); + } + + @Test + void bareLoginCurrentAuthorityReaderRejectsSourceAfterAccountAuthorityAndFenceAdvance() + throws Exception { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + ComposedConnectSourceFixture source = createCryptographicConnectSource(fixture, true); + UUID operationId = source.claim().operation().operationId(); + long fenceBefore = accountIssuanceFence(fixture); + ScopeState expectedAccountState = readAccountAuthority(fixture.accountUuid()); + Account account = readAccount(fixture.accountId()); + String presentedTokenHash = "c".repeat(64); + String logoutDigest = + AccountLogoutRequestDigest.accountLogoutAll( + fixture.accountUuid(), "control-ui", presentedTokenHash); + + assertThat( + logoutProducer() + .commit( + UUID.randomUUID(), + 1, + logoutDigest, + "control-ui", + presentedTokenHash, + account, + expectedAccountState)) + .isEqualTo(AccountLogoutAllAuthorityEventProducer.LogoutAllResult.LOGOUT_ALL_COMMITTED); + RuntimeMembershipSnapshotDto afterAdvance = readRuntimeMembershipSnapshot(fixture); + assertThat(afterAdvance.authorityTuple().accountAuthorityGeneration()) + .isEqualTo(Long.toString(expectedAccountState.generation() + 1L)); + assertThat(afterAdvance.issuanceFence()).isEqualTo(Long.toString(fenceBefore + 1L)); + List> accountSourceAfterAdvance = accountSourceFingerprint(fixture); + byte[] membershipEventAfterAdvance = membershipEventBytes(fixture); + String operationBefore = operationFingerprint(operationId); + String envelopeBefore = envelopeFingerprint(operationId); + + assertThatThrownBy(() -> readCurrentAuthority(source, source.requestDigest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Committed gameplay-connect source differs from current Account authority"); + + assertThat(operationFingerprint(operationId)).isEqualTo(operationBefore); + assertThat(envelopeFingerprint(operationId)).isEqualTo(envelopeBefore); + assertThat( + ownerTransaction( + () -> + connectIssuanceRepository + .readIssuanceFenceCapture(source.identity(), source.requestDigest()) + .orElseThrow())) + .isEqualTo(source.capture()); + assertThat(accountSourceFingerprint(fixture)).isEqualTo(accountSourceAfterAdvance); + assertThat(membershipEventBytes(fixture)).containsExactly(membershipEventAfterAdvance); + assertThat(membershipRow(fixture).get("lifecycle_state")).isEqualTo("ACTIVE"); + } + + @Test + void concurrentCaptureWaitsForAccountOwnerAdvanceAndBindsTheNewFence() throws Exception { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + AccountConnectTokenIssuanceIdentity identity = connectIdentity(fixture); + byte[] requestDigest = digest(141); + ClaimResult claim = + ownerTransaction(() -> connectIssuanceRepository.claim(identity, requestDigest)); + RuntimeMembershipSnapshotDto membershipBefore = readRuntimeMembershipSnapshot(fixture); + List> membershipSourceBefore = membershipAuthoritySourceFingerprint(fixture); + byte[] membershipEventBefore = membershipEventBytes(fixture); + long fenceBefore = accountIssuanceFence(fixture); + long fenceSourceVersionBefore = accountIssuanceFenceSourceVersion(fixture); + ScopeState expectedAccountState = readAccountAuthority(fixture.accountUuid()); + Account account = readAccount(fixture.accountId()); + UUID logoutRequestId = UUID.randomUUID(); + String presentedTokenHash = "d".repeat(64); + String logoutDigest = + AccountLogoutRequestDigest.accountLogoutAll( + fixture.accountUuid(), "control-ui", presentedTokenHash); + CountDownLatch authorityRowLocked = new CountDownLatch(1); + CountDownLatch releaseAuthorityRow = new CountDownLatch(1); + CountDownLatch captureTransactionStarted = new CountDownLatch(1); + AtomicInteger authorityHolderPid = new AtomicInteger(); + AtomicInteger captureWaiterPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(3); + + try { + Future authorityHolder = + executor.submit( + () -> + ownerTransaction( + () -> { + authorityGenerationRepository.read( + AuthorityScope.account(fixture.accountUuid())); + authorityHolderPid.set(currentBackendPid()); + authorityRowLocked.countDown(); + awaitLatch(releaseAuthorityRow); + return null; + })); + assertThat(authorityRowLocked.await(20, TimeUnit.SECONDS)).isTrue(); + + Future advance = + executor.submit( + () -> + logoutProducer() + .commit( + logoutRequestId, + 1, + logoutDigest, + "control-ui", + presentedTokenHash, + account, + expectedAccountState)); + int advancePid = + awaitAccountAdvanceBlockedOnGeneration( + dsl, authorityHolderPid.get(), Duration.ofSeconds(10)); + assertThat(advancePid) + .as("the real logout-all owner already holds its Account row while waiting on authority") + .isPositive(); + + Future capture = + executor.submit( + () -> + ownerTransaction( + () -> { + captureWaiterPid.set(currentBackendPid()); + captureTransactionStarted.countDown(); + return captureService().capture(claim, requestDigest); + })); + assertThat(captureTransactionStarted.await(20, TimeUnit.SECONDS)).isTrue(); + assertThat( + awaitDatabaseBlock( + dsl, captureWaiterPid.get(), advancePid, "%accounts%", Duration.ofSeconds(10))) + .as("capture blocks on the logout-all transaction's Account row lock") + .isTrue(); + + releaseAuthorityRow.countDown(); + assertThat(advance.get(45, TimeUnit.SECONDS)) + .isEqualTo(AccountLogoutAllAuthorityEventProducer.LogoutAllResult.LOGOUT_ALL_COMMITTED); + authorityHolder.get(45, TimeUnit.SECONDS); + AccountConnectIssuanceFenceEvidence captured = capture.get(45, TimeUnit.SECONDS); + + RuntimeMembershipSnapshotDto membershipAfter = readRuntimeMembershipSnapshot(fixture); + assertThat(membershipAfter.authorityTuple().accountAuthorityGeneration()) + .isEqualTo(Long.toString(expectedAccountState.generation() + 1L)); + assertThat(membershipAfter.issuanceFence()).isEqualTo(Long.toString(fenceBefore + 1L)); + assertThat(membershipAfter.membershipBaseline()) + .isEqualTo(membershipBefore.membershipBaseline()); + assertThat(membershipAfter.roles()).isEqualTo(membershipBefore.roles()); + assertThat(membershipAfter.membershipBaseline().membershipLifecycleState()) + .isEqualTo("ACTIVE"); + assertThat(membershipAfter.roles()).contains("player"); + assertThat(captured.issuanceFence()).isEqualTo(fenceBefore + 1L); + assertThat(captured.fenceSourceVersion()).isEqualTo(fenceSourceVersionBefore + 1L); + assertThat(captured.fenceSourceVersion()) + .isEqualTo(accountIssuanceFenceSourceVersion(fixture)); + assertThat( + ownerTransaction( + () -> + connectIssuanceRepository + .readIssuanceFenceCapture(identity, requestDigest) + .orElseThrow())) + .isEqualTo(captured); + assertThat(countConnectEnvelopes(identity)).isZero(); + assertThat(membershipAuthoritySourceFingerprint(fixture)).isEqualTo(membershipSourceBefore); + assertThat(membershipEventBytes(fixture)).containsExactly(membershipEventBefore); + } finally { + releaseAuthorityRow.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(20, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void concurrentCurrentAuthorityReadWaitsForAdvanceThenRejectsOriginalSource() throws Exception { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + ComposedConnectSourceFixture source = createCryptographicConnectSource(fixture, true); + UUID operationId = source.claim().operation().operationId(); + String operationBefore = operationFingerprint(operationId); + String envelopeBefore = envelopeFingerprint(operationId); + List> membershipSourceBefore = membershipAuthoritySourceFingerprint(fixture); + byte[] membershipEventBefore = membershipEventBytes(fixture); + ScopeState expectedAccountState = readAccountAuthority(fixture.accountUuid()); + Account account = readAccount(fixture.accountId()); + long fenceBefore = accountIssuanceFence(fixture); + UUID logoutRequestId = UUID.randomUUID(); + String presentedTokenHash = "e".repeat(64); + String logoutDigest = + AccountLogoutRequestDigest.accountLogoutAll( + fixture.accountUuid(), "control-ui", presentedTokenHash); + CountDownLatch authorityRowLocked = new CountDownLatch(1); + CountDownLatch releaseAuthorityRow = new CountDownLatch(1); + CountDownLatch readTransactionStarted = new CountDownLatch(1); + AtomicInteger authorityHolderPid = new AtomicInteger(); + AtomicInteger readWaiterPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(3); + + try { + Future authorityHolder = + executor.submit( + () -> + ownerTransaction( + () -> { + authorityGenerationRepository.read( + AuthorityScope.account(fixture.accountUuid())); + authorityHolderPid.set(currentBackendPid()); + authorityRowLocked.countDown(); + awaitLatch(releaseAuthorityRow); + return null; + })); + assertThat(authorityRowLocked.await(20, TimeUnit.SECONDS)).isTrue(); + + Future advance = + executor.submit( + () -> + logoutProducer() + .commit( + logoutRequestId, + 1, + logoutDigest, + "control-ui", + presentedTokenHash, + account, + expectedAccountState)); + int advancePid = + awaitAccountAdvanceBlockedOnGeneration( + dsl, authorityHolderPid.get(), Duration.ofSeconds(10)); + assertThat(advancePid) + .as("the real logout-all owner already holds its Account row while waiting on authority") + .isPositive(); + + Future currentRead = + executor.submit( + () -> + withGameSessionPeer( + () -> + ownerTransaction( + () -> { + readWaiterPid.set(currentBackendPid()); + readTransactionStarted.countDown(); + return source + .reader() + .read( + source.identity(), + source.requestDigest(), + source.signedGatewayContext()); + }))); + assertThat(readTransactionStarted.await(20, TimeUnit.SECONDS)).isTrue(); + assertThat( + awaitDatabaseBlock( + dsl, readWaiterPid.get(), advancePid, "%accounts%", Duration.ofSeconds(10))) + .as("the original-source reader blocks on the logout-all Account row lock") + .isTrue(); + + releaseAuthorityRow.countDown(); + assertThat(advance.get(45, TimeUnit.SECONDS)) + .isEqualTo(AccountLogoutAllAuthorityEventProducer.LogoutAllResult.LOGOUT_ALL_COMMITTED); + authorityHolder.get(45, TimeUnit.SECONDS); + assertThatThrownBy(() -> currentRead.get(45, TimeUnit.SECONDS)) + .hasCauseInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Committed gameplay-connect source differs from current Account authority"); + + RuntimeMembershipSnapshotDto membershipAfter = readRuntimeMembershipSnapshot(fixture); + assertThat(membershipAfter.authorityTuple().accountAuthorityGeneration()) + .isEqualTo(Long.toString(expectedAccountState.generation() + 1L)); + assertThat(membershipAfter.issuanceFence()).isEqualTo(Long.toString(fenceBefore + 1L)); + assertThat(membershipAfter.membershipBaseline().membershipLifecycleState()) + .isEqualTo("ACTIVE"); + assertThat(operationFingerprint(operationId)).isEqualTo(operationBefore); + assertThat(envelopeFingerprint(operationId)).isEqualTo(envelopeBefore); + assertThat( + ownerTransaction( + () -> + connectIssuanceRepository + .readIssuanceFenceCapture(source.identity(), source.requestDigest()) + .orElseThrow())) + .isEqualTo(source.capture()); + assertThat(membershipAuthoritySourceFingerprint(fixture)).isEqualTo(membershipSourceBefore); + assertThat(membershipEventBytes(fixture)).containsExactly(membershipEventBefore); + } finally { + releaseAuthorityRow.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(20, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void captureRollbackLeavesNeitherCaptureNorPartialCommittedSource() { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + List> accountSourceBefore = accountSourceFingerprint(fixture); + AccountConnectTokenIssuanceIdentity identity = connectIdentity(fixture); + byte[] requestDigest = digest(117); + + new TransactionTemplate(transactionManager) + .execute( + status -> { + ClaimResult claim = connectIssuanceRepository.claim(identity, requestDigest); + AccountConnectIssuanceFenceEvidence evidence = + captureService().capture(claim, requestDigest); + AccountEnvelopeBinding binding = + connectSourceBinding(claim, identity, requestDigest, evidence.digest()); + connectIssuanceRepository.completeWithEnvelope( + claim, + requestDigest, + Lifecycle.COMMITTED, + "SUCCESS", + syntheticTokenIdentity(), + digest(118), + binding, + syntheticEnvelope()); + status.setRollbackOnly(); + return null; + }); + + assertThat( + ownerTransaction( + () -> connectIssuanceRepository.find(identity, requestDigest).orElse(null))) + .isNull(); + assertThat(countConnectEnvelopes(identity)).isZero(); + assertThat(accountSourceFingerprint(fixture)).isEqualTo(accountSourceBefore); + assertThat(countMembershipRows(fixture)).isEqualTo(1L); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(1L); + assertThat(countStreamEvents(membershipStreamKey(fixture))).isEqualTo(1L); + } + + @Test + void absentAndInactiveMembershipRejectCaptureWithoutInitializingOrRejoining() { + JoinFixture neverJoined = fixture(); + assertCaptureRejectedWithoutMembershipMutation(neverJoined, false); + + JoinFixture inactive = fixture(); + assertThat(join(inactive).success()).isTrue(); + MembershipTransitionReceipt leftReceipt = + membershipLifecycleService.leave( + inactive.accountId(), inactive.tenantId(), "capture-left-" + UUID.randomUUID()); + assertThat(leftReceipt.transitionType()).isEqualTo("MEMBERSHIP_LEFT"); + assertCaptureRejectedWithoutMembershipMutation(inactive, true); + } + + @Test + void capturedEvidenceCannotBeReplacedByChangedIdentityDigestOrFenceValues() { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + ConnectClaimFixture claim = claimAndCapture(fixture); + assertThat(claim.claim().operation().lifecycle()).isEqualTo(Lifecycle.PENDING); + assertThat(countConnectEnvelopes(claim.identity())).isZero(); + String operationBefore = operationFingerprint(claim.claim().operation().operationId()); + AccountConnectIssuanceFenceEvidence original = claim.evidence(); + + assertCaptureReplacementRejected( + claim, + AccountConnectIssuanceFenceEvidence.capture( + UUID.randomUUID(), + original.accountUuid(), + original.tenantUuid(), + original.connectScopeHash(), + original.requestId(), + original.requestDigest(), + original.issuanceFence(), + original.fenceSourceVersion())); + assertCaptureReplacementRejected( + claim, + AccountConnectIssuanceFenceEvidence.capture( + original.operationId(), + UUID.randomUUID(), + original.tenantUuid(), + original.connectScopeHash(), + original.requestId(), + original.requestDigest(), + original.issuanceFence(), + original.fenceSourceVersion())); + assertCaptureReplacementRejected( + claim, + AccountConnectIssuanceFenceEvidence.capture( + original.operationId(), + original.accountUuid(), + UUID.randomUUID(), + original.connectScopeHash(), + original.requestId(), + original.requestDigest(), + original.issuanceFence(), + original.fenceSourceVersion())); + assertCaptureReplacementRejected( + claim, + AccountConnectIssuanceFenceEvidence.capture( + original.operationId(), + original.accountUuid(), + original.tenantUuid(), + AccountJoinDigest.tokenHash("changed-connect-scope"), + original.requestId(), + original.requestDigest(), + original.issuanceFence(), + original.fenceSourceVersion())); + assertCaptureReplacementRejected( + claim, + AccountConnectIssuanceFenceEvidence.capture( + original.operationId(), + original.accountUuid(), + original.tenantUuid(), + original.connectScopeHash(), + "changed-request-id", + original.requestDigest(), + original.issuanceFence(), + original.fenceSourceVersion())); + assertCaptureReplacementRejected( + claim, + AccountConnectIssuanceFenceEvidence.capture( + original.operationId(), + original.accountUuid(), + original.tenantUuid(), + original.connectScopeHash(), + original.requestId(), + digest(119), + original.issuanceFence(), + original.fenceSourceVersion())); + assertCaptureReplacementRejected( + claim, + AccountConnectIssuanceFenceEvidence.capture( + original.operationId(), + original.accountUuid(), + original.tenantUuid(), + original.connectScopeHash(), + original.requestId(), + original.requestDigest(), + original.issuanceFence() + 1L, + original.fenceSourceVersion())); + assertCaptureReplacementRejected( + claim, + AccountConnectIssuanceFenceEvidence.capture( + original.operationId(), + original.accountUuid(), + original.tenantUuid(), + original.connectScopeHash(), + original.requestId(), + original.requestDigest(), + original.issuanceFence(), + original.fenceSourceVersion() + 1L)); + assertThatThrownBy( + () -> ownerTransaction(() -> captureService().capture(claim.claim(), digest(120)))) + .isInstanceOf(AccountConnectTokenIssuanceRepository.IdempotencyConflictException.class); + + assertThat(operationFingerprint(claim.claim().operation().operationId())) + .isEqualTo(operationBefore); + assertThat( + ownerTransaction( + () -> captureService().read(claim.identity(), claim.requestDigest()).orElseThrow())) + .isEqualTo(original); + } + + @Test + void directRepositoryRejectsCaptureForAnotherPersistedAccountUuid() { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + AccountConnectTokenIssuanceIdentity identity = connectIdentity(fixture); + byte[] requestDigest = digest(130); + ClaimResult claim = + ownerTransaction(() -> connectIssuanceRepository.claim(identity, requestDigest)); + long foreignAccountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES (?, ?, ?) RETURNING id", + "capture-f-" + UUID.randomUUID(), + "capture-foreign-" + UUID.randomUUID() + "@example.com", + "test-hash") + .fetchOne(0, Long.class)); + UUID foreignAccountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", foreignAccountId) + .fetchOne(0, UUID.class)); + assertThat(foreignAccountId).isNotEqualTo(fixture.accountId()); + assertThat(foreignAccountUuid).isNotEqualTo(fixture.accountUuid()); + AccountConnectIssuanceFenceEvidence foreignAccountEvidence = + AccountConnectIssuanceFenceEvidence.capture( + claim.operation().operationId(), + foreignAccountUuid, + fixture.tenantUuid(), + AccountJoinDigest.tokenHash(identity.connectScopeId()), + identity.requestId(), + requestDigest, + accountIssuanceFence(fixture), + accountIssuanceFenceSourceVersion(fixture)); + String operationBefore = operationFingerprint(claim.operation().operationId()); + List> accountSourceBefore = accountSourceFingerprint(fixture); + + assertThatThrownBy( + () -> + ownerTransaction( + () -> + connectIssuanceRepository.captureIssuanceFence( + claim, requestDigest, foreignAccountEvidence))) + .isInstanceOf(AccountConnectTokenIssuanceRepository.EvidenceMismatchException.class) + .hasMessageContaining("exact Account UUID provenance"); + + assertThat(operationFingerprint(claim.operation().operationId())).isEqualTo(operationBefore); + assertThat(accountSourceFingerprint(fixture)).isEqualTo(accountSourceBefore); + assertThat(countConnectEnvelopes(identity)).isZero(); + assertThat( + ownerTransaction( + () -> connectIssuanceRepository.readIssuanceFenceCapture(identity, requestDigest))) + .isEmpty(); + } + + @Test + void populatedCaptureIsImmutableAndTerminalSourceCannotBeBackfilled() { + JoinFixture fixture = fixture(); + assertThat(join(fixture).success()).isTrue(); + ConnectSourceFixture committed = createCommittedConnectSource(fixture, true); + UUID operationId = committed.claim().operation().operationId(); + String operationBefore = operationFingerprint(operationId); + String envelopeBefore = envelopeFingerprint(operationId); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_connect_token_issuance_operations " + + "SET issuance_fence_capture_value = ? WHERE operation_id = ?", + committed.evidence().issuanceFence() + 1L, + operationId)) + .hasMessageContaining("capture cannot be replaced or removed"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_connect_token_issuance_operations SET " + + "issuance_fence_capture_schema = NULL, " + + "issuance_fence_capture_account_uuid = NULL, " + + "issuance_fence_capture_value = NULL, " + + "issuance_fence_capture_source_version = NULL, " + + "issuance_fence_capture_digest = NULL WHERE operation_id = ?", + operationId)) + .hasMessageContaining("capture cannot be replaced or removed"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_connect_token_response_envelopes SET ciphertext = ? " + + "WHERE operation_id = ?", + new byte[AccountEncryptedEnvelope.AUTHENTICATION_TAG_LENGTH_BYTES], + operationId)) + .hasMessageContaining("response envelope is immutable"); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM account_connect_token_issuance_operations WHERE operation_id = ?", + operationId)) + .hasMessageContaining("replay evidence cannot be deleted"); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM account_connect_token_response_envelopes WHERE operation_id = ?", + operationId)) + .hasMessageContaining("replay evidence cannot be deleted"); + assertThat(operationFingerprint(operationId)).isEqualTo(operationBefore); + assertThat(envelopeFingerprint(operationId)).isEqualTo(envelopeBefore); + + ConnectSourceFixture legacyTerminal = createCommittedConnectSource(fixture, false); + UUID legacyOperationId = legacyTerminal.claim().operation().operationId(); + String legacyOperationBefore = operationFingerprint(legacyOperationId); + String legacyEnvelopeBefore = envelopeFingerprint(legacyOperationId); + assertThat( + ownerTransaction( + () -> + captureService() + .read(legacyTerminal.identity(), legacyTerminal.requestDigest()))) + .isEmpty(); + assertThatThrownBy( + () -> + ownerTransaction( + () -> + captureService() + .capture(legacyTerminal.claim(), legacyTerminal.requestDigest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("pending"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_connect_token_issuance_operations SET " + + "issuance_fence_capture_schema = ?, " + + "issuance_fence_capture_account_uuid = ?, " + + "issuance_fence_capture_value = ?, " + + "issuance_fence_capture_source_version = ?, " + + "issuance_fence_capture_digest = ? WHERE operation_id = ?", + legacyTerminal.evidence().schemaName(), + legacyTerminal.evidence().accountUuid(), + legacyTerminal.evidence().issuanceFence(), + legacyTerminal.evidence().fenceSourceVersion(), + legacyTerminal.evidence().digest(), + legacyOperationId)) + .hasMessageContaining("capture requires a pending operation"); + assertThat(operationFingerprint(legacyOperationId)).isEqualTo(legacyOperationBefore); + assertThat(envelopeFingerprint(legacyOperationId)).isEqualTo(legacyEnvelopeBefore); + assertThat( + ownerTransaction( + () -> + captureService() + .read(legacyTerminal.identity(), legacyTerminal.requestDigest()))) + .isEmpty(); + } + + private void assertCaptureRejectedWithoutMembershipMutation( + JoinFixture fixture, boolean hasHistoricalMembership) { + RuntimeMembershipSnapshotDto membershipBefore = readRuntimeMembershipSnapshot(fixture); + List> accountSourceBefore = accountSourceFingerprint(fixture); + AccountConnectTokenIssuanceIdentity identity = connectIdentity(fixture); + byte[] requestDigest = digest(hasHistoricalMembership ? 122 : 121); + ClaimResult claim = + ownerTransaction(() -> connectIssuanceRepository.claim(identity, requestDigest)); + String operationBefore = operationFingerprint(claim.operation().operationId()); + + assertThatThrownBy(() -> ownerTransaction(() -> captureService().capture(claim, requestDigest))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("existing ACTIVE Account membership"); + + assertThat( + ownerTransaction( + () -> connectIssuanceRepository.readIssuanceFenceCapture(identity, requestDigest))) + .isEmpty(); + assertThat(operationFingerprint(claim.operation().operationId())).isEqualTo(operationBefore); + assertThat(accountSourceFingerprint(fixture)).isEqualTo(accountSourceBefore); + RuntimeMembershipSnapshotDto membershipAfter = readRuntimeMembershipSnapshot(fixture); + assertThat(membershipAfter.membershipBaseline()) + .isEqualTo(membershipBefore.membershipBaseline()); + assertThat(membershipAfter.roles()).isEqualTo(membershipBefore.roles()); + assertThat(membershipAfter.outboxCheckpoints()).isEqualTo(membershipBefore.outboxCheckpoints()); + assertThat(membershipAfter.outboxSourceEvidence()) + .isEqualTo(membershipBefore.outboxSourceEvidence()); + if (hasHistoricalMembership) { + assertThat(membershipAfter.membershipExists()).isTrue(); + assertThat(membershipAfter.membershipBaseline().membershipLifecycleState()) + .isEqualTo("INACTIVE"); + assertThat(countMembershipRows(fixture)).isEqualTo(1L); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(2L); + assertThat(countStreamEvents(membershipStreamKey(fixture))).isEqualTo(2L); + } else { + assertThat(membershipAfter.membershipExists()).isFalse(); + assertThat(membershipAfter.gameplayAdmissionAllowed()).isFalse(); + assertThat(membershipAfter.membershipBaseline().membershipLifecycleState()) + .isEqualTo("MISSING"); + assertThat(countMembershipRows(fixture)).isZero(); + assertThat(countMembershipTransitionReceipts(fixture)).isZero(); + assertThat(countStreamEvents(membershipStreamKey(fixture))).isZero(); + } + } + + private ConnectClaimFixture claimAndCapture(JoinFixture fixture) { + AccountConnectTokenIssuanceIdentity identity = connectIdentity(fixture); + byte[] requestDigest = digest(123); + return ownerTransaction( + () -> { + ClaimResult claim = connectIssuanceRepository.claim(identity, requestDigest); + AccountConnectIssuanceFenceEvidence evidence = + captureService().capture(claim, requestDigest); + return new ConnectClaimFixture(identity, requestDigest, claim, evidence); + }); + } + + private void assertCaptureReplacementRejected( + ConnectClaimFixture claim, AccountConnectIssuanceFenceEvidence candidate) { + assertThatThrownBy( + () -> + ownerTransaction( + () -> + connectIssuanceRepository.captureIssuanceFence( + claim.claim(), claim.requestDigest(), candidate))) + .isInstanceOf(AccountConnectTokenIssuanceRepository.EvidenceMismatchException.class); + } + + private ConnectSourceFixture createCommittedConnectSource( + JoinFixture fixture, boolean captureCurrentFence) { + AccountConnectTokenIssuanceIdentity identity = connectIdentity(fixture); + byte[] requestDigest = digest(captureCurrentFence ? 124 : 125); + return Objects.requireNonNull( + ownerTransaction( + () -> { + ClaimResult claim = connectIssuanceRepository.claim(identity, requestDigest); + AccountConnectIssuanceFenceEvidence evidence = + captureCurrentFence + ? captureService().capture(claim, requestDigest) + : currentFenceCandidate(fixture, identity, requestDigest, claim); + if (captureCurrentFence) { + assertThat(captureService().capture(claim, requestDigest)).isEqualTo(evidence); + } + AccountEnvelopeBinding binding = + connectSourceBinding(claim, identity, requestDigest, evidence.digest()); + AccountEncryptedEnvelope envelope = syntheticEnvelope(); + connectIssuanceRepository.completeWithEnvelope( + claim, + requestDigest, + Lifecycle.COMMITTED, + "SUCCESS", + syntheticTokenIdentity(), + digest(126), + binding, + envelope); + return new ConnectSourceFixture( + identity, requestDigest, claim, evidence, binding, envelope); + })); + } + + private ComposedConnectSourceFixture createCryptographicConnectSource( + JoinFixture fixture, boolean persistCapture) throws Exception { + ProofClock clock = new ProofClock(Instant.now().truncatedTo(ChronoUnit.SECONDS)); + KeyPair accountSigner = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + KeyPair gatewaySigner = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + Map gatewayKeys = + Map.of(GATEWAY_CONTEXT_KEY_ID, gatewaySigner.getPublic()); + AccountEnvelopeCrypto envelopeCrypto = ephemeralEnvelopeCrypto(); + AccountGameplayConnectSourceVerifier sourceVerifier = + new AccountGameplayConnectSourceVerifier( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + Map.of(ACCOUNT_SOURCE_KEY_ID, accountSigner.getPublic()), + 16 * 1024, + clock); + AccountTenantIdentityResolver tenantIdentityResolver = + new AccountTenantIdentityResolver( + tenantAssociationRepository, legacyTenantSourceEvidence, WORKLOAD_NAMESPACE); + AccountCommittedConnectSourceReader sourceReader = + new AccountCommittedConnectSourceReader( + connectIssuanceRepository, + accountRepository, + tenantIdentityResolver, + freshTenantIdentityRepository, + joinOperationRepository, + envelopeCrypto, + sourceVerifier, + gatewayKeys, + clock, + WORKLOAD_NAMESPACE); + AccountBareLoginCurrentAuthorityReader composedReader = + new AccountBareLoginCurrentAuthorityReader( + sourceReader, + captureService(), + membershipAuthorityEventProducer, + authorityGenerationRepository); + // Synthetic source scope/target only: this composes durable evidence without invoking + // connect-token issuance, selected-target catalog resolution, or an entitlement issuer. + AccountConnectTokenIssuanceIdentity identity = + new AccountConnectTokenIssuanceIdentity( + fixture.accountId(), + fixture.tenantUuid(), + "synthetic-capture-scope-" + UUID.randomUUID(), + "synthetic-capture-request-" + UUID.randomUUID()); + byte[] requestDigest = digest(131); + String tokenIdentity = "capture-composition-jti-" + UUID.randomUUID(); + + return ownerTransaction( + () -> { + ClaimResult claim = connectIssuanceRepository.claim(identity, requestDigest); + AccountConnectIssuanceFenceEvidence capture = + persistCapture + ? captureService().capture(claim, requestDigest) + : currentFenceCandidate(fixture, identity, requestDigest, claim); + RuntimeMembershipSnapshotDto membershipSnapshot = + membershipAuthorityEventProducer.readExistingRuntimeMembershipSnapshot( + fixture.accountUuid(), fixture.tenantUuid()); + Map sourceClaims = + currentGameplayConnectClaims( + fixture, identity, membershipSnapshot, tokenIdentity, clock.instant()); + byte[] compactJwtBytes = signAccountGameplayConnectJwt(sourceClaims, accountSigner); + String compactJwt = new String(compactJwtBytes, StandardCharsets.US_ASCII); + Map gatewayClaims = + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + sourceClaims, + clock.instant().getEpochSecond(), + "gateway-capture-proof-" + UUID.randomUUID()); + String signedGatewayContext = + GatewayConnectContextSignature.sign( + JSON.writeValueAsBytes(gatewayClaims), + GATEWAY_CONTEXT_KEY_ID, + gatewaySigner.getPrivate()); + AccountEnvelopeBinding binding = + connectSourceBinding(claim, identity, requestDigest, capture.digest()); + AccountEncryptedEnvelope envelope = + envelopeCrypto.encrypt( + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding, compactJwtBytes); + connectIssuanceRepository.completeWithEnvelope( + claim, + requestDigest, + Lifecycle.COMMITTED, + "SUCCESS", + tokenIdentity, + sha256(compactJwtBytes), + binding, + envelope); + return new ComposedConnectSourceFixture( + composedReader, + identity, + requestDigest, + claim, + capture, + membershipSnapshot, + binding, + envelope, + tokenIdentity, + compactJwt, + signedGatewayContext, + sourceClaims, + clock); + }); + } + + private Map currentGameplayConnectClaims( + JoinFixture fixture, + AccountConnectTokenIssuanceIdentity identity, + RuntimeMembershipSnapshotDto membershipSnapshot, + String tokenIdentity, + Instant issuedAt) { + BigInteger now = BigInteger.valueOf(issuedAt.getEpochSecond()); + Map claims = new LinkedHashMap<>(); + claims.put("iss", AccountServiceImpl.ACCOUNT_JWT_ISSUER); + claims.put("aud", "gameplay-connect"); + claims.put("iat", now.subtract(BigInteger.ONE)); + claims.put("exp", now.add(BigInteger.valueOf(20L))); + claims.put("jti", tokenIdentity); + claims.put("accountId", fixture.accountUuid().toString()); + claims.put("tenantId", fixture.tenantUuid().toString()); + // Routing claims are synthetic fixture values; the authority tuple and membership version + // below are copied from the real current Account snapshot. + claims.put("realmId", REALM_ID.toString()); + claims.put("worldSlug", WORLD_SLUG); + claims.put("realmSlug", REALM_SLUG); + claims.put("playableStateNamespaceId", "cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + claims.put("playableStateScope", "PLAYABLE_STATE_SCOPE_SHARED"); + claims.put("gameInstanceId", "dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + claims.put("pointerVersion", BigInteger.valueOf(POINTER_VERSION)); + claims.put("catalogRevision", BigInteger.valueOf(CATALOG_REVISION)); + claims.put("connectScopeId", identity.connectScopeId()); + claims.put("requestId", identity.requestId()); + claims.put("authorityTuple", authorityTupleClaims(membershipSnapshot.authorityTuple())); + claims.put("membershipVersion", membershipSnapshot.membershipBaseline().membershipVersion()); + // This is a synthetic replay-admission fixture value, not Account's separate capture fence. + claims.put("replayAdmissionFence", BigInteger.valueOf(9_001L)); + return Map.copyOf(claims); + } + + private Map authorityTupleClaims( + MembershipAuthorityEventV1Codec.AuthorityTuple tuple) { + Map claims = new LinkedHashMap<>(); + claims.put("issuerAuthGeneration", new BigInteger(tuple.issuerAuthGeneration())); + claims.put("accountAuthorityGeneration", new BigInteger(tuple.accountAuthorityGeneration())); + claims.put("tenantAuthorityGeneration", jsonCounterMap(tuple.tenantAuthorityGeneration())); + claims.put( + "membershipAuthorityGeneration", jsonCounterMap(tuple.membershipAuthorityGeneration())); + claims.put( + "privateRealmGrantVersions", + tuple.privateRealmGrantVersions().stream() + .map( + grant -> + Map.of( + "tenantId", grant.tenantId(), + "worldSlug", grant.worldSlug(), + "realmSlug", grant.realmSlug(), + "playtestLifecycleId", grant.playtestLifecycleId(), + "grantVersion", new BigInteger(grant.grantVersion()))) + .toList()); + tuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> + claims.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + new BigInteger(cutoff.accountAuthorityGeneration()), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + new BigInteger(cutoff.outboxSequence())))); + tuple + .tenantBillingCutoff() + .ifPresent( + cutoffs -> { + Map projected = new LinkedHashMap<>(); + cutoffs.forEach( + (tenantId, cutoff) -> + projected.put( + tenantId, + Map.of( + "tenantAuthorityGeneration", + new BigInteger(cutoff.tenantAuthorityGeneration()), + "tenantBillingSequence", + new BigInteger(cutoff.tenantBillingSequence()), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + new BigInteger(cutoff.outboxSequence())))); + claims.put("tenantBillingCutoff", Map.copyOf(projected)); + }); + return Map.copyOf(claims); + } + + private Map jsonCounterMap(Map values) { + Map projected = new LinkedHashMap<>(); + values.forEach((key, value) -> projected.put(key, new BigInteger(value))); + return Map.copyOf(projected); + } + + private byte[] signAccountGameplayConnectJwt(Map claims, KeyPair accountSigner) { + try { + String header = + "{\"alg\":\"EdDSA\",\"kid\":\"" + ACCOUNT_SOURCE_KEY_ID + "\",\"typ\":\"JWT\"}"; + String encodedHeader = BASE64_URL.encodeToString(header.getBytes(StandardCharsets.US_ASCII)); + String encodedPayload = BASE64_URL.encodeToString(JSON.writeValueAsBytes(claims)); + String signingInput = encodedHeader + "." + encodedPayload; + Signature signature = Signature.getInstance("Ed25519"); + signature.initSign(accountSigner.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return (signingInput + "." + BASE64_URL.encodeToString(signature.sign())) + .getBytes(StandardCharsets.US_ASCII); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException( + "Could not sign synthetic Account gameplay-connect source fixture", exception); + } + } + + private AccountEnvelopeCrypto ephemeralEnvelopeCrypto() throws Exception { + byte[] bareLoginKey = new byte[32]; + byte[] connectTokenKey = new byte[32]; + FIXTURE_RANDOM.nextBytes(bareLoginKey); + do { + FIXTURE_RANDOM.nextBytes(connectTokenKey); + } while (MessageDigest.isEqual(bareLoginKey, connectTokenKey)); + String manifest = + "version=1\nactiveKeyId=capture-test-key\nkey:capture-test-key:bare-login=" + + BASE64_URL.encodeToString(bareLoginKey) + + "\nkey:capture-test-key:connect-token=" + + BASE64_URL.encodeToString(connectTokenKey) + + "\n"; + Path manifestPath = tempDir.resolve("capture-envelope-ring-" + UUID.randomUUID() + ".v1"); + Files.writeString(manifestPath, manifest, StandardCharsets.US_ASCII); + java.util.Arrays.fill(bareLoginKey, (byte) 0); + java.util.Arrays.fill(connectTokenKey, (byte) 0); + return new AccountEnvelopeCrypto(manifestPath); + } + + private AccountBareLoginCurrentAuthorityReader.CurrentAuthorityReadback readCurrentAuthority( + ComposedConnectSourceFixture source, byte[] requestDigest) { + return withGameSessionPeer( + () -> + ownerTransaction( + () -> + source + .reader() + .read(source.identity(), requestDigest, source.signedGatewayContext()))); + } + + private T withGameSessionPeer(Supplier operation) { + Context scoped = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + WORKLOAD_NAMESPACE + "/sa/game-session-service") + .orElseThrow()); + Context previous = scoped.attach(); + try { + return operation.get(); + } finally { + scoped.detach(previous); + } + } + + private byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private byte[] sha256(String value) { + return sha256(value.getBytes(StandardCharsets.US_ASCII)); + } + + private List> membershipAuthoritySourceFingerprint(JoinFixture fixture) { + String streamKey = membershipStreamKey(fixture); + return List.of( + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_authority_generations " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()), + canonicalRows( + "SELECT s.xmin::text AS snapshot_xmin, r.xmin::text AS role_xmin, " + + "s.membership_id, s.snapshot_version, r.role_identifier " + + "FROM account_tenant_membership_role_snapshots s " + + "LEFT JOIN account_tenant_membership_role_snapshot_roles r " + + "USING (membership_id, snapshot_version) WHERE s.membership_id = " + + "(SELECT id FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?) " + + "ORDER BY r.role_identifier", + fixture.accountId(), + fixture.tenantId()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ? ORDER BY receipt_sequence", + fixture.accountId(), + fixture.tenantId()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + streamKey), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? ORDER BY outbox_sequence", + streamKey)); + } + + private AccountConnectIssuanceFenceEvidence currentFenceCandidate( + JoinFixture fixture, + AccountConnectTokenIssuanceIdentity identity, + byte[] requestDigest, + ClaimResult claim) { + return AccountConnectIssuanceFenceEvidence.capture( + claim.operation().operationId(), + fixture.accountUuid(), + fixture.tenantUuid(), + AccountJoinDigest.tokenHash(identity.connectScopeId()), + identity.requestId(), + requestDigest, + accountIssuanceFence(fixture), + accountIssuanceFenceSourceVersion(fixture)); + } + + private AccountEnvelopeBinding connectSourceBinding( + ClaimResult claim, + AccountConnectTokenIssuanceIdentity identity, + byte[] requestDigest, + byte[] issuanceFenceDigest) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.CONNECT_TOKEN_ISSUANCE, + claim.operation().operationId().toString(), + identity.requestId(), + Long.toString(identity.accountId()), + identity.tenantId().toString(), + identity.connectScopeId(), + null, + requestDigest, + digest(127), + digest(128), + issuanceFenceDigest, + digest(129)); + } + + private AccountConnectTokenAuthorityCaptureService captureService() { + return new AccountConnectTokenAuthorityCaptureService( + connectIssuanceRepository, + accountRepository, + joinOperationRepository, + membershipAuthorityEventProducer, + authorityGenerationRepository, + dataSource); + } + + private AccountConnectTokenIssuanceIdentity connectIdentity(JoinFixture fixture) { + return new AccountConnectTokenIssuanceIdentity( + fixture.accountId(), + fixture.tenantUuid(), + fixture.scope().connectScopeId(), + "capture-connect-" + UUID.randomUUID()); + } + + private AccountEncryptedEnvelope syntheticEnvelope() { + // Opaque fixture bytes exercise durable source binding; they are neither AEAD output nor a JWT. + return new AccountEncryptedEnvelope( + AccountEncryptedEnvelope.CURRENT_FORMAT_VERSION, + "fixture_key", + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + new byte[AccountEncryptedEnvelope.NONCE_LENGTH_BYTES], + new byte[AccountEncryptedEnvelope.AUTHENTICATION_TAG_LENGTH_BYTES]); + } + + private String syntheticTokenIdentity() { + return "synthetic-fixture-not-jwt-" + UUID.randomUUID(); + } + + private byte[] digest(int seed) { + byte[] value = new byte[32]; + for (int index = 0; index < value.length; index++) { + value[index] = (byte) (seed + index); + } + return value; + } + + private List> accountSourceFingerprint(JoinFixture fixture) { + String account = accountStreamKey(fixture.accountUuid()); + String issuer = issuerStreamKey(); + String membership = membershipStreamKey(fixture); + String tenant = tenantStreamKey(fixture.tenantUuid()); + Object[] streamKeys = {account, issuer, membership, tenant}; + return List.of( + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM accounts WHERE id = ?", fixture.accountId()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_approved_legacy_tenant_associations " + + "WHERE legacy_tenant_id = ?", + fixture.tenantId()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_canonical_tenant_identity_claims " + + "WHERE canonical_tenant_id = ?", + fixture.tenantUuid()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_authority_generations " + + "WHERE (scope_kind = 'ISSUER' AND issuer_id = ?) OR account_uuid = ? " + + "OR tenant_uuid = ? ORDER BY scope_kind, issuer_id, account_uuid, tenant_uuid", + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + fixture.accountUuid(), + fixture.tenantUuid()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + fixture.accountUuid()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()), + canonicalRows( + "SELECT s.xmin::text AS snapshot_xmin, r.xmin::text AS role_xmin, " + + "s.membership_id, s.snapshot_version, r.role_identifier " + + "FROM account_tenant_membership_role_snapshots s " + + "LEFT JOIN account_tenant_membership_role_snapshot_roles r " + + "USING (membership_id, snapshot_version) WHERE s.membership_id = " + + "(SELECT id FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?) " + + "ORDER BY r.role_identifier", + fixture.accountId(), + fixture.tenantId()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ? ORDER BY receipt_sequence", + fixture.accountId(), + fixture.tenantId()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_audit_outbox WHERE tenant_id = ? " + + "ORDER BY created_at, audit_event_id", + fixture.tenantId()), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key IN (?, ?, ?, ?) ORDER BY outbox_stream_key", + streamKeys), + canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_authority_outbox_events " + + "WHERE outbox_stream_key IN (?, ?, ?, ?) ORDER BY outbox_stream_key, outbox_sequence", + streamKeys)); + } + + private List canonicalRows(String query, Object... bindValues) { + return dsl.resultQuery(query, bindValues).fetch().stream() + .map(row -> canonicalRow(row.intoMap())) + .toList(); + } + + private String canonicalRow(Map row) { + return row.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map( + entry -> + entry.getKey() + + "=" + + (entry.getValue() instanceof byte[] bytes + ? HexFormat.of().formatHex(bytes) + : String.valueOf(entry.getValue()))) + .toList() + .toString(); + } + + private String operationFingerprint(UUID operationId) { + return canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_connect_token_issuance_operations " + + "WHERE operation_id = ?", + operationId) + .toString(); + } + + private String envelopeFingerprint(UUID operationId) { + return canonicalRows( + "SELECT xmin::text AS row_xmin, * FROM account_connect_token_response_envelopes " + + "WHERE operation_id = ?", + operationId) + .toString(); + } + + private long countConnectEnvelopes(AccountConnectTokenIssuanceIdentity identity) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_connect_token_response_envelopes " + + "WHERE account_id = ? AND tenant_id = ? AND connect_scope_hash = ? " + + "AND request_id = ?", + identity.accountId(), + identity.tenantId(), + AccountJoinDigest.tokenHash(identity.connectScopeId()), + identity.requestId()) + .fetchOne(0, Long.class)); + } + + private byte[] independentlyRehashCapture(AccountConnectIssuanceFenceEvidence evidence) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + appendFrame(preimage, evidence.schemaName()); + appendFrame(preimage, evidence.operationId().toString()); + appendFrame(preimage, evidence.accountUuid().toString()); + appendFrame(preimage, evidence.tenantUuid().toString()); + appendFrame(preimage, evidence.connectScopeHash()); + appendFrame(preimage, evidence.requestId()); + appendFrame(preimage, HexFormat.of().formatHex(evidence.requestDigest())); + appendFrame(preimage, Long.toString(evidence.issuanceFence())); + appendFrame(preimage, Long.toString(evidence.fenceSourceVersion())); + try { + return MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray()); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private void appendFrame(ByteArrayOutputStream output, String value) { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(encoded.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(encoded); + } + + private T ownerTransaction(Supplier operation) { + return new TransactionTemplate(transactionManager).execute(status -> operation.get()); + } + + private int currentBackendPid() { + return Objects.requireNonNull( + dsl.resultQuery("SELECT pg_backend_pid()").fetchOne(0, Integer.class), + "PostgreSQL did not return the owner transaction backend PID"); + } + + private int awaitAccountAdvanceBlockedOnGeneration( + DSLContext observer, int authorityHolderPid, Duration timeout) throws InterruptedException { + long deadline = System.nanoTime() + timeout.toNanos(); + while (System.nanoTime() < deadline) { + Integer waitingPid = + observer + .resultQuery( + "SELECT waiting.pid FROM pg_stat_activity waiting " + + "WHERE waiting.wait_event_type = 'Lock' " + + "AND waiting.query ILIKE '%account_authority_generations%' " + + "AND ? = ANY(pg_blocking_pids(waiting.pid)) " + + "AND EXISTS (SELECT 1 FROM pg_locks held " + + "WHERE held.pid = waiting.pid AND held.locktype = 'relation' " + + "AND held.relation = 'accounts'::regclass " + + "AND held.mode = 'RowShareLock' AND held.granted) " + + "ORDER BY waiting.query_start DESC LIMIT 1", + authorityHolderPid) + .fetchOne(0, Integer.class); + if (waitingPid != null) { + return waitingPid; + } + Thread.sleep(10L); + } + throw new AssertionError( + "PostgreSQL did not show the Account logout-all owner blocked after acquiring its Account row"); + } + + private boolean awaitDatabaseBlock( + DSLContext observer, int waitingPid, int blockingPid, String queryPattern, Duration timeout) + throws InterruptedException { + long deadline = System.nanoTime() + timeout.toNanos(); + while (System.nanoTime() < deadline) { + Boolean blocked = + observer + .resultQuery( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity waiting " + + "WHERE waiting.pid = ? AND waiting.wait_event_type = 'Lock' " + + "AND waiting.query ILIKE ? " + + "AND ? = ANY(pg_blocking_pids(waiting.pid)))", + waitingPid, + queryPattern, + blockingPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + + private void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent Account source fixture barrier timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent Account source fixture was interrupted", interrupted); + } + } + private JoinFixture fixture() { String suffix = UUID.randomUUID().toString(); long accountId = @@ -657,6 +2512,14 @@ private AccountMembershipSourceReader membershipSourceReader() { membershipAuthorityEventProducer, authorityGenerationRepository, transactionManager); } + private AccountMembershipCaptureSources readMembershipCaptureSources(JoinFixture fixture) { + return new TransactionTemplate(transactionManager) + .execute( + status -> + membershipAuthorityEventProducer.readExistingRuntimeMembershipCaptureSources( + fixture.accountUuid(), fixture.tenantUuid())); + } + private RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot(JoinFixture fixture) { return new TransactionTemplate(transactionManager) .execute( @@ -665,6 +2528,14 @@ private RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot(JoinFixture f fixture.accountUuid(), fixture.tenantUuid())); } + private long checkpoint(AccountMembershipCaptureSources sources, String streamKey) { + return sources.membershipSnapshot().outboxCheckpoints().stream() + .filter(checkpoint -> checkpoint.outboxStreamKey().equals(streamKey)) + .mapToLong(checkpoint -> Long.parseLong(checkpoint.outboxSequence())) + .findFirst() + .orElseThrow(() -> new IllegalStateException("Account source checkpoint is absent")); + } + private ScopeState readAccountAuthority(UUID accountUuid) { return new TransactionTemplate(transactionManager) .execute(status -> authorityGenerationRepository.read(AuthorityScope.account(accountUuid))); @@ -694,6 +2565,20 @@ private AccountLogoutAllAuthorityEventProducer logoutProducer() { transactionManager); } + private AccountIssuerAuthorityEventProducer issuerProducer() { + return new AccountIssuerAuthorityEventProducer( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + authorityGenerationRepository, + authorityOutboxRepository, + dsl, + transactionManager); + } + + private AccountTenantAuthorityEventProducer tenantProducer() { + return new AccountTenantAuthorityEventProducer( + authorityGenerationRepository, authorityOutboxRepository, dsl, transactionManager); + } + private byte[] membershipEventBytes(JoinFixture fixture) { return membershipEventBytes(fixture, 1L); } @@ -776,6 +2661,17 @@ private long accountIssuanceFence(JoinFixture fixture) { return fence; } + private long accountIssuanceFenceSourceVersion(JoinFixture fixture) { + Long sourceVersion = + dsl.resultQuery( + "SELECT source_version FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class); + assertThat(sourceVersion).isNotNull(); + return sourceVersion; + } + private Map accountIssuanceFenceRow(JoinFixture fixture) { var row = dsl.resultQuery( @@ -906,4 +2802,97 @@ private record JoinFixture( String requestId, DirectTextCallerContext caller, DirectTextJoinScope scope) {} + + private record ConnectClaimFixture( + AccountConnectTokenIssuanceIdentity identity, + byte[] requestDigest, + ClaimResult claim, + AccountConnectIssuanceFenceEvidence evidence) { + private ConnectClaimFixture { + requestDigest = requestDigest.clone(); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + } + + private record ConnectSourceFixture( + AccountConnectTokenIssuanceIdentity identity, + byte[] requestDigest, + ClaimResult claim, + AccountConnectIssuanceFenceEvidence evidence, + AccountEnvelopeBinding binding, + AccountEncryptedEnvelope envelope) { + private ConnectSourceFixture { + requestDigest = requestDigest.clone(); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + } + + private record CaptureReadback( + AccountConnectIssuanceFenceEvidence evidence, AccountCommittedConnectSource source) {} + + private record ComposedConnectSourceFixture( + AccountBareLoginCurrentAuthorityReader reader, + AccountConnectTokenIssuanceIdentity identity, + byte[] requestDigest, + ClaimResult claim, + AccountConnectIssuanceFenceEvidence capture, + RuntimeMembershipSnapshotDto membershipSnapshot, + AccountEnvelopeBinding binding, + AccountEncryptedEnvelope envelope, + String tokenIdentity, + String compactJwt, + String signedGatewayContext, + Map sourceClaims, + ProofClock clock) { + private ComposedConnectSourceFixture { + requestDigest = requestDigest.clone(); + sourceClaims = Map.copyOf(sourceClaims); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + } + + private static final class ProofClock extends Clock { + private final Instant initialInstant; + private final AtomicInteger instantReads = new AtomicInteger(); + private volatile int expiresOnRead = Integer.MAX_VALUE; + private volatile Instant expiredInstant; + + private ProofClock(Instant initialInstant) { + this.initialInstant = initialInstant; + } + + private void expireAfterReads(int readsUntilExpiry, Duration elapsed) { + expiresOnRead = instantReads.get() + readsUntilExpiry; + expiredInstant = initialInstant.plus(elapsed); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return new ProofClock(initialInstant); + } + + @Override + public Instant instant() { + int read = instantReads.incrementAndGet(); + Instant expired = expiredInstant; + return expired != null && read >= expiresOnRead ? expired : initialInstant; + } + } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountFreshUuidMembershipSnapshotIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountFreshUuidMembershipSnapshotIntegrationTest.java index 991fb851f2..867176a5d7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountFreshUuidMembershipSnapshotIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountFreshUuidMembershipSnapshotIntegrationTest.java @@ -24,17 +24,23 @@ 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.AccountFreshCaptureSources; import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourceRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountFreshCaptureSourceReader; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; import net.firedevops.firemud.accountservice.service.AccountMembershipSourceReader; +import net.firedevops.firemud.accountservice.service.AccountTenantAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.test.GatewayTestProperties; @@ -50,6 +56,7 @@ import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.test.util.AopTestUtils; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -86,6 +93,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private AccountMembershipAuthorityEventProducer producer; @Autowired private AccountAuthorityGenerationRepository authorityGenerationRepository; @Autowired private AccountAuthorityOutboxRepository authorityOutboxRepository; + @Autowired private AccountGlobalRoleSourceRepository globalRoleSourceRepository; @Autowired private FreshTenantIdentityAssociationRepository freshAssociationRepository; @Autowired private PlatformTransactionManager transactionManager; @@ -177,6 +185,158 @@ void freshUuidSnapshotEnrollsExactNonAdmittingBaselineAndRetriesWithoutSideEffec assertThat(issuanceFence(account.accountUuid())).isEqualTo(originalIssuanceFence); } + @Test + void freshGlobalRoleSourceComposesWithExistingMembershipVectorAndPreservesIndependentVersions() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + new AccountTenantAuthorityEventProducer( + authorityGenerationRepository, authorityOutboxRepository, dsl, transactionManager) + .advance(tenantUuid, UUID.randomUUID(), 1L, 1L); + readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid); + + Map pairBefore = membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + Map tenantGenerationBefore = + authorityGenerationRow("TENANT", null, tenantUuid).orElseThrow(); + Map membershipGenerationBefore = + authorityGenerationRow("MEMBERSHIP", account.accountUuid(), tenantUuid).orElseThrow(); + Map fenceBefore = issuanceFenceRow(account.accountUuid()); + Map roleSourceBefore = globalRoleSourceRow(account.accountUuid()); + AccountFreshCaptureSourceReader reader = + new AccountFreshCaptureSourceReader(producer, globalRoleSourceRepository); + TransactionTemplate ownerTransaction = new TransactionTemplate(transactionManager); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + + AccountFreshCaptureSources first = + ownerTransaction.execute(status -> reader.readExisting(account.accountUuid(), tenantUuid)); + AccountFreshCaptureSources retry = + ownerTransaction.execute(status -> reader.readExisting(account.accountUuid(), tenantUuid)); + + var persistedAccount = + dsl.resultQuery( + "SELECT id, account_uuid, account_uuid_source_numeric_id, " + + "account_uuid_provenance FROM accounts WHERE id = ?", + account.accountId()) + .fetchOne(); + assertThat(persistedAccount).isNotNull(); + assertThat(persistedAccount.get("account_uuid", UUID.class)).isEqualTo(account.accountUuid()); + assertThat(persistedAccount.get("account_uuid_provenance", String.class)) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name()); + assertThat(persistedAccount.get("account_uuid_source_numeric_id", Long.class)) + .isEqualTo(account.accountId()); + + var membershipSources = first.membershipSources(); + var authority = membershipSources.authoritySnapshot(); + assertThat(first.requestedAccountUuid()).isEqualTo(account.accountUuid()); + assertThat(first.requestedTenantUuid()).isEqualTo(tenantUuid); + assertThat(membershipSources.membershipSnapshot().accountUuid()) + .isEqualTo(account.accountUuid().toString()); + assertThat(membershipSources.membershipSnapshot().tenantUuid()) + .isEqualTo(tenantUuid.toString()); + assertThat(membershipSources.membershipSnapshot().membershipExists()).isFalse(); + assertThat(membershipSources.membershipSnapshot().gameplayAdmissionAllowed()).isFalse(); + assertThat(authority.issuer().sourceVersion()).isEqualTo(1L); + assertThat(authority.account().sourceVersion()).isEqualTo(1L); + assertThat(authority.tenants()) + .singleElement() + .satisfies( + tenant -> { + assertThat(tenant.sourceVersion()).isEqualTo(2L); + assertThat(tenant.generation()).isEqualTo(2L); + }); + assertThat(authority.memberships()) + .singleElement() + .satisfies( + membership -> { + assertThat(membership.sourceVersion()).isEqualTo(1L); + assertThat(membership.generation()).isEqualTo(1L); + }); + assertThat(authority.issuanceFence().value()).isEqualTo(1L); + assertThat(authority.issuanceFence().sourceVersion()).isEqualTo(1L); + assertThat(membershipSources.membershipSnapshot().outboxCheckpoints()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.outboxStreamKey()) + .isEqualTo("account:auth-authority:v1:tenant/" + tenantUuid); + assertThat(checkpoint.outboxSequence()).isEqualTo("1"); + }); + + var freshRoleSource = first.freshGlobalRoleSource(); + assertThat(freshRoleSource.accountUuid()).isEqualTo(account.accountUuid()); + assertThat(freshRoleSource.accountRowId()).isEqualTo(account.accountId()); + assertThat(freshRoleSource.accountUuidSourceNumericId()).isEqualTo(account.accountId()); + assertThat(freshRoleSource.accountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + assertThat(freshRoleSource.globalRoles()).isEmpty(); + assertThat(freshRoleSource.globalRoleSourceVersion()).isEqualTo(1L); + assertThat(authority.tenants().getFirst().sourceVersion()) + .isNotEqualTo(freshRoleSource.globalRoleSourceVersion()); + assertThat(retry.freshGlobalRoleSource()).isEqualTo(freshRoleSource); + assertThat(retry.membershipSources().authoritySnapshot()).isEqualTo(authority); + assertThat(retry.membershipSources().membershipSnapshot().membershipBaseline()) + .isEqualTo(membershipSources.membershipSnapshot().membershipBaseline()); + assertThat(retry.membershipSources().membershipSnapshot().outboxCheckpoints()) + .isEqualTo(membershipSources.membershipSnapshot().outboxCheckpoints()); + + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)).isEqualTo(pairBefore); + assertThat(authorityGenerationRow("TENANT", null, tenantUuid)).contains(tenantGenerationBefore); + assertThat(authorityGenerationRow("MEMBERSHIP", account.accountUuid(), tenantUuid)) + .contains(membershipGenerationBefore); + assertThat(issuanceFenceRow(account.accountUuid())).isEqualTo(fenceBefore); + assertThat(globalRoleSourceRow(account.accountUuid())).isEqualTo(roleSourceBefore); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + + AccountFixture otherAccount = accountFixture(); + var otherRoleSource = + ownerTransaction.execute( + status -> + globalRoleSourceRepository.readFreshEmptySourceForUpdate( + otherAccount.accountUuid())); + assertThatThrownBy( + () -> + new AccountFreshCaptureSources( + account.accountUuid(), tenantUuid, membershipSources, otherRoleSource)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("fresh Account identity"); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)).isEqualTo(pairBefore); + assertThat(globalRoleSourceRow(account.accountUuid())).isEqualTo(roleSourceBefore); + } + + @Test + void retainedAccountWithoutFreshGlobalRoleSourceIsDeniedWithoutEnrollment() { + AccountFixture account = retainedAccountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid); + + Map pairBefore = membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + Map membershipGenerationBefore = + authorityGenerationRow("MEMBERSHIP", account.accountUuid(), tenantUuid).orElseThrow(); + Map fenceBefore = issuanceFenceRow(account.accountUuid()); + assertThat(countGlobalRoleSources(account.accountUuid())).isZero(); + AccountFreshCaptureSourceReader reader = + new AccountFreshCaptureSourceReader(producer, globalRoleSourceRepository); + TransactionTemplate ownerTransaction = new TransactionTemplate(transactionManager); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + assertThatThrownBy( + () -> + ownerTransaction.execute( + status -> reader.readExisting(account.accountUuid(), tenantUuid))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Fresh canonical Account identity readback is invalid"); + + assertThat(countGlobalRoleSources(account.accountUuid())).isZero(); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)).isEqualTo(pairBefore); + assertThat(authorityGenerationRow("MEMBERSHIP", account.accountUuid(), tenantUuid)) + .contains(membershipGenerationBefore); + assertThat(issuanceFenceRow(account.accountUuid())).isEqualTo(fenceBefore); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + } + @Test void strictExistingMembershipReadDeniesFreshAssociationWithoutEnrollmentOrMutation() { AccountFixture account = accountFixture(); @@ -674,6 +834,181 @@ void concurrentFreshUuidSnapshotCallsInitializeOneExactPairBaseline() throws Exc } } + @Test + void tenantAdvanceWaitsForFreshCaptureSourceLocksAndPreservesCapturedVector() throws Exception { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + + var enrolledBaseline = + readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid); + assertThat(enrolledBaseline.membershipExists()).isFalse(); + assertThat(enrolledBaseline.gameplayAdmissionAllowed()).isFalse(); + assertThat(enrolledBaseline.membershipVersion()).isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(authorityGeneration("TENANT", null, tenantUuid)).isEqualTo(1L); + assertThat(authorityGeneration("MEMBERSHIP", account.accountUuid(), tenantUuid)).isEqualTo(1L); + + Map accountAuthorityBefore = + authorityGenerationRow("ACCOUNT", account.accountUuid(), null).orElseThrow(); + Map tenantAuthorityBefore = + authorityGenerationRow("TENANT", null, tenantUuid).orElseThrow(); + assertThat(tenantAuthorityBefore) + .containsEntry("generation", 1L) + .containsEntry("source_version", 1L); + Map membershipAuthorityBefore = + authorityGenerationRow("MEMBERSHIP", account.accountUuid(), tenantUuid).orElseThrow(); + Map issuanceFenceBefore = issuanceFenceRow(account.accountUuid()); + Map membershipPairBefore = + membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + Map globalRoleSourceBefore = globalRoleSourceRow(account.accountUuid()); + assertThat(globalRoleSourceBefore).containsEntry("global_role_source_version", 1L); + String tenantStreamKey = "account:auth-authority:v1:tenant/" + tenantUuid; + assertThat(countAuthorityEvents(tenantStreamKey)).isZero(); + assertThat(countAuthorityStreams(tenantStreamKey)).isZero(); + + AccountFreshCaptureSourceReader reader = + new AccountFreshCaptureSourceReader(producer, globalRoleSourceRepository); + TransactionTemplate captureOwnerTransaction = new TransactionTemplate(transactionManager); + captureOwnerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + captureOwnerTransaction.setReadOnly(false); + AccountTenantAuthorityEventProducer tenantProducer = + new AccountTenantAuthorityEventProducer( + authorityGenerationRepository, authorityOutboxRepository, dsl, transactionManager); + UUID requestId = UUID.randomUUID(); + + ExecutorService executor = Executors.newFixedThreadPool(2); + CountDownLatch captureReady = new CountDownLatch(1); + CountDownLatch releaseCapture = new CountDownLatch(1); + CountDownLatch advanceStarted = new CountDownLatch(1); + AtomicReference captureBackendPid = new AtomicReference<>(); + try { + Future captureFuture = + executor.submit( + () -> + captureOwnerTransaction.execute( + status -> { + AccountFreshCaptureSources capture = + reader.readExisting(account.accountUuid(), tenantUuid); + captureBackendPid.set(currentBackendPid()); + captureReady.countDown(); + await(releaseCapture); + return capture; + })); + assertThat(captureReady.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(captureBackendPid.get()).isNotNull(); + + Future advanceFuture = + executor.submit( + () -> { + advanceStarted.countDown(); + return tenantProducer.advance(tenantUuid, requestId, 1L, 1L); + }); + assertThat(advanceStarted.await(10, TimeUnit.SECONDS)).isTrue(); + + Integer waitingBackendPid = null; + long lockWaitDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < lockWaitDeadline && waitingBackendPid == null) { + waitingBackendPid = + dsl.resultQuery( + "SELECT pid FROM pg_stat_activity " + + "WHERE wait_event_type = 'Lock' " + + "AND CAST(? AS integer) = ANY(pg_blocking_pids(pid)) " + + "AND query ILIKE '%account_authority_generations%' " + + "ORDER BY query_start DESC LIMIT 1", + captureBackendPid.get()) + .fetchOne(0, Integer.class); + if (waitingBackendPid == null) { + Thread.sleep(10L); + } + } + assertThat(waitingBackendPid) + .as("tenant advancement must block on the captured authority-generation row") + .isNotNull(); + assertThat(advanceFuture.isDone()).isFalse(); + assertThat(authorityGeneration("TENANT", null, tenantUuid)).isEqualTo(1L); + assertThat(countAuthorityEvents(tenantStreamKey)).isZero(); + + releaseCapture.countDown(); + AccountFreshCaptureSources captured = captureFuture.get(20, TimeUnit.SECONDS); + var advancedEvent = advanceFuture.get(20, TimeUnit.SECONDS); + + assertThat(captured.requestedAccountUuid()).isEqualTo(account.accountUuid()); + assertThat(captured.requestedTenantUuid()).isEqualTo(tenantUuid); + var membershipSources = captured.membershipSources(); + assertThat(membershipSources.membershipSnapshot().membershipExists()).isFalse(); + assertThat(membershipSources.membershipSnapshot().gameplayAdmissionAllowed()).isFalse(); + assertThat(membershipSources.membershipSnapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(membershipSources.authoritySnapshot().tenants()) + .singleElement() + .satisfies( + tenant -> { + assertThat(tenant.generation()).isEqualTo(1L); + assertThat(tenant.sourceVersion()).isEqualTo(1L); + }); + assertThat(membershipSources.membershipSnapshot().outboxCheckpoints()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.outboxStreamKey()).isEqualTo(tenantStreamKey); + assertThat(checkpoint.outboxSequence()).isEqualTo("0"); + }); + assertThat(membershipSources.membershipSnapshot().outboxSourceEvidence()).isEmpty(); + assertThat(captured.freshGlobalRoleSource().globalRoles()).isEmpty(); + assertThat(captured.freshGlobalRoleSource().globalRoleSourceVersion()).isEqualTo(1L); + + assertThat(advancedEvent.requestId()).isEqualTo(requestId.toString()); + assertThat(advancedEvent.tenantId()).isEqualTo(tenantUuid.toString()); + assertThat(advancedEvent.outboxStreamKey()).isEqualTo(tenantStreamKey); + assertThat(advancedEvent.outboxSequence()).isEqualTo("1"); + assertThat(advancedEvent.tenantAuthorityGeneration()).isEqualTo("2"); + assertThat(advancedEvent.sourceVersion()).isEqualTo("2"); + var currentTenant = tenantProducer.readCurrent(tenantUuid); + assertThat(currentTenant.tenantAuthorityGeneration()).isEqualTo(2L); + assertThat(currentTenant.sourceVersion()).isEqualTo(2L); + assertThat(currentTenant.outboxStreamKey()).isEqualTo(tenantStreamKey); + assertThat(currentTenant.outboxSequence()).isEqualTo(1L); + assertThat(currentTenant.latestEvent()) + .hasValueSatisfying( + currentEvent -> { + assertThat(currentEvent.requestId()).isEqualTo(requestId.toString()); + assertThat(currentEvent.canonicalJson()).isEqualTo(advancedEvent.canonicalJson()); + assertThat(currentEvent.outboxSequence()).isEqualTo("1"); + assertThat(currentEvent.tenantAuthorityGeneration()).isEqualTo("2"); + assertThat(currentEvent.sourceVersion()).isEqualTo("2"); + }); + assertThat(countAuthorityEvents(tenantStreamKey)).isEqualTo(1L); + assertThat(countAuthorityStreams(tenantStreamKey)).isEqualTo(1L); + assertThat(authorityGenerationRow("TENANT", null, tenantUuid)) + .hasValueSatisfying( + row -> + assertThat(row) + .containsEntry("generation", 2L) + .containsEntry("source_version", 2L)); + + // The captured vector remains the exact pre-advance snapshot; the current source is newer. + assertThat(captured.freshGlobalRoleSource().globalRoleSourceVersion()).isNotEqualTo(2L); + assertThat(membershipSources.authoritySnapshot().tenants().getFirst().sourceVersion()) + .isNotEqualTo(currentTenant.sourceVersion()); + assertThat(authorityGenerationRow("ACCOUNT", account.accountUuid(), null)) + .contains(accountAuthorityBefore); + assertThat(authorityGenerationRow("MEMBERSHIP", account.accountUuid(), tenantUuid)) + .contains(membershipAuthorityBefore); + assertThat(issuanceFenceRow(account.accountUuid())).isEqualTo(issuanceFenceBefore); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)) + .isEqualTo(membershipPairBefore); + assertThat(globalRoleSourceRow(account.accountUuid())).isEqualTo(globalRoleSourceBefore); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + } finally { + releaseCapture.countDown(); + executor.shutdownNow(); + } + } + private AccountFixture accountFixture() { String suffix = UUID.randomUUID().toString().replace("-", ""); long accountId = @@ -706,6 +1041,41 @@ private AccountFixture accountFixture() { return new AccountFixture(accountId, accountUuid); } + private AccountFixture retainedAccountFixture() { + String suffix = UUID.randomUUID().toString().replace("-", ""); + UUID accountUuid = UUID.randomUUID(); + var accountRow = + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash, account_uuid, " + + "account_uuid_provenance) VALUES (?, ?, ?, ?, ?) " + + "RETURNING id, account_uuid, account_uuid_source_numeric_id", + "retained-capture-" + suffix, + "retained-capture-" + suffix + "@example.com", + "test-hash", + accountUuid, + AccountIdentityProvenance.ACCOUNT_V29_MIGRATION.name()) + .fetchOne(); + assertThat(accountRow).isNotNull(); + long accountId = Objects.requireNonNull(accountRow.get("id", Long.class)); + assertThat(accountRow.get("account_uuid", UUID.class)).isEqualTo(accountUuid); + assertThat(accountRow.get("account_uuid_source_numeric_id", Long.class)).isEqualTo(accountId); + 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); + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + authorityGenerationRepository.initializeIssuerIfAbsent( + AccountServiceImpl.ACCOUNT_JWT_ISSUER)); + return new AccountFixture(accountId, accountUuid); + } + private AccountMembershipSourceReader membershipSourceReader() { return new AccountMembershipSourceReader( producer, authorityGenerationRepository, transactionManager); @@ -784,6 +1154,28 @@ private Map membershipPairAuthorityRow(UUID accountUuid, UUID te return row.intoMap(); } + private Map globalRoleSourceRow(UUID accountUuid) { + var row = + dsl.resultQuery( + "SELECT xmin::text AS row_xmin, account_uuid, " + + "account_uuid_source_numeric_id, account_uuid_provenance, " + + "array_to_json(global_roles)::text AS global_roles, " + + "global_role_source_version FROM account_global_role_sources " + + "WHERE account_uuid = ?", + accountUuid) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private long countGlobalRoleSources(UUID accountUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_global_role_sources WHERE account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class)); + } + private long countMembershipPairAuthorities(UUID accountUuid, UUID tenantUuid) { return Objects.requireNonNull( dsl.resultQuery( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index 0f56baad43..d1604078fc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -1270,11 +1270,12 @@ void minimizedPriorJoinAuditWithoutMembershipOrReceiptKeepsJoinRetryable() { JoinFixture retry = fixture("active"); 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, " - + "next_attempt_at) " - + "VALUES (?, 'tenant', ?, 'account-service', " - + "'ACCOUNT_JOINED_PUBLIC_PRODUCTION', CURRENT_TIMESTAMP, 1, 1, ?, NULL, 'MINIMIZED', NULL)", + + "(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, next_attempt_at) " + + "VALUES (?, 'tenant', ?, 1, NULL, 'account-service', " + + "'ACCOUNT_JOINED_PUBLIC_PRODUCTION', CURRENT_TIMESTAMP, 1, 1, ?, NULL, " + + "'MINIMIZED', NULL)", UUID.randomUUID(), retry.tenantId(), "sha256:" + "0".repeat(64)); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/MembershipGenerationProjectionPostgresRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/MembershipGenerationProjectionPostgresRedisIntegrationTest.java index b2f4c9b1cb..da72f66a77 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/MembershipGenerationProjectionPostgresRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/MembershipGenerationProjectionPostgresRedisIntegrationTest.java @@ -105,7 +105,7 @@ class MembershipGenerationProjectionPostgresRedisIntegrationTest { private static final String WORKLOAD_NAMESPACE = "membership-generation-projection-test"; private static final String WORLD_SLUG = "membership-projection-proof-world"; private static final String REALM_SLUG = "production"; - private static final String NAMESPACE_ID = "membership-projection-proof-namespace"; + private static final String NAMESPACE_ID = "0e61cd22-45f6-4ee0-a3be-2f029e0a3c32"; private static final UUID REALM_ID = UUID.fromString("7bda1169-a8a3-4b43-96a4-53f8579ac164"); private static final long GAME_INSTANCE_ID = 79L; private static final long CATALOG_REVISION = 31L; 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 index a134b48707..287d49edb3 100644 --- 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 @@ -1399,24 +1399,89 @@ void canonicalTerminalJournalPreservesHistoryAndOnlyStoresContractShapedOutcomes operations.bindCanonicalPolicyEvidence( invalidSourceRequestId, unexpiredScope, callerBinding, true, 24L)); String missingSourceHash = AccountJoinDigest.tokenHash("missing-canonical-scope-source"); + Record invalidSourceBeforeFaultInjection = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT * FROM account_join_operations WHERE request_id = ?", + invalidSourceRequestId), + "Canonical JOIN operation row must exist before source-integrity proofs"); + Record originalScopeSourceBeforeFaultInjection = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT * FROM account_connect_scope_records WHERE scope_token_hash = ?", + invalidSourceBeforeFaultInjection.get("scope_token_hash", String.class)), + "Canonical JOIN operation must retain its original scope source"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> { + DSLContext transactionDsl = fixture.transactionDsl(); + transactionDsl.execute( + "ALTER TABLE account_join_operations " + + "DISABLE TRIGGER account_join_operation_identity_guard"); + transactionDsl.execute( + "UPDATE account_join_operations SET scope_token_hash = ? " + + "WHERE request_id = ?", + missingSourceHash, + invalidSourceRequestId); + })) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("account_join_operation_scope_reference_fk"); + Record invalidSourceAfterRejectedCorruption = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT * FROM account_join_operations WHERE request_id = ?", + invalidSourceRequestId), + "Rejected scope corruption must leave the operation row present"); + Record originalScopeSourceAfterRejectedCorruption = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT * FROM account_connect_scope_records WHERE scope_token_hash = ?", + invalidSourceBeforeFaultInjection.get("scope_token_hash", String.class)), + "Rejected scope corruption must leave its source row present"); + assertThat(invalidSourceAfterRejectedCorruption.intoMap()) + .containsExactlyEntriesOf(invalidSourceBeforeFaultInjection.intoMap()); + assertThat(originalScopeSourceAfterRejectedCorruption.intoMap()) + .containsExactlyEntriesOf(originalScopeSourceBeforeFaultInjection.intoMap()); + + // This deliberately simulates retained corrupt storage that ordinary production writes + // cannot create. The private fixture schema temporarily removes only the named FK and + // disables only the identity guard; the exact FK is restored as NOT VALID in the same + // transaction so it still guards every subsequent write. A failure rolls back all fixture DDL. fixture .transaction() .executeWithoutResult( status -> { DSLContext transactionDsl = fixture.transactionDsl(); + transactionDsl.execute( + "ALTER TABLE account_join_operations " + + "DROP CONSTRAINT account_join_operation_scope_reference_fk"); transactionDsl.execute( "ALTER TABLE account_join_operations " + "DISABLE TRIGGER account_join_operation_identity_guard"); - try { - transactionDsl.execute( - "UPDATE account_join_operations SET scope_token_hash = ? WHERE request_id = ?", - missingSourceHash, - invalidSourceRequestId); - } finally { - transactionDsl.execute( - "ALTER TABLE account_join_operations " - + "ENABLE TRIGGER account_join_operation_identity_guard"); - } + transactionDsl.execute( + "UPDATE account_join_operations SET scope_token_hash = ? WHERE request_id = ?", + missingSourceHash, + invalidSourceRequestId); + transactionDsl.execute( + "ALTER TABLE account_join_operations " + + "ENABLE TRIGGER account_join_operation_identity_guard"); + transactionDsl.execute( + "ALTER TABLE account_join_operations " + + "ADD CONSTRAINT account_join_operation_scope_reference_fk " + + "FOREIGN KEY (scope_token_hash) " + + "REFERENCES account_connect_scope_records(scope_token_hash) " + + "ON DELETE RESTRICT NOT VALID"); }); assertThatThrownBy( () -> diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGlobalRoleSourcePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGlobalRoleSourcePostgresIntegrationTest.java new file mode 100644 index 0000000000..5e965b8ca8 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGlobalRoleSourcePostgresIntegrationTest.java @@ -0,0 +1,506 @@ +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.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +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.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for Account's fresh-only explicit-empty global-role source prerequisite. */ +@Testcontainers(disabledWithoutDocker = true) +class AccountGlobalRoleSourcePostgresIntegrationTest { + private static final String MIGRATION_LOCATION = "classpath:db/migration"; + private static final String REPOSITORY_ACCOUNT = "global-role-source-repository"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void freshRepositoryAndDatabaseAccountsHaveStableIndependentExplicitEmptySources() { + Fixture fixture = fixture(false); + AccountRepository accountRepository = new AccountRepository(fixture.transactionDsl()); + AccountGlobalRoleSourceRepository sourceRepository = fixture.sourceRepository(); + + Account repositoryAccount = new Account(); + repositoryAccount.setUsername(REPOSITORY_ACCOUNT); + repositoryAccount.setEmail(REPOSITORY_ACCOUNT + "@example.test"); + repositoryAccount.setPasswordHash("hash"); + accountRepository.save(repositoryAccount); + + UUID databaseAccountUuid = + insertAccount(fixture.setupDsl(), "global-role-source-database", null); + + assertThatThrownBy( + () -> + sourceRepository.readFreshEmptySourceForUpdate(repositoryAccount.getAccountUuid())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account owner transaction"); + + AccountGlobalRoleSourceRepository.FreshEmptySource repositorySource = + inTransaction( + fixture.transaction(), + () -> + sourceRepository.readFreshEmptySourceForUpdate(repositoryAccount.getAccountUuid())); + AccountGlobalRoleSourceRepository.FreshEmptySource databaseSource = + inTransaction( + fixture.transaction(), + () -> sourceRepository.readFreshEmptySourceForUpdate(databaseAccountUuid)); + + assertThat(repositorySource.accountUuid()).isEqualTo(repositoryAccount.getAccountUuid()); + assertThat(repositorySource.accountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(databaseSource.accountUuid()).isEqualTo(databaseAccountUuid); + assertThat(databaseSource.accountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + assertExplicitEmpty(repositorySource); + assertExplicitEmpty(databaseSource); + + AccountGlobalRoleSourceRepository.FreshEmptySource repeatedRead = + inTransaction( + fixture.transaction(), + () -> + sourceRepository.readFreshEmptySourceForUpdate(repositoryAccount.getAccountUuid())); + assertThat(repeatedRead).isEqualTo(repositorySource); + assertThatThrownBy(() -> repositorySource.globalRoles().add("platformAdmin")) + .isInstanceOf(UnsupportedOperationException.class); + assertSourceStoredAsExactEmptyArray(fixture.setupDsl(), repositoryAccount.getAccountUuid()); + assertThat(sourceCount(fixture.setupDsl())).isEqualTo(2L); + + AccountAuthorityGenerationRepository generations = fixture.generations(); + AuthorityScope accountScope = AuthorityScope.account(repositoryAccount.getAccountUuid()); + ScopeState initialGeneration = + inTransaction(fixture.transaction(), () -> generations.initialize(accountScope)); + ScopeState advancedGeneration = + inTransaction( + fixture.transaction(), + () -> generations.advance(initialGeneration, initialGeneration.issuanceFence())); + assertThat(advancedGeneration.generation()).isEqualTo(initialGeneration.generation() + 1L); + assertThat(advancedGeneration.sourceVersion()) + .isEqualTo(initialGeneration.sourceVersion() + 1L); + assertThat( + inTransaction( + fixture.transaction(), + () -> + sourceRepository.readFreshEmptySourceForUpdate( + repositoryAccount.getAccountUuid()))) + .isEqualTo(repositorySource); + assertThat(globalRoleSourceVersion(fixture.setupDsl(), repositoryAccount.getAccountUuid())) + .isEqualTo(1L); + assertThat(sourceCount(fixture.setupDsl())).isEqualTo(2L); + } + + @Test + void v55DoesNotBackfillRetainedOrPreexistingFreshProvenanceRows() { + Fixture fixture = fixture(true); + UUID retainedUuid = UUID.randomUUID(); + UUID preexistingFreshUuid = UUID.randomUUID(); + insertPreexistingAccount( + fixture.setupDsl(), "global-role-source-retained", retainedUuid, "ACCOUNT_V29_MIGRATION"); + insertPreexistingAccount( + fixture.setupDsl(), + "global-role-source-preexisting-fresh", + preexistingFreshUuid, + "ACCOUNT_DATABASE_INSERT"); + Record retainedBefore = accountIdentityRecord(fixture.setupDsl(), retainedUuid); + Record freshBefore = accountIdentityRecord(fixture.setupDsl(), preexistingFreshUuid); + + migrateToLatest(fixture.dataSource(), fixture.schema()); + + assertThat(sourceCount(fixture.setupDsl())).isZero(); + assertThat(accountIdentityRecord(fixture.setupDsl(), retainedUuid)).isEqualTo(retainedBefore); + assertThat(accountIdentityRecord(fixture.setupDsl(), preexistingFreshUuid)) + .isEqualTo(freshBefore); + assertThatThrownBy( + () -> + inTransaction( + fixture.transaction(), + () -> fixture.sourceRepository().readFreshEmptySourceForUpdate(retainedUuid))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Fresh canonical Account identity readback is invalid"); + assertReaderDeniesMissingSource(fixture, preexistingFreshUuid); + assertThatThrownBy( + () -> + inTransaction( + fixture.transaction(), + () -> + fixture + .sourceRepository() + .readFreshEmptySourceForUpdate(UUID.randomUUID()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Persisted Account row is missing"); + } + + @Test + void nonnullLegacyPlayerAndCanonicalRoleScalarsDoNotInventSources() { + Fixture fixture = fixture(false); + List scalarRoles = List.of("player", "platformAdmin", "support", "billingAdmin"); + + for (int index = 0; index < scalarRoles.size(); index++) { + insertAccount( + fixture.setupDsl(), "global-role-source-scalar-" + index, scalarRoles.get(index)); + } + + assertThat(sourceCount(fixture.setupDsl())).isZero(); + assertThat( + fixture + .setupDsl() + .resultQuery("SELECT COUNT(*) FROM accounts WHERE role IS NOT NULL") + .fetchOne(0, Long.class)) + .isEqualTo((long) scalarRoles.size()); + } + + @Test + void directSourceWritesAndWrongScopeEvidenceCannotManufactureOrEraseBirthState() { + Fixture fixture = fixture(false); + UUID accountWithSource = + insertAccount(fixture.setupDsl(), "global-role-source-protected", null); + UUID accountWithoutSource = + insertAccount(fixture.setupDsl(), "global-role-source-no-birth", "player"); + Record sourceOwner = accountIdentityRecord(fixture.setupDsl(), accountWithSource); + Record nonSourceOwner = accountIdentityRecord(fixture.setupDsl(), accountWithoutSource); + + assertThatThrownBy( + () -> + insertSource( + fixture.setupDsl(), + accountWithoutSource, + nonSourceOwner.get("account_uuid_source_numeric_id", Long.class), + nonSourceOwner.get("account_uuid_provenance", String.class), + List.of(), + 1L)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "Account global-role source may only be inserted by its fresh Account birth path"); + assertThatThrownBy( + () -> + insertSource( + fixture.setupDsl(), + accountWithSource, + sourceOwner.get("account_uuid_source_numeric_id", Long.class), + sourceOwner.get("account_uuid_provenance", String.class), + List.of("platformAdmin"), + 1L)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "Account global-role source may only be inserted by its fresh Account birth path"); + assertThatThrownBy( + () -> + insertSource( + fixture.setupDsl(), + accountWithSource, + nonSourceOwner.get("account_uuid_source_numeric_id", Long.class), + nonSourceOwner.get("account_uuid_provenance", String.class), + List.of(), + 1L)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "Account global-role source may only be inserted by its fresh Account birth path"); + assertThat(sourceCount(fixture.setupDsl())).isEqualTo(1L); + + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_global_role_sources " + + "SET account_uuid_source_numeric_id = " + + "account_uuid_source_numeric_id + 1 " + + "WHERE account_uuid = ?", + accountWithSource)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "Fresh Account global-role source is immutable until a versioned writer exists"); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_global_role_sources WHERE account_uuid = ?", + accountWithSource)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "Fresh Account global-role source is immutable until a versioned writer exists"); + assertThat(sourceCount(fixture.setupDsl())).isEqualTo(1L); + assertThatThrownBy(() -> fixture.setupDsl().execute("TRUNCATE account_global_role_sources")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Fresh Account global-role source cannot be truncated"); + assertThat(sourceCount(fixture.setupDsl())).isEqualTo(1L); + + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE accounts SET role = 'support' WHERE account_uuid = ?", + accountWithSource)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "Account role change requires a versioned global-role source writer"); + assertThat(globalRoleSourceVersion(fixture.setupDsl(), accountWithSource)).isEqualTo(1L); + assertSourceStoredAsExactEmptyArray(fixture.setupDsl(), accountWithSource); + } + + @Test + void abortedFreshInsertLeavesNoAccountOrPartialSourceAndReadRequiresWritableTransaction() { + Fixture fixture = fixture(false); + AccountRepository accountRepository = new AccountRepository(fixture.transactionDsl()); + AccountGlobalRoleSourceRepository sourceRepository = fixture.sourceRepository(); + Account rolledBack = new Account(); + rolledBack.setUsername("global-role-source-rollback"); + rolledBack.setEmail("global-role-source-rollback@example.test"); + rolledBack.setPasswordHash("hash"); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> { + accountRepository.save(rolledBack); + throw new IllegalStateException("rollback fresh Account birth"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("rollback fresh Account birth"); + assertThat( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM accounts WHERE username = ?", rolledBack.getUsername()) + .fetchOne(0, Long.class)) + .isZero(); + assertThat(sourceCount(fixture.setupDsl())).isZero(); + + Account committed = new Account(); + committed.setUsername("global-role-source-readonly"); + committed.setEmail("global-role-source-readonly@example.test"); + committed.setPasswordHash("hash"); + accountRepository.save(committed); + assertThatThrownBy( + () -> + fixture + .readOnlyTransaction() + .execute( + status -> + sourceRepository.readFreshEmptySourceForUpdate( + committed.getAccountUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account owner transaction"); + assertThatThrownBy( + () -> + fixture + .repeatableReadTransaction() + .execute( + status -> + sourceRepository.readFreshEmptySourceForUpdate( + committed.getAccountUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ COMMITTED isolation"); + assertThat( + inTransaction( + fixture.transaction(), + () -> sourceRepository.readFreshEmptySourceForUpdate(committed.getAccountUuid()))) + .satisfies(source -> assertExplicitEmpty(source)); + } + + private Fixture fixture(boolean stopAtV54) { + String schema = "account_global_role_source_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway flyway = flyway(dataSource, schema, stopAtV54); + flyway.migrate(); + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + TransactionTemplate readOnlyTransaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + readOnlyTransaction.setReadOnly(true); + TransactionTemplate repeatableReadTransaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + repeatableReadTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + return new Fixture( + schema, + dataSource, + setupDsl, + transactionDsl, + transaction, + readOnlyTransaction, + repeatableReadTransaction, + new AccountGlobalRoleSourceRepository(transactionDsl, dataSource), + new AccountAuthorityGenerationRepository(transactionDsl)); + } + + private static Flyway flyway( + DriverManagerDataSource dataSource, String schema, boolean stopAtV54) { + Flyway flyway = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations(MIGRATION_LOCATION) + .load(); + if (!stopAtV54) { + return flyway; + } + return Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("54")) + .load(); + } + + private static void migrateToLatest(DriverManagerDataSource dataSource, String schema) { + flyway(dataSource, schema, false).migrate(); + } + + private static UUID insertAccount(DSLContext dsl, String username, String scalarRole) { + if (scalarRole == null) { + return dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash, role) " + + "VALUES (?, ?, ?, NULL) RETURNING account_uuid", + username, + username + "@example.test", + "hash") + .fetchOne(0, UUID.class); + } + return dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash, role) " + + "VALUES (?, ?, ?, ?) RETURNING account_uuid", + username, + username + "@example.test", + "hash", + scalarRole) + .fetchOne(0, UUID.class); + } + + private static void insertPreexistingAccount( + DSLContext dsl, String username, UUID accountUuid, String provenance) { + dsl.execute( + "INSERT INTO accounts (username, email, password_hash, role, account_uuid, " + + "account_uuid_provenance) VALUES (?, ?, ?, NULL, ?, ?)", + username, + username + "@example.test", + "hash", + accountUuid, + provenance); + } + + private static void insertSource( + DSLContext dsl, + UUID accountUuid, + Long sourceNumericId, + String provenance, + List globalRoles, + long sourceVersion) { + dsl.execute( + "INSERT INTO account_global_role_sources (account_uuid, account_uuid_source_numeric_id, " + + "account_uuid_provenance, global_roles, global_role_source_version) " + + "VALUES (?, ?, ?, ?::TEXT[], ?)", + accountUuid, + sourceNumericId, + provenance, + globalRoles.toArray(String[]::new), + sourceVersion); + } + + private static Record accountIdentityRecord(DSLContext dsl, UUID accountUuid) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", accountUuid), + "Expected exact Account identity row"); + } + + private static long sourceCount(DSLContext dsl) { + return Objects.requireNonNull( + dsl.resultQuery("SELECT COUNT(*) FROM account_global_role_sources") + .fetchOne(0, Long.class)); + } + + private static long globalRoleSourceVersion(DSLContext dsl, UUID accountUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT global_role_source_version FROM account_global_role_sources " + + "WHERE account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class)); + } + + private static void assertSourceStoredAsExactEmptyArray(DSLContext dsl, UUID accountUuid) { + Record source = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT cardinality(global_roles) AS role_count, global_roles = ARRAY[]::TEXT[] " + + "AS is_exact_empty, global_role_source_version " + + "FROM account_global_role_sources WHERE account_uuid = ?", + accountUuid), + "Expected durable fresh global-role source"); + assertThat(source.get("role_count", Integer.class)).isZero(); + assertThat(source.get("is_exact_empty", Boolean.class)).isTrue(); + assertThat(source.get("global_role_source_version", Long.class)).isEqualTo(1L); + } + + private static void assertExplicitEmpty( + AccountGlobalRoleSourceRepository.FreshEmptySource source) { + assertThat(source.globalRoles()).isEmpty(); + assertThat(source.globalRoleSourceVersion()).isEqualTo(1L); + assertThat(source.accountUuidSourceNumericId()).isEqualTo(source.accountRowId()); + } + + private static void assertReaderDeniesMissingSource(Fixture fixture, UUID accountUuid) { + assertThatThrownBy( + () -> + inTransaction( + fixture.transaction(), + () -> fixture.sourceRepository().readFreshEmptySourceForUpdate(accountUuid))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Fresh Account global-role source is missing"); + } + + private static T inTransaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext setupDsl, + DSLContext transactionDsl, + TransactionTemplate transaction, + TransactionTemplate readOnlyTransaction, + TransactionTemplate repeatableReadTransaction, + AccountGlobalRoleSourceRepository sourceRepository, + AccountAuthorityGenerationRepository generations) {} +} 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 9e92eff7d2..e09a43b311 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 @@ -69,30 +69,44 @@ class AccountRepositoryIntegrationTest { @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + private DriverManagerDataSource adminDataSource; private DriverManagerDataSource dataSource; private DSLContext dsl; private AccountRepository repository; @BeforeAll void setUpRepository() { + adminDataSource = new DriverManagerDataSource(); + adminDataSource.setDriverClassName(postgres.getDriverClassName()); + adminDataSource.setUrl(postgres.getJdbcUrl()); + adminDataSource.setUsername(postgres.getUsername()); + adminDataSource.setPassword(postgres.getPassword()); + } + + @BeforeEach + void setUpIsolatedSchema() { + String schema = "account_repository_it_" + UUID.randomUUID().toString().replace("-", ""); + DSL.using(adminDataSource, SQLDialect.POSTGRES).execute("CREATE SCHEMA " + schema); + dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(postgres.getDriverClassName()); - dataSource.setUrl(postgres.getJdbcUrl()); + String jdbcUrl = postgres.getJdbcUrl(); + dataSource.setUrl(jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema); dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); - Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .load() + .migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); repository = new AccountRepository(dsl); } - @BeforeEach - void cleanTables() { - dsl.execute("TRUNCATE TABLE account_audit_outbox"); - dsl.execute("TRUNCATE TABLE accounts RESTART IDENTITY CASCADE"); - } - @Test void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { JdbcTemplate jdbc = new JdbcTemplate(dataSource); @@ -1189,6 +1203,16 @@ void globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows() { "SELECT COUNT(*) FROM " + schema + ".profiles WHERE account_id = ?", legacyAccountId)) .isEqualTo(1L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + + schema + + ".account_global_role_sources WHERE account_uuid = (SELECT account_uuid " + + "FROM " + + schema + + ".accounts WHERE id = ?)", + legacyAccountId)) + .isEqualTo(0L); long newAccountId = Objects.requireNonNull( @@ -1213,6 +1237,32 @@ void globalRegistrationMigrationPreservesAndQuarantinesUnprovenTenantRows() { + ".account_tenant_membership WHERE account_id = ?", newAccountId)) .isEqualTo(0L); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + schema + ".accounts SET role = 'platformAdmin' WHERE id = ?", + newAccountId)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "Account role change requires a versioned global-role source writer"); + assertThat( + dsl.fetchValue("SELECT role FROM " + schema + ".accounts WHERE id = ?", newAccountId)) + .isNull(); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM " + + schema + + ".account_global_role_sources source " + + "JOIN " + + schema + + ".accounts account_row ON account_row.account_uuid = source.account_uuid " + + "WHERE account_row.id = ? " + + "AND source.account_uuid_source_numeric_id = account_row.id " + + "AND source.account_uuid_provenance = account_row.account_uuid_provenance " + + "AND source.global_roles = ARRAY[]::TEXT[] " + + "AND source.global_role_source_version = 1", + newAccountId)) + .isEqualTo(1L); } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java index 7349671ba3..f90f4c444c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java @@ -11,6 +11,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.time.LocalDateTime; +import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -41,6 +42,7 @@ class CredentialCleanupRepositoryIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); private DSLContext dsl; + private DataSource adminDataSource; private DataSource dataSource; private PasswordResetTokenRepository passwordResetTokenRepository; private EmailVerificationTokenRepository emailVerificationTokenRepository; @@ -48,19 +50,33 @@ class CredentialCleanupRepositoryIntegrationTest { @BeforeAll void setUpRepositories() { - dataSource = newDataSource(); - Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + adminDataSource = newDataSource(); + } + + @BeforeEach + void setUpIsolatedSchema() { + String schema = "credential_cleanup_it_" + UUID.randomUUID().toString().replace("-", ""); + DSL.using(adminDataSource, SQLDialect.POSTGRES).execute("CREATE SCHEMA " + schema); + + DriverManagerDataSource schemaDataSource = newDataSource(); + String jdbcUrl = postgres.getJdbcUrl(); + schemaDataSource.setUrl( + jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema); + dataSource = schemaDataSource; + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .load() + .migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); passwordResetTokenRepository = new PasswordResetTokenRepository(dsl); emailVerificationTokenRepository = new EmailVerificationTokenRepository(dsl); emailLoginChallengeRepository = new AccountEmailLoginChallengeRepository(dsl); } - @BeforeEach - void cleanTables() { - dsl.execute("TRUNCATE TABLE accounts RESTART IDENTITY CASCADE"); - } - @Test void passwordResetCleanupIsBoundedStrictAndIdempotent() { LocalDateTime capturedNow = LocalDateTime.of(2026, 9, 19, 12, 0); @@ -258,7 +274,7 @@ private interface ExpiredCleanupOperation { int deleteExpired(DSLContext cleanupDsl, LocalDateTime capturedNow); } - private DataSource newDataSource() { + private DriverManagerDataSource newDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(postgres.getDriverClassName()); dataSource.setUrl(postgres.getJdbcUrl()); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java index a798750989..033cbb9647 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountAuthenticationUuidIntegrationTest.java @@ -105,18 +105,14 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoSpyBean private AccountEmailLoginChallengeRepository challengeRepositorySpy; @BeforeEach - void cleanDatabaseAndObserveOwnerTransaction() { - dsl.execute("TRUNCATE TABLE account_audit_outbox"); - dsl.execute("TRUNCATE TABLE accounts RESTART IDENTITY CASCADE"); - AccountEmailLoginChallengeRepository challengeRepositoryTarget = - AopTestUtils.getUltimateTargetObject(challengeRepositorySpy); + void observeOwnerTransaction() { doAnswer( invocation -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); invocation.callRealMethod(); return null; }) - .when(challengeRepositoryTarget) + .when(challengeRepositorySpy) .lockAccountChallenge(anyLong()); } @@ -134,6 +130,7 @@ void repositoryInsertAuthenticationUsesExactPersistedUuidAndPrivateStorageKey() UUID returnedAccountUuid = UUID.fromString(created.id()); long accountId = accountService.resolveAccountStorageId(returnedAccountUuid); Account persisted = accountRepository.findById(accountId).orElseThrow(); + String expectedRegistrationAuditPayload = "{\"accountId\":\"" + returnedAccountUuid + "\"}"; assertThat(created.id()) .isEqualTo(persisted.getAccountUuid().toString()) @@ -149,14 +146,14 @@ void repositoryInsertAuthenticationUsesExactPersistedUuidAndPrivateStorageKey() "SELECT payload FROM account_audit_outbox " + "WHERE scope = 'platform' AND tenant_id IS NULL " + "AND producer_service = 'account-service' " - + "AND event_type = 'ACCOUNT_REGISTERED'") + + "AND event_type = 'ACCOUNT_REGISTERED' AND payload = ?", + expectedRegistrationAuditPayload) .fetchOne(), "Expected durable ACCOUNT_REGISTERED platform audit row"); String registrationAuditPayload = Objects.requireNonNull( registrationAudit.get(0, String.class), "Expected registration audit payload"); - assertThat(registrationAuditPayload) - .isEqualTo("{\"accountId\":\"" + returnedAccountUuid + "\"}"); + assertThat(registrationAuditPayload).isEqualTo(expectedRegistrationAuditPayload); assertAuthenticationAndPrivateLookup(username, accountId, persisted.getAccountUuid()); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountFreshCaptureSourcesTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountFreshCaptureSourcesTest.java new file mode 100644 index 0000000000..9f1dbe728f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountFreshCaptureSourcesTest.java @@ -0,0 +1,88 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountFreshCaptureSources; +import net.firedevops.firemud.accountservice.dto.AccountMembershipCaptureSources; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourceRepository.FreshEmptySource; +import org.junit.jupiter.api.Test; + +class AccountFreshCaptureSourcesTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("a50fdfca-f085-4a65-9ea1-ec99cda0f645"); + private static final UUID TENANT_UUID = UUID.fromString("8e35f45a-fd75-496e-aa40-a2a4da03ee4c"); + + @Test + void retainsExactMembershipSourcesAndFreshRoleBirthEvidenceSeparately() { + AccountMembershipCaptureSources membershipSources = + membershipSources(ACCOUNT_UUID, TENANT_UUID); + FreshEmptySource roleSource = freshSource(ACCOUNT_UUID, 73L); + + AccountFreshCaptureSources sources = + new AccountFreshCaptureSources(ACCOUNT_UUID, TENANT_UUID, membershipSources, roleSource); + + assertThat(sources.membershipSources()).isSameAs(membershipSources); + assertThat(sources.freshGlobalRoleSource()).isSameAs(roleSource); + assertThat(sources.freshGlobalRoleSource().globalRoleSourceVersion()).isEqualTo(1L); + } + + @Test + void rejectsMembershipSourcesFromAnotherRequestedAccountOrTenant() { + AccountMembershipCaptureSources wrongAccount = + membershipSources(UUID.randomUUID(), TENANT_UUID); + AccountMembershipCaptureSources wrongTenant = + membershipSources(ACCOUNT_UUID, UUID.randomUUID()); + + assertThatThrownBy( + () -> + new AccountFreshCaptureSources( + ACCOUNT_UUID, TENANT_UUID, wrongAccount, freshSource(ACCOUNT_UUID, 73L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("membership sources differ"); + assertThatThrownBy( + () -> + new AccountFreshCaptureSources( + ACCOUNT_UUID, TENANT_UUID, wrongTenant, freshSource(ACCOUNT_UUID, 73L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("membership sources differ"); + } + + @Test + void rejectsFreshGlobalRoleEvidenceForAnotherAccount() { + AccountMembershipCaptureSources membershipSources = + membershipSources(ACCOUNT_UUID, TENANT_UUID); + + assertThatThrownBy( + () -> + new AccountFreshCaptureSources( + ACCOUNT_UUID, + TENANT_UUID, + membershipSources, + freshSource(UUID.randomUUID(), 74L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("fresh Account identity"); + } + + private static AccountMembershipCaptureSources membershipSources( + UUID accountUuid, UUID tenantUuid) { + AccountMembershipCaptureSources sources = mock(AccountMembershipCaptureSources.class); + when(sources.requestedAccountUuid()).thenReturn(accountUuid); + when(sources.requestedTenantUuid()).thenReturn(tenantUuid); + return sources; + } + + private static FreshEmptySource freshSource(UUID accountUuid, long accountRowId) { + return new FreshEmptySource( + accountUuid, + accountRowId, + accountRowId, + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, + List.of(), + 1L); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSourcesTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSourcesTest.java new file mode 100644 index 0000000000..b06623c8bb --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountMembershipCaptureSourcesTest.java @@ -0,0 +1,584 @@ +package net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import org.junit.jupiter.api.Test; + +class AccountMembershipCaptureSourcesTest { + private static final String STREAM_PREFIX = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + + @Test + void retainsExactLockedScopeVersionsRoleHeaderEventAndFenceImmutably() { + CaptureFixture fixture = activeFixture(); + AccountMembershipCaptureSources sources = fixture.sources(); + + assertThat(sources.authoritySnapshot()).isSameAs(fixture.authoritySnapshot()); + assertThat(sources.authoritySnapshot().issuer().sourceVersion()).isEqualTo(1L); + assertThat(sources.authoritySnapshot().account().sourceVersion()).isEqualTo(1L); + assertThat(sources.authoritySnapshot().tenants().getFirst().sourceVersion()).isEqualTo(1L); + assertThat(sources.authoritySnapshot().memberships().getFirst().sourceVersion()).isEqualTo(1L); + assertThat(sources.authoritySnapshot().issuanceFence().value()).isEqualTo(1L); + assertThat(sources.authoritySnapshot().issuanceFence().sourceVersion()).isEqualTo(1L); + assertThat(sources.membershipSnapshot().authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(sources.membershipSnapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(sources.membershipSnapshot().sourceEvent().canonicalJson()) + .isEqualTo(fixture.event().canonicalJson()); + assertThat(sources.roleSource().orElseThrow()).isSameAs(fixture.roleSource()); + assertThat(sources.roleSource().orElseThrow().accountUuid()).isEqualTo(fixture.accountUuid()); + assertThat(sources.roleSource().orElseThrow().tenantId()).isEqualTo(81L); + assertThat(sources.roleSource().orElseThrow().tenantUuid()).isNull(); + assertThat(sources.roleSource().orElseThrow().tenantProvenance()).isNull(); + assertThat(sources.retainedTenantAssociation()).contains(fixture.tenantAssociation()); + assertThat(sources.roleSource().orElseThrow().snapshotVersion()).isEqualTo(2L); + + assertThatThrownBy(() -> sources.membershipSnapshot().outboxCheckpoints().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> sources.membershipSnapshot().outboxSourceEvidence().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> sources.roleSource().orElseThrow().roles().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> sources.authoritySnapshot().memberships().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void retainsOnlyAuthenticatedNonadmittingSequenceZeroAbsence() { + CaptureFixture fixture = missingFixture(); + AccountMembershipCaptureSources sources = fixture.sources(); + + assertThat(sources.membershipSnapshot().membershipExists()).isFalse(); + assertThat(sources.membershipSnapshot().gameplayAdmissionAllowed()).isFalse(); + assertThat(sources.membershipSnapshot().membershipBaseline().membershipLifecycleState()) + .isEqualTo("MISSING"); + assertThat(sources.membershipSnapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(sources.membershipSnapshot().outboxCheckpoints()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.outboxStreamKey()) + .isEqualTo(membershipStream(fixture.accountUuid(), fixture.tenantUuid())); + assertThat(checkpoint.outboxSequence()).isEqualTo("0"); + }); + assertThat(sources.membershipSnapshot().outboxSourceEvidence()) + .noneMatch( + source -> + source + .outboxStreamKey() + .equals(membershipStream(fixture.accountUuid(), fixture.tenantUuid()))); + assertThat(sources.membershipSnapshot().sourceEvent()).isNull(); + assertThat(sources.roleSource()).isEmpty(); + } + + @Test + void rejectsRequestScopeTupleSourceVersionCheckpointAndFenceMixes() { + CaptureFixture fixture = activeFixture(); + CompositeSnapshot original = fixture.authoritySnapshot(); + + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + UUID.randomUUID(), + fixture.tenantUuid(), + original, + fixture.membershipSnapshot(), + Optional.of(fixture.roleSource()), + Optional.of(fixture.tenantAssociation()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact canonical request"); + + ScopeState mixedTenant = + new ScopeState( + original.tenants().getFirst().scope(), + original.tenants().getFirst().generation() + 1L, + original.tenants().getFirst().sourceVersion() + 1L, + null); + CompositeSnapshot mixedTuple = + new CompositeSnapshot( + original.issuer(), + original.account(), + List.of(mixedTenant), + original.memberships(), + original.issuanceFence()); + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + mixedTuple, + fixture.membershipSnapshot(), + Optional.of(fixture.roleSource()), + Optional.of(fixture.tenantAssociation()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("authority generations or fence"); + + ScopeState mixedIssuerVersion = + new ScopeState( + original.issuer().scope(), + original.issuer().generation(), + original.issuer().sourceVersion() + 1L, + null); + CompositeSnapshot mixedCheckpoint = + new CompositeSnapshot( + mixedIssuerVersion, + original.account(), + original.tenants(), + original.memberships(), + original.issuanceFence()); + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + mixedCheckpoint, + fixture.membershipSnapshot(), + Optional.of(fixture.roleSource()), + Optional.of(fixture.tenantAssociation()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("checkpoints differ"); + + IssuanceFence changedFence = new IssuanceFence(fixture.accountUuid(), 2L, 2L); + CompositeSnapshot mixedFence = + new CompositeSnapshot( + original.issuer(), + new ScopeState(original.account().scope(), 1L, 1L, changedFence), + original.tenants(), + List.of( + new ScopeState(original.memberships().getFirst().scope(), 1L, 1L, changedFence)), + changedFence); + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + mixedFence, + fixture.membershipSnapshot(), + Optional.of(fixture.roleSource()), + Optional.of(fixture.tenantAssociation()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("authority generations or fence"); + } + + @Test + void rejectsMismatchedRoleHeaderAndMembershipEventCheckpoint() { + CaptureFixture fixture = activeFixture(); + RoleSnapshot mixedRoleHeader = + new RoleSnapshot( + fixture.roleSource().accountId(), + fixture.roleSource().tenantId(), + fixture.roleSource().membershipId(), + fixture.roleSource().snapshotVersion() + 1L, + fixture.roleSource().roles(), + fixture.roleSource().accountUuid(), + fixture.roleSource().tenantUuid(), + fixture.roleSource().tenantProvenance()); + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.authoritySnapshot(), + fixture.membershipSnapshot(), + Optional.of(mixedRoleHeader), + Optional.of(fixture.tenantAssociation()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("role header and identity"); + + List mixedCheckpoints = + new ArrayList<>( + fixture.membershipSnapshot().outboxCheckpoints().stream() + .map( + checkpoint -> + checkpoint + .outboxStreamKey() + .equals( + membershipStream(fixture.accountUuid(), fixture.tenantUuid())) + ? new OutboxCheckpointEntry( + membershipStream(fixture.accountUuid(), fixture.tenantUuid()), "2") + : checkpoint) + .toList()); + assertThatThrownBy( + () -> + new RuntimeMembershipSnapshotDto( + fixture.accountUuid().toString(), + fixture.tenantUuid().toString(), + fixture.accountUuid().toString(), + fixture.tenantUuid().toString(), + true, + true, + new RuntimeMembershipSnapshotDto.MembershipBaseline( + "ACTIVE", Map.of(fixture.tenantUuid().toString(), "2"), "1"), + fixture.roleSource().roles(), + fixture.membershipSnapshot().authorityTuple(), + "1", + Instant.EPOCH, + mixedCheckpoints, + fixture.membershipSnapshot().outboxSourceEvidence(), + fixture.event())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void bindsRawAndCanonicalRoleHeadersToTheExactRetainedAssociation() { + CaptureFixture fixture = activeFixture(); + ApprovedAssociation association = fixture.tenantAssociation(); + + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.authoritySnapshot(), + fixture.membershipSnapshot(), + Optional.of(fixture.roleSource()), + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + + ApprovedAssociation substitutedTenant = + copyAssociation( + association, + association.legacyTenantId(), + UUID.randomUUID(), + association.operationId(), + association.manifestDigest()); + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.authoritySnapshot(), + fixture.membershipSnapshot(), + Optional.of(fixture.roleSource()), + Optional.of(substitutedTenant))) + .isInstanceOf(IllegalArgumentException.class); + + RoleSnapshot mismatchedAccountHeader = + new RoleSnapshot( + fixture.roleSource().accountId(), + fixture.roleSource().tenantId(), + fixture.roleSource().membershipId(), + fixture.roleSource().snapshotVersion(), + fixture.roleSource().roles(), + UUID.fromString("5a29ea5e-a463-4f8a-a1cf-11e0cb35731d"), + null, + null); + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.authoritySnapshot(), + fixture.membershipSnapshot(), + Optional.of(mismatchedAccountHeader), + Optional.of(association))) + .isInstanceOf(IllegalArgumentException.class); + + ApprovedAssociation wrongLegacyId = + copyAssociation( + association, + association.legacyTenantId() + 1L, + association.canonicalTenantId(), + association.operationId(), + association.manifestDigest()); + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.authoritySnapshot(), + fixture.membershipSnapshot(), + Optional.of(fixture.roleSource()), + Optional.of(wrongLegacyId))) + .isInstanceOf(IllegalArgumentException.class); + + VerifiedTenantProvenance canonicalProvenance = + new VerifiedTenantProvenance( + association.legacyTenantId(), + TenantProvenanceKind.APPROVED_RETAINED, + association.operationId(), + association.manifestDigest()); + RoleSnapshot canonicalRoleHeader = + new RoleSnapshot( + fixture.roleSource().accountId(), + fixture.roleSource().tenantId(), + fixture.roleSource().membershipId(), + fixture.roleSource().snapshotVersion(), + fixture.roleSource().roles(), + fixture.accountUuid(), + fixture.tenantUuid(), + canonicalProvenance); + assertThat( + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.authoritySnapshot(), + fixture.membershipSnapshot(), + Optional.of(canonicalRoleHeader), + Optional.of(association))) + .isNotNull(); + + ApprovedAssociation wrongProvenance = + copyAssociation( + association, + association.legacyTenantId(), + association.canonicalTenantId(), + UUID.randomUUID(), + association.manifestDigest()); + assertThatThrownBy( + () -> + new AccountMembershipCaptureSources( + fixture.accountUuid(), + fixture.tenantUuid(), + fixture.authoritySnapshot(), + fixture.membershipSnapshot(), + Optional.of(canonicalRoleHeader), + Optional.of(wrongProvenance))) + .isInstanceOf(IllegalArgumentException.class); + } + + private CaptureFixture missingFixture() { + UUID accountUuid = UUID.fromString("1c69f3f4-b0f2-4a3a-8eb7-f4f9025746d1"); + UUID tenantUuid = UUID.fromString("8f3b4a30-d5f2-4ddc-a7f3-bb4c729e0461"); + IssuanceFence fence = new IssuanceFence(accountUuid, 1L, 1L); + CompositeSnapshot authoritySnapshot = + new CompositeSnapshot( + new ScopeState( + AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER), 1L, 1L, null), + new ScopeState(AuthorityScope.account(accountUuid), 1L, 1L, fence), + List.of(new ScopeState(AuthorityScope.tenant(tenantUuid), 1L, 1L, null)), + List.of( + new ScopeState(AuthorityScope.membership(accountUuid, tenantUuid), 1L, 1L, fence)), + fence); + AuthorityTuple authorityTuple = + new AuthorityTuple( + "1", + "1", + Map.of(tenantUuid.toString(), "1"), + Map.of(tenantUuid.toString(), "1"), + List.of(), + Optional.empty(), + Optional.empty()); + List checkpoints = + new ArrayList<>( + List.of( + new OutboxCheckpointEntry(accountStream(accountUuid), "0"), + new OutboxCheckpointEntry(issuerStream(), "0"), + new OutboxCheckpointEntry(membershipStream(accountUuid, tenantUuid), "0"), + new OutboxCheckpointEntry(tenantStream(tenantUuid), "0"))); + RuntimeMembershipSnapshotDto membershipSnapshot = + new RuntimeMembershipSnapshotDto( + accountUuid.toString(), + tenantUuid.toString(), + accountUuid.toString(), + tenantUuid.toString(), + false, + false, + new RuntimeMembershipSnapshotDto.MembershipBaseline( + "MISSING", Map.of(tenantUuid.toString(), "1"), "1"), + List.of(), + authorityTuple, + "1", + Instant.EPOCH, + checkpoints, + List.of(), + null); + checkpoints.clear(); + return new CaptureFixture( + accountUuid, tenantUuid, authoritySnapshot, membershipSnapshot, null, null, null); + } + + private CaptureFixture activeFixture() { + UUID accountUuid = UUID.fromString("76e4fb60-0e16-4b1f-90e5-3ccf465007e1"); + UUID tenantUuid = UUID.fromString("ab4ee2cd-d93c-4a87-b975-c832e197d7c1"); + IssuanceFence fence = new IssuanceFence(accountUuid, 1L, 1L); + ScopeState issuer = + new ScopeState(AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER), 1L, 1L, null); + ScopeState account = new ScopeState(AuthorityScope.account(accountUuid), 1L, 1L, fence); + ScopeState tenant = new ScopeState(AuthorityScope.tenant(tenantUuid), 1L, 1L, null); + ScopeState membership = + new ScopeState(AuthorityScope.membership(accountUuid, tenantUuid), 1L, 1L, fence); + CompositeSnapshot authoritySnapshot = + new CompositeSnapshot(issuer, account, List.of(tenant), List.of(membership), fence); + AuthorityTuple authorityTuple = + new AuthorityTuple( + "1", + "1", + Map.of(tenantUuid.toString(), "1"), + Map.of(tenantUuid.toString(), "1"), + List.of(), + Optional.empty(), + Optional.empty()); + String membershipStream = membershipStream(accountUuid, tenantUuid); + var event = + MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "test-membership-event-1"), + Map.entry("requestId", "test-membership-request-1"), + Map.entry("outboxStreamKey", membershipStream), + Map.entry("outboxSequence", "1"), + Map.entry("sourceScope", "membership/" + accountUuid + "/" + tenantUuid), + Map.entry("accountId", accountUuid.toString()), + Map.entry("tenantId", tenantUuid.toString()), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(tenantUuid.toString(), "2")), + Map.entry("membershipAuthorityGeneration", "1"), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(tenantUuid.toString(), "1"), + "membershipAuthorityGeneration", Map.of(tenantUuid.toString(), "1"), + "privateRealmGrantVersions", List.of())), + Map.entry("issuanceFence", "1"), + Map.entry("roles", List.of("player")), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false))); + List checkpoints = + new ArrayList<>( + List.of( + new OutboxCheckpointEntry(accountStream(accountUuid), "0"), + new OutboxCheckpointEntry(issuerStream(), "0"), + new OutboxCheckpointEntry(membershipStream, "1"), + new OutboxCheckpointEntry(tenantStream(tenantUuid), "0"))); + List sourceEvidence = + new ArrayList<>( + List.of( + new OutboxSourceEvidence( + membershipStream, + "1", + event.eventId(), + event.eventDigest(), + event.canonicalJson()))); + RuntimeMembershipSnapshotDto membershipSnapshot = + new RuntimeMembershipSnapshotDto( + accountUuid.toString(), + tenantUuid.toString(), + accountUuid.toString(), + tenantUuid.toString(), + true, + true, + new RuntimeMembershipSnapshotDto.MembershipBaseline( + "ACTIVE", Map.of(tenantUuid.toString(), "2"), "1"), + List.of("player"), + authorityTuple, + "1", + Instant.EPOCH, + checkpoints, + sourceEvidence, + event); + checkpoints.clear(); + sourceEvidence.clear(); + + ApprovedAssociation association = + new ApprovedAssociation( + 81L, + tenantUuid, + "legacy-game-account-capture-source-test", + 51L, + "sha256:" + "b".repeat(64), + UUID.fromString("f1d82a71-d966-43da-a5cc-e9ac1ea4d8cb"), + "sha256:" + "a".repeat(64), + "test-signature", + "account-test-namespace", + "test-signer", + "account-test-owner", + "account-capture-source-test", + "2026-10-04T00:00:00Z", + 1, + 1); + RoleSnapshot roleSource = + new RoleSnapshot(41L, 81L, 33L, 2L, List.of("player"), accountUuid, null, null); + return new CaptureFixture( + accountUuid, + tenantUuid, + authoritySnapshot, + membershipSnapshot, + event, + roleSource, + association); + } + + private ApprovedAssociation copyAssociation( + ApprovedAssociation source, + long legacyTenantId, + UUID canonicalTenantId, + UUID operationId, + String manifestDigest) { + return new ApprovedAssociation( + legacyTenantId, + canonicalTenantId, + source.sourceLegacyGameTenantId(), + source.sourceGameRowId(), + source.accountEvidenceDigest(), + operationId, + manifestDigest, + source.manifestSignature(), + source.targetNamespace(), + source.signerKeyId(), + source.approvedBy(), + source.approvalReference(), + source.signedAt(), + source.operationEntryCount(), + source.manifestSchemaVersion()); + } + + private static String issuerStream() { + return STREAM_PREFIX + "issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER; + } + + private static String accountStream(UUID accountUuid) { + return STREAM_PREFIX + "account/" + accountUuid; + } + + private static String tenantStream(UUID tenantUuid) { + return STREAM_PREFIX + "tenant/" + tenantUuid; + } + + private static String membershipStream(UUID accountUuid, UUID tenantUuid) { + return STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; + } + + private record CaptureFixture( + UUID accountUuid, + UUID tenantUuid, + CompositeSnapshot authoritySnapshot, + RuntimeMembershipSnapshotDto membershipSnapshot, + MembershipAuthorityEventV1Codec.MembershipEvent event, + RoleSnapshot roleSource, + ApprovedAssociation tenantAssociation) { + AccountMembershipCaptureSources sources() { + return new AccountMembershipCaptureSources( + accountUuid, + tenantUuid, + authoritySnapshot, + membershipSnapshot, + Optional.ofNullable(roleSource), + Optional.ofNullable(tenantAssociation)); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountBareLoginTokenIdentityFenceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountBareLoginTokenIdentityFenceTest.java new file mode 100644 index 0000000000..1269396dc4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountBareLoginTokenIdentityFenceTest.java @@ -0,0 +1,141 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.time.Instant; +import java.util.HexFormat; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginTokenIdentityFence; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginTokenIdentityFenceRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class AccountBareLoginTokenIdentityFenceTest { + private static final UUID OPERATION_ID = UUID.fromString("018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f"); + private static final UUID ACCOUNT_UUID = UUID.fromString("018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a"); + private static final UUID TENANT_UUID = UUID.fromString("018f8f0a-4d9e-7c46-be37-8c1d0e9f7a5b"); + private static final String CONNECT_SCOPE_ID = "scope-private-login"; + private static final String REQUEST_ID = "bare-login-request-001"; + private static final String TOKEN_IDENTITY = "jti-private-delegation-001"; + private static final byte[] REQUEST_DIGEST = HexFormat.of().parseHex("12".repeat(32)); + private static final byte[] TOKEN_HASH = HexFormat.of().parseHex("34".repeat(32)); + + @Test + void keepsInitialIdentityAndAccountFenceVersionsIndependentAndCopiesBytes() { + byte[] requestDigest = REQUEST_DIGEST.clone(); + byte[] tokenHash = TOKEN_HASH.clone(); + AccountBareLoginTokenIdentityFence evidence = capture(requestDigest, tokenHash, 4L, 9L); + requestDigest[0]++; + tokenHash[0]++; + evidence.requestDigest()[1]++; + evidence.tokenHash()[1]++; + + assertThat(evidence.requestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(evidence.tokenHash()).isEqualTo(TOKEN_HASH); + assertThat(evidence.profile()).isEqualTo(AccountBareLoginTokenIdentityFence.PROFILE_NAME); + assertThat(evidence.tokenIdentityFence()).isEqualTo(1L); + assertThat(evidence.tokenIdentityFenceSourceVersion()).isEqualTo(1L); + assertThat(evidence.accountIssuanceFence()).isEqualTo(4L); + assertThat(evidence.accountIssuanceFenceSourceVersion()).isEqualTo(9L); + assertThat(evidence.sameInitialCapture(capture(REQUEST_DIGEST, TOKEN_HASH, 4L, 9L))).isTrue(); + assertThat(evidence.toString()) + .doesNotContain(TOKEN_IDENTITY) + .doesNotContain(HexFormat.of().formatHex(TOKEN_HASH)); + } + + @Test + void rejectsAChangedCurrentAccountFenceAsDifferentInitialEvidence() { + AccountBareLoginTokenIdentityFence original = capture(REQUEST_DIGEST, TOKEN_HASH, 4L, 9L); + AccountBareLoginTokenIdentityFence changed = capture(REQUEST_DIGEST, TOKEN_HASH, 5L, 10L); + + assertThat(original.sameInitialCapture(changed)).isFalse(); + } + + @Test + void rejectsNonInitialIdentityFenceVersionsAndMalformedTokenIdentity() { + assertThatThrownBy( + () -> + new AccountBareLoginTokenIdentityFence( + AccountBareLoginTokenIdentityFence.SCHEMA_NAME, + OPERATION_ID, + SOURCE_OPERATION_ID, + 17L, + ACCOUNT_UUID, + TENANT_UUID, + AccountJoinDigest.tokenHash(CONNECT_SCOPE_ID), + REQUEST_ID, + 1, + REQUEST_DIGEST, + AccountBareLoginTokenIdentityFence.PROFILE_NAME, + TOKEN_IDENTITY, + TOKEN_HASH, + 2L, + 1L, + 4L, + 9L, + Instant.EPOCH)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> capture(REQUEST_DIGEST, TOKEN_HASH, 0L, 9L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> capture(REQUEST_DIGEST, new byte[31], 4L, 9L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void captureRequiresARealOwnerTransactionBeforeAccessingStorage() { + DSLContext dsl = mock(DSLContext.class); + DataSource dataSource = mock(DataSource.class); + AccountBareLoginTokenIdentityFenceRepository repository = + new AccountBareLoginTokenIdentityFenceRepository(dsl, dataSource); + + assertThatThrownBy( + () -> + repository.captureInitial( + exchangeIdentity(), + OPERATION_ID, + ACCOUNT_UUID, + REQUEST_DIGEST, + TOKEN_IDENTITY, + TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account owner transaction"); + verifyNoInteractions(dsl, dataSource); + } + + private static AccountBareLoginTokenIdentityFence capture( + byte[] requestDigest, byte[] tokenHash, long accountFence, long accountFenceSourceVersion) { + AccountBareLoginExchangeIdentity identity = exchangeIdentity(); + return new AccountBareLoginTokenIdentityFence( + AccountBareLoginTokenIdentityFence.SCHEMA_NAME, + OPERATION_ID, + identity.sourceConnectOperationId(), + identity.accountId(), + ACCOUNT_UUID, + identity.tenantId(), + AccountJoinDigest.tokenHash(CONNECT_SCOPE_ID), + identity.requestId(), + 1, + requestDigest, + AccountBareLoginTokenIdentityFence.PROFILE_NAME, + TOKEN_IDENTITY, + tokenHash, + 1L, + 1L, + accountFence, + accountFenceSourceVersion, + Instant.parse("2026-10-04T00:00:00Z")); + } + + private static AccountBareLoginExchangeIdentity exchangeIdentity() { + return new AccountBareLoginExchangeIdentity( + SOURCE_OPERATION_ID, 17L, TENANT_UUID, CONNECT_SCOPE_ID, REQUEST_ID); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceEvidenceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceEvidenceTest.java new file mode 100644 index 0000000000..6f8c14ffd5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountConnectIssuanceFenceEvidenceTest.java @@ -0,0 +1,185 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.HexFormat; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountConnectIssuanceFenceEvidence; +import org.junit.jupiter.api.Test; + +class AccountConnectIssuanceFenceEvidenceTest { + private static final UUID OPERATION_ID = UUID.fromString("018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"); + private static final UUID ACCOUNT_UUID = UUID.fromString("018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f"); + private static final UUID TENANT_UUID = UUID.fromString("018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a"); + private static final String CONNECT_SCOPE_HASH = "sha256:" + "a".repeat(64); + private static final String REQUEST_ID = "requΓͺte-ι›ͺ-001"; + private static final byte[] REQUEST_DIGEST = HexFormat.of().parseHex("64".repeat(32)); + private static final String EXPECTED_DIGEST = + "91271de72c31addc5d3b88be733a18537c314be833671798bc903c1677c2b70d"; + + @Test + void reproducesIndependentUnicodeAndLargeCounterVector() { + AccountConnectIssuanceFenceEvidence evidence = + AccountConnectIssuanceFenceEvidence.capture( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + CONNECT_SCOPE_HASH, + REQUEST_ID, + REQUEST_DIGEST, + 9_007_199_254_740_993L, + Long.MAX_VALUE); + + assertThat(HexFormat.of().formatHex(evidence.digest())).isEqualTo(EXPECTED_DIGEST); + assertThat(evidence.issuanceFence()).isEqualTo(9_007_199_254_740_993L); + assertThat(evidence.fenceSourceVersion()).isEqualTo(Long.MAX_VALUE); + } + + @Test + void changesDigestWhenAnyBoundFieldChanges() { + byte[] expected = HexFormat.of().parseHex(EXPECTED_DIGEST); + + assertDifferentDigest( + UUID.fromString("018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"), + ACCOUNT_UUID, + TENANT_UUID, + CONNECT_SCOPE_HASH, + REQUEST_ID, + REQUEST_DIGEST, + 9_007_199_254_740_993L, + Long.MAX_VALUE, + expected); + assertDifferentDigest( + OPERATION_ID, + UUID.fromString("018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e50"), + TENANT_UUID, + CONNECT_SCOPE_HASH, + REQUEST_ID, + REQUEST_DIGEST, + 9_007_199_254_740_993L, + Long.MAX_VALUE, + expected); + assertDifferentDigest( + OPERATION_ID, + ACCOUNT_UUID, + UUID.fromString("018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f40"), + CONNECT_SCOPE_HASH, + REQUEST_ID, + REQUEST_DIGEST, + 9_007_199_254_740_993L, + Long.MAX_VALUE, + expected); + assertDifferentDigest( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + "sha256:" + "b".repeat(64), + REQUEST_ID, + REQUEST_DIGEST, + 9_007_199_254_740_993L, + Long.MAX_VALUE, + expected); + assertDifferentDigest( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + CONNECT_SCOPE_HASH, + "requΓͺte-ι›ͺ-002", + REQUEST_DIGEST, + 9_007_199_254_740_993L, + Long.MAX_VALUE, + expected); + byte[] changedRequestDigest = REQUEST_DIGEST.clone(); + changedRequestDigest[0]++; + assertDifferentDigest( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + CONNECT_SCOPE_HASH, + REQUEST_ID, + changedRequestDigest, + 9_007_199_254_740_993L, + Long.MAX_VALUE, + expected); + assertDifferentDigest( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + CONNECT_SCOPE_HASH, + REQUEST_ID, + REQUEST_DIGEST, + 9_007_199_254_740_992L, + Long.MAX_VALUE, + expected); + assertDifferentDigest( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + CONNECT_SCOPE_HASH, + REQUEST_ID, + REQUEST_DIGEST, + 9_007_199_254_740_993L, + Long.MAX_VALUE - 1, + expected); + } + + @Test + void copiesDigestInputsAndAccessorsAndRejectsMalformedUnicode() { + byte[] mutableRequestDigest = REQUEST_DIGEST.clone(); + AccountConnectIssuanceFenceEvidence evidence = + AccountConnectIssuanceFenceEvidence.capture( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + CONNECT_SCOPE_HASH, + REQUEST_ID, + mutableRequestDigest, + 9_007_199_254_740_993L, + Long.MAX_VALUE); + mutableRequestDigest[0]++; + byte[] returnedRequestDigest = evidence.requestDigest(); + returnedRequestDigest[1]++; + byte[] returnedDigest = evidence.digest(); + returnedDigest[2]++; + + assertThat(evidence.requestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(HexFormat.of().formatHex(evidence.digest())).isEqualTo(EXPECTED_DIGEST); + assertThatThrownBy( + () -> + AccountConnectIssuanceFenceEvidence.capture( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + CONNECT_SCOPE_HASH, + "invalid-\uD800", + REQUEST_DIGEST, + 1L, + 1L)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertDifferentDigest( + UUID operationId, + UUID accountUuid, + UUID tenantUuid, + String connectScopeHash, + String requestId, + byte[] requestDigest, + long issuanceFence, + long fenceSourceVersion, + byte[] expected) { + byte[] actual = + AccountConnectIssuanceFenceEvidence.calculateDigest( + AccountConnectIssuanceFenceEvidence.SCHEMA_NAME, + operationId, + accountUuid, + tenantUuid, + connectScopeHash, + requestId, + requestDigest, + issuanceFence, + fenceSourceVersion); + assertThat(actual).isNotEqualTo(expected); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGlobalRoleSourceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGlobalRoleSourceRepositoryTest.java new file mode 100644 index 0000000000..cde5f3588a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGlobalRoleSourceRepositoryTest.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.List; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +class AccountGlobalRoleSourceRepositoryTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + + private final DSLContext dsl = mock(DSLContext.class); + private final DataSource dataSource = mock(DataSource.class); + private final AccountGlobalRoleSourceRepository repository = + new AccountGlobalRoleSourceRepository(dsl, dataSource); + + @Test + void sourceReadRequiresTheCallersAccountTransaction() throws ReflectiveOperationException { + Transactional annotation = + AccountGlobalRoleSourceRepository.class + .getMethod("readFreshEmptySourceForUpdate", UUID.class) + .getAnnotation(Transactional.class); + + assertThat(annotation).isNotNull(); + assertThat(annotation.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat(annotation.isolation()).isEqualTo(Isolation.READ_COMMITTED); + } + + @Test + void missingOrNilAccountUuidFailsBeforeDatabaseAccess() { + assertThatThrownBy(() -> repository.readFreshEmptySourceForUpdate(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.readFreshEmptySourceForUpdate(new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(dsl, dataSource); + } + + @Test + void directInvocationWithoutAnActiveOwnerTransactionFailsBeforeDatabaseAccess() { + assertThatThrownBy(() -> repository.readFreshEmptySourceForUpdate(ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account owner transaction"); + + verifyNoInteractions(dsl, dataSource); + } + + @Test + void freshEmptySourceRetainsExactIdentityAndIndependentPositiveSourceVersion() { + var source = + new AccountGlobalRoleSourceRepository.FreshEmptySource( + ACCOUNT_UUID, + 7L, + 7L, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, + List.of(), + 1L); + + assertThat(source.accountUuid()).isEqualTo(ACCOUNT_UUID); + assertThat(source.accountRowId()).isEqualTo(7L); + assertThat(source.accountUuidSourceNumericId()).isEqualTo(7L); + assertThat(source.accountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(source.globalRoles()).isEmpty(); + assertThat(source.globalRoleSourceVersion()).isEqualTo(1L); + } + + @Test + void malformedOrNonFreshSourceValuesAreRejected() { + assertThatThrownBy( + () -> + new AccountGlobalRoleSourceRepository.FreshEmptySource( + ACCOUNT_UUID, + 7L, + 8L, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, + List.of(), + 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGlobalRoleSourceRepository.FreshEmptySource( + ACCOUNT_UUID, + 7L, + 7L, + AccountIdentityProvenance.ACCOUNT_V29_MIGRATION, + List.of(), + 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGlobalRoleSourceRepository.FreshEmptySource( + ACCOUNT_UUID, + 7L, + 7L, + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, + List.of("platformAdmin"), + 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGlobalRoleSourceRepository.FreshEmptySource( + ACCOUNT_UUID, + 7L, + 7L, + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, + List.of(), + 0L)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalogTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalogTest.java new file mode 100644 index 0000000000..f9fa7f4b07 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTokenProfileCatalogTest.java @@ -0,0 +1,1469 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ActualClaimMaps; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.AuthorityMapShape; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ClaimFieldPresence; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ControlUiShape; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.DeploymentCeilings; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.NonTenantDelegationShape; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.PlayerBootstrapShape; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.PrivateRealmGrantShape; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.PrivateRealmTarget; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.ProfileLimits; +import net.firedevops.firemud.accountservice.security.AccountTokenProfileCatalog.TenantBoundDelegationShape; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AccountTokenProfileCatalogTest { + private static final UUID TENANT_A = UUID.fromString("00000000-0000-4000-8000-000000000001"); + private static final UUID TENANT_B = UUID.fromString("00000000-0000-4000-8000-000000000002"); + private static final UUID TENANT_C = UUID.fromString("00000000-0000-4000-8000-000000000003"); + private static final UUID TENANT_D = UUID.fromString("00000000-0000-4000-8000-000000000004"); + private static final UUID LIFECYCLE_A = UUID.fromString("00000000-0000-4000-8000-000000000011"); + private static final String LARGE_GRANT_VERSION = "900719925474099312345678901234567890"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final DeploymentCeilings DEPLOYMENT = + new DeploymentCeilings(64_000, 48_000, 64_000, 3_600); + + @Test + void requiresExplicitVersionCompleteProfileSetAndExactAudiences() { + Map limits = validLimits(); + + assertThrows( + IllegalArgumentException.class, + () -> + new AccountTokenProfileCatalog("account-token-profile-catalog/v2", limits, DEPLOYMENT)); + + Map missing = validLimits(); + missing.remove(AccountTokenProfileCatalog.PLAYER_BOOTSTRAP); + assertThrows( + IllegalArgumentException.class, + () -> + new AccountTokenProfileCatalog( + AccountTokenProfileCatalog.VERSION, missing, DEPLOYMENT)); + + Map forbiddenProfile = validLimits(); + forbiddenProfile.put("gameplay-connect", forbiddenLimits("gameplay-connect")); + assertThrows( + IllegalArgumentException.class, + () -> + new AccountTokenProfileCatalog( + AccountTokenProfileCatalog.VERSION, forbiddenProfile, DEPLOYMENT)); + forbiddenProfile.remove("gameplay-connect"); + forbiddenProfile.put("gateway-context", forbiddenLimits("gateway-context")); + assertThrows( + IllegalArgumentException.class, + () -> + new AccountTokenProfileCatalog( + AccountTokenProfileCatalog.VERSION, forbiddenProfile, DEPLOYMENT)); + + Map wrongAudience = validLimits(); + wrongAudience.put( + AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, + limits("gateway", 600, 1, 1, 1, 1, 1, 16_000, 12_000, 32_000, Optional.empty())); + assertThrows( + IllegalArgumentException.class, + () -> + new AccountTokenProfileCatalog( + AccountTokenProfileCatalog.VERSION, wrongAudience, DEPLOYMENT)); + } + + @Test + void rejectsMissingZeroNegativeAndInconsistentFiniteLimits() { + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.CONTROL_UI, + limits("control-ui", 0, 2, 2, 2, 2, 0, 16_000, 12_000, 32_000, Optional.of(4)))); + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.CONTROL_UI, + limits("control-ui", 900, -1, 2, 2, 2, 0, 16_000, 12_000, 32_000, Optional.of(4)))); + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.CONTROL_UI, + limits("control-ui", 900, 5, 2, 2, 2, 0, 16_000, 12_000, 32_000, Optional.of(4)))); + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.CONTROL_UI, + limits("control-ui", 900, 2, 2, 2, 2, 0, 16_000, 12_000, 32_000, Optional.empty()))); + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.CONTROL_UI, + limits("control-ui", 900, 2, 2, 2, 2, 0, 16_000, 12_000, 32_000, Optional.of(0)))); + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.CONTROL_UI, + limits("control-ui", 900, 2, 2, 2, 2, 0, 0, 12_000, 32_000, Optional.of(4)))); + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.CONTROL_UI, + limits("control-ui", -1, 2, 2, 2, 2, 0, 16_000, 12_000, 32_000, Optional.of(4)))); + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.CONTROL_UI, + limits("control-ui", 900, 2, 2, 2, 2, 0, 16_000, 12_000, -1, Optional.of(4)))); + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.CONTROL_UI, + limits("control-ui", 900, 2, 2, 2, 2, 0, 16_000, -1, 32_000, Optional.of(4)))); + + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.PLAYER_BOOTSTRAP, + limits( + "player-bootstrap", 300, 0, 1, 0, 0, 0, 8_000, 12_000, 16_000, Optional.empty()))); + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, + limits( + "account-service", 600, 2, 1, 1, 1, 1, 16_000, 12_000, 32_000, Optional.empty()))); + + assertInvalidCatalog(validLimits(), new DeploymentCeilings(11_999, 48_000, 64_000, 3_600)); + assertInvalidCatalog(validLimits(), new DeploymentCeilings(64_000, 15_999, 64_000, 3_600)); + assertInvalidCatalog(validLimits(), new DeploymentCeilings(64_000, 48_000, 31_999, 3_600)); + assertInvalidCatalog(validLimits(), new DeploymentCeilings(64_000, 48_000, 64_000, 899)); + + assertInvalidCatalog( + replace( + validLimits(), + AccountTokenProfileCatalog.CONTROL_UI, + limits("control-ui", 900, 2, 2, 2, 2, 0, 33_000, 12_000, 32_000, Optional.of(4)))); + } + + @Test + void keepsCatalogAndTypedShapeInputsDefensivelyImmutableAndRedactsDiagnostics() { + Map mutableProfiles = validLimits(); + AccountTokenProfileCatalog catalog = + new AccountTokenProfileCatalog( + AccountTokenProfileCatalog.VERSION, mutableProfiles, DEPLOYMENT); + mutableProfiles.clear(); + + assertEquals(3, catalog.profiles().size()); + assertThrows( + UnsupportedOperationException.class, + () -> catalog.profiles().put("control-ui", uiLimits())); + assertEquals(DEPLOYMENT, catalog.deploymentCeilings()); + + List mutableGrants = new ArrayList<>(); + PrivateRealmGrantShape grant = grant(TENANT_A, LIFECYCLE_A, LARGE_GRANT_VERSION); + mutableGrants.add(grant); + AuthorityMapShape authority = + new AuthorityMapShape( + Set.of(TENANT_A), Set.of(TENANT_A), Set.of(TENANT_A), Set.of(), mutableGrants); + mutableGrants.clear(); + + assertEquals(Set.of(TENANT_A), authority.tenantAuthorityKeys()); + assertEquals(List.of(grant), authority.privateRealmGrants()); + assertThrows( + UnsupportedOperationException.class, () -> authority.tenantAuthorityKeys().add(TENANT_B)); + assertThrows( + UnsupportedOperationException.class, () -> authority.privateRealmGrants().add(grant)); + + ControlUiShape originalUiShape = controlUiShape(); + Set mutableTenants = new HashSet<>(originalUiShape.scopedTenantKeys()); + ControlUiShape copiedUiShape = + new ControlUiShape( + originalUiShape.claims(), + originalUiShape.authority(), + mutableTenants, + originalUiShape.scopedRoleKeys(), + originalUiShape.tenantAuthorityRouteKeys(), + originalUiShape.requiredCallerMembershipKeys(), + originalUiShape.billingSafeTenantKeys(), + originalUiShape.applicableBillingCutoffKeys()); + mutableTenants.clear(); + + assertEquals(originalUiShape.scopedTenantKeys(), copiedUiShape.scopedTenantKeys()); + assertThrows( + UnsupportedOperationException.class, () -> copiedUiShape.scopedTenantKeys().add(TENANT_C)); + assertThrows( + UnsupportedOperationException.class, () -> copiedUiShape.scopedRoleKeys().add(TENANT_C)); + assertThrows( + UnsupportedOperationException.class, + () -> copiedUiShape.tenantAuthorityRouteKeys().add(TENANT_C)); + assertThrows( + UnsupportedOperationException.class, + () -> copiedUiShape.requiredCallerMembershipKeys().add(TENANT_C)); + assertThrows( + UnsupportedOperationException.class, + () -> copiedUiShape.billingSafeTenantKeys().add(TENANT_C)); + assertThrows( + UnsupportedOperationException.class, + () -> copiedUiShape.applicableBillingCutoffKeys().add(TENANT_C)); + + Set mutableNonTenantRoles = new HashSet<>(); + NonTenantDelegationShape copiedNonTenantShape = + new NonTenantDelegationShape( + delegationClaims(false, false), emptyAuthority(), mutableNonTenantRoles); + mutableNonTenantRoles.add(TENANT_B); + assertTrue(copiedNonTenantShape.scopedRoleKeys().isEmpty()); + assertThrows( + UnsupportedOperationException.class, + () -> copiedNonTenantShape.scopedRoleKeys().add(TENANT_B)); + + String marker = "eyJhbGciOiJub25lIn0.secret.signature"; + IllegalArgumentException failure = + assertThrows( + IllegalArgumentException.class, + () -> + catalogWithUiPostSignLimits(5, 7) + .validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, marker, "{}")); + assertFalse(failure.getMessage().contains(marker)); + assertFalse(catalog.toString().contains(marker)); + assertTrue(grant.toString().contains("redacted")); + assertFalse(grant.toString().contains(LARGE_GRANT_VERSION)); + } + + @Test + void checksCheckedUtcEpochSecondLifetimeAtExactAndInvalidBoundaries() { + AccountTokenProfileCatalog catalog = catalog(); + + assertEquals( + 900, catalog.validateTokenLifetime(AccountTokenProfileCatalog.CONTROL_UI, 1_000, 1_900)); + assertThrows( + IllegalArgumentException.class, + () -> catalog.validateTokenLifetime(AccountTokenProfileCatalog.CONTROL_UI, 1_000, 1_901)); + assertThrows( + IllegalArgumentException.class, + () -> catalog.validateTokenLifetime(AccountTokenProfileCatalog.CONTROL_UI, 1_000, 1_000)); + assertThrows( + IllegalArgumentException.class, + () -> catalog.validateTokenLifetime(AccountTokenProfileCatalog.CONTROL_UI, 1_001, 1_000)); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validateTokenLifetime( + AccountTokenProfileCatalog.CONTROL_UI, Long.MIN_VALUE, Long.MAX_VALUE)); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validateTokenLifetime( + AccountTokenProfileCatalog.CONTROL_UI, Long.MAX_VALUE, Long.MAX_VALUE)); + } + + @Test + void validatesControlUiIndependentMapsAndBillingSafeTenantRelationship() { + AccountTokenProfileCatalog catalog = catalog(); + ControlUiShape valid = controlUiShape(); + validatePreSign(catalog, AccountTokenProfileCatalog.CONTROL_UI, valid, tupleJson(valid)); + + AuthorityMapShape wrongTenantAuthority = + authority( + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_A, TENANT_B), + List.of()); + ControlUiShape extraTargetTenant = + new ControlUiShape( + controlUiClaims(true), + wrongTenantAuthority, + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_A), + Set.of(TENANT_A), + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_B), + Set.of(TENANT_A, TENANT_B)); + assertInvalidShape(catalog, AccountTokenProfileCatalog.CONTROL_UI, extraTargetTenant); + + AuthorityMapShape missingBillingSafeMembershipVersion = + authority( + Set.of(TENANT_A), + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_A), + Set.of(TENANT_A, TENANT_B), + List.of()); + ControlUiShape missingVersion = + new ControlUiShape( + controlUiClaims(true), + missingBillingSafeMembershipVersion, + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_A), + Set.of(TENANT_A), + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_B), + Set.of(TENANT_A, TENANT_B)); + assertInvalidShape(catalog, AccountTokenProfileCatalog.CONTROL_UI, missingVersion); + + ControlUiShape misclassifiedBillingSafe = + new ControlUiShape( + controlUiClaims(true), + valid.authority(), + valid.scopedTenantKeys(), + valid.scopedRoleKeys(), + Set.of(TENANT_A, TENANT_B), + valid.requiredCallerMembershipKeys(), + valid.billingSafeTenantKeys(), + valid.applicableBillingCutoffKeys()); + assertInvalidShape(catalog, AccountTokenProfileCatalog.CONTROL_UI, misclassifiedBillingSafe); + + ControlUiShape missingCutoffObject = + new ControlUiShape( + controlUiClaims(false), + valid.authority(), + valid.scopedTenantKeys(), + valid.scopedRoleKeys(), + valid.tenantAuthorityRouteKeys(), + valid.requiredCallerMembershipKeys(), + valid.billingSafeTenantKeys(), + valid.applicableBillingCutoffKeys()); + assertInvalidShape(catalog, AccountTokenProfileCatalog.CONTROL_UI, missingCutoffObject); + + ControlUiShape wrongAudience = + new ControlUiShape( + claims("player-bootstrap", true, true, false), + valid.authority(), + valid.scopedTenantKeys(), + valid.scopedRoleKeys(), + valid.tenantAuthorityRouteKeys(), + valid.requiredCallerMembershipKeys(), + valid.billingSafeTenantKeys(), + valid.applicableBillingCutoffKeys()); + assertInvalidShape(catalog, AccountTokenProfileCatalog.CONTROL_UI, wrongAudience); + + ControlUiShape missingRequiredTupleMap = + new ControlUiShape( + claimsWithoutMembershipVersion(), + valid.authority(), + valid.scopedTenantKeys(), + valid.scopedRoleKeys(), + valid.tenantAuthorityRouteKeys(), + valid.requiredCallerMembershipKeys(), + valid.billingSafeTenantKeys(), + valid.applicableBillingCutoffKeys()); + assertInvalidShape(catalog, AccountTokenProfileCatalog.CONTROL_UI, missingRequiredTupleMap); + + ControlUiShape overSharedScope = + new ControlUiShape( + controlUiClaims(false), + authority( + Set.of(TENANT_A, TENANT_B, TENANT_C, uuid(4), uuid(5)), + Set.of(TENANT_A, TENANT_B, TENANT_C, uuid(4), uuid(5)), + Set.of(TENANT_A, TENANT_B, TENANT_C, uuid(4), uuid(5)), + Set.of(), + List.of()), + Set.of(TENANT_A, TENANT_B, TENANT_C, uuid(4), uuid(5)), + Set.of(TENANT_A, TENANT_B, TENANT_C, uuid(4), uuid(5)), + Set.of(TENANT_A, TENANT_B, TENANT_C, uuid(4), uuid(5)), + Set.of(TENANT_A, TENANT_B, TENANT_C, uuid(4), uuid(5)), + Set.of(), + Set.of()); + assertInvalidShape(catalog, AccountTokenProfileCatalog.CONTROL_UI, overSharedScope); + } + + @Test + void acceptsEachControlUiFieldAtItsExactFiniteCardinalityAndRejectsOneOver() { + AccountTokenProfileCatalog catalog = catalog(); + ControlUiShape exactBoundary = controlUiShapeAtFiniteLimits(); + validatePreSign( + catalog, AccountTokenProfileCatalog.CONTROL_UI, exactBoundary, tupleJson(exactBoundary)); + + assertInvalidShape( + catalogWithUiFieldLimits(2, 4, 4, 3), AccountTokenProfileCatalog.CONTROL_UI, exactBoundary); + assertInvalidShape( + catalogWithUiFieldLimits(3, 3, 4, 3), AccountTokenProfileCatalog.CONTROL_UI, exactBoundary); + assertInvalidShape( + catalogWithUiFieldLimits(3, 4, 3, 3), AccountTokenProfileCatalog.CONTROL_UI, exactBoundary); + assertInvalidShape( + catalogWithUiFieldLimits(3, 4, 4, 2), AccountTokenProfileCatalog.CONTROL_UI, exactBoundary); + } + + @Test + void acceptsOptionalSingleAccountSecurityCutoffWithoutTreatingItAsTokenScope() { + AccountTokenProfileCatalog catalog = catalog(); + ControlUiShape shape = controlUiShape(); + ControlUiShape withAccountCutoff = + new ControlUiShape( + controlUiClaims(true, true), + shape.authority(), + shape.scopedTenantKeys(), + shape.scopedRoleKeys(), + shape.tenantAuthorityRouteKeys(), + shape.requiredCallerMembershipKeys(), + shape.billingSafeTenantKeys(), + shape.applicableBillingCutoffKeys()); + validatePreSign( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + withAccountCutoff, + tupleJson(withAccountCutoff)); + } + + @Test + void enforcesEmptyBootstrapAndNonTenantDelegationShapes() { + AccountTokenProfileCatalog catalog = catalog(); + PlayerBootstrapShape bootstrap = + new PlayerBootstrapShape(bootstrapClaims(), emptyAuthority(), Set.of()); + validatePreSign( + catalog, AccountTokenProfileCatalog.PLAYER_BOOTSTRAP, bootstrap, tupleJson(bootstrap)); + + AuthorityMapShape bootstrapWithTenant = + authority(Set.of(TENANT_A), Set.of(), Set.of(), Set.of(), List.of()); + PlayerBootstrapShape wrongBootstrap = + new PlayerBootstrapShape(bootstrapClaims(), bootstrapWithTenant, Set.of()); + assertInvalidShape(catalog, AccountTokenProfileCatalog.PLAYER_BOOTSTRAP, wrongBootstrap); + + NonTenantDelegationShape nonTenant = + new NonTenantDelegationShape(delegationClaims(false, false), emptyAuthority(), Set.of()); + validatePreSign( + catalog, + AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, + nonTenant, + tupleJson(nonTenant)); + + NonTenantDelegationShape nonTenantWithRole = + new NonTenantDelegationShape( + delegationClaims(true, false), emptyAuthority(), Set.of(TENANT_A)); + assertInvalidShape( + catalog, AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, nonTenantWithRole); + } + + @Test + void enforcesTenantDelegationExactMapsOptionalCutoffAndLifecycleBoundGrant() { + AccountTokenProfileCatalog catalog = catalog(); + TenantBoundDelegationShape publicDelegation = + tenantDelegation(true, Optional.empty(), List.of()); + validatePreSign( + catalog, + AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, + publicDelegation, + tupleJson(publicDelegation)); + + TenantBoundDelegationShape privateDelegation = + tenantDelegation( + false, + Optional.of(new PrivateRealmTarget(TENANT_A, "emberfall", "preview", LIFECYCLE_A)), + List.of(grant(TENANT_A, LIFECYCLE_A, LARGE_GRANT_VERSION))); + validatePreSign( + catalog, + AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, + privateDelegation, + tupleJson(privateDelegation)); + + TenantBoundDelegationShape missingGrant = + tenantDelegation( + false, + Optional.of(new PrivateRealmTarget(TENANT_A, "emberfall", "preview", LIFECYCLE_A)), + List.of()); + assertInvalidShape( + catalog, AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, missingGrant); + + TenantBoundDelegationShape wrongLifecycle = + tenantDelegation( + false, + Optional.of(new PrivateRealmTarget(TENANT_A, "emberfall", "preview", LIFECYCLE_A)), + List.of(grant(TENANT_A, uuid(99), "7"))); + assertInvalidShape( + catalog, AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, wrongLifecycle); + + TenantBoundDelegationShape otherTenantGrantAndTarget = + new TenantBoundDelegationShape( + delegationClaims(true, true), + authority( + Set.of(TENANT_A), + Set.of(TENANT_A), + Set.of(TENANT_A), + Set.of(TENANT_A), + List.of(grant(TENANT_B, LIFECYCLE_A, "7"))), + TENANT_A, + Set.of(TENANT_A), + false, + Optional.of(new PrivateRealmTarget(TENANT_B, "emberfall", "preview", LIFECYCLE_A))); + assertInvalidShape( + catalog, + AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, + otherTenantGrantAndTarget); + + TenantBoundDelegationShape wrongCutoffKey = + new TenantBoundDelegationShape( + delegationClaims(true, true), + authority( + Set.of(TENANT_A), Set.of(TENANT_A), Set.of(TENANT_A), Set.of(TENANT_B), List.of()), + TENANT_A, + Set.of(TENANT_A), + true, + Optional.empty()); + assertInvalidShape( + catalog, AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, wrongCutoffKey); + + assertThrows(IllegalArgumentException.class, () -> grant(TENANT_A, LIFECYCLE_A, "01")); + assertThrows(IllegalArgumentException.class, () -> grant(TENANT_A, LIFECYCLE_A, "0")); + } + + @Test + void rejectsNonCanonicalAndOverLimitAuthorityTupleBeforeSigning() { + ControlUiShape shape = controlUiShape(); + String canonicalTuple = tupleJson(shape); + long tupleBytes = canonicalTuple.getBytes(StandardCharsets.UTF_8).length; + AccountTokenProfileCatalog exact = catalogWithUiTupleLimit(tupleBytes); + validatePreSign(exact, AccountTokenProfileCatalog.CONTROL_UI, shape, canonicalTuple); + + AccountTokenProfileCatalog oneByteSmaller = catalogWithUiTupleLimit(tupleBytes - 1); + assertThrows( + IllegalArgumentException.class, + () -> + oneByteSmaller.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + shape, + actualClaimMaps(shape), + 1_000, + 1_900, + canonicalTuple)); + + assertThrows( + IllegalArgumentException.class, + () -> + catalog() + .validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + shape, + actualClaimMaps(shape), + 1_000, + 1_900, + "{\"tenantAuthorityGeneration\":{},\"accountAuthorityGeneration\":\"1\"}")); + } + + @Test + void bindsSerializedAuthorityTupleMapsAndGrantsToTheSuppliedTypedShape() { + AccountTokenProfileCatalog catalog = catalog(); + ControlUiShape shape = controlUiShape(); + validatePreSign(catalog, AccountTokenProfileCatalog.CONTROL_UI, shape, tupleJson(shape)); + + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + shape, + actualClaimMaps(shape), + 1_000, + 1_900, + tupleJson( + shape, + Map.of( + "tenantAuthorityGeneration", + generationMap(Set.of(TENANT_A, TENANT_B, TENANT_C, TENANT_D)))))); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + shape, + actualClaimMaps(shape), + 1_000, + 1_900, + tupleJson( + shape, + Map.of("membershipAuthorityGeneration", generationMap(Set.of(TENANT_A)))))); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + shape, + actualClaimMaps(shape), + 1_000, + 1_900, + tupleJson(shape, Map.of("tenantBillingCutoff", cutoffMap(Set.of(TENANT_A)))))); + + ControlUiShape withAccountCutoff = + new ControlUiShape( + controlUiClaims(true, true), + shape.authority(), + shape.scopedTenantKeys(), + shape.scopedRoleKeys(), + shape.tenantAuthorityRouteKeys(), + shape.requiredCallerMembershipKeys(), + shape.billingSafeTenantKeys(), + shape.applicableBillingCutoffKeys()); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + withAccountCutoff, + actualClaimMaps(withAccountCutoff), + 1_000, + 1_900, + tupleJsonWithoutField(withAccountCutoff, "accountSecurityCutoff"))); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + shape, + actualClaimMaps(shape), + 1_000, + 1_900, + tupleJson( + shape, + Map.of( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + "1", + "outboxSequence", + "1", + "outboxStreamKey", + "account"))))); + + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + shape, + actualClaimMaps(shape), + 1_000, + 1_900, + tupleJsonWithoutField(shape, "tenantAuthorityGeneration"))); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + shape, + actualClaimMaps(shape), + 1_000, + 1_900, + tupleJson(shape, Collections.singletonMap("tenantAuthorityGeneration", null)))); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + shape, + actualClaimMaps(shape), + 1_000, + 1_900, + tupleJson(shape, Map.of("membershipAuthorityGeneration", "not-a-map")))); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + shape, + actualClaimMaps(shape), + 1_000, + 1_900, + tupleJson(shape, Collections.singletonMap("privateRealmGrantVersions", null)))); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + shape, + actualClaimMaps(shape), + 1_000, + 1_900, + tupleJson(shape, Map.of("privateRealmGrantVersions", Map.of())))); + + TenantBoundDelegationShape privateShape = + tenantDelegation( + false, + Optional.of(new PrivateRealmTarget(TENANT_A, "emberfall", "preview", LIFECYCLE_A)), + List.of(grant(TENANT_A, LIFECYCLE_A, LARGE_GRANT_VERSION))); + String differentGrant = + tupleJson( + privateShape, + Map.of( + "privateRealmGrantVersions", + grantList(List.of(grant(TENANT_A, LIFECYCLE_A, "7"))))); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, + privateShape, + actualClaimMaps(privateShape), + 1_000, + 1_600, + differentGrant)); + String differentGrantIdentity = + tupleJson( + privateShape, + Map.of( + "privateRealmGrantVersions", + grantList(List.of(grant(TENANT_B, LIFECYCLE_A, LARGE_GRANT_VERSION))))); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, + privateShape, + actualClaimMaps(privateShape), + 1_000, + 1_600, + differentGrantIdentity)); + } + + @Test + void bindsActualMembershipVersionAndScopedRoleValuesToTypedScopeWithoutRounding() { + AccountTokenProfileCatalog catalog = catalog(); + ControlUiShape shape = controlUiShape(); + BigInteger largeVersion = new BigInteger("900719925474099312345678901234567890"); + Map membershipVersion = new LinkedHashMap<>(); + membershipVersion.put(TENANT_A.toString(), largeVersion); + membershipVersion.put(TENANT_B.toString(), BigInteger.ONE); + List rolesForTenantA = new ArrayList<>(List.of("tenantAdmin", "designer")); + Map> scopedRoles = new LinkedHashMap<>(); + scopedRoles.put(TENANT_A.toString(), rolesForTenantA); + + ActualClaimMaps copied = + new ActualClaimMaps(Optional.of(membershipVersion), Optional.of(scopedRoles)); + membershipVersion.clear(); + rolesForTenantA.clear(); + scopedRoles.clear(); + + assertEquals(largeVersion, copied.membershipVersion().orElseThrow().get(TENANT_A.toString())); + assertEquals( + List.of("tenantAdmin", "designer"), + copied.scopedRoles().orElseThrow().get(TENANT_A.toString())); + assertThrows( + UnsupportedOperationException.class, + () -> copied.membershipVersion().orElseThrow().put(TENANT_C.toString(), BigInteger.ONE)); + assertThrows( + UnsupportedOperationException.class, + () -> copied.scopedRoles().orElseThrow().get(TENANT_A.toString()).add("player")); + + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, shape, copied, 1_000, 1_900, tupleJson(shape)); + } + + @Test + void rejectsActualMembershipVersionAndScopedRoleScopeOrValueMismatches() { + AccountTokenProfileCatalog catalog = catalog(); + ControlUiShape shape = controlUiShape(); + ActualClaimMaps valid = actualClaimMaps(shape); + + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + shape, + new ActualClaimMaps( + Optional.of(Map.of(TENANT_A.toString(), BigInteger.ONE)), valid.scopedRoles())); + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + shape, + new ActualClaimMaps( + Optional.of( + Map.of( + TENANT_A.toString(), BigInteger.ONE, + TENANT_B.toString(), BigInteger.ONE, + TENANT_C.toString(), BigInteger.ONE)), + valid.scopedRoles())); + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + shape, + new ActualClaimMaps( + Optional.of( + Map.of(TENANT_C.toString(), BigInteger.ONE, TENANT_B.toString(), BigInteger.ONE)), + valid.scopedRoles())); + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + shape, + new ActualClaimMaps( + Optional.of( + Map.of( + UUID.fromString("abcdef00-0000-4000-8000-000000000001") + .toString() + .toUpperCase(), + BigInteger.ONE, + TENANT_B.toString(), + BigInteger.ONE)), + valid.scopedRoles())); + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + shape, + new ActualClaimMaps( + Optional.of( + Map.of( + TENANT_A.toString(), BigInteger.ZERO, + TENANT_B.toString(), BigInteger.ONE)), + valid.scopedRoles())); + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + shape, + new ActualClaimMaps( + Optional.of( + Map.of( + TENANT_A.toString(), + BigInteger.valueOf(-1), + TENANT_B.toString(), + BigInteger.ONE)), + valid.scopedRoles())); + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + shape, + new ActualClaimMaps( + valid.membershipVersion(), + Optional.of(Map.of(TENANT_B.toString(), List.of("designer"))))); + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + shape, + new ActualClaimMaps( + valid.membershipVersion(), + Optional.of( + Map.of( + TENANT_A.toString(), List.of("designer"), + TENANT_B.toString(), List.of("moderator"))))); + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + shape, + new ActualClaimMaps( + valid.membershipVersion(), + Optional.of(Map.of(TENANT_A.toString(), List.of("billingAdmin"))))); + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + shape, + new ActualClaimMaps( + valid.membershipVersion(), + Optional.of(Map.of(TENANT_A.toString(), List.of("designer", "designer"))))); + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + shape, + new ActualClaimMaps( + valid.membershipVersion(), Optional.of(Map.of(TENANT_A.toString(), List.of())))); + } + + @Test + void preservesRequiredEmptyScopedRolesAndOptionalDelegationOmissionSeparately() { + AccountTokenProfileCatalog catalog = catalog(); + ControlUiShape emptyControlUi = + new ControlUiShape( + controlUiClaims(false), + emptyAuthority(), + Set.of(), + Set.of(), + Set.of(), + Set.of(), + Set.of(), + Set.of()); + ActualClaimMaps presentEmpty = + new ActualClaimMaps(Optional.of(Map.of()), Optional.of(Map.of())); + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + emptyControlUi, + presentEmpty, + 1_000, + 1_900, + tupleJson(emptyControlUi)); + + TenantBoundDelegationShape omittedScopedRoles = + new TenantBoundDelegationShape( + delegationClaims(false, false), + authority(Set.of(TENANT_A), Set.of(TENANT_A), Set.of(TENANT_A), Set.of(), List.of()), + TENANT_A, + Set.of(), + true, + Optional.empty()); + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, + omittedScopedRoles, + new ActualClaimMaps( + Optional.of(Map.of(TENANT_A.toString(), BigInteger.ONE)), Optional.empty()), + 1_000, + 1_600, + tupleJson(omittedScopedRoles)); + + TenantBoundDelegationShape emptyScopedRoles = + new TenantBoundDelegationShape( + delegationClaims(true, false), + omittedScopedRoles.authority(), + TENANT_A, + Set.of(), + true, + Optional.empty()); + catalog.validatePreSignCandidate( + AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, + emptyScopedRoles, + new ActualClaimMaps( + Optional.of(Map.of(TENANT_A.toString(), BigInteger.ONE)), Optional.of(Map.of())), + 1_000, + 1_600, + tupleJson(emptyScopedRoles)); + + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + emptyControlUi, + new ActualClaimMaps(Optional.empty(), Optional.of(Map.of()))); + assertInvalidClaimMaps( + catalog, + AccountTokenProfileCatalog.CONTROL_UI, + emptyControlUi, + new ActualClaimMaps(Optional.of(Map.of()), Optional.empty())); + } + + @Test + void checksPostSignCompactJwtAndCanonicalRegistryRecordUtf8ExactBoundaries() { + String compactJwt = "YQ.Yg.Yw"; + String canonicalRecord = "{\"a\":1}"; + AccountTokenProfileCatalog exact = catalogWithUiPostSignLimits(8, 7); + + exact.validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, compactJwt, canonicalRecord); + assertThrows( + IllegalArgumentException.class, + () -> + exact.validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, "YWE.Yg.Yw", canonicalRecord)); + assertThrows( + IllegalArgumentException.class, + () -> + exact.validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, compactJwt, "{\"a\":10}")); + + String unicodeRecord = "{\"x\":\"Γ©\"}"; + int unicodeUtf8Length = unicodeRecord.getBytes(StandardCharsets.UTF_8).length; + AccountTokenProfileCatalog unicodeBoundary = catalogWithUiPostSignLimits(8, unicodeUtf8Length); + unicodeBoundary.validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, compactJwt, unicodeRecord); + assertTrue(unicodeUtf8Length > unicodeRecord.length()); + } + + @Test + void rejectsInvalidCompactJwtAndNonCanonicalRegistryRecordWithoutEchoingJwt() { + AccountTokenProfileCatalog catalog = catalog(); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, "YQ.Yg", "{}")); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, "YQ.Yg.Γ©", "{}")); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, "YQ.Yg.Yw", "{ \"a\":1}")); + + String compactJwt = "aGVhZGVy.c2VjcmV0.c2lnbmF0dXJl"; + IllegalArgumentException failure = + assertThrows( + IllegalArgumentException.class, + () -> + catalogWithUiPostSignLimits(8, 7) + .validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, compactJwt, "{\"a\":1}")); + assertFalse(failure.getMessage().contains(compactJwt)); + } + + @Test + void rejectsMalformedRawAndEscapedSurrogatesBeforeUtf8ByteMeasurement() { + AccountTokenProfileCatalog catalog = catalog(); + String compactJwt = "YQ.Yg.Yw"; + String rawHighSurrogate = new String(new char[] {(char) 0xD800}); + String rawLowSurrogate = new String(new char[] {(char) 0xDC00}); + String decomposedAccent = new String(new char[] {'e', (char) 0x0301}); + + catalog.validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + compactJwt, + "{\"value\":\"" + decomposedAccent + "\"}"); + + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + compactJwt, + "{\"value\":\"" + rawHighSurrogate + "\"}")); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, + compactJwt, + "{\"value\":\"" + rawLowSurrogate + "\"}")); + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePostSignCandidate( + AccountTokenProfileCatalog.CONTROL_UI, compactJwt, "{\"value\":\"\\ud800\"}")); + } + + private static void validatePreSign( + AccountTokenProfileCatalog catalog, + String profileId, + AccountTokenProfileCatalog.ProfileShape shape, + String tupleJson) { + catalog.validatePreSignCandidate( + profileId, shape, actualClaimMaps(shape), 1_000, 1_000 + lifetime(profileId), tupleJson); + } + + private static ActualClaimMaps actualClaimMaps(AccountTokenProfileCatalog.ProfileShape shape) { + Optional> membershipVersion = Optional.empty(); + if (shape.claims().membershipVersionPresent()) { + Map values = new TreeMap<>(); + shape + .authority() + .membershipVersionKeys() + .forEach(tenantId -> values.put(tenantId.toString(), BigInteger.ONE)); + membershipVersion = Optional.of(values); + } + + Optional>> scopedRoles = Optional.empty(); + if (shape.claims().scopedRolesPresent()) { + Map> values = new TreeMap<>(); + shape + .scopedRoleKeys() + .forEach(tenantId -> values.put(tenantId.toString(), List.of("moderator"))); + scopedRoles = Optional.of(values); + } + return new ActualClaimMaps(membershipVersion, scopedRoles); + } + + private static void assertInvalidClaimMaps( + AccountTokenProfileCatalog catalog, + String profileId, + AccountTokenProfileCatalog.ProfileShape shape, + ActualClaimMaps actualClaims) { + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + profileId, + shape, + actualClaims, + 1_000, + 1_000 + lifetime(profileId), + tupleJson(shape))); + } + + private static long lifetime(String profileId) { + return switch (profileId) { + case AccountTokenProfileCatalog.CONTROL_UI -> 900; + case AccountTokenProfileCatalog.PLAYER_BOOTSTRAP -> 300; + case AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION -> 600; + default -> throw new IllegalArgumentException("unsupported test profile"); + }; + } + + private static AccountTokenProfileCatalog catalog() { + return new AccountTokenProfileCatalog( + AccountTokenProfileCatalog.VERSION, validLimits(), DEPLOYMENT); + } + + private static AccountTokenProfileCatalog catalogWithUiTupleLimit(long tupleLimit) { + Map profiles = validLimits(); + ProfileLimits current = profiles.get(AccountTokenProfileCatalog.CONTROL_UI); + profiles.put( + AccountTokenProfileCatalog.CONTROL_UI, + limits( + current.audience(), + current.maxTokenLifetimeSeconds(), + current.maxTenantAuthorityEntries(), + current.maxMembershipAuthorityEntries(), + current.maxMembershipVersionEntries(), + current.maxTenantBillingCutoffEntries(), + current.maxPrivateRealmGrantEntries(), + tupleLimit, + current.maxCompactJwtBytes(), + current.maxRegistryRecordBytes(), + current.maxControlUiTenantScopes())); + return new AccountTokenProfileCatalog(AccountTokenProfileCatalog.VERSION, profiles, DEPLOYMENT); + } + + private static AccountTokenProfileCatalog catalogWithUiFieldLimits( + int tenantAuthority, int membershipAuthority, int membershipVersion, int billingCutoff) { + Map profiles = validLimits(); + ProfileLimits current = profiles.get(AccountTokenProfileCatalog.CONTROL_UI); + profiles.put( + AccountTokenProfileCatalog.CONTROL_UI, + limits( + current.audience(), + current.maxTokenLifetimeSeconds(), + tenantAuthority, + membershipAuthority, + membershipVersion, + billingCutoff, + current.maxPrivateRealmGrantEntries(), + current.maxAuthorityTupleBytes(), + current.maxCompactJwtBytes(), + current.maxRegistryRecordBytes(), + current.maxControlUiTenantScopes())); + return new AccountTokenProfileCatalog(AccountTokenProfileCatalog.VERSION, profiles, DEPLOYMENT); + } + + private static AccountTokenProfileCatalog catalogWithUiPostSignLimits( + long compactLimit, long recordLimit) { + Map profiles = validLimits(); + ProfileLimits current = profiles.get(AccountTokenProfileCatalog.CONTROL_UI); + profiles.put( + AccountTokenProfileCatalog.CONTROL_UI, + limits( + current.audience(), + current.maxTokenLifetimeSeconds(), + current.maxTenantAuthorityEntries(), + current.maxMembershipAuthorityEntries(), + current.maxMembershipVersionEntries(), + current.maxTenantBillingCutoffEntries(), + current.maxPrivateRealmGrantEntries(), + Math.min(current.maxAuthorityTupleBytes(), recordLimit), + compactLimit, + recordLimit, + current.maxControlUiTenantScopes())); + return new AccountTokenProfileCatalog( + AccountTokenProfileCatalog.VERSION, + profiles, + new DeploymentCeilings( + Math.max(compactLimit, 12_000), + DEPLOYMENT.maxCoordinationAuthorityTupleBytes(), + DEPLOYMENT.maxCoordinationRegistryRecordBytes(), + DEPLOYMENT.maxRegistryTokenLifetimeSeconds())); + } + + private static Map validLimits() { + Map profiles = new LinkedHashMap<>(); + profiles.put(AccountTokenProfileCatalog.CONTROL_UI, uiLimits()); + profiles.put( + AccountTokenProfileCatalog.PLAYER_BOOTSTRAP, + limits("player-bootstrap", 300, 0, 0, 0, 0, 0, 8_000, 12_000, 16_000, Optional.empty())); + profiles.put( + AccountTokenProfileCatalog.GAME_SESSION_ACCOUNT_DELEGATION, + limits("account-service", 600, 1, 1, 1, 1, 1, 16_000, 12_000, 32_000, Optional.empty())); + return profiles; + } + + private static ProfileLimits uiLimits() { + return limits("control-ui", 900, 3, 4, 4, 3, 0, 16_000, 12_000, 32_000, Optional.of(4)); + } + + private static ProfileLimits forbiddenLimits(String audience) { + return limits(audience, 10, 0, 0, 0, 0, 0, 1, 1, 1, Optional.empty()); + } + + private static ProfileLimits limits( + String audience, + long lifetime, + int tenantAuthority, + int membershipAuthority, + int membershipVersion, + int billingCutoff, + int grants, + long tupleBytes, + long compactJwtBytes, + long recordBytes, + Optional controlUiScopes) { + return new ProfileLimits( + audience, + lifetime, + tenantAuthority, + membershipAuthority, + membershipVersion, + billingCutoff, + grants, + tupleBytes, + compactJwtBytes, + recordBytes, + controlUiScopes); + } + + private static Map replace( + Map profiles, String profileId, ProfileLimits limits) { + profiles.put(profileId, limits); + return profiles; + } + + private static void assertInvalidCatalog(Map profiles) { + assertInvalidCatalog(profiles, DEPLOYMENT); + } + + private static void assertInvalidCatalog( + Map profiles, DeploymentCeilings ceilings) { + assertThrows( + IllegalArgumentException.class, + () -> + new AccountTokenProfileCatalog(AccountTokenProfileCatalog.VERSION, profiles, ceilings)); + } + + private static void assertInvalidShape( + AccountTokenProfileCatalog catalog, + String profileId, + AccountTokenProfileCatalog.ProfileShape shape) { + assertThrows( + IllegalArgumentException.class, + () -> + catalog.validatePreSignCandidate( + profileId, + shape, + actualClaimMaps(shape), + 1_000, + 1_000 + lifetime(profileId), + tupleJson(shape))); + } + + private static ControlUiShape controlUiShape() { + return new ControlUiShape( + controlUiClaims(true), + authority( + Set.of(TENANT_A), + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_A, TENANT_B), + List.of()), + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_A), + Set.of(TENANT_A), + Set.of(TENANT_A, TENANT_B), + Set.of(TENANT_B), + Set.of(TENANT_A, TENANT_B)); + } + + private static ControlUiShape controlUiShapeAtFiniteLimits() { + return new ControlUiShape( + controlUiClaims(true), + authority( + Set.of(TENANT_A, TENANT_B, TENANT_C), + Set.of(TENANT_A, TENANT_B, TENANT_C, TENANT_D), + Set.of(TENANT_A, TENANT_B, TENANT_C, TENANT_D), + Set.of(TENANT_A, TENANT_B, TENANT_C), + List.of()), + Set.of(TENANT_A, TENANT_B, TENANT_C, TENANT_D), + Set.of(TENANT_A, TENANT_B, TENANT_C), + Set.of(TENANT_A, TENANT_B, TENANT_C), + Set.of(TENANT_A, TENANT_B, TENANT_C, TENANT_D), + Set.of(TENANT_D), + Set.of(TENANT_A, TENANT_B, TENANT_C)); + } + + private static TenantBoundDelegationShape tenantDelegation( + boolean publicProduction, + Optional target, + List grants) { + return new TenantBoundDelegationShape( + delegationClaims(true, !publicProduction && !grants.isEmpty()), + authority( + Set.of(TENANT_A), + Set.of(TENANT_A), + Set.of(TENANT_A), + !publicProduction && !grants.isEmpty() ? Set.of(TENANT_A) : Set.of(), + grants), + TENANT_A, + Set.of(TENANT_A), + publicProduction, + target); + } + + private static PrivateRealmGrantShape grant(UUID tenantId, UUID lifecycleId, String version) { + return new PrivateRealmGrantShape(tenantId, "emberfall", "preview", lifecycleId, version); + } + + private static AuthorityMapShape authority( + Set tenantAuthority, + Set membershipAuthority, + Set membershipVersion, + Set billingCutoff, + List grants) { + return new AuthorityMapShape( + tenantAuthority, membershipAuthority, membershipVersion, billingCutoff, grants); + } + + private static AuthorityMapShape emptyAuthority() { + return authority(Set.of(), Set.of(), Set.of(), Set.of(), List.of()); + } + + private static ClaimFieldPresence controlUiClaims(boolean cutoffPresent) { + return controlUiClaims(cutoffPresent, false); + } + + private static ClaimFieldPresence controlUiClaims( + boolean cutoffPresent, boolean accountCutoffPresent) { + return claims("control-ui", true, cutoffPresent, accountCutoffPresent); + } + + private static ClaimFieldPresence bootstrapClaims() { + return claims("player-bootstrap", true, false, false); + } + + private static ClaimFieldPresence delegationClaims( + boolean scopedRolesPresent, boolean cutoffPresent) { + return claims("account-service", scopedRolesPresent, cutoffPresent, false); + } + + private static ClaimFieldPresence claims( + String audience, + boolean scopedRolesPresent, + boolean tenantCutoffPresent, + boolean accountCutoff) { + return new ClaimFieldPresence( + true, + true, + true, + true, + audience, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + scopedRolesPresent, + tenantCutoffPresent, + accountCutoff); + } + + private static ClaimFieldPresence claimsWithoutMembershipVersion() { + return new ClaimFieldPresence( + true, + true, + true, + true, + "control-ui", + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false); + } + + private static String tupleJson(AccountTokenProfileCatalog.ProfileShape shape) { + return canonicalTupleJson(tupleMap(shape)); + } + + private static String tupleJson( + AccountTokenProfileCatalog.ProfileShape shape, Map overrides) { + Map tuple = tupleMap(shape); + tuple.putAll(overrides); + return canonicalTupleJson(tuple); + } + + private static String tupleJsonWithoutField( + AccountTokenProfileCatalog.ProfileShape shape, String field) { + Map tuple = tupleMap(shape); + tuple.remove(field); + return canonicalTupleJson(tuple); + } + + private static Map tupleMap(AccountTokenProfileCatalog.ProfileShape shape) { + AuthorityMapShape authority = shape.authority(); + Map tuple = new TreeMap<>(); + tuple.put("accountAuthorityGeneration", "1"); + tuple.put("issuerAuthGeneration", "1"); + tuple.put("membershipAuthorityGeneration", generationMap(authority.membershipAuthorityKeys())); + tuple.put("privateRealmGrantVersions", grantList(authority.privateRealmGrants())); + tuple.put("tenantAuthorityGeneration", generationMap(authority.tenantAuthorityKeys())); + if (!authority.tenantBillingCutoffKeys().isEmpty()) { + tuple.put("tenantBillingCutoff", cutoffMap(authority.tenantBillingCutoffKeys())); + } + if (shape.claims().accountSecurityCutoffPresent()) { + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + "1", + "outboxSequence", + "1", + "outboxStreamKey", + "account")); + } + return tuple; + } + + private static String canonicalTupleJson(Map tuple) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(tuple)), + StandardCharsets.UTF_8); + } catch (Exception exception) { + throw new IllegalStateException("test tuple could not be canonicalized", exception); + } + } + + private static Map generationMap(Set tenantIds) { + Map map = new TreeMap<>(); + tenantIds.forEach(tenantId -> map.put(tenantId.toString(), "1")); + return map; + } + + private static List> grantList(List grants) { + List> values = new ArrayList<>(); + for (PrivateRealmGrantShape grant : grants) { + Map value = new TreeMap<>(); + value.put("grantVersion", grant.grantVersionDecimal()); + value.put("playtestLifecycleId", grant.playtestLifecycleId().toString()); + value.put("realmSlug", grant.realmSlug()); + value.put("tenantId", grant.tenantId().toString()); + value.put("worldSlug", grant.worldSlug()); + values.add(value); + } + return values; + } + + private static Map cutoffMap(Set tenantIds) { + Map values = new TreeMap<>(); + tenantIds.forEach( + tenantId -> + values.put( + tenantId.toString(), + Map.of( + "outboxSequence", "1", + "outboxStreamKey", "tenant", + "tenantAuthorityGeneration", "1", + "tenantBillingSequence", "1"))); + return values; + } + + private static UUID uuid(long suffix) { + return UUID.fromString(String.format("00000000-0000-4000-8000-%012d", suffix)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountBareLoginCurrentAuthorityReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountBareLoginCurrentAuthorityReaderTest.java new file mode 100644 index 0000000000..1e7969ac32 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountBareLoginCurrentAuthorityReaderTest.java @@ -0,0 +1,702 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.time.Instant; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto.MembershipBaseline; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountConnectIssuanceFenceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.service.AccountBareLoginCurrentAuthorityReader; +import net.firedevops.firemud.accountservice.service.AccountBareLoginCurrentAuthorityReader.CurrentAuthorityReadback; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader.OriginalSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountConnectTokenAuthorityCaptureService; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.PrivateRealmGrantVersion; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +class AccountBareLoginCurrentAuthorityReaderTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("00000000-0000-4000-8000-000000000001"); + private static final UUID TENANT_UUID = UUID.fromString("00000000-0000-4000-8000-000000000002"); + private static final UUID REALM_UUID = UUID.fromString("00000000-0000-4000-8000-000000000003"); + private static final UUID GAME_INSTANCE_UUID = + UUID.fromString("00000000-0000-4000-8000-000000000004"); + private static final UUID NAMESPACE_UUID = + UUID.fromString("00000000-0000-4000-8000-000000000005"); + private static final UUID OPERATION_ID = UUID.fromString("00000000-0000-4000-8000-000000000006"); + private static final String REQUEST_ID = "bare-login-request-1"; + private static final String CONNECT_SCOPE_ID = "connect-scope-1"; + private static final String SIGNED_CONTEXT = "signed-gateway-context-secret-marker"; + private static final Instant NOW = Instant.parse("2026-04-06T12:00:00Z"); + private static final byte[] REQUEST_DIGEST = filled(32, (byte) 0x31); + private static final byte[] TOKEN_HASH = filled(32, (byte) 0x42); + + private AccountCommittedConnectSourceReader committedSourceReader; + private AccountConnectTokenAuthorityCaptureService captureService; + private AccountMembershipAuthorityEventProducer membershipProducer; + private AccountAuthorityGenerationRepository authorityGenerationRepository; + private AccountBareLoginCurrentAuthorityReader reader; + + @BeforeEach + void setUp() { + committedSourceReader = mock(AccountCommittedConnectSourceReader.class); + captureService = mock(AccountConnectTokenAuthorityCaptureService.class); + membershipProducer = mock(AccountMembershipAuthorityEventProducer.class); + authorityGenerationRepository = mock(AccountAuthorityGenerationRepository.class); + reader = + new AccountBareLoginCurrentAuthorityReader( + committedSourceReader, + captureService, + membershipProducer, + authorityGenerationRepository); + } + + @Test + void composesExactCurrentEvidenceInOrderAndReturnsOnlyRedactedImmutableFacts() { + Fixture fixture = fixture(); + installHappyPath(fixture); + + CurrentAuthorityReadback result = + reader.read(fixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT); + + assertEquals(OPERATION_ID, result.operationId()); + assertEquals(ACCOUNT_UUID, result.accountUuid()); + assertEquals(TENANT_UUID, result.tenantUuid()); + assertEquals(REQUEST_ID, result.requestId()); + assertEquals(6L, result.issuanceFence()); + assertEquals(7L, result.fenceSourceVersion()); + assertEquals(Map.of(TENANT_UUID.toString(), "8"), result.membershipVersion()); + assertEquals("ACTIVE", result.membershipLifecycleState()); + assertEquals(List.of("player"), result.roles()); + assertEquals(fixture.authorityTuple(), result.authorityTuple()); + assertEquals(4, result.checkpoints().size()); + assertEquals(4, result.sourceEvents().size()); + assertArrayEquals(REQUEST_DIGEST, result.requestDigest()); + assertArrayEquals(fixture.capture().digest(), result.captureDigest()); + assertFalse(result.toString().contains(SIGNED_CONTEXT)); + assertFalse(result.toString().contains("connect-jti-1")); + assertFalse(result.toString().contains("canonicalEventJson")); + + byte[] returnedHash = result.sourceTokenHash(); + returnedHash[0] ^= 0x7f; + assertArrayEquals(TOKEN_HASH, result.sourceTokenHash()); + byte[] returnedRequestDigest = result.requestDigest(); + returnedRequestDigest[0] ^= 0x7f; + assertArrayEquals(REQUEST_DIGEST, result.requestDigest()); + byte[] returnedCaptureDigest = result.captureDigest(); + returnedCaptureDigest[0] ^= 0x7f; + assertArrayEquals(fixture.capture().digest(), result.captureDigest()); + assertThrows( + UnsupportedOperationException.class, + () -> result.membershipVersion().put(TENANT_UUID.toString(), "9")); + assertThrows( + UnsupportedOperationException.class, + () -> + result + .checkpoints() + .add(new AccountBareLoginCurrentAuthorityReader.CheckpointReadback("x", "1"))); + assertThrows( + UnsupportedOperationException.class, + () -> result.authorityTuple().tenantAuthorityGeneration().put(TENANT_UUID.toString(), "9")); + + InOrder ordered = + inOrder( + committedSourceReader, + captureService, + membershipProducer, + authorityGenerationRepository); + ordered.verify(committedSourceReader).read(fixture.identity(), SIGNED_CONTEXT); + ordered + .verify(captureService) + .read(eq(fixture.identity()), argThat(digest -> Arrays.equals(REQUEST_DIGEST, digest))); + ordered + .verify(membershipProducer) + .readExistingRuntimeMembershipSnapshot(ACCOUNT_UUID, TENANT_UUID); + ordered.verify(authorityGenerationRepository).read(AuthorityScope.account(ACCOUNT_UUID)); + ordered.verify(committedSourceReader).read(fixture.identity(), SIGNED_CONTEXT); + } + + @Test + void strictPeerOrCurrentContextDenialStopsBeforeCaptureAndAuthorityReads() { + Fixture fixture = fixture(); + when(committedSourceReader.read(fixture.identity(), SIGNED_CONTEXT)) + .thenThrow(new AdminAuthorizationException("exact Game Session peer required")); + + assertThrows( + AdminAuthorizationException.class, + () -> reader.read(fixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + + verify(committedSourceReader).read(fixture.identity(), SIGNED_CONTEXT); + verifyNoInteractions(captureService, membershipProducer, authorityGenerationRepository); + } + + @Test + void absentCaptureCannotBeInferredFromCurrentFenceOrReachMembershipRead() { + Fixture fixture = fixture(); + when(committedSourceReader.read(fixture.identity(), SIGNED_CONTEXT)) + .thenReturn(fixture.source()); + when(captureService.read( + eq(fixture.identity()), argThat(digest -> Arrays.equals(REQUEST_DIGEST, digest)))) + .thenReturn(Optional.empty()); + + assertThrows( + IllegalStateException.class, + () -> reader.read(fixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + + verify(captureService) + .read(eq(fixture.identity()), argThat(digest -> Arrays.equals(REQUEST_DIGEST, digest))); + verify(membershipProducer, never()) + .readExistingRuntimeMembershipSnapshot(any(UUID.class), any(UUID.class)); + verifyNoInteractions(authorityGenerationRepository); + } + + @Test + void captureMustMatchExactRequestDigestAndOperationBeforeCurrentReads() { + Fixture fixture = fixture(); + AccountConnectIssuanceFenceEvidence wrongDigestCapture = + AccountConnectIssuanceFenceEvidence.capture( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + fixture.capture().connectScopeHash(), + REQUEST_ID, + filled(32, (byte) 0x33), + 6L, + 7L); + installHappyPath(fixture); + when(captureService.read( + eq(fixture.identity()), argThat(digest -> Arrays.equals(REQUEST_DIGEST, digest)))) + .thenReturn(Optional.of(wrongDigestCapture)); + + assertThrows( + IllegalStateException.class, + () -> reader.read(fixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + + verify(membershipProducer, never()) + .readExistingRuntimeMembershipSnapshot(any(UUID.class), any(UUID.class)); + verifyNoInteractions(authorityGenerationRepository); + } + + @Test + void comparesEveryAuthorityTupleMemberIncludingGrantAndBothOptionalCutoffs() { + assertDeniedWithTuple( + new AuthorityTuple( + "4", + "2", + Map.of(TENANT_UUID.toString(), "4"), + Map.of(TENANT_UUID.toString(), "5"), + List.of(), + Optional.of(accountCutoff("2", "12")), + Optional.empty())); + assertDeniedWithTuple( + new AuthorityTuple( + "3", + "3", + Map.of(TENANT_UUID.toString(), "4"), + Map.of(TENANT_UUID.toString(), "5"), + List.of(), + Optional.of(accountCutoff("3", "12")), + Optional.empty())); + assertDeniedWithTuple( + new AuthorityTuple( + "3", + "2", + Map.of(TENANT_UUID.toString(), "6"), + Map.of(TENANT_UUID.toString(), "5"), + List.of(), + Optional.of(accountCutoff("2", "12")), + Optional.empty())); + assertDeniedWithTuple( + new AuthorityTuple( + "3", + "2", + Map.of(TENANT_UUID.toString(), "4"), + Map.of(TENANT_UUID.toString(), "6"), + List.of(), + Optional.of(accountCutoff("2", "12")), + Optional.empty())); + assertDeniedWithTuple( + new AuthorityTuple( + "3", + "2", + Map.of(TENANT_UUID.toString(), "4"), + Map.of(TENANT_UUID.toString(), "5"), + List.of( + new PrivateRealmGrantVersion( + TENANT_UUID.toString(), "emberfall", "preview", "playtest-lifecycle-1", "7")), + Optional.of(accountCutoff("2", "12")), + Optional.empty())); + assertDeniedWithTuple( + new AuthorityTuple( + "3", + "2", + Map.of(TENANT_UUID.toString(), "4"), + Map.of(TENANT_UUID.toString(), "5"), + List.of(), + Optional.of(accountCutoff("2", "13")), + Optional.empty())); + assertDeniedWithTuple( + new AuthorityTuple( + "3", + "2", + Map.of(TENANT_UUID.toString(), "4"), + Map.of(TENANT_UUID.toString(), "5"), + List.of(), + Optional.of(accountCutoff("3", "12")), + Optional.empty())); + assertDeniedWithTuple( + new AuthorityTuple( + "3", + "2", + Map.of(TENANT_UUID.toString(), "4"), + Map.of(TENANT_UUID.toString(), "5"), + List.of(), + Optional.of( + new AccountSecurityCutoff("2", "account:auth-authority:v1:account/other", "12")), + Optional.empty())); + assertDeniedWithTuple( + new AuthorityTuple( + "3", + "2", + Map.of(TENANT_UUID.toString(), "4"), + Map.of(TENANT_UUID.toString(), "5"), + List.of(), + Optional.of(accountCutoff("2", "12")), + Optional.of( + Map.of( + TENANT_UUID.toString(), + new TenantBillingCutoff( + "4", "1", "account:auth-authority:v1:tenant/" + TENANT_UUID, "14"))))); + } + + @Test + void membershipVersionIsComparedAsItsOwnExactOneTenantMap() { + Fixture fixture = fixture(); + installHappyPath(fixture); + when(fixture.snapshot().membershipBaseline()) + .thenReturn(new MembershipBaseline("ACTIVE", Map.of(TENANT_UUID.toString(), "9"), "5")); + + assertThrows( + IllegalStateException.class, + () -> reader.read(fixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + + verify(authorityGenerationRepository).read(AuthorityScope.account(ACCOUNT_UUID)); + verify(committedSourceReader, org.mockito.Mockito.times(1)) + .read(fixture.identity(), SIGNED_CONTEXT); + } + + @Test + void membershipVersionAcceptsCanonicalDecimalStringsBeyondPrimitiveIntegerRange() { + Fixture base = fixture(); + String largeVersion = "1234567890123456789012345678901234567890"; + Map sourceClaims = new LinkedHashMap<>(base.source().originalSourceClaims()); + sourceClaims.put("membershipVersion", Map.of(TENANT_UUID.toString(), largeVersion)); + Map gatewayClaims = + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + sourceClaims, NOW.getEpochSecond(), "gateway-request-1"); + Fixture fixture = + new Fixture( + base.identity(), + sourceEvidence(sourceClaims, gatewayClaims), + base.capture(), + base.snapshot(), + base.authorityTuple(), + base.accountAuthority()); + installHappyPath(fixture); + when(fixture.snapshot().membershipBaseline()) + .thenReturn( + new MembershipBaseline("ACTIVE", Map.of(TENANT_UUID.toString(), largeVersion), "5")); + + CurrentAuthorityReadback result = + reader.read(fixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT); + + assertEquals(Map.of(TENANT_UUID.toString(), largeVersion), result.membershipVersion()); + verify(committedSourceReader, org.mockito.Mockito.times(2)) + .read(fixture.identity(), SIGNED_CONTEXT); + } + + @Test + void membershipVersionRejectsNonStringNoncanonicalAndWrongTenantSourceValues() { + List invalidValues = + List.of( + Map.of(TENANT_UUID.toString(), BigInteger.valueOf(8)), + Map.of(TENANT_UUID.toString(), "08"), + Map.of(TENANT_UUID.toString(), "0"), + Map.of("00000000-0000-4000-8000-000000000099", "8"), + Map.of(TENANT_UUID.toString(), "8", "00000000-0000-4000-8000-000000000099", "9")); + + for (Object invalidValue : invalidValues) { + org.mockito.Mockito.clearInvocations( + committedSourceReader, captureService, membershipProducer, authorityGenerationRepository); + Fixture fixture = fixture(); + Map sourceClaims = + new LinkedHashMap<>(fixture.source().originalSourceClaims()); + sourceClaims.put("membershipVersion", invalidValue); + // This substitutes source-reader output to exercise defensive validation. It does not claim + // that Gateway or the production source verifier accepts these malformed source claims. + OriginalSourceEvidence substitutedSource = + sourceEvidence(sourceClaims, fixture.source().gatewayContextClaims()); + installHappyPath(fixture); + doReturn(substitutedSource) + .when(committedSourceReader) + .read(fixture.identity(), SIGNED_CONTEXT); + + assertThrows( + IllegalStateException.class, + () -> reader.read(fixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + + verify(committedSourceReader, org.mockito.Mockito.times(1)) + .read(fixture.identity(), SIGNED_CONTEXT); + } + } + + @Test + void captureCounterAndFenceSourceVersionMustEqualCurrentDurableAccountFence() { + Fixture fixture = fixture(); + AccountConnectIssuanceFenceEvidence wrongCounterCapture = + AccountConnectIssuanceFenceEvidence.capture( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + fixture.capture().connectScopeHash(), + REQUEST_ID, + REQUEST_DIGEST, + 7L, + 7L); + installHappyPath(fixture); + when(captureService.read( + eq(fixture.identity()), argThat(digest -> Arrays.equals(REQUEST_DIGEST, digest)))) + .thenReturn(Optional.of(wrongCounterCapture)); + + assertThrows( + IllegalStateException.class, + () -> reader.read(fixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + verify(committedSourceReader, org.mockito.Mockito.times(1)) + .read(fixture.identity(), SIGNED_CONTEXT); + + org.mockito.Mockito.clearInvocations( + committedSourceReader, captureService, membershipProducer, authorityGenerationRepository); + Fixture wrongSourceVersion = fixture(); + AccountConnectIssuanceFenceEvidence wrongSourceVersionCapture = + AccountConnectIssuanceFenceEvidence.capture( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + wrongSourceVersion.capture().connectScopeHash(), + REQUEST_ID, + REQUEST_DIGEST, + 6L, + 8L); + installHappyPath(wrongSourceVersion); + when(captureService.read( + eq(wrongSourceVersion.identity()), + argThat(digest -> Arrays.equals(REQUEST_DIGEST, digest)))) + .thenReturn(Optional.of(wrongSourceVersionCapture)); + + assertThrows( + IllegalStateException.class, + () -> reader.read(wrongSourceVersion.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + verify(committedSourceReader, org.mockito.Mockito.times(1)) + .read(wrongSourceVersion.identity(), SIGNED_CONTEXT); + } + + @Test + void sourceIdentityMismatchFailsBeforeCaptureAndNoMembershipEnrollmentIsAttempted() { + Fixture fixture = fixture(); + Map changedClaims = + new LinkedHashMap<>(fixture.source().originalSourceClaims()); + changedClaims.put("tenantId", "00000000-0000-4000-8000-000000000099"); + OriginalSourceEvidence wrongTenantSource = + sourceEvidence(changedClaims, fixture.source().gatewayContextClaims()); + when(committedSourceReader.read(fixture.identity(), SIGNED_CONTEXT)) + .thenReturn(wrongTenantSource); + + assertThrows( + IllegalStateException.class, + () -> reader.read(fixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + + verifyNoInteractions(captureService, membershipProducer, authorityGenerationRepository); + } + + @Test + void finalStrictSourceReadRejectsExpiryOrChangedSourceProvenance() { + Fixture fixture = fixture(); + installHappyPath(fixture); + when(committedSourceReader.read(fixture.identity(), SIGNED_CONTEXT)) + .thenReturn(fixture.source()) + .thenThrow(new IllegalArgumentException("current source expired")); + + assertThrows( + IllegalArgumentException.class, + () -> reader.read(fixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + verify(committedSourceReader, org.mockito.Mockito.times(2)) + .read(fixture.identity(), SIGNED_CONTEXT); + + org.mockito.Mockito.clearInvocations( + committedSourceReader, captureService, membershipProducer, authorityGenerationRepository); + Fixture changedFinalSource = fixture(); + installHappyPath(changedFinalSource); + OriginalSourceEvidence changedKeySource = + new OriginalSourceEvidence( + OPERATION_ID, + "different-envelope-key", + TOKEN_HASH, + "gateway-key-1", + changedFinalSource.source().originalSourceClaims(), + changedFinalSource.source().gatewayContextClaims()); + when(committedSourceReader.read(changedFinalSource.identity(), SIGNED_CONTEXT)) + .thenReturn(changedFinalSource.source(), changedKeySource); + + assertThrows( + IllegalStateException.class, + () -> reader.read(changedFinalSource.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + verify(committedSourceReader, org.mockito.Mockito.times(2)) + .read(changedFinalSource.identity(), SIGNED_CONTEXT); + + org.mockito.Mockito.clearInvocations( + committedSourceReader, captureService, membershipProducer, authorityGenerationRepository); + Fixture changedHashFixture = fixture(); + installHappyPath(changedHashFixture); + OriginalSourceEvidence changedHashSource = + new OriginalSourceEvidence( + OPERATION_ID, + "envelope-key-1", + filled(32, (byte) 0x43), + "gateway-key-1", + changedHashFixture.source().originalSourceClaims(), + changedHashFixture.source().gatewayContextClaims()); + when(committedSourceReader.read(changedHashFixture.identity(), SIGNED_CONTEXT)) + .thenReturn(changedHashFixture.source(), changedHashSource); + + assertThrows( + IllegalStateException.class, + () -> reader.read(changedHashFixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + verify(committedSourceReader, org.mockito.Mockito.times(2)) + .read(changedHashFixture.identity(), SIGNED_CONTEXT); + + org.mockito.Mockito.clearInvocations( + committedSourceReader, captureService, membershipProducer, authorityGenerationRepository); + Fixture changedClaimsFixture = fixture(); + installHappyPath(changedClaimsFixture); + Map changedClaims = + new LinkedHashMap<>(changedClaimsFixture.source().originalSourceClaims()); + changedClaims.put("pointerVersion", BigInteger.valueOf(24)); + Map changedGatewayClaims = + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + changedClaims, NOW.getEpochSecond(), "gateway-request-1"); + OriginalSourceEvidence changedClaimsSource = + sourceEvidence(changedClaims, changedGatewayClaims); + when(committedSourceReader.read(changedClaimsFixture.identity(), SIGNED_CONTEXT)) + .thenReturn(changedClaimsFixture.source(), changedClaimsSource); + + assertThrows( + IllegalStateException.class, + () -> reader.read(changedClaimsFixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + verify(committedSourceReader, org.mockito.Mockito.times(2)) + .read(changedClaimsFixture.identity(), SIGNED_CONTEXT); + } + + private void assertDeniedWithTuple(AuthorityTuple changedTuple) { + org.mockito.Mockito.clearInvocations( + committedSourceReader, captureService, membershipProducer, authorityGenerationRepository); + Fixture fixture = fixture(); + installHappyPath(fixture); + when(fixture.snapshot().authorityTuple()).thenReturn(changedTuple); + assertThrows( + IllegalStateException.class, + () -> reader.read(fixture.identity(), REQUEST_DIGEST, SIGNED_CONTEXT)); + verify(committedSourceReader, org.mockito.Mockito.times(1)) + .read(fixture.identity(), SIGNED_CONTEXT); + } + + private void installHappyPath(Fixture fixture) { + doReturn(fixture.source()).when(committedSourceReader).read(fixture.identity(), SIGNED_CONTEXT); + when(captureService.read( + eq(fixture.identity()), argThat(digest -> Arrays.equals(REQUEST_DIGEST, digest)))) + .thenReturn(Optional.of(fixture.capture())); + when(membershipProducer.readExistingRuntimeMembershipSnapshot(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn(fixture.snapshot()); + when(authorityGenerationRepository.read(AuthorityScope.account(ACCOUNT_UUID))) + .thenReturn(fixture.accountAuthority()); + } + + private Fixture fixture() { + AccountConnectTokenIssuanceIdentity identity = + new AccountConnectTokenIssuanceIdentity(101L, TENANT_UUID, CONNECT_SCOPE_ID, REQUEST_ID); + AuthorityTuple authorityTuple = currentAuthorityTuple(); + Map sourceClaims = sourceClaims(); + Map gatewayClaims = + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + sourceClaims, NOW.getEpochSecond(), "gateway-request-1"); + OriginalSourceEvidence source = sourceEvidence(sourceClaims, gatewayClaims); + AccountConnectIssuanceFenceEvidence capture = + AccountConnectIssuanceFenceEvidence.capture( + OPERATION_ID, + ACCOUNT_UUID, + TENANT_UUID, + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(CONNECT_SCOPE_ID), + REQUEST_ID, + REQUEST_DIGEST, + 6L, + 7L); + + List checkpoints = + List.of( + new OutboxCheckpointEntry("account:auth-authority:v1:account/" + ACCOUNT_UUID, "3"), + new OutboxCheckpointEntry("account:auth-authority:v1:issuer/account-service", "2"), + new OutboxCheckpointEntry( + "account:auth-authority:v1:membership/" + ACCOUNT_UUID + "/" + TENANT_UUID, "5"), + new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + TENANT_UUID, "4")); + List sourceEvents = + checkpoints.stream() + .map( + checkpoint -> + new OutboxSourceEvidence( + checkpoint.outboxStreamKey(), + checkpoint.outboxSequence(), + "event-" + checkpoint.outboxSequence(), + "sha256:" + "a".repeat(64), + "{}")) + .toList(); + RuntimeMembershipSnapshotDto snapshot = mock(RuntimeMembershipSnapshotDto.class); + when(snapshot.requestAccountUuid()).thenReturn(ACCOUNT_UUID.toString()); + when(snapshot.requestTenantUuid()).thenReturn(TENANT_UUID.toString()); + when(snapshot.accountUuid()).thenReturn(ACCOUNT_UUID.toString()); + when(snapshot.tenantUuid()).thenReturn(TENANT_UUID.toString()); + when(snapshot.membershipExists()).thenReturn(true); + when(snapshot.gameplayAdmissionAllowed()).thenReturn(true); + when(snapshot.membershipBaseline()) + .thenReturn(new MembershipBaseline("ACTIVE", Map.of(TENANT_UUID.toString(), "8"), "5")); + when(snapshot.roles()).thenReturn(List.of("player")); + when(snapshot.authorityTuple()).thenReturn(authorityTuple); + when(snapshot.issuanceFence()).thenReturn("6"); + when(snapshot.evaluatedAt()).thenReturn(NOW); + when(snapshot.outboxCheckpoints()).thenReturn(checkpoints); + when(snapshot.outboxSourceEvidence()).thenReturn(sourceEvents); + + ScopeState accountAuthority = + new ScopeState( + AuthorityScope.account(ACCOUNT_UUID), 2L, 9L, new IssuanceFence(ACCOUNT_UUID, 6L, 7L)); + return new Fixture(identity, source, capture, snapshot, authorityTuple, accountAuthority); + } + + private static Map sourceClaims() { + Map claims = new LinkedHashMap<>(); + claims.put("iss", "https://account.example.test"); + claims.put("aud", "gameplay-connect"); + claims.put("iat", BigInteger.valueOf(NOW.getEpochSecond() - 1)); + claims.put("exp", BigInteger.valueOf(NOW.getEpochSecond() + 29)); + claims.put("jti", "connect-jti-1"); + claims.put("accountId", ACCOUNT_UUID.toString()); + claims.put("tenantId", TENANT_UUID.toString()); + claims.put("realmId", REALM_UUID.toString()); + claims.put("worldSlug", "emberfall"); + claims.put("realmSlug", "public-production"); + claims.put("playableStateNamespaceId", NAMESPACE_UUID.toString()); + claims.put("playableStateScope", "PLAYABLE_STATE_SCOPE_SHARED"); + claims.put("gameInstanceId", GAME_INSTANCE_UUID.toString()); + claims.put("pointerVersion", BigInteger.valueOf(23)); + claims.put("catalogRevision", BigInteger.valueOf(41)); + claims.put("connectScopeId", CONNECT_SCOPE_ID); + claims.put("requestId", REQUEST_ID); + claims.put("authorityTuple", sourceAuthorityTuple()); + claims.put("membershipVersion", Map.of(TENANT_UUID.toString(), "8")); + // This Gateway replay fence intentionally differs from the Account issuance fence below. + claims.put("replayAdmissionFence", BigInteger.valueOf(29)); + return claims; + } + + private static Map sourceAuthorityTuple() { + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", BigInteger.valueOf(3)); + tuple.put("accountAuthorityGeneration", BigInteger.valueOf(2)); + tuple.put("tenantAuthorityGeneration", Map.of(TENANT_UUID.toString(), BigInteger.valueOf(4))); + tuple.put( + "membershipAuthorityGeneration", Map.of(TENANT_UUID.toString(), BigInteger.valueOf(5))); + tuple.put("privateRealmGrantVersions", List.of()); + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + BigInteger.valueOf(2), + "outboxStreamKey", + "account:auth-authority:v1:account/" + ACCOUNT_UUID, + "outboxSequence", + BigInteger.valueOf(12))); + return tuple; + } + + private static AuthorityTuple currentAuthorityTuple() { + return new AuthorityTuple( + "3", + "2", + Map.of(TENANT_UUID.toString(), "4"), + Map.of(TENANT_UUID.toString(), "5"), + List.of(), + Optional.of(accountCutoff("2", "12")), + Optional.empty()); + } + + private static AccountSecurityCutoff accountCutoff(String generation, String sequence) { + return accountCutoff(generation, sequence, "account:auth-authority:v1:account/" + ACCOUNT_UUID); + } + + private static AccountSecurityCutoff accountCutoff( + String generation, String sequence, String outboxStreamKey) { + return new AccountSecurityCutoff(generation, outboxStreamKey, sequence); + } + + private static OriginalSourceEvidence sourceEvidence( + Map sourceClaims, Map gatewayClaims) { + return new OriginalSourceEvidence( + OPERATION_ID, "envelope-key-1", TOKEN_HASH, "gateway-key-1", sourceClaims, gatewayClaims); + } + + private static byte[] filled(int length, byte value) { + byte[] bytes = new byte[length]; + Arrays.fill(bytes, value); + return bytes; + } + + private record Fixture( + AccountConnectTokenIssuanceIdentity identity, + OriginalSourceEvidence source, + AccountConnectIssuanceFenceEvidence capture, + RuntimeMembershipSnapshotDto snapshot, + AuthorityTuple authorityTuple, + ScopeState accountAuthority) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountConnectTokenAuthorityCaptureServiceGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountConnectTokenAuthorityCaptureServiceGuardTest.java new file mode 100644 index 0000000000..878ea90eaa --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountConnectTokenAuthorityCaptureServiceGuardTest.java @@ -0,0 +1,275 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepository.ClaimResult; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.AccountConnectTokenAuthorityCaptureService; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountConnectTokenAuthorityCaptureServiceGuardTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("07891384-1a41-4f17-a135-048db46a705e"); + private static final UUID TENANT_UUID = UUID.fromString("b46c3e99-7c0c-4f25-9bc4-a3e9af5d415f"); + private static final byte[] REQUEST_DIGEST = new byte[32]; + + @Test + void captureRejectsMissingOwnerTransactionBeforeAnyCollaboratorInteraction() { + Repositories repositories = new Repositories(); + boolean priorActive = TransactionSynchronizationManager.isActualTransactionActive(); + boolean priorReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + Integer priorIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + + try { + assertThatThrownBy( + () -> repositories.service().capture(mock(ClaimResult.class), REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + repositories.verifyNoReads(); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(priorActive); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(priorReadOnly); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(priorIsolation); + } + } + + @Test + void captureRejectsAutocommitConnectionBeforeAnyCollaboratorInteraction() throws Exception { + Repositories repositories = new Repositories(); + bindConnection( + repositories.dataSource, + true, + Connection.TRANSACTION_READ_COMMITTED, + false, + "read committed", + "off"); + TransactionState prior = captureTransactionState(); + + try { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy( + () -> repositories.service().capture(mock(ClaimResult.class), REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("transaction-bound JDBC connection"); + repositories.verifyNoReads(); + } finally { + unbindConnection(repositories.dataSource, prior); + } + } + + @Test + void readRejectsNonReadCommittedJdbcConnectionBeforeAnyCollaboratorInteraction() + throws Exception { + Repositories repositories = new Repositories(); + bindConnection( + repositories.dataSource, + false, + Connection.TRANSACTION_REPEATABLE_READ, + false, + "repeatable read", + "off"); + TransactionState prior = captureTransactionState(); + AccountConnectTokenIssuanceIdentity identity = + new AccountConnectTokenIssuanceIdentity( + 9L, TENANT_UUID, "opaque-connect-scope", "request-guard"); + + try { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repositories.service().read(identity, REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ COMMITTED"); + repositories.verifyNoReads(); + } finally { + unbindConnection(repositories.dataSource, prior); + } + } + + @Test + void readRejectsPostgresReadOnlyTransactionBeforeAnyCollaboratorInteraction() throws Exception { + Repositories repositories = new Repositories(); + bindConnection( + repositories.dataSource, + false, + Connection.TRANSACTION_READ_COMMITTED, + false, + "read committed", + "on"); + TransactionState prior = captureTransactionState(); + AccountConnectTokenIssuanceIdentity identity = + new AccountConnectTokenIssuanceIdentity( + 9L, TENANT_UUID, "opaque-connect-scope", "request-guard"); + + try { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repositories.service().read(identity, REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + repositories.verifyNoReads(); + } finally { + unbindConnection(repositories.dataSource, prior); + } + } + + @Test + void readRejectsPostgresIsolationThatDisagreesWithJdbcBeforeAnyCollaboratorInteraction() + throws Exception { + Repositories repositories = new Repositories(); + bindConnection( + repositories.dataSource, + false, + Connection.TRANSACTION_READ_COMMITTED, + false, + "repeatable read", + "off"); + TransactionState prior = captureTransactionState(); + AccountConnectTokenIssuanceIdentity identity = + new AccountConnectTokenIssuanceIdentity( + 9L, TENANT_UUID, "opaque-connect-scope", "request-guard"); + + try { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repositories.service().read(identity, REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ COMMITTED"); + repositories.verifyNoReads(); + } finally { + unbindConnection(repositories.dataSource, prior); + } + } + + @Test + void readRejectsJdbcReadOnlyConnectionBeforeAnyCollaboratorInteraction() throws Exception { + Repositories repositories = new Repositories(); + bindConnection( + repositories.dataSource, + false, + Connection.TRANSACTION_READ_COMMITTED, + true, + "read committed", + "off"); + TransactionState prior = captureTransactionState(); + AccountConnectTokenIssuanceIdentity identity = + new AccountConnectTokenIssuanceIdentity( + 9L, TENANT_UUID, "opaque-connect-scope", "request-guard"); + + try { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repositories.service().read(identity, REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + repositories.verifyNoReads(); + } finally { + unbindConnection(repositories.dataSource, prior); + } + } + + @SuppressFBWarnings( + value = {"OBL_UNSATISFIED_OBLIGATION", "ODR_OPEN_DATABASE_RESOURCE"}, + justification = "Only Mockito JDBC mocks are created; no driver resources are acquired") + private static void bindConnection( + DataSource dataSource, + boolean autoCommit, + int isolation, + boolean readOnly, + String postgresIsolation, + String postgresReadOnly) + throws Exception { + Connection connection = mock(Connection.class); + Statement statement = mock(Statement.class); + ResultSet isolationResult = oneRow(postgresIsolation); + ResultSet readOnlyResult = oneRow(postgresReadOnly); + when(connection.getAutoCommit()).thenReturn(autoCommit); + when(connection.getTransactionIsolation()).thenReturn(isolation); + when(connection.isReadOnly()).thenReturn(readOnly); + doReturn(statement).when(connection).createStatement(); + doReturn(isolationResult).when(statement).executeQuery("SHOW transaction_isolation"); + doReturn(readOnlyResult).when(statement).executeQuery("SHOW transaction_read_only"); + TransactionSynchronizationManager.bindResource(dataSource, new ConnectionHolder(connection)); + } + + private static ResultSet oneRow(String value) throws Exception { + ResultSet result = mock(ResultSet.class); + when(result.next()).thenReturn(true, false); + when(result.getString(1)).thenReturn(value); + return result; + } + + private static void unbindConnection(DataSource dataSource, TransactionState prior) { + TransactionSynchronizationManager.unbindResourceIfPossible(dataSource); + TransactionSynchronizationManager.setActualTransactionActive(prior.active()); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(prior.readOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(prior.isolationLevel()); + } + + private static TransactionState captureTransactionState() { + return new TransactionState( + TransactionSynchronizationManager.isActualTransactionActive(), + TransactionSynchronizationManager.isCurrentTransactionReadOnly(), + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()); + } + + private record TransactionState(boolean active, boolean readOnly, Integer isolationLevel) {} + + private static final class Repositories { + private final AccountConnectTokenIssuanceRepository issuanceRepository = + mock(AccountConnectTokenIssuanceRepository.class); + private final AccountRepository accountRepository = mock(AccountRepository.class); + private final AccountJoinOperationRepository joinOperationRepository = + mock(AccountJoinOperationRepository.class); + private final AccountMembershipAuthorityEventProducer membershipProducer = + mock(AccountMembershipAuthorityEventProducer.class); + private final AccountAuthorityGenerationRepository generationRepository = + mock(AccountAuthorityGenerationRepository.class); + private final DataSource dataSource = mock(DataSource.class); + + private AccountConnectTokenAuthorityCaptureService service() { + return new AccountConnectTokenAuthorityCaptureService( + issuanceRepository, + accountRepository, + joinOperationRepository, + membershipProducer, + generationRepository, + dataSource); + } + + private void verifyNoReads() { + verifyNoInteractions( + issuanceRepository, + accountRepository, + joinOperationRepository, + membershipProducer, + generationRepository, + dataSource); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountFreshCaptureSourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountFreshCaptureSourceReaderTest.java new file mode 100644 index 0000000000..285a629ddd --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountFreshCaptureSourceReaderTest.java @@ -0,0 +1,108 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountFreshCaptureSources; +import net.firedevops.firemud.accountservice.dto.AccountMembershipCaptureSources; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourceRepository.FreshEmptySource; +import net.firedevops.firemud.accountservice.service.AccountFreshCaptureSourceReader; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountFreshCaptureSourceReaderTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("a50fdfca-f085-4a65-9ea1-ec99cda0f645"); + private static final UUID TENANT_UUID = UUID.fromString("8e35f45a-fd75-496e-aa40-a2a4da03ee4c"); + + private final AccountMembershipAuthorityEventProducer membershipProducer = + mock(AccountMembershipAuthorityEventProducer.class); + private final AccountGlobalRoleSourceRepository globalRoleSourceRepository = + mock(AccountGlobalRoleSourceRepository.class); + private final AccountFreshCaptureSourceReader reader = + new AccountFreshCaptureSourceReader(membershipProducer, globalRoleSourceRepository); + + @BeforeEach + void markCallerOwnedWritableTransactionActive() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void readsMembershipVectorBeforeFreshRoleSourceInTheCallerTransaction() { + AccountMembershipCaptureSources membershipSources = mock(AccountMembershipCaptureSources.class); + when(membershipSources.requestedAccountUuid()).thenReturn(ACCOUNT_UUID); + when(membershipSources.requestedTenantUuid()).thenReturn(TENANT_UUID); + FreshEmptySource roleSource = freshSource(ACCOUNT_UUID); + when(membershipProducer.readExistingRuntimeMembershipCaptureSources(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn(membershipSources); + when(globalRoleSourceRepository.readFreshEmptySourceForUpdate(ACCOUNT_UUID)) + .thenReturn(roleSource); + + AccountFreshCaptureSources result = reader.readExisting(ACCOUNT_UUID, TENANT_UUID); + + assertThat(result.membershipSources()).isSameAs(membershipSources); + assertThat(result.freshGlobalRoleSource()).isSameAs(roleSource); + InOrder sourceOrder = inOrder(membershipProducer, globalRoleSourceRepository); + sourceOrder + .verify(membershipProducer) + .readExistingRuntimeMembershipCaptureSources(ACCOUNT_UUID, TENANT_UUID); + sourceOrder.verify(globalRoleSourceRepository).readFreshEmptySourceForUpdate(ACCOUNT_UUID); + } + + @Test + void rejectsAbsentRoleSourceWithoutReturningPartialMembershipSources() { + AccountMembershipCaptureSources membershipSources = mock(AccountMembershipCaptureSources.class); + when(membershipProducer.readExistingRuntimeMembershipCaptureSources(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn(membershipSources); + doThrow(new IllegalStateException("Fresh Account global-role source is missing")) + .when(globalRoleSourceRepository) + .readFreshEmptySourceForUpdate(ACCOUNT_UUID); + + assertThatThrownBy(() -> reader.readExisting(ACCOUNT_UUID, TENANT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("global-role source is missing"); + inOrder(membershipProducer, globalRoleSourceRepository) + .verify(globalRoleSourceRepository) + .readFreshEmptySourceForUpdate(ACCOUNT_UUID); + } + + @Test + void rejectsCallsOutsideWritableOwnerTransactionsBeforeReadingEitherSource() { + TransactionSynchronizationManager.setActualTransactionActive(false); + + assertThatThrownBy(() -> reader.readExisting(ACCOUNT_UUID, TENANT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable caller-owned"); + verifyNoInteractions(membershipProducer, globalRoleSourceRepository); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> reader.readExisting(ACCOUNT_UUID, TENANT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable caller-owned"); + verifyNoInteractions(membershipProducer, globalRoleSourceRepository); + } + + private static FreshEmptySource freshSource(UUID accountUuid) { + return new FreshEmptySource( + accountUuid, 73L, 73L, AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, List.of(), 1L); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java index c7144da440..578c29d67a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java @@ -20,7 +20,8 @@ public record PublishedReleaseBundleDto( String scriptPatchVersion, LocalDateTime publishedAt, UUID canonicalTenantId, - UUID canonicalVersionId) { + UUID canonicalVersionId, + String publishedReleaseBundleRef) { public PublishedReleaseBundleDto { requiredManifestAssetKeys = List.copyOf(requiredManifestAssetKeys == null ? List.of() : requiredManifestAssetKeys); @@ -43,7 +44,8 @@ public PublishedReleaseBundleDto( String scriptPatchVersion, LocalDateTime publishedAt, UUID canonicalTenantId, - UUID canonicalVersionId) { + UUID canonicalVersionId, + String publishedReleaseBundleRef) { this( id, tenantId, @@ -60,6 +62,7 @@ public PublishedReleaseBundleDto( scriptPatchVersion, publishedAt, canonicalTenantId, - canonicalVersionId); + canonicalVersionId, + publishedReleaseBundleRef); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java index a65dc230f8..110d6cea4e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java @@ -7,6 +7,7 @@ @Data public class PublishedReleaseBundle { private Long id; + private String publishedReleaseBundleRef; private String tenantId; private Long versionId; private UUID canonicalTenantId; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index 8af3da647d..68cf5a2407 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java @@ -24,6 +24,8 @@ public class PublishedReleaseBundleRepository { DSL.table(DSL.name("version")).as("source_version"); private static final Table GAME_SOURCE = DSL.table(DSL.name("game")).as("source_game"); private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + DSL.field(DSL.name("published_release_bundle_ref"), String.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); private static final Field CANONICAL_TENANT_ID = @@ -116,9 +118,11 @@ private PublishedReleaseBundle insertNewBundle( DSLContext tx, PublishedReleaseBundle bundle, LocalDateTime publishedAt) { CanonicalSource source = findExactCanonicalSource(tx, bundle); rejectCallerIdentitySubstitution(bundle, source); + String publishedReleaseBundleRef = UUID.randomUUID().toString(); Long generatedId = tx.insertInto(TABLE_REF) + .set(PUBLISHED_RELEASE_BUNDLE_REF, publishedReleaseBundleRef) .set(TENANT_ID, bundle.getTenantId()) .set(VERSION_ID, bundle.getVersionId()) .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) @@ -141,7 +145,7 @@ private PublishedReleaseBundle insertNewBundle( } PublishedReleaseBundle persisted = findById(tx, generatedId).orElseThrow(); - verifyPersistedSource(persisted, bundle, source); + verifyPersistedSource(persisted, bundle, source, publishedReleaseBundleRef); return persisted; } @@ -198,13 +202,17 @@ private void rejectCallerIdentitySubstitution( } private void verifyPersistedSource( - PublishedReleaseBundle persisted, PublishedReleaseBundle requested, CanonicalSource source) { + PublishedReleaseBundle persisted, + PublishedReleaseBundle requested, + CanonicalSource source, + String publishedReleaseBundleRef) { if (!Objects.equals(persisted.getTenantId(), requested.getTenantId()) || !Objects.equals(persisted.getVersionId(), requested.getVersionId()) || !Objects.equals(persisted.getCanonicalTenantId(), source.canonicalTenantId()) - || !Objects.equals(persisted.getCanonicalVersionId(), source.canonicalVersionId())) { + || !Objects.equals(persisted.getCanonicalVersionId(), source.canonicalVersionId()) + || !Objects.equals(persisted.getPublishedReleaseBundleRef(), publishedReleaseBundleRef)) { throw new IllegalStateException( - "Published release bundle readback does not match its exact Version source"); + "Published release bundle readback does not match its source identity and owner reference"); } } @@ -218,6 +226,7 @@ private PublishedReleaseBundle toEntity(Record record) { } PublishedReleaseBundle bundle = new PublishedReleaseBundle(); bundle.setId(record.get(ID)); + bundle.setPublishedReleaseBundleRef(record.get(PUBLISHED_RELEASE_BUNDLE_REF)); bundle.setTenantId(record.get(TENANT_ID)); bundle.setVersionId(record.get(VERSION_ID)); bundle.setCanonicalTenantId(record.get(CANONICAL_TENANT_ID)); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 389978b2e5..8ebdc647c2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -760,6 +760,9 @@ public void getPublishedReleaseBundle( .setCanonicalTenantId(bundle.canonicalTenantId().toString()) .setCanonicalVersionId(bundle.canonicalVersionId().toString()); } + if (bundle.publishedReleaseBundleRef() != null) { + bundleBuilder.setPublishedReleaseBundleRef(bundle.publishedReleaseBundleRef()); + } builder.setBundle(bundleBuilder.build()); } catch (AdminAuthorizationException ex) { builder.setError( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index 4e69876f13..b4d491e439 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -181,6 +181,11 @@ private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( "unsupported published release bundle attestation schema " + bundle.attestationSchemaVersion()); } + if (bundle.publishedReleaseBundleRef() == null + || bundle.publishedReleaseBundleRef().isBlank()) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "published release bundle has no persisted opaque reference"); + } String descriptorId = "ld-" + UUID.randomUUID(); AuthoredWorldLaunchDescriptorEvidence evidence = @@ -194,7 +199,7 @@ private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( bundle.generationConfigRevision(), version.versionStateEpoch(), bundle.id(), - releaseBundleRef(request.canonicalTenantId().toString(), bundle.id(), versionId), + bundle.publishedReleaseBundleRef(), remapSetId != null, remapSetId); LaunchDescriptor descriptor = new LaunchDescriptor(); @@ -581,10 +586,6 @@ private PublishedReleaseBundleDto requirePublishedReleaseBundle(String tenantId, } } - private String releaseBundleRef(String canonicalTenantId, long bundleId, long versionId) { - return "release-bundle:" + canonicalTenantId + ":" + versionId + ":" + bundleId; - } - private static String normalizeBlank(String value) { return value == null || value.isBlank() ? null : value; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index e290d3e592..96e884a1c4 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -138,7 +138,8 @@ private PublishedReleaseBundleDto toDto(PublishedReleaseBundle entity) { entity.getScriptPatchVersion(), entity.getPublishedAt(), entity.getCanonicalTenantId(), - entity.getCanonicalVersionId()); + entity.getCanonicalVersionId(), + entity.getPublishedReleaseBundleRef()); } private boolean isCanonicalNonNilUuid(UUID value) { diff --git a/services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql b/services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql new file mode 100644 index 0000000000..d1a0bc0b5b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql @@ -0,0 +1,56 @@ +ALTER TABLE published_release_bundle + ADD COLUMN published_release_bundle_ref VARCHAR(128); + +ALTER TABLE published_release_bundle + ADD CONSTRAINT ck_published_release_bundle_ref_nonblank + CHECK (published_release_bundle_ref IS NULL OR BTRIM(published_release_bundle_ref) <> ''); + +CREATE UNIQUE INDEX uq_published_release_bundle_opaque_ref + ON published_release_bundle(published_release_bundle_ref) + WHERE published_release_bundle_ref IS NOT NULL; + +-- Retained bundles intentionally remain NULL. New owner inserts must supply an identity, and +-- once assigned the opaque reference cannot be changed independently of the bundle. +-- [jooq ignore start] +CREATE FUNCTION enforce_published_release_bundle_reference() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.published_release_bundle_ref IS NULL + OR BTRIM(NEW.published_release_bundle_ref) = '' THEN + RAISE EXCEPTION 'new published release bundles require an opaque reference'; + END IF; + ELSE + IF NEW.published_release_bundle_ref IS DISTINCT FROM OLD.published_release_bundle_ref THEN + RAISE EXCEPTION 'published release bundle reference is immutable'; + END IF; + IF OLD.published_release_bundle_ref IS NOT NULL AND ( + NEW.id IS DISTINCT FROM OLD.id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id + OR NEW.version_number IS DISTINCT FROM OLD.version_number + OR NEW.attestation_schema_version IS DISTINCT FROM OLD.attestation_schema_version + OR NEW.publish_workflow_id IS DISTINCT FROM OLD.publish_workflow_id + OR NEW.manifest_hash IS DISTINCT FROM OLD.manifest_hash + OR NEW.generation_config_revision IS DISTINCT FROM OLD.generation_config_revision + OR NEW.required_manifest_asset_keys_json + IS DISTINCT FROM OLD.required_manifest_asset_keys_json + OR NEW.participant_digests_json IS DISTINCT FROM OLD.participant_digests_json + OR NEW.command_definitions_json IS DISTINCT FROM OLD.command_definitions_json + OR NEW.script_only IS DISTINCT FROM OLD.script_only + OR NEW.script_patch_version IS DISTINCT FROM OLD.script_patch_version + OR NEW.published_at IS DISTINCT FROM OLD.published_at) THEN + RAISE EXCEPTION 'published release bundle attestation is immutable'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_published_release_bundle_reference + BEFORE INSERT OR UPDATE ON published_release_bundle + FOR EACH ROW + EXECUTE FUNCTION enforce_published_release_bundle_reference(); +-- [jooq ignore end] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 85fa1d8ad8..2745d88a1f 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -40,11 +40,14 @@ class PublishedReleaseCanonicalIdentityIntegrationTest { private static final MigrationVersion V35 = MigrationVersion.fromVersion("35"); private static final MigrationVersion V35_1 = MigrationVersion.fromVersion("35.1"); private static final MigrationVersion V35_2 = MigrationVersion.fromVersion("35.2"); + private static final MigrationVersion V36 = MigrationVersion.fromVersion("36"); private static final Table VERSION = DSL.table(DSL.name("version")); private static final Table RELEASE_BUNDLE = DSL.table(DSL.name("published_release_bundle")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + DSL.field(DSL.name("published_release_bundle_ref"), String.class); private static final Field CANONICAL_TENANT_ID = DSL.field(DSL.name("canonical_tenant_id"), UUID.class); private static final Field CANONICAL_VERSION_ID = @@ -81,6 +84,29 @@ void migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped() { assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); assertThat(row.get(CANONICAL_VERSION_ID)).isNull(); }); + migrate(fixture.dataSource(), fixture.schema(), V36); + + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .dsl() + .select(PUBLISHED_RELEASE_BUNDLE_REF) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne(PUBLISHED_RELEASE_BUNDLE_REF)) + .isNull(); + PublishedReleaseBundle retained = + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), retainedVersionId) + .orElseThrow(); + assertThat(retained.getCanonicalTenantId()).isNull(); + assertThat(retained.getCanonicalVersionId()).isNull(); + assertThat(retained.getPublishedReleaseBundleRef()).isNull(); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(retained)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); assertThatThrownBy( () -> fixture @@ -93,7 +119,7 @@ void migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped() { @Test void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTransaction() { - Fixture fixture = fixture(V35_2); + Fixture fixture = fixture(V36); Game owner = saveGame(fixture, "fresh-release-source"); Game other = saveGame(fixture, "other-release-source"); Version version = saveVersion(fixture, owner); @@ -102,6 +128,7 @@ void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTran fixture.releaseBundleRepository().save(bundle(owner.getTenantId(), version.getId())); assertThat(saved.getCanonicalTenantId()).isEqualTo(owner.getCanonicalTenantId()); assertThat(saved.getCanonicalVersionId()).isEqualTo(version.getCanonicalVersionId()); + assertThat(saved.getPublishedReleaseBundleRef()).isNotBlank(); assertThat( fixture .releaseBundleRepository() @@ -145,7 +172,7 @@ void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTran @Test void repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction() { - Fixture fixture = fixture(V35_2); + Fixture fixture = fixture(V36); Game owner = saveGame(fixture, "outer-release-rollback-owner"); Version version = saveVersion(fixture, owner); String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); @@ -165,6 +192,7 @@ void repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction() { .isEqualTo(owner.getCanonicalTenantId()); assertThat(saved.getCanonicalVersionId()) .isEqualTo(version.getCanonicalVersionId()); + assertThat(saved.getPublishedReleaseBundleRef()).isNotBlank(); Version publishingVersion = fixture .versionRepository() @@ -214,7 +242,7 @@ void repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction() { @Test void deniesWrongTenantNilAndSubstitutedCallerOrDatabaseIdentityWithoutGrowingBundles() { - Fixture fixture = fixture(V35_2); + Fixture fixture = fixture(V36); Game owner = saveGame(fixture, "denied-release-owner"); Game other = saveGame(fixture, "denied-release-other"); Version version = saveVersion(fixture, owner); @@ -279,9 +307,42 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD Long retainedVersionId = insertRetainedVersion(fixture.dsl(), game.getTenantId()); Long retainedBundleId = insertRetainedBundle(fixture.dsl(), game.getTenantId(), retainedVersionId); + Map retainedTupleBeforeIdentityMigration = + retainedTuple(fixture.dsl(), retainedBundleId); + String retainedXminBeforeIdentityMigration = bundleXmin(fixture.dsl(), retainedBundleId); migrate(fixture.dataSource(), fixture.schema(), V35_1); migrate(fixture.dataSource(), fixture.schema(), V35_2); + Map retainedTupleBeforeV36 = retainedTuple(fixture.dsl(), retainedBundleId); + String retainedXminBeforeV36 = bundleXmin(fixture.dsl(), retainedBundleId); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)) + .isEqualTo(retainedTupleBeforeIdentityMigration); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)) + .isEqualTo(retainedXminBeforeIdentityMigration); + assertThat( + fixture + .dsl() + .select(CANONICAL_TENANT_ID, CANONICAL_VERSION_ID) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); + assertThat(row.get(CANONICAL_VERSION_ID)).isNull(); + }); + migrate(fixture.dataSource(), fixture.schema(), V36); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBeforeV36); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBeforeV36); + assertThat( + fixture + .dsl() + .select(PUBLISHED_RELEASE_BUNDLE_REF) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne(PUBLISHED_RELEASE_BUNDLE_REF)) + .isNull(); + Version mappedVersion = saveVersion(fixture, game); PublishedReleaseBundle mapped = fixture.releaseBundleRepository().save(bundle(game.getTenantId(), mappedVersion.getId())); @@ -354,6 +415,16 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(PUBLISHED_RELEASE_BUNDLE_REF, "attempted-retained-release-reference") + .where(ID.eq(retainedBundleId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); assertThatThrownBy( () -> fixture @@ -373,6 +444,7 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD .orElseThrow(); assertThat(retained.getCanonicalTenantId()).isNull(); assertThat(retained.getCanonicalVersionId()).isNull(); + assertThat(retained.getPublishedReleaseBundleRef()).isNull(); assertThatThrownBy(() -> fixture.releaseBundleRepository().save(retained)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Published release bundle is immutable"); @@ -399,6 +471,7 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD .orElseThrow(); assertThat(retainedAfterAttempts.getCanonicalTenantId()).isNull(); assertThat(retainedAfterAttempts.getCanonicalVersionId()).isNull(); + assertThat(retainedAfterAttempts.getPublishedReleaseBundleRef()).isNull(); assertThat(retainedAfterAttempts.getManifestHash()).isEqualTo("sha256:retained"); assertThatThrownBy( @@ -536,13 +609,14 @@ private void insertRawBundle( + "attestation_schema_version, publish_workflow_id, manifest_hash, " + "generation_config_revision, required_manifest_asset_keys_json, " + "participant_digests_json, command_definitions_json, script_only, " - + "canonical_tenant_id, canonical_version_id) " + + "canonical_tenant_id, canonical_version_id, published_release_bundle_ref) " + "VALUES (?, ?, 1, 'v1', 'direct-write-test', 'sha256:raw', 'generation-1', " - + "'[]', '[]', '[]', FALSE, ?, ?)", + + "'[]', '[]', '[]', FALSE, ?, ?, ?)", tenantId, versionId, canonicalTenantId, - canonicalVersionId); + canonicalVersionId, + UUID.randomUUID().toString()); } private long bundleCount(DSLContext dsl) { @@ -566,6 +640,7 @@ private Map releaseBundleTuple(DSLContext dsl, Long bundleId) { return Objects.requireNonNull( dsl.fetchOne( "SELECT id, tenant_id, version_id, canonical_tenant_id, canonical_version_id, " + + "published_release_bundle_ref, " + "version_number, attestation_schema_version, publish_workflow_id, " + "manifest_hash, generation_config_revision, " + "required_manifest_asset_keys_json, participant_digests_json, " diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 5ce645d2ae..11e5f795b8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -116,6 +116,15 @@ void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionC ResolvedLaunchDescriptorDto original = launchDescriptorService.resolveLaunchDescriptor(fixture.request()); assertThat(original.canonicalTenantId()).isEqualTo(fixture.canonicalTenantId().toString()); + assertThat(original.publishedReleaseBundleRef()) + .isEqualTo(fixture.bundle().getPublishedReleaseBundleRef()); + assertThat( + publishedReleaseBundleRepository + .findByTenantIdAndVersionId( + fixture.privateSourceTenantKey(), fixture.version().getId()) + .orElseThrow() + .getPublishedReleaseBundleRef()) + .isEqualTo(original.publishedReleaseBundleRef()); assertThat(original.authoredWorldBinding()).isNotNull(); assertThat(original.authoredWorldBinding().authoredWorldSourceOperationId()) .isEqualTo(fixture.source().operationId()); @@ -152,6 +161,8 @@ void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionC .isEqualTo(original.authoredWorldBinding().requestDigest()); assertThat(persisted.getResultDigest()) .isEqualTo(original.authoredWorldBinding().resultDigest()); + assertThat(persisted.getPublishedReleaseBundleRef()) + .isEqualTo(original.publishedReleaseBundleRef()); assertThat( dsl.fetchCount( LAUNCH_DESCRIPTOR, @@ -433,7 +444,7 @@ void rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim() { } @Test - void v35MigrationPreservesRetainedUnboundDescriptorAndCanonicalResolveDeniesIt() { + void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill() { String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = isolatedDataSource(schema); migrate(dataSource, schema, MigrationVersion.fromVersion("34")); @@ -495,6 +506,9 @@ void v35MigrationPreservesRetainedUnboundDescriptorAndCanonicalResolveDeniesIt() "sha256:" + "d".repeat(64), "gen-rev:" + suffix) .fetchOne(0, Long.class); + if (bundleId == null) { + throw new IllegalStateException("Retained V34 release bundle insertion returned no identity"); + } String requestId = "retained-cp-" + suffix; String legacyDescriptorId = "ld-retained-" + suffix; isolatedDsl.execute( @@ -514,9 +528,27 @@ void v35MigrationPreservesRetainedUnboundDescriptorAndCanonicalResolveDeniesIt() "legacy-release-ref-" + suffix); Map retainedV34Snapshot = legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId); + Map retainedBundleSnapshot = + retainedReleaseBundleSnapshot(isolatedDsl, bundleId); migrate(dataSource, schema, null); LaunchDescriptorRepository launchRepository = new LaunchDescriptorRepository(isolatedDsl); + var retainedBundleReference = + isolatedDsl.fetchOne( + "SELECT published_release_bundle_ref FROM published_release_bundle WHERE id = ?", + bundleId); + if (retainedBundleReference == null) { + throw new IllegalStateException("Retained V34 release bundle reference row is missing"); + } + assertThat(retainedBundleReference.get("published_release_bundle_ref", String.class)).isNull(); + assertThat(retainedReleaseBundleSnapshot(isolatedDsl, bundleId)) + .isEqualTo(retainedBundleSnapshot); + assertThat( + new PublishedReleaseBundleRepository(isolatedDsl) + .findByTenantIdAndVersionId(privateTenantKey, versionId) + .orElseThrow() + .getPublishedReleaseBundleRef()) + .isNull(); assertThat(legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId)) .isEqualTo(retainedV34Snapshot); LaunchDescriptor before = @@ -875,6 +907,21 @@ var record = return record.intoMap(); } + private Map retainedReleaseBundleSnapshot(DSLContext isolatedDsl, long bundleId) { + var record = + isolatedDsl.fetchOne( + "SELECT id, tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, generation_config_revision, " + + "required_manifest_asset_keys_json, participant_digests_json, " + + "command_definitions_json, script_only, script_patch_version, published_at " + + "FROM published_release_bundle WHERE id = ?", + bundleId); + if (record == null) { + throw new IllegalStateException("Retained V34 release bundle fixture is missing"); + } + return record.intoMap(); + } + private String privateTenantKey() { return "src-" + UUID.randomUUID().toString().replace("-", ""); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 50c9ecee7e..29ba77152d 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -34,6 +34,7 @@ import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -84,6 +85,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private VersionAssetArtifactRepository versionAssetArtifactRepository; @Autowired private VersionRepository versionRepository; @Autowired private VersionTemplateRemapSetRepository templateRemapSetRepository; + @Autowired private DSLContext dsl; @MockitoBean private AssetExportService assetExportService; @MockitoBean private PublishGateService publishGateService; @MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService; @@ -271,6 +273,52 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.PUBLISHED); assertThat(bundle.getPublishWorkflowId()).isEqualTo(publishWorkflowId); assertThat(bundle.getManifestHash()).isEqualTo("transaction-proof-manifest"); + assertThat(bundle.getPublishedReleaseBundleRef()).isNotBlank(); + assertThat(bundle.getPublishedReleaseBundleRef()) + .isNotEqualTo( + "release-bundle:" + tenantId + ":" + publishedVersion.id() + ":" + bundle.getId()); + PublishedReleaseBundle durableBundle = + publishedReleaseBundleRepository + .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .orElseThrow(); + assertThat(durableBundle.getPublishedReleaseBundleRef()) + .isEqualTo(bundle.getPublishedReleaseBundleRef()); + PublishedReleaseBundle changedReference = + publishedReleaseBundleRepository + .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .orElseThrow(); + changedReference.setPublishedReleaseBundleRef("replacement-opaque-release-reference"); + assertThatThrownBy(() -> publishedReleaseBundleRepository.save(changedReference)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + PublishedReleaseBundle changedTuple = + publishedReleaseBundleRepository + .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .orElseThrow(); + changedTuple.setManifestHash("changed-manifest"); + assertThatThrownBy(() -> publishedReleaseBundleRepository.save(changedTuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE published_release_bundle " + + "SET published_release_bundle_ref = ? WHERE id = ?", + "replacement-opaque-release-reference", + durableBundle.getId())) + .hasStackTraceContaining("published release bundle attestation is immutable"); + assertThat( + publishedReleaseBundleRepository + .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .orElseThrow() + .getPublishedReleaseBundleRef()) + .isEqualTo(bundle.getPublishedReleaseBundleRef()); + assertThat( + publishedReleaseBundleRepository + .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .orElseThrow() + .getManifestHash()) + .isEqualTo("transaction-proof-manifest"); assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.PUBLISHED); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java index 11620c5387..3d9459c62a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java @@ -31,10 +31,17 @@ void newBundleUsesExactPersistedVersionAndGameIdentityAndReadsItBack() throws Ex "tenant-key", "NEW_GAME_ROW"); - PublishedReleaseBundle saved = fixture.repository().save(bundle("tenant-key", 17L)); + PublishedReleaseBundle requested = bundle("tenant-key", 17L); + requested.setPublishedReleaseBundleRef("caller-supplied-release-reference"); + PublishedReleaseBundle saved = fixture.repository().save(requested); assertThat(saved.getId()).isNotNull(); assertThat(saved.getCanonicalTenantId()).isEqualTo(TENANT_UUID); assertThat(saved.getCanonicalVersionId()).isEqualTo(VERSION_UUID); + assertThat(saved.getPublishedReleaseBundleRef()) + .isNotBlank() + .isNotEqualTo("caller-supplied-release-reference"); + assertThat(requested.getPublishedReleaseBundleRef()) + .isEqualTo("caller-supplied-release-reference"); assertThat(fixture.repository().findByTenantIdAndVersionId("tenant-key", 17L).orElseThrow()) .usingRecursiveComparison() .isEqualTo(saved); @@ -131,6 +138,7 @@ private static Fixture fixture() throws Exception { dsl.execute( "CREATE TABLE published_release_bundle (" + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " + + "published_release_bundle_ref VARCHAR(128), " + "tenant_id VARCHAR(36) NOT NULL, version_id BIGINT NOT NULL, " + "canonical_tenant_id UUID, canonical_version_id UUID, version_number INT NOT NULL, " + "attestation_schema_version VARCHAR(16) NOT NULL, " diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index ac9275bd14..5aa18c1ccd 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -98,6 +98,7 @@ void launchDescriptorRejectsJwtOnlyInternalServiceIdentity() { null, java.time.LocalDateTime.parse("2026-04-14T12:00:00"), null, + null, null)); GameDesignGrpcService service = new GameDesignGrpcService( @@ -157,6 +158,7 @@ public void onCompleted() {} assertNotNull(bundleRef.get()); assertEquals("", bundleRef.get().getError().getCode()); assertEquals(11L, bundleRef.get().getBundle().getId()); + assertEquals("", bundleRef.get().getBundle().getPublishedReleaseBundleRef()); assertNotNull(descriptorRef.get()); assertEquals("PERMISSION_DENIED", descriptorRef.get().getError().getCode()); Mockito.verifyNoInteractions(launchDescriptorService); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index c0553dea2b..c324059bed 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -193,7 +193,8 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { null, LocalDateTime.parse("2026-04-14T12:00:00"), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), - UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"))); + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference")); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { @@ -207,6 +208,9 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { assertEquals("", ref.get().getError().getCode()); assertEquals(11L, ref.get().getBundle().getId()); + assertEquals( + "opaque-owner-issued-release-reference", + ref.get().getBundle().getPublishedReleaseBundleRef()); assertEquals("abc123", ref.get().getBundle().getManifestHash()); assertEquals("genrev-1", ref.get().getBundle().getGenerationConfigRevision()); assertEquals(2, ref.get().getBundle().getRequiredManifestAssetKeysCount()); @@ -241,6 +245,7 @@ void getPublishedReleaseBundleRejectsPartialCanonicalIdentity() { null, LocalDateTime.parse("2026-04-14T12:00:00"), UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + null, null)); AtomicReference ref = new AtomicReference<>(); @@ -276,7 +281,8 @@ void getPublishedReleaseBundleRejectsNilCanonicalIdentity() { null, LocalDateTime.parse("2026-04-14T12:00:00"), UUID.fromString("00000000-0000-0000-0000-000000000000"), - UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"))); + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + null)); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { @@ -1142,8 +1148,9 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { false, null, LocalDateTime.parse("2026-04-14T12:00:00"), - null, - null)); + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference")); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index 64a014f89a..3c446e7c56 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.clearInvocations; @@ -47,12 +48,15 @@ class LaunchDescriptorServiceImplTest { private static final String NAMESPACE = "test"; private static final UUID CANONICAL_TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"); private static final UUID SOURCE_OPERATION_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); private static final UUID SOURCE_REGISTRATION_ID = UUID.fromString("32345678-1234-4234-8234-123456789abc"); private static final String WORLD_SLUG = "silver-march"; private static final String PRIVATE_SOURCE_TENANT_KEY = "game-owner-key-901"; + private static final String PUBLISHED_RELEASE_BUNDLE_REF = "opaque-release-reference-from-owner"; @Mock private GameTemplateRepository gameTemplateRepository; @Mock private LaunchDescriptorRepository launchDescriptorRepository; @@ -101,8 +105,7 @@ void resolveLaunchDescriptorPersistsCanonicalBindingAndResolvedRelease() { assertEquals("genrev-1", resolved.generationConfigRevision()); assertEquals(17L, resolved.versionStateEpoch()); assertEquals(11L, resolved.releaseBundleId()); - assertEquals( - "release-bundle:" + CANONICAL_TENANT_ID + ":7:11", resolved.publishedReleaseBundleRef()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); assertNotNull(resolved.authoredWorldBinding()); assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); assertEquals( @@ -484,6 +487,48 @@ void resolveLaunchDescriptorReportsMissingReleaseBundleDeterministically() { thrown.getMessage()); } + @Test + void missingOpaqueBundleReferenceDeniesCreationAndExactRetryWithoutSynthesizing() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-missing-reference", 9L); + stubTemplate(request, 7L, null); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + stubSource(request, source); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(releaseBundle(7L, 11L, "v1", null)); + AtomicReference stored = new AtomicReference<>(); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenAnswer(invocation -> Optional.ofNullable(stored.get())); + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + stored.set(descriptor); + return descriptor; + }); + + IllegalArgumentException first = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + IllegalArgumentException retry = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "RELEASE_BUNDLE_NOT_FOUND: published release bundle has no persisted opaque reference", + first.getMessage()); + assertEquals(first.getMessage(), retry.getMessage()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, stored.get().getOutcomeStatus()); + assertEquals("RELEASE_BUNDLE_NOT_FOUND", stored.get().getFailureCode()); + assertNull(stored.get().getPublishedReleaseBundleRef()); + verify(publishedReleaseBundleService, times(1)) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + @Test void resolveLaunchDescriptorAcceptsEqualLargeReleaseVersionIdsByValue() { AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-large-version", 9L); @@ -510,8 +555,7 @@ void resolveLaunchDescriptorAcceptsEqualLargeReleaseVersionIdsByValue() { assertEquals(11L, resolved.releaseBundleId()); assertNotNull(resolved.authoredWorldBinding()); assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); - assertEquals( - "release-bundle:" + CANONICAL_TENANT_ID + ":1000:11", resolved.publishedReleaseBundleRef()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); } @Test @@ -644,6 +688,11 @@ private void stubBundle(long versionId, long bundleId, String schemaVersion) { private PublishedReleaseBundleDto releaseBundle( Long versionId, long bundleId, String schemaVersion) { + return releaseBundle(versionId, bundleId, schemaVersion, PUBLISHED_RELEASE_BUNDLE_REF); + } + + private PublishedReleaseBundleDto releaseBundle( + Long versionId, long bundleId, String schemaVersion, String publishedReleaseBundleRef) { return new PublishedReleaseBundleDto( bundleId, PRIVATE_SOURCE_TENANT_KEY, @@ -658,8 +707,9 @@ private PublishedReleaseBundleDto releaseBundle( false, null, LocalDateTime.now(), - null, - null); + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + publishedReleaseBundleRef); } @SuppressWarnings("removal") @@ -680,7 +730,7 @@ private LaunchDescriptor descriptorFor( "genrev-1", 17L, bundleId, - "release-bundle:" + CANONICAL_TENANT_ID + ":" + versionId + ":" + bundleId, + PUBLISHED_RELEASE_BUNDLE_REF, false, null); AuthoredWorldSourceEvidence source = sourceEvidence(request.worldSlug()); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 7339e9fd47..47f0ae67bb 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -75,6 +75,7 @@ void createFullVersionBundlePersistsImmutableAttestation() { invocation -> { PublishedReleaseBundle entity = invocation.getArgument(0); entity.setId(11L); + entity.setPublishedReleaseBundleRef("owner-issued-reference-11"); return entity; }); @@ -97,6 +98,7 @@ void createFullVersionBundlePersistsImmutableAttestation() { assertEquals(1, dto.participantDigests().size()); assertEquals(List.of(validCommandDefinition()), dto.commandDefinitions()); assertEquals("v1", dto.attestationSchemaVersion()); + assertEquals("owner-issued-reference-11", dto.publishedReleaseBundleRef()); assertEquals(sourceIdentity().getCanonicalTenantId(), dto.canonicalTenantId()); assertEquals(sourceIdentity().getCanonicalVersionId(), dto.canonicalVersionId()); org.mockito.Mockito.verify(repository) @@ -121,6 +123,7 @@ void retainedBundleWithoutCanonicalIdentityStaysAbsent() { assertNull(dto.canonicalTenantId()); assertNull(dto.canonicalVersionId()); + assertNull(dto.publishedReleaseBundleRef()); } private Version sourceIdentity() { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java index c08cd8be10..cebbf19a8f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java @@ -8,6 +8,7 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; @@ -128,8 +129,9 @@ void repairFailsClosedWhenManifestHashDrifts() { false, null, LocalDateTime.now(), - null, - null)); + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference")); when(assetExportService.exportAssets("tenant-1", 8)) .thenReturn(new ExportedAssetManifest("different", List.of("manifest.json"))); @@ -172,8 +174,9 @@ void repairFailsClosedWhenAttestedAssetKeysDrift() { false, null, LocalDateTime.now(), - null, - null)); + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference")); when(assetExportService.exportAssets("tenant-1", 8)) .thenReturn(new ExportedAssetManifest("attested", List.of("manifest.json"))); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 8788633606..5b00e7df3f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -14,6 +14,7 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; @@ -205,8 +206,9 @@ void publishFullVersionUsesTenantScopedVersionSequence() { false, null, LocalDateTime.now(), - null, - null)); + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference")); when(versionAssetArtifactService.markPublished( any(String.class), any(Long.class), @@ -484,8 +486,9 @@ void succeededReplayUsesStoredBundleAfterLifecycleDriftWithoutWritesOrGates() { false, null, LocalDateTime.now(), - null, - null); + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference"); VersionAssetArtifactStateDto driftedArtifact = new VersionAssetArtifactStateDto( "tenant-1", @@ -559,8 +562,9 @@ void succeededReplayRejectsMismatchedCommittedBundleIdentity() { false, null, LocalDateTime.now(), - null, - null); + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference"); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) @@ -651,8 +655,9 @@ void legacySucceededAttemptReplaysWithoutBackfillOrMutableReads() { false, null, LocalDateTime.now(), - null, - null); + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference"); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.of(bundle)); @@ -773,8 +778,9 @@ void pendingAttemptStillReconcilesCompleteReadbackThroughCurrentGates() { false, null, LocalDateTime.now(), - null, - null); + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference"); VersionAssetArtifactStateDto artifact = new VersionAssetArtifactStateDto( "tenant-1", @@ -999,8 +1005,9 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { false, null, LocalDateTime.now(), - null, - null); + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference"); when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) .thenReturn(Optional.of(attempt)); when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java index fff00f4b4a..d549ce9eb9 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImplTest.java @@ -19,6 +19,7 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; @@ -1804,8 +1805,9 @@ private PublishedReleaseBundleDto publishedReleaseBundle( false, null, LocalDateTime.parse("2026-04-26T10:00:00"), - null, - null); + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + "opaque-owner-issued-release-reference"); } private PublishedPluginVersion uploadedPluginVersion( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java new file mode 100644 index 0000000000..7ffea40a81 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; + +/** Exact immutable source/catalog/descriptor evidence consumed by one launch preparation. */ +public record CanonicalLaunchPreparationSnapshot( + UUID operationId, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalogSnapshot, + IntakeReceipt sourceIntakeReceipt, + AuthoredWorldLaunchDescriptorEvidence launchDescriptorEvidence, + String requestDigest, + String receiptDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + public CanonicalLaunchPreparationSnapshot { + requireNonNil(operationId, "operationId"); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(launchDescriptorEvidence, "launchDescriptorEvidence"); + requireDigest(requestDigest, "requestDigest"); + requireDigest(receiptDigest, "receiptDigest"); + requireConsumedEvidence( + request, catalogSnapshot, sourceIntakeReceipt, launchDescriptorEvidence); + } + + /** Revalidates the complete closed shared descriptor and all local identity joins. */ + public void requireValid() { + requireConsumedEvidence( + request, catalogSnapshot, sourceIntakeReceipt, launchDescriptorEvidence); + launchDescriptorEvidence.requireValid(); + } + + private static void requireConsumedEvidence( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !source.equals(catalog.sourceIntakeReceipt()) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !descriptor.request().equals(request.descriptorRequest(catalog, source.source()))) { + throw new IllegalArgumentException( + "Launch preparation evidence does not match its exact request, catalog, and source"); + } + descriptor.requireValid(); + } + + 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 requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java new file mode 100644 index 0000000000..1b9b7cdded --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java @@ -0,0 +1,130 @@ +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.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.springframework.lang.Nullable; + +/** Immutable input for source-qualified Game Design launch preparation; it grants no authority. */ +public record CreateCanonicalLaunchPreparationRequest( + String controlPlaneRequestId, + UUID actingAccountUuid, + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID catalogCreationRequestId, + long catalogRevision, + UUID sourceIntakeOperationId, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + @Nullable String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + @Nullable Long sourceVersionId, + boolean targetVersionIdPresent, + @Nullable Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + @Nullable String requestedRuntimeFlagsJson) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CreateCanonicalLaunchPreparationRequest { + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireNonNil(actingAccountUuid, "actingAccountUuid"); + 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"); + requireNonNil(sourceIntakeOperationId, "sourceIntakeOperationId"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + if (gameTemplateId <= 0L) { + throw new IllegalArgumentException("gameTemplateId must be positive"); + } + requireOptional( + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + "requestedScriptPatchVersion"); + requireOptional(sourceVersionIdPresent, sourceVersionId, "sourceVersionId"); + if (sourceVersionIdPresent && sourceVersionId <= 0L) { + throw new IllegalArgumentException("sourceVersionId must be positive when present"); + } + requireOptional(targetVersionIdPresent, targetVersionId, "targetVersionId"); + if (targetVersionIdPresent && targetVersionId <= 0L) { + throw new IllegalArgumentException("targetVersionId must be positive when present"); + } + requireOptional( + requestedRuntimeFlagsJsonPresent, requestedRuntimeFlagsJson, "requestedRuntimeFlagsJson"); + } + + public AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest( + CanonicalRealmCatalogSnapshot catalog, AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(source, "source"); + return new AuthoredWorldLaunchDescriptorEvidence.Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + catalog.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text, name); + } + } + + private static void requireText(String value, String name, int maxUtf8Bytes) { + Objects.requireNonNull(value, name); + byte[] bytes = strictUtf8(value, name); + if (value.isBlank() || bytes.length > maxUtf8Bytes) { + throw new IllegalArgumentException(name + " must be nonblank and bounded"); + } + } + + 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", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java index 9cadb667af..0133d1004b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java @@ -202,6 +202,30 @@ public Optional read( return Optional.of(receipt); } + /** + * Resolves the one committed source for an exact canonical world selector. + * + *

This owner-local read does not infer source operation IDs or digests from retained numeric + * keys. The returned original receipt still requires exact comparison with the selected catalog + * and separately proved retained association before any launch use. + */ + @Transactional(propagation = Propagation.NEVER, readOnly = true) + public Optional readByWorldSelector( + String namespace, UUID canonicalTenantId, String worldSlug) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake read requires a committed-outcome owner read"); + } + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + Record record = findByWorldSelector(namespace, canonicalTenantId, worldSlug); + if (record == null) { + return Optional.empty(); + } + IntakeReceipt receipt = toReceipt(record); + requireTenantBinding(receipt.source()); + return Optional.of(receipt); + } + /** Reads an exact committed retry by its stable intake request without allocating owner state. */ @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) public Optional readByIntakeRequest(String namespace, UUID intakeRequestId) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java new file mode 100644 index 0000000000..52511f5c61 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java @@ -0,0 +1,656 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +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.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.JSONB; +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 persistence for source-qualified launch preparation evidence. */ +@Repository +public class GameSessionCanonicalLaunchPreparationRepository { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final String REQUEST_DOMAIN = + "game-session-canonical-launch-preparation-request/v1"; + private static final String RECEIPT_DOMAIN = + "game-session-canonical-launch-preparation-receipt/v1"; + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + + private static final Table PREPARATION = + DSL.table(DSL.name("game_session_canonical_launch_preparation")); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field ACTING_ACCOUNT_UUID = + DSL.field(DSL.name("acting_account_uuid"), UUID.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field REALM_ID = DSL.field(DSL.name("realm_id"), UUID.class); + private static final Field CATALOG_CREATION_REQUEST_ID = + DSL.field(DSL.name("catalog_creation_request_id"), UUID.class); + private static final Field CATALOG_REVISION = + DSL.field(DSL.name("catalog_revision"), Long.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_REQUEST_ID = + DSL.field(DSL.name("source_intake_request_id"), UUID.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 CATALOG_REQUEST_DIGEST = + DSL.field(DSL.name("catalog_request_digest"), String.class); + private static final Field CATALOG_RECEIPT_DIGEST = + DSL.field(DSL.name("catalog_receipt_digest"), String.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_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field DESCRIPTOR_REQUEST_DIGEST = + DSL.field(DSL.name("descriptor_request_digest"), String.class); + private static final Field DESCRIPTOR_RESULT_DIGEST = + DSL.field(DSL.name("descriptor_result_digest"), String.class); + private static final Field 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 REQUEST_EVIDENCE_JSON = + DSL.field(DSL.name("request_evidence_json"), JSONB.class); + private static final Field CATALOG_EVIDENCE_JSON = + DSL.field(DSL.name("catalog_evidence_json"), JSONB.class); + private static final Field SOURCE_INTAKE_EVIDENCE_JSON = + DSL.field(DSL.name("source_intake_evidence_json"), JSONB.class); + private static final Field LAUNCH_DESCRIPTOR_EVIDENCE_JSON = + DSL.field(DSL.name("launch_descriptor_evidence_json"), JSONB.class); + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected owner collaborators are validated before use; construction acquires no resources.") + public GameSessionCanonicalLaunchPreparationRepository( + DSLContext dsl, GameSessionCanonicalRealmCatalogRepository catalogRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + } + + /** Reads one complete committed preparation without repairing or re-resolving evidence. */ + @Transactional(propagation = Propagation.NEVER, readOnly = true) + public Optional readByControlPlaneRequestId( + String targetNamespace, String controlPlaneRequestId) { + requireSelector(targetNamespace, controlPlaneRequestId); + requireCommittedRead(); + Record row = find(targetNamespace, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(toSnapshot(row)); + } + + /** + * Persists one exact immutable source/catalog/descriptor composition under a caller-owned + * writable READ COMMITTED transaction. No network operation is performed while owner rows are + * locked. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalLaunchPreparationSnapshot persistPrepared( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot committedCatalog, + IntakeReceipt committedSource, + AuthoredWorldLaunchDescriptorEvidence descriptorEvidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(committedCatalog, "committedCatalog"); + Objects.requireNonNull(committedSource, "committedSource"); + Objects.requireNonNull(descriptorEvidence, "descriptorEvidence"); + requireWritableReadCommittedOwnerTransaction(); + requireEvidenceMatchesRequest(request, committedCatalog, committedSource, descriptorEvidence); + + Record existing = find(request.targetNamespace(), request.controlPlaneRequestId()); + if (existing != null) { + return requireExactPrepared( + existing, request, committedCatalog, committedSource, descriptorEvidence); + } + + CanonicalRealmCatalogSnapshot lockedCatalog = + catalogRepository.lockExactInitialPublicProduction( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision()); + if (!committedCatalog.equals(lockedCatalog)) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical catalog changed after launch preparation readback"); + } + IntakeReceipt lockedSource = lockExactSource(committedSource); + if (!committedSource.equals(lockedSource) + || !committedCatalog.sourceIntakeReceipt().equals(lockedSource)) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed authored-world source changed before launch preparation persistence"); + } + + UUID operationId = UUID.randomUUID(); + requireNonNil(operationId, "operationId"); + String requestDigest = + requestDigest(request, committedCatalog, committedSource, descriptorEvidence); + String receiptDigest = + receiptDigest( + operationId, + request, + committedCatalog, + committedSource, + descriptorEvidence, + requestDigest); + dsl.insertInto(PREPARATION) + .set(TARGET_NAMESPACE, request.targetNamespace()) + .set(CONTROL_PLANE_REQUEST_ID, request.controlPlaneRequestId()) + .set(OPERATION_ID, operationId) + .set(ACTING_ACCOUNT_UUID, request.actingAccountUuid()) + .set(CANONICAL_TENANT_ID, request.canonicalTenantId()) + .set(REALM_ID, request.realmId()) + .set(CATALOG_CREATION_REQUEST_ID, request.catalogCreationRequestId()) + .set(CATALOG_REVISION, request.catalogRevision()) + .set(SOURCE_INTAKE_OPERATION_ID, committedSource.operationId()) + .set(SOURCE_INTAKE_REQUEST_ID, committedSource.intakeRequestId()) + .set(SOURCE_REGISTRATION_REQUEST_ID, committedSource.source().registrationRequestId()) + .set(SOURCE_OPERATION_ID, committedSource.source().operationId()) + .set(CATALOG_REQUEST_DIGEST, committedCatalog.requestDigest()) + .set(CATALOG_RECEIPT_DIGEST, committedCatalog.receiptDigest()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, committedSource.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, committedSource.receiptDigest()) + .set(SOURCE_EVIDENCE_DIGEST, committedSource.source().evidenceDigest()) + .set(DESCRIPTOR_REQUEST_DIGEST, descriptorEvidence.requestDigest()) + .set(DESCRIPTOR_RESULT_DIGEST, descriptorEvidence.resultDigest()) + .set(REQUEST_DIGEST, requestDigest) + .set(RECEIPT_DIGEST, receiptDigest) + .set(REQUEST_EVIDENCE_JSON, toJson(request, "request")) + .set(CATALOG_EVIDENCE_JSON, toJson(committedCatalog, "catalog")) + .set(SOURCE_INTAKE_EVIDENCE_JSON, toJson(committedSource, "source intake")) + .set(LAUNCH_DESCRIPTOR_EVIDENCE_JSON, toJson(descriptorEvidence, "launch descriptor")) + .onConflictDoNothing() + .execute(); + + Record stored = find(request.targetNamespace(), request.controlPlaneRequestId()); + if (stored == null) { + throw new LaunchPreparationConflictException( + "Canonical launch preparation conflicts with existing immutable owner evidence"); + } + return requireExactPrepared( + stored, request, committedCatalog, committedSource, descriptorEvidence); + } + + public static String requestDigest( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + requireEvidenceMatchesRequest(request, catalog, source, descriptor); + AuthoredWorldSourceEvidence authoredSource = source.source(); + return digest( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.controlPlaneRequestId(), + request.actingAccountUuid().toString(), + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + request.sourceIntakeOperationId().toString(), + Long.toString(request.gameTemplateId()), + Boolean.toString(request.requestedScriptPatchVersionPresent()), + optional( + request.requestedScriptPatchVersionPresent(), request.requestedScriptPatchVersion()), + Boolean.toString(request.sourceVersionIdPresent()), + optional(request.sourceVersionIdPresent(), decimal(request.sourceVersionId())), + Boolean.toString(request.targetVersionIdPresent()), + optional(request.targetVersionIdPresent(), decimal(request.targetVersionId())), + Boolean.toString(request.requestedRuntimeFlagsJsonPresent()), + optional(request.requestedRuntimeFlagsJsonPresent(), request.requestedRuntimeFlagsJson()), + catalog.targetNamespace(), + catalog.tenantId().toString(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.realmId().toString(), + catalog.realmSlug(), + catalog.realmDisplayName(), + Boolean.toString(catalog.visible()), + Boolean.toString(catalog.publicProduction()), + catalog.stateScope(), + catalog.playableStateNamespaceId().toString(), + catalog.characterCreationPolicy(), + Long.toString(catalog.catalogRevision()), + catalog.creationRequestId().toString(), + catalog.requestDigest(), + catalog.receiptDigest(), + source.operationId().toString(), + source.intakeRequestId().toString(), + source.requestDigest(), + source.receiptDigest(), + Integer.toString(authoredSource.schemaVersion()), + authoredSource.registrationRequestId().toString(), + authoredSource.operationId().toString(), + authoredSource.requestDigest(), + authoredSource.canonicalTenantId().toString(), + authoredSource.tenantSlug(), + authoredSource.worldSlug(), + authoredSource.worldDisplayName(), + Long.toString(authoredSource.sourceGameRowId()), + authoredSource.sourceGameTenantKey(), + authoredSource.provenanceKind(), + authoredSource.evidenceDigest(), + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + public static String receiptDigest( + UUID operationId, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + String requestDigest) { + requireNonNil(operationId, "operationId"); + requireDigest(requestDigest, "requestDigest"); + return digest( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + operationId.toString(), + requestDigest, + request.targetNamespace(), + request.controlPlaneRequestId(), + request.actingAccountUuid().toString(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + catalog.requestDigest(), + catalog.receiptDigest(), + source.operationId().toString(), + source.intakeRequestId().toString(), + source.requestDigest(), + source.receiptDigest(), + source.source().evidenceDigest(), + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + private CanonicalLaunchPreparationSnapshot requireExactPrepared( + Record row, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + CanonicalLaunchPreparationSnapshot stored = toSnapshot(row); + if (!stored.request().equals(request) + || !stored.catalogSnapshot().equals(catalog) + || !stored.sourceIntakeReceipt().equals(source) + || !stored.launchDescriptorEvidence().equals(descriptor)) { + throw new LaunchPreparationConflictException( + "controlPlaneRequestId was reused with changed launch preparation evidence"); + } + return stored; + } + + private CanonicalLaunchPreparationSnapshot toSnapshot(Record row) { + try { + CreateCanonicalLaunchPreparationRequest request = + fromJson( + row.get(REQUEST_EVIDENCE_JSON, JSONB.class), + CreateCanonicalLaunchPreparationRequest.class); + CanonicalRealmCatalogSnapshot catalog = + fromJson( + row.get(CATALOG_EVIDENCE_JSON, JSONB.class), CanonicalRealmCatalogSnapshot.class); + IntakeReceipt source = + fromJson(row.get(SOURCE_INTAKE_EVIDENCE_JSON, JSONB.class), IntakeReceipt.class); + AuthoredWorldLaunchDescriptorEvidence descriptor = + fromJson( + row.get(LAUNCH_DESCRIPTOR_EVIDENCE_JSON, JSONB.class), + AuthoredWorldLaunchDescriptorEvidence.class); + CanonicalLaunchPreparationSnapshot snapshot = + new CanonicalLaunchPreparationSnapshot( + required(row.get(OPERATION_ID), "operationId"), + request, + catalog, + source, + descriptor, + required(row.get(REQUEST_DIGEST), "requestDigest"), + required(row.get(RECEIPT_DIGEST), "receiptDigest")); + snapshot.requireValid(); + String expectedRequestDigest = requestDigest(request, catalog, source, descriptor); + String expectedReceiptDigest = + receiptDigest( + snapshot.operationId(), request, catalog, source, descriptor, expectedRequestDigest); + if (!request.targetNamespace().equals(required(row.get(TARGET_NAMESPACE), "targetNamespace")) + || !request + .controlPlaneRequestId() + .equals(required(row.get(CONTROL_PLANE_REQUEST_ID), "controlPlaneRequestId")) + || !request + .actingAccountUuid() + .equals(required(row.get(ACTING_ACCOUNT_UUID), "actingAccountUuid")) + || !request + .canonicalTenantId() + .equals(required(row.get(CANONICAL_TENANT_ID), "canonicalTenantId")) + || !request.realmId().equals(required(row.get(REALM_ID), "realmId")) + || !request + .catalogCreationRequestId() + .equals(required(row.get(CATALOG_CREATION_REQUEST_ID), "catalogCreationRequestId")) + || request.catalogRevision() != required(row.get(CATALOG_REVISION), "catalogRevision") + || !source + .operationId() + .equals(required(row.get(SOURCE_INTAKE_OPERATION_ID), "sourceIntakeOperationId")) + || !source + .intakeRequestId() + .equals(required(row.get(SOURCE_INTAKE_REQUEST_ID), "sourceIntakeRequestId")) + || !source + .source() + .registrationRequestId() + .equals( + required(row.get(SOURCE_REGISTRATION_REQUEST_ID), "sourceRegistrationRequestId")) + || !source + .source() + .operationId() + .equals(required(row.get(SOURCE_OPERATION_ID), "sourceOperationId")) + || !catalog + .requestDigest() + .equals(required(row.get(CATALOG_REQUEST_DIGEST), "catalogRequestDigest")) + || !catalog + .receiptDigest() + .equals(required(row.get(CATALOG_RECEIPT_DIGEST), "catalogReceiptDigest")) + || !source + .requestDigest() + .equals(required(row.get(SOURCE_INTAKE_REQUEST_DIGEST), "sourceIntakeRequestDigest")) + || !source + .receiptDigest() + .equals(required(row.get(SOURCE_INTAKE_RECEIPT_DIGEST), "sourceIntakeReceiptDigest")) + || !source + .source() + .evidenceDigest() + .equals(required(row.get(SOURCE_EVIDENCE_DIGEST), "sourceEvidenceDigest")) + || !descriptor + .requestDigest() + .equals(required(row.get(DESCRIPTOR_REQUEST_DIGEST), "descriptorRequestDigest")) + || !descriptor + .resultDigest() + .equals(required(row.get(DESCRIPTOR_RESULT_DIGEST), "descriptorResultDigest")) + || !expectedRequestDigest.equals(snapshot.requestDigest()) + || !expectedReceiptDigest.equals(snapshot.receiptDigest())) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted launch preparation evidence does not match its stored identity and digests"); + } + return snapshot; + } catch (InvalidLaunchPreparationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted canonical launch preparation evidence is invalid", exception); + } + } + + private IntakeReceipt lockExactSource(IntakeReceipt expected) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ? FOR UPDATE", + expected.source().targetNamespace(), + expected.operationId()); + if (row == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Exact committed authored-world source intake is missing at launch preparation commit"); + } + try { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required(row.get("source_schema_version", Integer.class), "sourceSchemaVersion"), + required(row.get("target_namespace", String.class), "sourceTargetNamespace"), + required( + row.get("source_registration_request_id", UUID.class), + "sourceRegistrationRequestId"), + required(row.get("source_operation_id", UUID.class), "sourceOperationId"), + required(row.get("source_request_digest", String.class), "sourceRequestDigest"), + required(row.get("canonical_tenant_id", UUID.class), "sourceCanonicalTenantId"), + required(row.get("tenant_slug", String.class), "sourceTenantSlug"), + required(row.get("world_slug", String.class), "sourceWorldSlug"), + required(row.get("world_display_name", String.class), "sourceWorldDisplayName"), + required(row.get("source_game_row_id", Long.class), "sourceGameRowId"), + required(row.get("source_game_tenant_key", String.class), "sourceGameTenantKey"), + required(row.get("source_provenance_kind", String.class), "sourceProvenanceKind"), + required(row.get("source_evidence_digest", String.class), "sourceEvidenceDigest")); + if (!Integer.valueOf(SCHEMA_VERSION).equals(row.get("schema_version", Integer.class))) { + throw new IllegalArgumentException("Unsupported source intake schema version"); + } + IntakeReceipt locked = + new IntakeReceipt( + required(row.get("operation_id", UUID.class), "sourceIntakeOperationId"), + required(row.get("intake_request_id", UUID.class), "sourceIntakeRequestId"), + required(row.get("request_digest", String.class), "sourceIntakeRequestDigest"), + source, + required(row.get("receipt_digest", String.class), "sourceIntakeReceiptDigest")); + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch preparation requires exact fresh authored-world source evidence"); + } + return locked; + } catch (InvalidLaunchPreparationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted authored-world source evidence is invalid", exception); + } + } + + private Record find(String targetNamespace, String controlPlaneRequestId) { + return dsl.selectFrom(PREPARATION) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) + .fetchOne(); + } + + private static void requireEvidenceMatchesRequest( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(descriptor, "descriptor"); + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !source.equals(catalog.sourceIntakeReceipt()) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !descriptor.request().equals(request.descriptorRequest(catalog, source.source()))) { + throw new InvalidLaunchPreparationEvidenceException( + "Launch preparation does not match exact fresh catalog/source/descriptor evidence"); + } + descriptor.requireValid(); + } + + private static void requireSelector(String namespace, String controlPlaneRequestId) { + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId is required"); + } + strictUtf8(controlPlaneRequestId); + } + + private static void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Launch preparation read requires committed owner evidence"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Launch preparation persistence requires a writable owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Launch preparation persistence requires the owner READ COMMITTED connection"); + } + return null; + }); + Record isolation = dsl.fetchOne("SHOW transaction_isolation"); + if (isolation == null + || !"read committed".equalsIgnoreCase(isolation.get(0, String.class).trim())) { + throw new IllegalStateException("Launch preparation persistence requires READ COMMITTED"); + } + } + + private static JSONB toJson(Object value, String name) { + try { + return JSONB.valueOf(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException("Could not store exact " + name + " evidence", exception); + } + } + + private static T fromJson(JSONB value, Class type) { + if (value == null) { + throw new InvalidLaunchPreparationEvidenceException("Persisted JSON evidence is missing"); + } + try { + return JSON.readValue(value.data(), type); + } catch (IOException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted closed launch preparation evidence cannot be decoded", exception); + } + } + + private static String digest(String domain, String... values) { + try { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + writeSegment(preimage, domain); + for (String value : values) { + writeSegment(preimage, value); + } + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "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", exception); + } + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static String optional(boolean present, String value) { + return present ? Objects.requireNonNull(value, "present optional value") : ""; + } + + private static void requireDigest(String value, String fieldName) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(fieldName + " must be a canonical SHA-256 digest"); + } + } + + private static void requireNonNil(UUID value, String fieldName) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a non-nil UUID"); + } + } + + private static T required(T value, String fieldName) { + if (value == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted launch preparation " + fieldName + " is missing"); + } + return value; + } + + public static final class LaunchPreparationConflictException extends IllegalStateException { + public LaunchPreparationConflictException(String message) { + super(message); + } + } + + public static final class InvalidLaunchPreparationEvidenceException + extends IllegalStateException { + public InvalidLaunchPreparationEvidenceException(String message) { + super(message); + } + + public InvalidLaunchPreparationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java new file mode 100644 index 0000000000..f1080ab98f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java @@ -0,0 +1,189 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.InvalidLaunchPreparationEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.LaunchPreparationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired Game Session consumer for exact source-qualified launch preparation. It persists no game + * instance, calls no World API, and does not authorize creator or launch actions. + */ +public class GameSessionCanonicalLaunchPreparationService { + private final AuthoredWorldLaunchDescriptorClient descriptorClient; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final GameSessionAuthoredWorldSourceRepository sourceRepository; + private final GameSessionCanonicalLaunchPreparationRepository preparationRepository; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted owner collaborators and namespace are validated before use; construction acquires no resources.") + public GameSessionCanonicalLaunchPreparationService( + AuthoredWorldLaunchDescriptorClient descriptorClient, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.descriptorClient = Objects.requireNonNull(descriptorClient, "descriptorClient"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.sourceRepository = Objects.requireNonNull(sourceRepository, "sourceRepository"); + this.preparationRepository = + Objects.requireNonNull(preparationRepository, "preparationRepository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Resolves and independently reads back exact immutable Game Design evidence before taking any + * catalog/source owner locks. Exact retries return the original preparation without network I/O. + */ + public CanonicalLaunchPreparationSnapshot prepare( + CreateCanonicalLaunchPreparationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new SecurityException("Launch preparation namespace does not match this workload"); + } + + Optional prior = + preparationRepository.readByControlPlaneRequestId( + workloadNamespace, request.controlPlaneRequestId()); + if (prior.isPresent()) { + CanonicalLaunchPreparationSnapshot stored = prior.orElseThrow(); + stored.requireValid(); + if (!stored.request().equals(request)) { + throw new LaunchPreparationConflictException( + "controlPlaneRequestId was reused with changed launch preparation inputs"); + } + return stored; + } + + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(workloadNamespace, request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Exact committed canonical realm catalog is missing")); + requireCatalogBinding(request, catalog); + IntakeReceipt source = + sourceRepository + .read( + request.sourceIntakeOperationId(), + request.canonicalTenantId(), + catalog.worldSlug(), + workloadNamespace) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Exact committed authored-world source intake is missing")); + requireSourceBinding(request, catalog, source); + + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = + request.descriptorRequest(catalog, source.source()); + AuthoredWorldLaunchDescriptorEvidence resolved = descriptorClient.resolve(descriptorRequest); + if (resolved == null + || !descriptorRequest.equals(resolved.request()) + || !workloadNamespace.equals(resolved.targetNamespace())) { + throw new InvalidLaunchPreparationEvidenceException( + "Resolved Game Design descriptor does not match the exact launch preparation request"); + } + resolved.requireValid(); + + AuthoredWorldLaunchDescriptorEvidence readback = + descriptorClient.get( + new GetRequest(UUID.randomUUID(), descriptorRequest, resolved.resultDigest())); + if (!resolved.equals(readback)) { + throw new InvalidLaunchPreparationEvidenceException( + "Independent Game Design descriptor readback differs from the resolved evidence"); + } + + CanonicalLaunchPreparationSnapshot written = + ownerTransaction.execute( + status -> preparationRepository.persistPrepared(request, catalog, source, readback)); + if (written == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Game Session owner transaction returned no launch preparation result"); + } + + Optional committed = + preparationRepository.readByControlPlaneRequestId( + workloadNamespace, request.controlPlaneRequestId()); + if (committed.isEmpty()) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation is missing after independent readback"); + } + CanonicalLaunchPreparationSnapshot exact = committed.orElseThrow(); + exact.requireValid(); + if (!written.equals(exact)) { + throw new InvalidLaunchPreparationEvidenceException( + "Launch preparation changed during independent commit readback"); + } + return exact; + } + + private static void requireCatalogBinding( + CreateCanonicalLaunchPreparationRequest request, CanonicalRealmCatalogSnapshot catalog) { + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !catalog.visible() + || !catalog.publicProduction()) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch request does not match the exact committed initial catalog"); + } + } + + private static void requireSourceBinding( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source) { + if (!request.targetNamespace().equals(source.source().targetNamespace()) + || !request.canonicalTenantId().equals(source.source().canonicalTenantId()) + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !catalog.sourceIntakeReceipt().equals(source) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !catalog.worldSlug().equals(source.source().worldSlug())) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch request does not match the exact fresh source intake"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical launch preparation cannot enter from an ambient transaction"); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V14__canonical_launch_preparation.sql b/services/game-session-service/src/main/resources/db/migration/V14__canonical_launch_preparation.sql new file mode 100644 index 0000000000..72545e354f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V14__canonical_launch_preparation.sql @@ -0,0 +1,88 @@ +-- Evidence-only canonical launch preparation. It creates no runtime instance or admission state. +CREATE TABLE game_session_canonical_launch_preparation ( + target_namespace character varying(63) NOT NULL, + control_plane_request_id character varying(128) NOT NULL, + operation_id uuid NOT NULL, + acting_account_uuid uuid 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, + source_intake_operation_id uuid NOT NULL, + source_intake_request_id uuid NOT NULL, + source_registration_request_id uuid NOT NULL, + source_operation_id uuid NOT NULL, + catalog_request_digest character varying(71) NOT NULL, + catalog_receipt_digest character varying(71) NOT NULL, + source_intake_request_digest character varying(71) NOT NULL, + source_intake_receipt_digest character varying(71) NOT NULL, + source_evidence_digest character varying(71) NOT NULL, + descriptor_request_digest character varying(71) NOT NULL, + descriptor_result_digest character varying(71) NOT NULL, + request_digest character varying(71) NOT NULL, + receipt_digest character varying(71) NOT NULL, + request_evidence_json jsonb NOT NULL, + catalog_evidence_json jsonb NOT NULL, + source_intake_evidence_json jsonb NOT NULL, + launch_descriptor_evidence_json jsonb NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_canonical_launch_preparation + PRIMARY KEY (target_namespace, control_plane_request_id), + CONSTRAINT uq_gs_canonical_launch_preparation_operation UNIQUE (operation_id), + CONSTRAINT fk_gs_canonical_launch_preparation_catalog + FOREIGN KEY (target_namespace, realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id), + CONSTRAINT fk_gs_canonical_launch_preparation_source_intake + FOREIGN KEY (source_intake_operation_id) + REFERENCES game_session_authored_world_source_intake (operation_id), + CONSTRAINT chk_gs_canonical_launch_preparation_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 octet_length(control_plane_request_id) BETWEEN 1 AND 128 + AND btrim(control_plane_request_id) <> '' + AND operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND acting_account_uuid <> '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 > 0 + 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_launch_preparation_digests CHECK ( + catalog_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND catalog_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_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND request_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gs_canonical_launch_preparation_json CHECK ( + jsonb_typeof(request_evidence_json) = 'object' + AND jsonb_typeof(catalog_evidence_json) = 'object' + AND jsonb_typeof(source_intake_evidence_json) = 'object' + AND jsonb_typeof(launch_descriptor_evidence_json) = 'object') +); + +-- [jooq ignore start] +CREATE FUNCTION reject_game_session_canonical_launch_preparation_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Canonical launch preparation evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'gs_canonical_launch_preparation_immutable'; +END; +$$; + +CREATE TRIGGER game_session_canonical_launch_preparation_immutable +BEFORE UPDATE OR DELETE ON game_session_canonical_launch_preparation +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_launch_preparation_mutation(); + +CREATE TRIGGER game_session_canonical_launch_preparation_no_truncate +BEFORE TRUNCATE ON game_session_canonical_launch_preparation +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_launch_preparation_mutation(); +-- [jooq ignore stop] 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 8dea3a22f8..2f8061b01f 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 @@ -37,6 +37,9 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.IllegalTransactionStateException; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionProxyFactoryBean; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; @@ -127,6 +130,82 @@ void registersAdditionalWorldsAndReplaysExactReceiptWithoutMutation() { assertThat(fixture.dsl.fetchCount(INTAKES)).isEqualTo(2); } + @Test + void worldSelectorReadReturnsExactCommittedReceiptWithoutEnrollment() { + Fixture fixture = fixture(); + GameSessionAuthoredWorldSourceRepository proxiedRepository = + transactionalRepository(fixture.repository, fixture.transactionManager); + UUID tenantId = uuid(301); + AuthoredWorldSourceEvidence original = + source(tenantId, uuid(302), uuid(303), "selector-tenant", "selector-world", "Selector"); + assertThat(proxiedRepository.readByWorldSelector(NAMESPACE, tenantId, "selector-world")) + .isEmpty(); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(INTAKES)).isZero(); + IntakeReceipt receipt = fixture.register(uuid(304), original); + String intakeXmin = + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + receipt.operationId()); + String bindingXmin = + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId); + assertThat(proxiedRepository.readByWorldSelector(NAMESPACE, tenantId, "selector-world")) + .contains(receipt); + assertThat(proxiedRepository.readByWorldSelector("other-space", tenantId, "selector-world")) + .isEmpty(); + assertThat(proxiedRepository.readByWorldSelector(NAMESPACE, uuid(305), "selector-world")) + .isEmpty(); + assertThat(proxiedRepository.readByWorldSelector(NAMESPACE, tenantId, "other-world")).isEmpty(); + assertThat( + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + receipt.operationId())) + .isEqualTo(intakeXmin); + assertThat( + fixture.xmin( + "SELECT xmin::text AS xmin FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenantId)) + .isEqualTo(bindingXmin); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(INTAKES)).isEqualTo(1); + } + + @Test + void worldSelectorReadRejectsAmbientOwnerTransactionAndMalformedScope() { + Fixture fixture = fixture(); + GameSessionAuthoredWorldSourceRepository proxiedRepository = + transactionalRepository(fixture.repository, fixture.transactionManager); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> + proxiedRepository.readByWorldSelector( + NAMESPACE, uuid(306), "selector-world"))) + .isInstanceOf(IllegalTransactionStateException.class); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> + fixture.repository.readByWorldSelector( + NAMESPACE, uuid(306), "selector-world"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + assertThatThrownBy( + () -> + fixture.repository.readByWorldSelector(NAMESPACE, new UUID(0, 0), "selector-world")) + .isInstanceOf(IllegalArgumentException.class); + assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); + assertThat(fixture.dsl.fetchCount(INTAKES)).isZero(); + } + @Test void changedRequestAndDuplicateSourceOrSelectorClaimsLeaveNoPartialRows() { Fixture fixture = fixture(); @@ -744,6 +823,18 @@ private Fixture fixture() { dsl, new GameSessionAuthoredWorldSourceRepository(dsl), transactionManager, transactions); } + private GameSessionAuthoredWorldSourceRepository transactionalRepository( + GameSessionAuthoredWorldSourceRepository target, + DataSourceTransactionManager transactionManager) { + TransactionProxyFactoryBean proxyFactory = new TransactionProxyFactoryBean(); + proxyFactory.setTransactionManager(transactionManager); + proxyFactory.setTransactionAttributeSource(new AnnotationTransactionAttributeSource()); + proxyFactory.setTarget(target); + proxyFactory.setProxyTargetClass(true); + proxyFactory.afterPropertiesSet(); + return (GameSessionAuthoredWorldSourceRepository) proxyFactory.getObject(); + } + private void assertConflict(Runnable registration) { assertThatThrownBy(registration::run).isInstanceOf(RegistrationConflictException.class); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java new file mode 100644 index 0000000000..74c72fac1a --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java @@ -0,0 +1,588 @@ +package integration.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +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.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +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.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; +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; + +/** + * Real PostgreSQL source/catalog transactions and immutable preparation storage. Game Design's + * descriptor response is deliberately synthetic here; this is not transport or mTLS proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalLaunchPreparationServiceIntegrationTest { + private static final String NAMESPACE = "canonical-launch-it"; + private static final UUID TENANT = uuid(101); + private static final UUID SOURCE_OPERATION = uuid(102); + private static final UUID INTAKE_REQUEST = uuid(104); + private static final UUID CATALOG_REQUEST = uuid(105); + private static final UUID ACTOR = uuid(106); + private static final UUID REALM = uuid(107); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final long RETAINED_TENANT_ID = 917L; + private static final long RETAINED_GAME_INSTANCE_ID = 901L; + private static final UUID RETAINED_REALM_ID = uuid(108); + private static final UUID RETAINED_PLAYABLE_NAMESPACE_ID = uuid(109); + private static final UUID RETAINED_SHARED_NAMESPACE_ID = uuid(110); + 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 + commitsExactFreshSourceCatalogAndSyntheticDescriptorThenReplaysWithoutChangingRetainedRows() { + Fixture fixture = fixture(true, true); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + IntakeReceipt source = java.util.Objects.requireNonNull(fixture.preV14Source); + CanonicalRealmCatalogSnapshot catalog = java.util.Objects.requireNonNull(fixture.preV14Catalog); + assertThat( + fixture.sourceRepository.read( + source.operationId(), TENANT, source.source().worldSlug(), NAMESPACE)) + .contains(source); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .contains(catalog); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + AuthoredWorldLaunchDescriptorClient syntheticGameDesign = syntheticGameDesignClient(); + GameSessionCanonicalLaunchPreparationService service = fixture.service(syntheticGameDesign); + + CanonicalLaunchPreparationSnapshot first = service.prepare(request); + // A repeated call models recovery after the caller loses the first successful response. + CanonicalLaunchPreparationSnapshot retry = service.prepare(request); + + assertThat(first).isEqualTo(retry); + assertThat(first.operationId()).isNotEqualTo(NIL_UUID); + assertThat(first.catalogSnapshot()).isEqualTo(catalog); + assertThat(first.sourceIntakeReceipt()).isEqualTo(source); + first.launchDescriptorEvidence().requireValid(); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT game_instance_uuid FROM game_instances WHERE id = ?", + RETAINED_GAME_INSTANCE_ID) + .get("game_instance_uuid", UUID.class)) + .isNull(); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT representation_version, tenant_id, game_instance_id, realm_id, " + + "canonical_tenant_id, playable_state_namespace_id FROM gameplay_admission_pointer " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID)) + .satisfies( + row -> { + assertThat(row.get("representation_version", Integer.class)).isEqualTo(1); + assertThat(row.get("tenant_id", Long.class)).isEqualTo(RETAINED_TENANT_ID); + assertThat(row.get("game_instance_id", Long.class)).isEqualTo(501L); + assertThat(row.get("realm_id", UUID.class)).isEqualTo(RETAINED_REALM_ID); + assertThat(row.get("canonical_tenant_id", UUID.class)).isNull(); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_PLAYABLE_NAMESPACE_ID); + }); + 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); + verify(syntheticGameDesign, times(1)).resolve(any()); + verify(syntheticGameDesign, times(1)).get(any(GetRequest.class)); + } + + @Test + void ownerRollbackLeavesNoPartialPreparationAndImmutableRowsRejectMutation() { + Fixture fixture = fixture(false, false); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + IntakeReceipt source = fixture.registerFreshSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request, catalog, source); + + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> { + fixture.preparationRepository.persistPrepared( + request, catalog, source, descriptor); + throw new IllegalStateException("forced owner rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("forced owner rollback"); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + + CanonicalLaunchPreparationSnapshot committed = + fixture.service(syntheticGameDesignClient()).prepare(request); + assertThat( + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .contains(committed); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_canonical_launch_preparation " + + "SET receipt_digest = ? WHERE target_namespace = ?", + digest("f"), + NAMESPACE)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_launch_preparation " + + "WHERE target_namespace = ?", + NAMESPACE)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE game_session_canonical_launch_preparation")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThat( + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .contains(committed); + + // Simulate privileged storage corruption in this isolated test schema; normal update/delete + // paths remain blocked by the immutable trigger above. + fixture.transactions.execute( + status -> { + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_launch_preparation DISABLE TRIGGER " + + "game_session_canonical_launch_preparation_immutable"); + fixture.dsl.execute( + "UPDATE game_session_canonical_launch_preparation " + + "SET catalog_evidence_json = jsonb_set(catalog_evidence_json, " + + "'{realmDisplayName}', to_jsonb(CAST(? AS text))) " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + "Tampered Realm Display Name", + NAMESPACE, + request.controlPlaneRequestId()); + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_launch_preparation ENABLE TRIGGER " + + "game_session_canonical_launch_preparation_immutable"); + return null; + }); + assertThatThrownBy( + () -> + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .isInstanceOf( + GameSessionCanonicalLaunchPreparationRepository + .InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("stored identity and digests"); + } + + @Test + void concurrentExactPreparationsReturnOneImmutableOperation() throws Exception { + Fixture fixture = fixture(false, false); + IntakeReceipt source = fixture.registerFreshSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + CountDownLatch bothResolved = new CountDownLatch(2); + AuthoredWorldLaunchDescriptorClient concurrentGameDesign = + concurrentSyntheticGameDesignClient(bothResolved); + GameSessionCanonicalLaunchPreparationService service = fixture.service(concurrentGameDesign); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> service.prepare(request)); + Future second = + executor.submit(() -> service.prepare(request)); + + assertThat(bothResolved.await(15, TimeUnit.SECONDS)).isTrue(); + CanonicalLaunchPreparationSnapshot firstResult = first.get(15, TimeUnit.SECONDS); + CanonicalLaunchPreparationSnapshot secondResult = second.get(15, TimeUnit.SECONDS); + + assertThat(firstResult).isEqualTo(secondResult); + assertThat(firstResult.operationId()).isEqualTo(secondResult.operationId()); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isEqualTo(1); + verify(concurrentGameDesign, times(2)).resolve(any()); + verify(concurrentGameDesign, times(2)).get(any(GetRequest.class)); + } finally { + executor.shutdownNow(); + } + } + + private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient() { + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenAnswer( + invocation -> { + AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); + return syntheticDescriptor(request); + }); + when(client.get(any(GetRequest.class))) + .thenAnswer( + invocation -> { + GetRequest request = invocation.getArgument(0); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request.expectedRequest()); + assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + return descriptor; + }); + return client; + } + + private static AuthoredWorldLaunchDescriptorClient concurrentSyntheticGameDesignClient( + CountDownLatch bothResolved) { + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenAnswer( + invocation -> { + AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); + bothResolved.countDown(); + try { + if (!bothResolved.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent exact attempts did not both resolve"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent exact attempt was interrupted", exception); + } + return syntheticDescriptor(request); + }); + when(client.get(any(GetRequest.class))) + .thenAnswer( + invocation -> { + GetRequest request = invocation.getArgument(0); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request.expectedRequest()); + assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + return descriptor; + }); + return client; + } + + private static AuthoredWorldLaunchDescriptorEvidence syntheticDescriptor( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source) { + return syntheticDescriptor(request.descriptorRequest(catalog, source.source())); + } + + private static AuthoredWorldLaunchDescriptorEvidence syntheticDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "synthetic-descriptor-" + request.controlPlaneRequestId(), + 515, + false, + null, + "{}", + "generation-config-1", + 4, + 616, + "synthetic-published-release-616", + false, + null); + } + + private static CreateCanonicalLaunchPreparationRequest request( + IntakeReceipt source, CanonicalRealmCatalogSnapshot catalog) { + return new CreateCanonicalLaunchPreparationRequest( + "canonical-launch-it-" + catalog.realmId(), + ACTOR, + NAMESPACE, + TENANT, + catalog.realmId(), + catalog.creationRequestId(), + catalog.catalogRevision(), + source.operationId(), + 404, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private Fixture fixture( + boolean seedRetainedNumericRows, boolean seedCanonicalOwnerEvidenceBeforeV14) { + String schema = "gs_canonical_launch_" + 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 game_instances (id, tenant_id, runtime_version, owner_account_id, status) " + + "VALUES (?, ?, ?, ?, ?)", + RETAINED_GAME_INSTANCE_ID, + RETAINED_TENANT_ID, + "retained-runtime", + 77L, + "RUNNING"); + 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_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) + .target(MigrationVersion.fromVersion("13")) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext transactionalDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(transactionalDsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(transactionalDsl); + IntakeReceipt preV14Source = null; + CanonicalRealmCatalogSnapshot preV14Catalog = null; + if (seedCanonicalOwnerEvidenceBeforeV14) { + preV14Source = + java.util.Objects.requireNonNull( + transactions.execute( + status -> sourceRepository.register(INTAKE_REQUEST, freshSource()))); + CreateCanonicalRealmCatalogRequest catalogRequest = + new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST, + NAMESPACE, + TENANT, + preV14Source.operationId(), + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var preparedCatalog = catalogRepository.prepareInitialPublicProduction(catalogRequest); + preV14Catalog = + java.util.Objects.requireNonNull( + transactions.execute( + status -> catalogRepository.createInitialPublicProduction(preparedCatalog))); + } + + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + GameSessionCanonicalLaunchPreparationRepository preparationRepository = + new GameSessionCanonicalLaunchPreparationRepository(transactionalDsl, catalogRepository); + return new Fixture( + transactionalDsl, + sourceRepository, + catalogRepository, + preparationRepository, + transactionManager, + transactions, + preV14Source, + preV14Catalog); + } + + private static AuthoredWorldSourceEvidence freshSource() { + String worldSlug = "violet-wilds"; + String tenantSlug = "tenant-" + TENANT.toString().substring(0, 8); + String displayName = "Violet Wilds"; + UUID registrationRequestId = uuid(111); + long sourceGameRowId = 821; + String sourceGameTenantKey = "fresh-source-821"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, TENANT, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + 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 String digest(String letter) { + return "sha256:" + letter.repeat(64); + } + + 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, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + IntakeReceipt preV14Source, + CanonicalRealmCatalogSnapshot preV14Catalog) { + IntakeReceipt registerFreshSource() { + IntakeReceipt receipt = + transactions.execute(status -> sourceRepository.register(INTAKE_REQUEST, freshSource())); + return java.util.Objects.requireNonNull(receipt); + } + + CanonicalRealmCatalogSnapshot createCatalog(IntakeReceipt source) { + CreateCanonicalRealmCatalogRequest request = + new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST, + NAMESPACE, + TENANT, + source.operationId(), + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var prepared = catalogRepository.prepareInitialPublicProduction(request); + CanonicalRealmCatalogSnapshot created = + transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); + return java.util.Objects.requireNonNull(created); + } + + GameSessionCanonicalLaunchPreparationService service( + AuthoredWorldLaunchDescriptorClient descriptorClient) { + return new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java new file mode 100644 index 0000000000..5cf3d26346 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java @@ -0,0 +1,657 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.InvalidLaunchPreparationEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.LaunchPreparationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionCanonicalLaunchPreparationServiceTest { + private static final String NAMESPACE = "canonical-launch-test"; + private static final String CONTROL_PLANE_REQUEST = "launch-attempt-1"; + private static final UUID ACTOR = uuid(1); + private static final UUID TENANT = uuid(2); + private static final UUID SOURCE_OPERATION = uuid(3); + private static final UUID SOURCE_INTAKE_OPERATION = uuid(4); + private static final UUID INTAKE_REQUEST = uuid(5); + private static final UUID REALM = uuid(6); + private static final UUID CATALOG_REQUEST = uuid(7); + + private final AuthoredWorldLaunchDescriptorClient descriptorClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + private final GameSessionCanonicalRealmCatalogRepository catalogRepository = + mock(GameSessionCanonicalRealmCatalogRepository.class); + private final GameSessionAuthoredWorldSourceRepository sourceRepository = + mock(GameSessionAuthoredWorldSourceRepository.class); + private final GameSessionCanonicalLaunchPreparationRepository preparationRepository = + mock(GameSessionCanonicalLaunchPreparationRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final GameSessionCanonicalLaunchPreparationService service = + new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsAmbientTransactionBeforeAnyOwnerReadOrNetworkCall() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> service.prepare(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void resolvesThenGetsExactDescriptorOutsideShortOwnerTransactionAndReadsCommitBack() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot snapshot = snapshot(request, catalog, intake, descriptor); + stubNewPreparation(request, source, intake, catalog, descriptor, snapshot); + + assertThat(service.prepare(request)).isEqualTo(snapshot); + + ArgumentCaptor getRequest = ArgumentCaptor.forClass(GetRequest.class); + verify(descriptorClient).resolve(descriptor.request()); + verify(descriptorClient).get(getRequest.capture()); + assertThat(getRequest.getValue().expectedRequest()).isEqualTo(descriptor.request()); + assertThat(getRequest.getValue().expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + assertThat(getRequest.getValue().requestId()).isNotEqualTo(SOURCE_OPERATION); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.commitCount).isEqualTo(1); + verify(preparationRepository).persistPrepared(request, catalog, intake, descriptor); + } + + @Test + void changedDurableCommitReadbackFailsWithoutRepairingTheStoredPreparation() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot written = snapshot(request, catalog, intake, descriptor); + CanonicalLaunchPreparationSnapshot changedReadback = + snapshot(request, catalog, intake, descriptor, uuid(14)); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(changedReadback)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(descriptor.request())).thenReturn(descriptor); + when(descriptorClient.get(any(GetRequest.class))).thenReturn(descriptor); + when(preparationRepository.persistPrepared(request, catalog, intake, descriptor)) + .thenReturn(written); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("changed during independent commit readback"); + + verify(preparationRepository, times(1)).persistPrepared(request, catalog, intake, descriptor); + verify(preparationRepository, times(2)) + .readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + } + + @Test + void exactRetryReturnsOriginalPreparationWithoutRepeatingSourceOrDescriptorCalls() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot original = snapshot(request, catalog, intake, descriptor); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + + assertThat(service.prepare(request)).isEqualTo(original); + + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedRetryInputConflictsBeforeUpstreamResolutionOrMutation() { + CreateCanonicalLaunchPreparationRequest originalRequest = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(originalRequest, catalog, source); + CanonicalLaunchPreparationSnapshot original = + snapshot(originalRequest, catalog, intake, descriptor); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + CreateCanonicalLaunchPreparationRequest changed = + new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + NAMESPACE, + TENANT, + REALM, + CATALOG_REQUEST, + 1, + SOURCE_INTAKE_OPERATION, + 71, + true, + "", // Present-empty remains distinct from absence. + false, + null, + false, + null, + false, + null); + + assertThatThrownBy(() -> service.prepare(changed)) + .isInstanceOf(LaunchPreparationConflictException.class) + .hasMessageContaining("changed"); + + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void catalogAndSourceSubstitutionFailBeforeDescriptorResolution() { + CreateCanonicalLaunchPreparationRequest request = request(); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + CanonicalRealmCatalogSnapshot changedCatalog = catalog(intake(source()), uuid(88)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(changedCatalog)); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + + resetRepositories(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source, uuid(89)); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact fresh source intake"); + verifyNoInteractions(descriptorClient); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + } + + @Test + void namespaceTenantAndCatalogSelectorMismatchesFailBeforeDescriptorResolution() { + CreateCanonicalLaunchPreparationRequest wrongNamespace = + request(NAMESPACE + "-other", TENANT, CATALOG_REQUEST, 1); + assertThatThrownBy(() -> service.prepare(wrongNamespace)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("namespace"); + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + + resetRepositories(); + CreateCanonicalLaunchPreparationRequest wrongTenant = + request(NAMESPACE, uuid(91), CATALOG_REQUEST, 1); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog(intake(source())))); + + assertThatThrownBy(() -> service.prepare(wrongTenant)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + + resetRepositories(); + UUID changedCatalogRequestId = uuid(92); + CreateCanonicalLaunchPreparationRequest wrongCatalog = + request(NAMESPACE, TENANT, changedCatalogRequestId, 2); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, changedCatalogRequestId)) + .thenReturn(Optional.of(catalog(intake(source())))); + + assertThatThrownBy(() -> service.prepare(wrongCatalog)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + } + + @Test + void descriptorAndIndependentReadbackMustBothMatchCompleteSharedEvidence() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence.Request expected = + request.descriptorRequest(catalog, source); + AuthoredWorldLaunchDescriptorEvidence substituted = + AuthoredWorldLaunchDescriptorEvidence.create( + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + CONTROL_PLANE_REQUEST, + TENANT, + catalog.worldSlug(), + uuid(90), + source.evidenceDigest(), + 71, + false, + null, + false, + null, + false, + null, + false, + null), + "descriptor-90", + 72, + false, + null, + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(expected)).thenReturn(substituted); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("does not match"); + verify(descriptorClient, never()).get(any()); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + + resetRepositories(); + AuthoredWorldLaunchDescriptorEvidence resolved = descriptor(request, catalog, source); + AuthoredWorldLaunchDescriptorEvidence changedReadback = + AuthoredWorldLaunchDescriptorEvidence.create( + resolved.request(), + "changed-descriptor-readback", + 74, + false, + null, + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(resolved.request())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return resolved; + }); + when(descriptorClient.get(any(GetRequest.class))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return changedReadback; + }); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("readback differs"); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + } + + @Test + void requestDigestBindsOptionalPresenceAndDescriptorDigest() { + CreateCanonicalLaunchPreparationRequest absent = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence absentDescriptor = descriptor(absent, catalog, source); + CreateCanonicalLaunchPreparationRequest presentEmpty = + new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + NAMESPACE, + TENANT, + REALM, + CATALOG_REQUEST, + 1, + SOURCE_INTAKE_OPERATION, + 71, + true, + "", + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence presentEmptyDescriptor = + descriptor(presentEmpty, catalog, source); + + assertThat( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, catalog, intake, absentDescriptor)) + .isNotEqualTo( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + presentEmpty, catalog, intake, presentEmptyDescriptor)); + + CanonicalRealmCatalogSnapshot changedCatalogPayload = + new CanonicalRealmCatalogSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.realmId(), + "changed-realm-slug", + "Changed Realm Display Name", + catalog.visible(), + catalog.publicProduction(), + catalog.stateScope(), + uuid(93), + catalog.characterCreationPolicy(), + catalog.catalogRevision(), + catalog.creationRequestId(), + catalog.requestDigest(), + catalog.receiptDigest(), + intake); + assertThat( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, changedCatalogPayload, intake, absentDescriptor)) + .isNotEqualTo( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, catalog, intake, absentDescriptor)); + } + + private void stubNewPreparation( + CreateCanonicalLaunchPreparationRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + IntakeReceipt intake, + CanonicalRealmCatalogSnapshot catalog, + AuthoredWorldLaunchDescriptorEvidence descriptor, + CanonicalLaunchPreparationSnapshot snapshot) { + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(snapshot)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(descriptor.request())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return descriptor; + }); + when(descriptorClient.get(any(GetRequest.class))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return descriptor; + }); + when(preparationRepository.persistPrepared(request, catalog, intake, descriptor)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(descriptor.authoredWorldSourceOperationId()) + .isEqualTo(sourceEvidence.operationId()); + return snapshot; + }); + } + + private void resetRepositories() { + org.mockito.Mockito.reset( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + } + + private static CreateCanonicalLaunchPreparationRequest request() { + return request(NAMESPACE, TENANT, CATALOG_REQUEST, 1); + } + + private static CreateCanonicalLaunchPreparationRequest request( + String namespace, UUID tenant, UUID catalogRequest, long catalogRevision) { + return new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + namespace, + tenant, + REALM, + catalogRequest, + catalogRevision, + SOURCE_INTAKE_OPERATION, + 71, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static AuthoredWorldSourceEvidence source() { + String world = "violet-wilds"; + String tenantSlug = "north-star"; + String displayName = "Violet Wilds"; + UUID registrationId = uuid(10); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationId, TENANT, tenantSlug, world, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationId, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + tenantSlug, + world, + displayName, + 44, + "fresh-source-key-44", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationId, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + tenantSlug, + world, + displayName, + 44, + "fresh-source-key-44", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static IntakeReceipt intake(AuthoredWorldSourceEvidence source) { + return intake(source, SOURCE_INTAKE_OPERATION); + } + + private static IntakeReceipt intake(AuthoredWorldSourceEvidence source, UUID operationId) { + String requestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(INTAKE_REQUEST, source); + return new IntakeReceipt( + operationId, + INTAKE_REQUEST, + requestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, source.evidenceDigest())); + } + + private static CanonicalRealmCatalogSnapshot catalog(IntakeReceipt source) { + return catalog(source, REALM); + } + + private static CanonicalRealmCatalogSnapshot catalog(IntakeReceipt source, UUID realmId) { + return new CanonicalRealmCatalogSnapshot( + NAMESPACE, + TENANT, + source.source().tenantSlug(), + source.source().worldSlug(), + realmId, + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + uuid(12), + "explicit-policy-v1", + 1, + CATALOG_REQUEST, + digest("c"), + digest("d"), + source); + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptor( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + AuthoredWorldSourceEvidence source) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request.descriptorRequest(catalog, source), + "launch-descriptor-1", + 72, + false, + null, + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + } + + private static CanonicalLaunchPreparationSnapshot snapshot( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return snapshot(request, catalog, source, descriptor, uuid(13)); + } + + private static CanonicalLaunchPreparationSnapshot snapshot( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID operationId) { + String requestDigest = + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + request, catalog, source, descriptor); + return new CanonicalLaunchPreparationSnapshot( + operationId, + request, + catalog, + source, + descriptor, + requestDigest, + GameSessionCanonicalLaunchPreparationRepository.receiptDigest( + operationId, request, catalog, source, descriptor, requestDigest)); + } + + private static String digest(String letter) { + return "sha256:" + letter.repeat(64); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private TransactionDefinition startedWith; + private int commitCount; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commitCount++; + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java index 706f09e1ce..d85a0faa44 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java @@ -484,8 +484,9 @@ private void validateAttestedLaunchInputs(PreparedWorldInstanceRequest request) throw new IllegalArgumentException( "RELEASE_ATTESTATION_MISMATCH: world activation request does not match the published release bundle"); } - if (!releaseBundleRef(request.tenantId(), request.versionId(), request.releaseBundleId()) - .equals(request.publishedReleaseBundleRef())) { + String publishedReleaseBundleRef = bundle.getPublishedReleaseBundleRef(); + if (publishedReleaseBundleRef.isBlank() + || !publishedReleaseBundleRef.equals(request.publishedReleaseBundleRef())) { throw new IllegalArgumentException( "RELEASE_ATTESTATION_MISMATCH: published release bundle ref mismatch"); } @@ -647,10 +648,6 @@ private String normalizeBlank(String value) { return value == null || value.isBlank() ? null : value; } - private String releaseBundleRef(long tenantId, long versionId, long releaseBundleId) { - return "prb:" + tenantId + ":" + versionId + ":" + releaseBundleId; - } - private void requireSupportedReleaseAttestationSchema(String schemaVersion) { if (!SUPPORTED_RELEASE_ATTESTATION_SCHEMA_VERSION.equals(schemaVersion)) { throw new IllegalArgumentException( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index ebf18c3cb0..734e967ae4 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -56,6 +56,7 @@ import org.springframework.transaction.support.TransactionOperations; class WorldLifecycleCommandServiceImplTest { + private static final String PERSISTED_RELEASE_BUNDLE_REF = "opaque-release-ref-from-game-design"; private WorldInstanceRepository worldInstanceRepository; private RegionInstanceRepository regionInstanceRepository; private ZoneRepository zoneRepository; @@ -129,6 +130,7 @@ public T execute(TransactionCallback action) { .setManifestHash("manifest-11") .addRequiredManifestAssetKeys("manifest.json") .setGenerationConfigRevision("genrev-11") + .setPublishedReleaseBundleRef(PERSISTED_RELEASE_BUNDLE_REF) .build()) .build()); when(gameDesignClient.getVersionAssetArtifactState(42L, 11L)) @@ -205,7 +207,7 @@ void prepareWorldInstanceMaterializesSeededRoomIdentityAndActivatesOwnerLifecycl "{}", "genrev-11", 77L, - "prb:42:11:77", + PERSISTED_RELEASE_BUNDLE_REF, 77L)); assertEquals("PREPARING", prepared.status()); @@ -267,16 +269,129 @@ void prepareWorldInstancePersistsPreparingLifecycle() { "{}", "genrev-11", 77L, - "prb:42:11:77", + PERSISTED_RELEASE_BUNDLE_REF, 77L)); assertEquals("PREPARING", snapshot.status()); assertEquals(1L, snapshot.lifecycleEpoch()); + assertEquals(PERSISTED_RELEASE_BUNDLE_REF, snapshot.publishedReleaseBundleRef()); + verify(worldInstanceRepository).save(any(WorldInstance.class)); verify(regionInstanceRepository).save(any()); verify(zoneInstanceRepository).save(any()); verify(roomInstanceRepository).save(any()); } + @Test + void exactRetryRetainsPersistedOpaqueReleaseBundleReference() { + AtomicReference persisted = new AtomicReference<>(); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.empty()) + .thenAnswer(invocation -> Optional.of(persisted.get())); + when(worldInstanceRepository.save(any(WorldInstance.class))) + .thenAnswer( + invocation -> { + WorldInstance instance = invocation.getArgument(0); + persisted.set(instance); + return instance; + }); + PreparedWorldInstanceRequest request = + new PreparedWorldInstanceRequest( + 42L, + 101L, + 7L, + "cp-1", + "ld-1", + 11L, + "patch-1", + "{}", + "genrev-11", + 77L, + PERSISTED_RELEASE_BUNDLE_REF, + 77L); + + var first = service.prepareWorldInstance(request); + var retry = service.prepareWorldInstance(request); + + assertEquals(PERSISTED_RELEASE_BUNDLE_REF, first.publishedReleaseBundleRef()); + assertEquals(PERSISTED_RELEASE_BUNDLE_REF, retry.publishedReleaseBundleRef()); + assertEquals(PERSISTED_RELEASE_BUNDLE_REF, persisted.get().getPublishedReleaseBundleRef()); + verify(worldInstanceRepository, times(1)).save(any(WorldInstance.class)); + verify(gameDesignClient, times(1)).getPublishedReleaseBundle(42L, 11L); + } + + @Test + void prepareWorldInstanceRejectsSubstitutedReleaseBundleRefBeforePersistence() { + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.empty()); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + service.prepareWorldInstance( + new PreparedWorldInstanceRequest( + 42L, + 101L, + 7L, + "cp-1", + "ld-1", + 11L, + null, + "{}", + "genrev-11", + 77L, + "substituted-release-reference", + 77L))); + + assertEquals( + "RELEASE_ATTESTATION_MISMATCH: published release bundle ref mismatch", error.getMessage()); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verify(regionInstanceRepository, never()).save(any()); + } + + @Test + void prepareWorldInstanceRejectsMissingPersistedReleaseBundleRefBeforePersistence() { + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.empty()); + when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) + .thenReturn( + GetPublishedReleaseBundleResponse.newBuilder() + .setBundle( + PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setAttestationSchemaVersion("v1") + .setManifestHash("manifest-11") + .addRequiredManifestAssetKeys("manifest.json") + .setGenerationConfigRevision("genrev-11") + .build()) + .build()); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + service.prepareWorldInstance( + new PreparedWorldInstanceRequest( + 42L, + 101L, + 7L, + "cp-1", + "ld-1", + 11L, + null, + "{}", + "genrev-11", + 77L, + PERSISTED_RELEASE_BUNDLE_REF, + 77L))); + + assertEquals( + "RELEASE_ATTESTATION_MISMATCH: published release bundle ref mismatch", error.getMessage()); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verify(regionInstanceRepository, never()).save(any()); + } + @Test void activatePreparedWorldInstancePromotesPreparingRow() { WorldInstance instance = new WorldInstance(); @@ -288,7 +403,7 @@ void activatePreparedWorldInstancePromotesPreparingRow() { instance.setVersionId(11L); instance.setGenerationConfigRevision("genrev-11"); instance.setReleaseBundleId(77L); - instance.setPublishedReleaseBundleRef("prb:42:11:77"); + instance.setPublishedReleaseBundleRef(PERSISTED_RELEASE_BUNDLE_REF); instance.setVersionStateEpoch(77L); instance.setLifecycleEpoch(1L); instance.setStatus("PREPARING"); @@ -314,7 +429,7 @@ void failPreparedWorldInstanceMarksPreparingRowFailed() { instance.setVersionId(11L); instance.setGenerationConfigRevision("genrev-11"); instance.setReleaseBundleId(77L); - instance.setPublishedReleaseBundleRef("prb:42:11:77"); + instance.setPublishedReleaseBundleRef(PERSISTED_RELEASE_BUNDLE_REF); instance.setVersionStateEpoch(77L); instance.setLifecycleEpoch(1L); instance.setStatus("PREPARING"); @@ -340,7 +455,7 @@ void terminateWorldInstanceDeletesRuntimeWorldStateBeforeFinalizing() { instance.setVersionId(11L); instance.setReleaseBundleId(77L); instance.setGenerationConfigRevision("genrev-11"); - instance.setPublishedReleaseBundleRef("prb:42:11:77"); + instance.setPublishedReleaseBundleRef(PERSISTED_RELEASE_BUNDLE_REF); instance.setVersionStateEpoch(77L); instance.setLifecycleEpoch(2L); instance.setStatus("ACTIVE"); @@ -651,7 +766,7 @@ void prepareWorldInstanceRejectsReleaseBundleMismatch() { "{}", "wrong-rev", 77L, - "prb:42:11:77", + PERSISTED_RELEASE_BUNDLE_REF, 77L))); assertEquals( @@ -693,7 +808,7 @@ void prepareWorldInstanceRejectsUnsupportedReleaseBundleSchema() { "{}", "genrev-11", 77L, - "prb:42:11:77", + PERSISTED_RELEASE_BUNDLE_REF, 77L))); assertEquals( @@ -736,7 +851,7 @@ void prepareWorldInstanceRejectsMissingRequiredManifestAssetKeyProof() { "{}", "genrev-11", 77L, - "prb:42:11:77", + PERSISTED_RELEASE_BUNDLE_REF, 77L))); assertEquals( @@ -755,7 +870,7 @@ private WorldInstance activeWorldInstance() { instance.setVersionId(11L); instance.setReleaseBundleId(77L); instance.setGenerationConfigRevision("genrev-11"); - instance.setPublishedReleaseBundleRef("prb:42:11:77"); + instance.setPublishedReleaseBundleRef(PERSISTED_RELEASE_BUNDLE_REF); instance.setVersionStateEpoch(77L); instance.setLifecycleEpoch(2L); instance.setStatus("ACTIVE");