diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index e5273bceec..4386d34933 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -17,6 +17,7 @@ const ALL_SERVICES = [ const ALL_MODULES = [ "common-data-runtime", "common-platform-core", + "common-redis-contracts", "common-saga", "common-temporal", "common-security", @@ -50,6 +51,7 @@ const SHARED_PREFIXES = [ "services/common-library/", "services/common-data-runtime/", "services/common-platform-core/", + "services/common-redis-contracts/", "services/common-saga/", "services/common-temporal/", "services/common-security/", diff --git a/.github/scripts/classify-change-scope.test.cjs b/.github/scripts/classify-change-scope.test.cjs index 075a679e3f..022ea89092 100644 --- a/.github/scripts/classify-change-scope.test.cjs +++ b/.github/scripts/classify-change-scope.test.cjs @@ -261,6 +261,27 @@ test("shared modules force every Gradle module, including common-temporal", () = assert.deepEqual(result.bootableModules, ALL_SERVICES.concat("hosted-environment-identity-controller")); }); +test("common Redis contracts use shared-library validation without becoming bootable", () => { + const result = classifyChangeScope([ + "services/common-redis-contracts/src/main/java/example/RedisContract.java", + ]); + + assert.equal(result.runAll, true); + assert.deepEqual(result.affectedModules, ALL_MODULES); + assert.equal(result.affectedModules.includes("common-redis-contracts"), true); + assert.equal(result.bootableModules.includes("common-redis-contracts"), false); +}); + +test("root Gradle build and settings changes include common Redis contract validation", () => { + for (const path of ["build.gradle.kts", "settings.gradle.kts"]) { + const result = classifyChangeScope([path]); + + assert.equal(result.runAll, true, path); + assert.equal(result.affectedModules.includes("common-redis-contracts"), true, path); + assert.equal(result.bootableModules.includes("common-redis-contracts"), false, path); + } +}); + test("controller and load-testing changes receive their own module checks", () => { const controllerResult = classifyChangeScope([ "services/hosted-environment-identity-controller/src/main/java/example/Controller.java", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1d4eb1f392..98975ad927 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: @@ -59,6 +58,7 @@ jobs: const completeModules = [ "common-data-runtime", "common-platform-core", + "common-redis-contracts", "common-saga", "common-temporal", "common-security", @@ -1073,6 +1073,86 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run Account membership readback socket mTLS component proof + if: ${{ !cancelled() && matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:crossServiceTest \ + --tests crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest#exactGameSessionPeerReceivesNonadmittingPositiveMissingBaselineOverSocketMtls()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest#exactGameSessionPeerReceivesBoundActiveMembershipEventOverSocketMtls()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest#[1] clientIdentity = "wrong-service"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest#[2] clientIdentity = "wrong-namespace"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest#[1] serverIdentity = "game-session"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest#[2] serverIdentity = "wrong-account-namespace"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest#missingClientCertificateIsRejectedByTheRequiredTlsHandshake()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest#exactGameSessionPeerCannotSendMalformedTypedContextToTheCandidateHandler()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest#exactPeerCannotReceiveCrossBoundProducerSnapshot()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest#exactAccountPeerCannotDeliverCrossBoundRecipientEchoes()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcMtlsCrossServiceTest#exactAccountPeerCannotDeliverMalformedCurrentMembershipCarrier()' \ + game-session-service + + - name: Upload Account membership readback socket mTLS proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-membership-readback-mtls-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/crossServiceTest/TEST-*AccountMembershipAuthorityGrpcMtlsCrossServiceTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run Account membership PostgreSQL readback socket mTLS proof + if: ${{ !cancelled() && matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:crossServiceTest \ + --tests crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest#realMembershipSnapshotAndSequenceZeroBaselineCrossPostgresAndAuthenticatedSocket()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest#retainedInactiveLeftAndReactivationSnapshotsCrossPostgresAndAuthenticatedSocket()' \ + game-session-service + + - name: Upload Account membership PostgreSQL readback socket mTLS proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-membership-postgresql-readback-mtls-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/crossServiceTest/TEST-*AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run registered Game Session issuer projection Redis component proof + if: ${{ !cancelled() && matrix.module == 'game-session-service' }} + run: | + ./gradlew :game-session-service:integrationTest \ + --tests integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#authenticatedCurrentBootstrapAndContiguousEventUseDeterministicPersistentSnapshots()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#authenticatedSequenceZeroAbsenceBootstrapsWithoutEventIdentityOrAdmissionEvidence()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#gapAndAuthenticatedOlderDuplicateHaveDistinctNoMutationOutcomes()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#staleExpectedBytesAreNonMutatingThroughTheRegisteredOwnerScript()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#unknownOrDuplicateJsonFieldsQuarantineWithoutChangingBytesOrTtl()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#expiringProjectionIsQuarantinedWithoutChangingItsBytesOrExpiration()' \ + --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#ownerPrincipalCannotInvokeEvalDirectly()' \ + game-session-service + + - name: Upload registered issuer projection Redis proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-session-issuer-projection-redis-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/integrationTest/TEST-*IssuerAuthorityProjectionRedisIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Game Session management owner UUID PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | @@ -1149,6 +1229,88 @@ jobs: fi echo "::endgroup::" + - name: Verify Account tenant-generation source PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#atomicallyAdvancesEnrolledTenantSourceAndReadsBackExactCheckpointWithoutAccountFenceChange()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#exactRetryRecoversOriginalEventAfterLaterTenantAdvances()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#historicalReadbackReturnsRequestedEventAndCurrentSourceFromOneTenantFence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#concurrentHistoricalReadWaitsForTenantFenceAndReturnsConsistentCurrentEvidence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#concurrentExactRequestSerializesAndCommitsOneTenantEvent()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#unknownTenantStaleBindingAndChangedRetryFailWithoutEnrollmentOrMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#sequenceZeroRequiresOriginalBaselineAndPositiveHistoryRequiresBothCountersToProgress()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#persistedNumericTenantScopeEvidenceIsRejectedWithoutChangingSourceState()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#historicalReadRejectsMissingRetainedPayloadAndCurrentReadRejectsChangedDigestEvidence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#appendFailureRollsBackTenantSourceAndOutboxTogether()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#transactionLocalReadbackFailureRollsBackTenantAdvance()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantAuthorityProducerPostgresIntegrationTest#unavailablePostCommitReadLeavesDurableEventAndExactRetryRecoversIt()' \ + account-service + + - name: Upload Account tenant-generation source PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-tenant-generation-source-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*TenantAuthorityProducerPostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Verify Account logout-all source PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#commitsAccountGenerationFenceClosedEventCheckpointAndImmutableReceiptTogether()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#exactRetryRecoversOriginalResultAfterLaterSourceAdvanceWithoutRewritingCounters()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#changedRequestBindingsConflictWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#concurrentExactRequestCommitsOnlyOneAuthorityAdvanceAndEvent()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#eventInsertFailureRollsBackGenerationFenceCheckpointAndReceipt()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#sourceCounterOverflowFailsBeforeAnyCutoffMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#passwordResetThenLogoutAllPreservesBothReceiptsAndResetRetry()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#logoutAllThenPasswordResetValidatesMixedLatestSourceAndPreservesLogoutReceipt()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#currentSourceReadbackProvesPristineAccountAndRejectsUnknownAccountWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#historicalReadbackPreservesMixedEventsWhileReturningCurrentSourceAndResetRetryStaysSuperseded()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#invalidHistoricalSelectorsFailWithoutChangingAnyAccountSourceEvidence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#historicalReaderHoldsAccountFenceThroughSelectedAndCurrentSourceReadback()' \ + account-service + + - name: Upload Account logout-all source PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-logout-all-source-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountLogoutAllAuthorityProducerPostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Verify Account generation projection PostgreSQL and Redis proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountGenerationProjectionPostgresRedisIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountGenerationProjectionPostgresRedisIntegrationTest#installsPristineAccountBaselineFromCurrentDurableSourceAndReadsItBackExactly()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountGenerationProjectionPostgresRedisIntegrationTest#accountCoordinationPrincipalCannotInvokeEvalDirectly()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountGenerationProjectionPostgresRedisIntegrationTest#projectsActualPasswordResetAndLogoutAllCheckpointsWithoutRewritingSqlHistory()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountGenerationProjectionPostgresRedisIntegrationTest#unknownAccountCannotSynthesizeProjectionOrChangeSourceRows()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountGenerationProjectionPostgresRedisIntegrationTest#malformedExpiringAndAheadRedisValuesAreNeverOverwritten()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountGenerationProjectionPostgresRedisIntegrationTest#staleSourceCandidateCannotReplaceAProjectionFromANewerAccountCommit()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountGenerationProjectionPostgresRedisIntegrationTest#absentProjectionRacingAnAccountAdvanceReturnsSourceChanged()' \ + account-service + + - name: Upload Account generation projection PostgreSQL and Redis proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-generation-projection-postgresql-redis-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountGenerationProjectionPostgresRedisIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Verify Account issuer authority PostgreSQL proof cases if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | @@ -1266,6 +1428,24 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceRepositoryIntegrationTest#directDeletionOfIssuanceOperationOrResponseEnvelopeIsRejected()' \ account-service + - name: Verify Account current recipient source composition PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#postJoinSnapshotCarriesCurrentCompositeSourcesWithoutRewritingMembershipEvent()' \ + account-service + + - name: Upload Account current recipient source composition PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-current-recipient-source-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: 🔎 Verify Account authority exhaustion rollback proof if: ${{ matrix.module == 'account-service' }} run: | @@ -1276,8 +1456,18 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationIntegrationTest#compositeSnapshotBlocksIssuerAndTenantAdvanceAndKeepsScopeSetsIndependent()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationIntegrationTest#exhaustedAccountCountersRollbackTheWholeCallerTransaction()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepositoryIntegrationTest#exhaustedSequenceRejectsAppendWithoutChangingEventCheckpointOrCallerSentinel()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepositoryIntegrationTest#missingHeadWithNoExactHistoryIsEmptyDespiteAnotherStreamsRetainedEvent()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepositoryIntegrationTest#databaseRejectsDeletingAHeadWithRetainedHistoryWithoutChangingEvidence()' \ account-service + - name: Preserve Account authority outbox history PostgreSQL XML + if: ${{ !cancelled() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-outbox-history-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountAuthorityOutboxRepositoryIntegrationTest.xml + if-no-files-found: error + - name: 🔎 Verify Account committed connect source readback proof if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | @@ -1430,7 +1620,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/build.gradle.kts b/build.gradle.kts index b65fe5e93f..804301fd4e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -225,15 +225,17 @@ subprojects { dependencies { implementation(platform(libs.findLibrary("spring-boot-dependencies").get())) testImplementation(platform(libs.findLibrary("spring-boot-dependencies").get())) - implementation(libs.findLibrary("protobuf-java").get()) - implementation(libs.findLibrary("grpc-netty-shaded").get()) - implementation(libs.findLibrary("grpc-protobuf").get()) - implementation(libs.findLibrary("grpc-stub").get()) - implementation("javax.annotation:javax.annotation-api:1.3.2") - testImplementation(libs.findLibrary("spring-boot-starter-test").get()) - testImplementation(libs.findLibrary("spring-boot-starter-restclient-test").get()) - testImplementation(libs.findLibrary("spring-boot-resttestclient").get()) - testImplementation(libs.findLibrary("spring-boot-starter-webmvc-test").get()) + if (name != "common-redis-contracts") { + implementation(libs.findLibrary("protobuf-java").get()) + implementation(libs.findLibrary("grpc-netty-shaded").get()) + implementation(libs.findLibrary("grpc-protobuf").get()) + implementation(libs.findLibrary("grpc-stub").get()) + implementation("javax.annotation:javax.annotation-api:1.3.2") + testImplementation(libs.findLibrary("spring-boot-starter-test").get()) + testImplementation(libs.findLibrary("spring-boot-starter-restclient-test").get()) + testImplementation(libs.findLibrary("spring-boot-resttestclient").get()) + testImplementation(libs.findLibrary("spring-boot-starter-webmvc-test").get()) + } testRuntimeOnly(libs.findLibrary("junit-platform-launcher").get()) if (projectDir.parentFile.name == "services" && !name.startsWith("common-")) { testImplementation(testFixtures(project(":common-test-support"))) 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 abfe427775..12be4e0f59 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 @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Basic JWT/JWKS and account/tenant token-state foundations exist, but the accepted single-record contract is not implemented end to end. Current issuance still writes scope-duplicated account/tenant keys, downstream validators do not consistently enforce `session:auth:token:`, and complete authority-generation checks, token-profile count/encoded-byte/total-size bounds with pre-signing and pre-registration rejection proof, per-token `/auth/logout`, `/auth/logout-all`, durable operation evidence, retry classification, cleanup, and revocation proof remain incomplete. +The single-record registry, complete immutable authorization bundle and ordinary-token issuance/revocation contract are not implemented end to end. Unwired source receipts and focused component proof do not authorize credentials or enable logout routes; current runtime still uses legacy session keys. Current capability, executed proof and activation limits are owned by [Player Access and Session](../../project-management/implementation-tracking/player-access-and-session.md#current-status). ## Decision Record diff --git a/design/architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md b/design/architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md index 6ec47623ff..1572d7625d 100644 --- a/design/architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md +++ b/design/architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The monotonic generation contract is target state and is not fully implemented or proved. The current Unit 1B draft adds durable generation-storage primitives, initializes the Account UUID scope for newly registered global accounts, idempotently enrolls the exact Account JWT issuer at startup, and enrolls retained Account and approved tenant UUID scopes without resetting advanced state. Account V33 adds separately sequenced, immutable authority-outbox storage, and the current explicit first-JOIN candidate emits one canonical membership event with its committed membership, role snapshot, audit, receipt, and operation in an Account transaction. That candidate still needs executed PostgreSQL proof; retained inactive reactivation denies without a canonical current INACTIVE event. Event delivery and Redis projections, the fenced runtime membership snapshot and Game Session consumer, complete authority-mutation composition, transactional token issuance/revocation ordering, and cross-scope validation proof remain outstanding. Account runtime still uses legacy session keys and incomplete issued-token/auth-generation enforcement; the runtime membership RPC remains denied. +The complete monotonic-generation and revocation contract remains unimplemented end to end. Durable source, membership and unwired authenticated-consumer components have focused proof, but they do not supply a complete ordinary-token authorization bundle, delivered revocation or production admission. The live membership RPC and unproved credential paths remain denied. [Player Access and Session](../../project-management/implementation-tracking/player-access-and-session.md#current-status) owns current implementation, executed proof and remaining activation gates. ## Decision Record diff --git a/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md b/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md index 4525dd0ad0..f31dda9f8c 100644 --- a/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md +++ b/design/architecture/decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -This decision is not implemented. The shared Redis-contract foundation, owner-local descriptor contributions, repository aggregation, ownership enforcement, and descriptor-driven proof remain gaps. +This decision is partially implemented. The narrow `common-redis-contracts` module provides immutable descriptors, explicit prefix ownership and invocation validation for role, principal, script identity/digest, key/argument arity and cluster slots. It has no executable owner scripts or automatic runtime wiring. Complete repository aggregation, existing-script/prefix coverage, ownership enforcement, descriptor-driven generic CI, rollout/coexistence evidence and deployed role/ACL proof remain gaps; a selected registered invocation does not establish those global guarantees. Current proof status remains in the [Shared Runtime tracker](../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#capability-status). ## Decision Record diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 9a1d31ca1b..3446560c60 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -59,7 +59,7 @@ Manages user accounts and authentication for the platform. It stores profile dat - **Internal:** - Logging & Admin Service for audit logging. - Game Session Service consumes tokens to create gameplay sessions. -- **External:** PostgreSQL for account data, Redis for transient session data. +- **External:** PostgreSQL for account data, Redis for transient session data. Account is the sole writer of its canonical generation projections; the owner-local [Account generation snapshot projection](./runtime-and-data.md#account-generation-snapshot-projection) defines its exact storage, reprojection and readback consequences. This boundary does not grant Game Session write authority or establish production authorization, reset recovery or deployed Redis readiness. > See [**Gateway Architecture**](../../system-architecture-gateway.md), [**Deployment Environments**](../../infrastructure/deployment-environments.md), diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index f1a062dd8f..a37610c09f 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -126,7 +126,7 @@ Profile gRPC read payloads carry the exact persisted canonical `accountId` and i - `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). -- `GetTenantMembershipForRuntime` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. The request carries typed `PlayerExecutionContext`; the method is not exposed through the bearer-token public-method list and accepts only the exact Game Session peer. The Account handler still fails closed before producer/data access because authenticated caller/target evidence is unavailable. The held-back same-snapshot candidate carries the exact one-tenant `membershipVersion` map, independent authority generation, canonical event content separately from its checkpoints, and exact caller/target/request echoes; Game Session recomputes the event digest and compares the event with the response. Sequence zero carries no event. These component checks do not establish a live authenticated snapshot, complete producer/consumer proof, or runtime activation. +- `GetTenantMembershipForRuntime` (request carrying typed `PlayerExecutionContext`) – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. The proto and Game Session consumer carry the typed player context with canonical Account/tenant UUIDs. The method is not exposed through the bearer-token public-method list and accepts only the exact Game Session peer. The candidate Account encoder and Game Session reader validate the current source/checkpoint inventory separately from the unchanged historical membership event under [Authentication's source/recipient boundary](../../system-architecture-authentication.md#authority-source-events-and-recipient-evidence); zero membership sequence has no membership event and grants no admission, even when other applicable source streams have advanced. The Account handler still fails closed before the candidate producer/data read. A live authenticated same-snapshot response, complete producer/consumer proof, and runtime activation remain incomplete. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context. The current tenant-only proto/request lacks both complete alternatives, so the direct gRPC handler fails closed before the underlying producer read; Game Session's older consumer request must be converged before admission can rely on this route. Logging & Admin and `control-ui` callers use the redacted route variants. - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. The currently exposed `GetRealmAccessGrantForRuntime` request cannot carry that lifecycle-bound typed caller/target evidence and its direct gRPC handler fails closed before reading grant data. @@ -152,6 +152,12 @@ The private digest frame starts with its domain and then each field in the decla The stored receipt and event must be read back exactly before success, including after a lost response. Concurrent retries serialize on the exact Account/source scope and one-use token claim; token consumption, password mutation, authority advance, event append and receipt insertion roll back together on any failure. Receipt cleanup remains Account-owned and must prove its retained recovery/replay horizon, holds and references before deletion; expiry alone is not deletion proof and no fixed retention interval is invented here. The current candidate composes this Account-local producer and immutable receipt; it does not implement downstream event delivery, authenticated recipient readback, projection consumption, or active-binding termination. The capability and execution gates remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +### Account-Owned Account Source Readback + +Account's owner-local source readback selects one exact canonical Account UUID, locks its persisted identity/credential row and Account source generation/issuance-fence rows in producer order, and holds those locks through the complete current and selected historical read. It does not enroll missing authority. The current snapshot binds the exact Account source scope, positive generation/source version, actual local issuance fence, derived stream and latest checkpoint/event. Sequence zero requires the original positive 1/1 source baseline and proved absence of committed stream history; event identity, digest and payload are absent at zero. A positive checkpoint must match the exact latest closed [password-reset](../../system-architecture-authentication.md#account-password-reset-source-event) or [logout-all](../../system-architecture-authentication.md#account-logout-all-source-event) event and its immutable operation receipt. Unsupported event types or contradictory source, receipt or checkpoint content fail closed. + +A historical selector is a positive outbox sequence in that exact Account stream. Readback returns the unchanged requested event together with the current source snapshot, validates its complete canonical payload/digest and immutable receipt binding, and rejects missing, cross-scope or ahead-of-current evidence. A later password reset does not erase the prior reset source event or make its old verifier current authority: historical source validation proves the original receipt, while password-reset operation recovery still requires its original current-password postcondition and deadline. Source readback cannot recover a superseded password-reset result, return credentials, supply recipient authorization, or substitute for the complete Account evidence bundle. The source snapshot carries no password verifier or private operation receipt. Authentication, transport, event delivery, projection consumption and live activation are separate proof obligations; an owner-local reader alone enables none of them. + ### Account-Owned Issuer Authority Advance and Readback An issuer authority operation binds the exact configured Account `issuerId`, a caller-retained canonical non-nil UUID `requestId`, and the expected positive persisted generation and source version. Its operation identity is the exact `{issuerId, requestId}` pair; requests for another issuer are rejected, not redirected or normalized. One successful operation compare-and-advances both counters by one and commits the [issuer generation source event](../../system-architecture-authentication.md#issuer-generation-source-event) and outbox checkpoint atomically. Its stable event ID is `account-issuer-authority-event-v1:`; its complete immutable event binds the resulting counters, exact issuer scope and sequence. There is no individual Account selector or issuance fence. Missing, contradictory, stale or overflowed source evidence fails closed before reporting success; this operation does not enroll missing authority or rotate JWT keys. @@ -166,6 +172,12 @@ The dedicated internal `account.v1.IssuerAuthorityService/ReadIssuerAuthorityFor The closed response uses `schema_version=account-auth-issuer-source-readback/v1`, exact `target_namespace` and `request_id`, the complete `source_snapshot`, and `requested_event_canonical_json` present only for the explicit historical selector. The snapshot carries exactly the issuer, derived scope and stream, generation/source version and checkpoint sequence as canonical decimal strings, plus the complete canonical latest event only at positive sequence. Historical selection additionally returns the exact requested event's canonical JSON. The receiver rejects unknown fields, mismatched scope/request/namespace, incorrect presence, changed event bytes/digest, regressed or ahead-of-snapshot evidence, and malformed counters; consumer comparison is arbitrary precision. Denials return a terminal gRPC status without partial source content. This transport cannot advance authority, enroll a source, return a recipient tuple/fence, install a projection or admit gameplay. Its candidate handler and client remain unwired until producer, mutual peer authentication, same-snapshot readback and negative proof pass. +### Account-Owned Tenant Authority Source Advance and Readback + +The owner-local tenant generation operation binds an already-enrolled canonical tenant UUID, stable canonical operation UUID and exact expected positive source generation/version. Its immutable operation key is the exact `{tenantId, requestId}` pair, consistent with per-source-stream outbox identity; a request UUID in another tenant stream is a distinct scoped operation, not recovery of the original or proof of authorization for that tenant. Account compare-and-advances that tenant row and commits its distinct [tenant generation source event](../../system-architecture-authentication.md#tenant-generation-source-event) with the exact tenant-stream checkpoint atomically, then reads back the complete durable result before returning it. A changed original expected state or persisted binding conflicts; an exact retry after later advances returns its original event without another mutation or reset to sequence zero. Missing source enrollment, contradictory pristine history, gaps, overflow or mismatched event/checkpoint deny. This component neither initializes identity associations nor changes a recipient Account fence. + +Current and selected historical source evidence must come from one fenced Account snapshot, with historical content kept distinct from current progress. Sequence zero requires the proved positive original baseline and absence of committed stream history. This primitive is not an authenticated endpoint or gameplay authority. Its future caller must authorize a tenant-wide cutoff before mutation; authenticated producer/consumer, derived projection/delivery and complete recipient readback remain required. Subscription/billing transitions retain their independent billing-ledger/cutoff composition and cannot be implemented by relabeling this event or substituting its outbox sequence for `tenantBillingSequence`. Detailed implementation and proof status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + ### Operator Authorization References `IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, and the immutable `authorityEvidenceBundle/v1`; Account never exposes that evidence through an external route, logs, audit text, or client-visible response. @@ -289,6 +301,10 @@ Every tenant-targeted request identifies its tenant in the route or request cont The canonical token refresh, replacement, generation, revocation, fencing, logout, and retry contract is defined in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). At this Account boundary, `/auth/logout` and `/auth/logout-all` accept the declared request identity, apply the Account-owned durable registry/authority mutation, and publish the local audit/outbox consequence. Raw JWT values are not exposed in API responses or local evidence. The current legacy Account session-key implementation does not yet provide the target registry-backed retry proof. +For `AuthLogoutAll`, Account durably binds the canonical operation UUID, request-digest version and exact digest, operation kind `ACCOUNT_LOGOUT_ALL`, canonical Account identity, exact accepted token profile and presented-token hash to one immutable lifecycle result. The source primitive verifies the canonical `ACCOUNT_LOGOUT_ALL` request digest defined by [ADR 0035](../../decisions/adr-0035-single-record-issued-token-registry.md#durable-idempotency-evidence-and-retry-semantics) before an initial mutation; receipt and readback retain the same profile binding. The initial authorized commit advances the Account source generation/version and applicable local issuance fence together with the closed [Account logout-all source event](../../system-architecture-authentication.md#account-logout-all-source-event), its exact outbox checkpoint and that receipt. The private numeric Account association is verified independently; it is not a public identity. Source-only producer primitives do not perform the required token-registry/bundle authorization or enable a public route. + +After the local token validation required by [ADR 0036](../../decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md#lifecycle-only-logout-retry-exception), exact recovery checks the original request, digest, kind, token profile and token identity and reads back the same committed receipt and event. A changed caller binding conflicts; later server-resolved authority counters do not rewrite the original request or cause a second cutoff. Recovery returns only the stored lifecycle result, never credentials or reusable authorization evidence. Missing or contradictory durable readback fails closed. The Account source stream can contain both declared password-reset and logout-all events; each historical event retains its own closed schema and digest, and neither type may be relabeled as the other to prove a current checkpoint. + ## Runtime Membership and Entitlement API Consequences The canonical membership, entitlement response shape, freshness, and sequence contract is [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). This API document retains only the local surfaces and transport consequences: diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index cf26b69e0c..782b2b6577 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -28,11 +28,11 @@ Account V25 enforces the live tenant-scoped profile identity `(tenantId, account Account V29 keeps the numeric `accounts.id` primary key and adds an immutable canonical `account_uuid` per Account. Retained rows receive `ACCOUNT_V29_MIGRATION` provenance and a source numeric row equal to their unchanged primary key; an Account insert trigger binds new rows to their numeric key, while `AccountRepository` assigns UUIDs with `ACCOUNT_REPOSITORY_INSERT` provenance and verifies exact persisted identity readback. Database uniqueness constraints prevent duplicate UUID/source mappings. Authentication responses and their signed Account subject now consume that persisted UUID after exact provenance/source-row checks. Account-qualified self-service selectors and subject-bound profile RPCs compare the canonical UUID before Account resolves its private row key; this lookup neither enrolls nor repairs missing identity. Other resource DTOs, bootstrap/runtime requests and cross-owner consumers still have numeric migration gaps, and this Account-local bridge creates no tenant UUID mapping. Focused migration/immutability execution and consumer limits remain in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md); local PostgreSQL cases skip when Docker is unavailable. -The current Unit 1B authority and membership candidates build on distinct V31–V36 migrations for issuer/account/tenant generations and fences, roles, immutable authority events, retained Account enrollment, connect issuance/envelopes, and pair authority. The v1 event preserves the exact one-tenant `membershipVersion` map, complete committed event and role evidence, and immutable history; a producer may derive a local numeric value only after validating that map. A never-joined pair may expose a positive version/generation baseline at sequence zero only after same-fence pair provenance and row/receipt/event absence proof; that baseline never admits gameplay. The first JOIN advances version and event sequence from the baseline, advances generation only when caller-bound authority was invalidated, and commits membership, roles, event, receipt, audit, and terminal operation evidence together. Retained positive history is never renumbered; contradictory or unproved inactive retained rows remain denied. V40 creates transition receipts and V41 protects their immutability while preserving valid insertion/stream-head advancement. The unwired Account-owned LEFT transition is V42: it changes only an already-proved retained ACTIVE pair to retained INACTIVE, preserves roles, advances membership version/generation, and records the invalidating event, receipt, audit envelope, and pair authority in one owner transaction. Its current-INACTIVE reader requires the existing pair and membership plus the exact latest positive LEFT receipt and matching checkpoint/event/fence; replay after reactivation is historical readback, not current authority. The newly composed migration/LEFT sequence has not executed against PostgreSQL locally; historical exact-head LEFT proof remains recorded separately in the tracker. Public route authentication and runtime enablement remain absent. Runtime RPCs, event delivery/projections, Game Session consumption, fresh-tenant UUID handoff, old-issuer fencing, and complete token issuance remain open. V35 issuance/envelope and key-ring delivery are not production-wired; detailed proof and rollout limits belong in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). +Unit 1B adds V31 positive authority-generation rows and an Account-local issuance fence, enrolls the exact JWT issuer idempotently at startup, initializes new global Account UUID generation and fence during registration, and enrolls canonical tenant generations only after approved retained-association readback. V34 enrolls retained Account UUIDs without resetting advanced state; V33 supplies independently sequenced immutable authority events; and V36 stores durable Account/tenant pair authority, including non-admitting sequence-zero snapshots. V40 stores membership transition receipts and V41 protects their immutability; V42 adds the held-back LEFT lifecycle component without rewriting retained positive history. JOIN and that LEFT lifecycle component write membership evidence under the Account owner transaction. The membership producer now composes current issuer, Account, tenant, and membership evidence into the closed supported recipient carrier; the proto/encoder carries it, and the client, adapter, and PLAY consumer validate it. This transport remains unwired: the active Account RPC denies before producer/data access, so it does not establish live membership reads or gameplay admission. Event delivery and Redis projection, fresh-tenant positive JOIN, old-issuer fencing, and token issuance remain incomplete. V35 connect-issuance operation/envelope storage remains unwired; production issuance still uses the legacy path, with key-ring deployment and exact-result recovery proof open. Detailed capability and proof status remain in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). The fresh-tenant Account consumer is a UUID-only owner boundary, separate from retained-manifest import and membership authority. The Account normal workload authenticates to Game Design's `ResolveFreshTenantCreation` read, verifies the closed operation-bound request, digest, source, and receipt evidence, then stores an immutable canonical-UUID association under a claim index shared with retained associations; that index rejects conflicts regardless of which evidence path arrives first. Unknown response fields fail closed rather than extending this evidence implicitly. Only after exact source readback may Account commit the association and invoke existing tenant-generation initialization without resetting existing state. Both the fresh-source client and the distinct retained-association client require file-backed workload mTLS and the configured workload namespace; before accepting response content they verify the exact Game Design server workload URI under the [cross-service trust owner](../../system-architecture-security.md#cross-service-trust), not merely a trusted CA or DNS name. Missing, ambiguous, another-service or cross-namespace server identity denies the read. The #2915 source and association components now have passing focused PostgreSQL proof, with the limits recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md); mocked client and local TLS construction are not live authenticated handoff or activation proof. They create no numeric Account tenant alias or selector and enable no runtime path. The identity direction is owned by [Multi-Tenancy](../../system-architecture-multi-tenancy.md#canonical-identity-and-retained-key-bridge), and Game Design's evidence contract by its [API contract](../game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback). -The V38.1 candidate adds the immutable fresh UUID association without a numeric tenant alias. V39 extends the existing pair authority table for that UUID-only association: a fresh pair has no legacy numeric tenant key, while an approved retained pair keeps its positive one-to-one bridge unchanged. Contradictory preexisting fresh numeric keys abort migration without reinterpretation or deletion. A fenced fresh-UUID producer reads back the exact immutable association and constructs the existing complete, nonadmitting never-joined snapshot from its positive pair baseline and pristine upstream authority. It does not create membership or event history, support fresh positive JOIN, reset progressed authority, or enable the runtime RPC; canonical request propagation, advanced source-event support and their producer/consumer proof remain open in the tracker. +V38.1 stores the immutable UUID-only fresh association. The V39 candidate extends pair authority to the UUID-only fresh-tenant association while preserving the approved retained numeric bridge; contradictory preexisting fresh numeric keys abort migration. Its fenced producer reads back the immutable fresh association and composes a non-admitting never-joined snapshot from the positive pair baseline and current upstream source evidence. It creates no membership or event history, does not support fresh positive JOIN, and does not enable the runtime RPC. Current recipient composition and the unwired Account/Game Session transport validations are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md); neither is live admission proof. V35 and the bare-LOGIN migration now named V37.1 retain their originally published numeric storage definitions. V39.1 permits the UUID storage-shape transition only when the entire operation/envelope table set is locked and empty; retained evidence blocks unchanged pending separate Account-owned audited recovery, never an inferred identity mapping. Old-writer quiescence, exact database proof and activation limits are recorded in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). @@ -44,17 +44,17 @@ Registration creates only a global Account row and platform-scoped audit evidenc Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. -Current Account membership, entitlement, and grant runtime handlers fail `FAILED_PRECONDITION` before data access because caller/target binding is unavailable; no live membership snapshot or composed admission is established. Game Session's typed supplied-authority consumer and Account's fenced snapshot reader remain held-back components, not runtime activation. See the following contract/status sections and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +The held-back runtime membership carrier now contains Account/tenant identity, `authorityAvailability`, membership existence/admission/lifecycle/version/generation, roles, evaluation time, the membership baseline, request echoes, `authorityTuple`, `issuanceFence`, and source/checkpoint evidence. The Account proto/encoder carries this closed supported carrier; the Game Session client/adapter/PLAY validate it, including recipient binding and freshness. Unsupported private-grant or billing authority is rejected rather than inferred. This validates the candidate current recipient carrier, not a complete immutable ordinary authorization bundle or live admission: the active Account RPC still returns `FAILED_PRECONDITION` before producer/data access, so text `PLAY` remains unavailable on that path. The current entitlement response likewise lacks the complete Account-authenticated bundle, caller/target binding, authority tuple, billing cutoff, checkpoint set, and fence evidence required by the target contract. Its consumer checks only the represented tenant, positive entitlement version, and evaluation-time fields; this subset does not establish complete snapshot or fence proof. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present. The membership RPC request carries typed `PlayerExecutionContext`, but the active Account handler still denies before producer/data access; candidate transport and consumer validation do not activate it. Account REST connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipLifecycleState`, `membershipVersion`, and `evaluatedAt`. It admits only an existing `ACTIVE` admitting membership; on an eligible public-production target, missing or explicit `INACTIVE` membership may return `JOIN_REQUIRED`, while another present non-admitting state is rejected. Non-public REST realm discovery, character listing, and connect-token issuance now fail closed even when the legacy four-field grant row exists, because it cannot prove the current lifecycle and state generation. The target lifecycle-qualified grant authority is not implemented. Public-production discovery and explicit `JOIN` retain their existing behavior, but connect-token issuance currently fails closed and produces no successful selected-target credential until the complete evidence path is available. Issuance does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes `JOINED` only from exact positive operation/membership/provisional-receipt/audit proof and `ALREADY_ACTIVE` only from matching positive retained receipt history and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. The current cached-success connect-token path rechecks current public-target eligibility, membership lifecycle/admission, and entitlement before failing with retryable `AUTH_UNAVAILABLE` when complete selected-target evidence is unavailable; it does not return the cached success. Fresh success likewise remains denied until the independent same-snapshot membership map/generation/issuance-fence proof and durable registry-backed issuance exist. This guard is not a complete Account-signed `gameplay-connect` producer or live path. The unwired Account component reads an original successful V35 connect-issuance operation and its exact purpose-bound encrypted response envelope under the Account row fence. Its local successful-envelope payload is the strict UTF-8 compact Account JWT, not a reconstructed token or a second credential. It verifies the independently signed Gateway context, the exact Game Session workload identity, Account UUID provenance and the exact canonical tenant association, the stored token hash and identity, the original Account signature/profile, and complete original source/context correspondence. Fresh tenant provenance comes only from the immutable V38.1 owner association; retained tenant provenance comes only from the approved bridge and current retained-source digest. Neither path infers a numeric tenant alias. It rechecks the unchanged source and context deadlines after any fence wait. Its immutable result is original-source evidence only: stored authority/postcondition digest binding is not proof of current authority, registry readiness, or admission. This component is not registered as a runtime credential producer or RPC handler; live fresh tenant handoff, complete Account-authenticated evidence, current-authority and registry consumption, protected key delivery, and end-to-end exchange remain separate activation gates. Focused proof status is recorded in the [player access and session tracker](../../../project-management/implementation-tracking/player-access-and-session.md). -The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. The membership request carries typed `PlayerExecutionContext` with exact canonical Account/tenant UUIDs rather than private numeric row keys. Its held-back encoder validates the canonical selected target and exact identity echoes; the unwired producer resolves fresh UUIDs only through V38.1 evidence and retained UUIDs through the approved association and current source digest under the Account fence. Game Session rejects invalid Account/tenant UUID selectors before making the call. Account's handler still denies before producer/data access with `FAILED_PRECONDITION`: the canonical session/catalog handoff and authenticated complete producer/consumer proof remain incomplete. This typed request is not a working admission path. The entitlement and realm-grant reads retain their local request shapes and likewise remain denied until their exact caller/target contracts are carried and verified. Detailed proof and activation gates remain in the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md). +The current `application.yml` and `application-prod.yml` do not classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. The membership request uses typed `PlayerExecutionContext` with canonical Account/tenant UUIDs; the held-back producer resolves fresh UUIDs through V38.1 evidence and retained UUIDs through the approved association under the Account fence. The candidate client and PLAY consumer reject invalid Account/tenant UUID selectors before making the call and validate the closed recipient carrier, while the active Account handler still denies with `FAILED_PRECONDITION` before producer/data access. The candidate is therefore not a working admission path; runtime activation and authenticated end-to-end proof remain open. Entitlement and realm-grant reads also remain denied until their caller/target contracts are carried and verified. Detailed current proof and activation gates remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). -The unwired Account snapshot reader builds a one-tenant version map, four ordered checkpoints, and separate positive source-event evidence from one fenced transaction. Sequence zero is allowed only with same-fence positive absence/provenance and baseline checks; advanced upstream history without its event proof fails closed, and the account-local issuance fence is preserved. This is a component, not an authenticated gRPC response or admission path. +The unwired current-recipient membership producer now composes issuer, Account, tenant, and membership source/checkpoint evidence under one Account owner fence, preserving immutable membership events as historical evidence while validating current recipient state. Its response candidate carries the supported authority tuple, issuance fence, ordered checkpoints, and source evidence; the closed Game Session validators reject incomplete or contradictory content. Sequence-zero reads remain non-admitting and require a positive pair baseline plus proved absence history. This candidate producer and its consumer do not authenticate a live RPC or enable the denied method or Game Session admission; detailed composition and proof limits are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). -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 deny even the exact Game Session peer until Unit 1B provides typed caller/target binding. Focused negative tests cover the local guards, but composed certificate and consumer proof remains open; REST guards alone do not protect direct gRPC calls. +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. @@ -154,6 +154,14 @@ If you change Redis usage for this service, you must read and apply: - [Redis Cache & Rate Limiting](../../system-architecture-redis-cache.md) - [Redis Operations & Migrations](../../system-architecture-redis-operations.md) +### Account Generation Snapshot Projection + +Account alone writes `session:auth:generation:account:` under the ownership and generation rules in [ADR 0036](../../decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md). The Account-local physical record uses `schemaVersion: "account-auth-account-generation-projection/v1"` and exactly `accountId`, `accountAuthorityGeneration`, `sourceVersion`, `outboxStreamKey`, and `outboxSequence`, with `sourceEvent` present only for a positive checkpoint. The generation, source version and sequence are canonical decimal strings; only the sequence permits zero. The Account UUID and source stream must match the persisted association and owner-local [Account source readback](./api-contracts.md#account-owned-account-source-readback). `sourceEvent` retains the complete exact canonical JSON of the latest declared reset or logout-all event as a string, rather than copying its fields into another event schema. A proved original positive 1/1 source baseline has sequence zero and omits `sourceEvent`; a missing Redis key is not proof of that baseline. + +This is current-snapshot reprojection by the source owner, not delivery-consumer advancement. Account obtains the candidate internally from its fenced SQL source reader. An explicitly initialized, owner-local Coordination client using `account_coord_app` applies a registered single-key byte-exact CAS through verified `SCRIPT LOAD` and `EVALSHA`, without an `EVAL` fallback; no generic client or Game Session writer may supply authority. The complete record has no TTL. Missing or lower projection state can be installed from exact durable source evidence; a higher generation/source version/checkpoint, same-position conflict, malformed state or TTL is refused without repair. Poisoned state requires the separate audited Account recovery workflow, not a silent overwrite. A successful write or exact replay requires complete Redis readback and a fresh matching Account source readback; an intervening source advance or newer writer returns a non-converged result rather than stale success or a blind retry. + +The record stores no recipient tuple, issuance fence, token identity or time-based freshness assertion. Its source evidence does not authenticate a caller, implement the complete authorization bundle or grant admission. [ADR 0036](../../decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md#generation-authorities) still requires the complete Account bundle and exact applicable durable/projected equality for authorization. Narrower resets preserve this family; cluster-loss repair remains Account-owned and subject to the existing [reset-policy matrix](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). This storage definition does not implement or authorize reset orchestration, live ACL/cohort cutover or runtime activation. Implementation and executed proof belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + ## Session and Token Model **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. @@ -217,7 +225,7 @@ Runtime caller contract: - Minimum request fields: `accountId`, `tenantId`, `requestId`. - Target minimum response fields: `accountId`, `tenantId`, `membershipExists`, `membershipLifecycleState`, `authorityAvailability`, `roles[]`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, `authorityTuple`, `evaluatedAt`, and the applicable `outboxCheckpoints[]` entry for the membership authority stream. - `membershipAuthorityGeneration` is an opaque Account-owned value. Runtime callers compare it only for exact freshness/equality and must not infer ordering or authority from its representation. It is the authoritative generation for connect-token issuance, gameplay-token refresh, gameplay binding and reconnect validation, and membership revocation. -- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before a snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The current proto carries explicit `authorityAvailability`, string-map `membershipVersion`, and opaque string `membershipAuthorityGeneration`; the held-back response also binds lifecycle, baseline, roles, canonical UUID identity echoes, complete authority tuple, issuance fence, ordered checkpoints, and separate source-event evidence from one Account fence. Game Session's supplied-authority `PLAY` validates the complete carrier, including map, lifecycle/admission, generation, roles, tuple/checkpoint/event content and digest/response agreement, and denies unsupported advanced authority rather than resetting checkpoints. Sequence zero carries no event and is non-admitting. These local checks do not establish a live Account snapshot or admission: the Account handler still rejects before producer/data access, and same-snapshot issuance map/generation/fence comparison and durable registry proof remain open. Detailed implementation and proof limits belong in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). +- `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The held-back candidate carries that explicit availability, lifecycle, roles, the exact one-tenant version map, the authority tuple, issuance fence, checkpoints, and separate source-event evidence. Request identities and exact response echoes use canonical Account/tenant UUIDs rather than private retained numeric selectors. Game Session validates their correspondence and denies absent, unknown or unavailable availability and missing, contradictory or unsupported source evidence rather than resetting checkpoints. Current issuer, Account and tenant source evidence remains separate from the immutable membership event under [Authentication's source/recipient boundary](../../system-architecture-authentication.md#authority-source-events-and-recipient-evidence). The live Account RPC rejects before data access; neither mocked responses nor the disabled encoder establish a live Account-authenticated snapshot, fresh-UUID handoff, or admission. Detailed implementation and proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). - `GetTenantEntitlementsForRuntime(tenantId, requestId)` is the authoritative internal entitlement surface for gameplay/runtime flows. Runtime callers may cache its positive result only under the strict-new-commitment and bounded-continuity rules in [ADR 0028](../../decisions/adr-0028-differentiated-entitlement-freshness.md); the cache never becomes a second writer. - Minimum request fields: `tenantId`, `requestId`. - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `verifiedConnectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 52e8de1e2e..5e6d1db920 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -14,6 +14,8 @@ Realm-catalog identity status: Game Session pointer and audit rows persist a sep This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: +The dedicated source client, pure issuer-projection transition layer and registered owner-local Redis store remain unwired. The store uses an explicitly initialized Coordination connection rather than ambient Redis templates; it grants no recipient authorization. Executed component proof and remaining delivery, role/ACL, deployment and activation limits belong to the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md); the issuer-projection contract remains owned by [ADR 0022](../../decisions/adr-0022-account-authority-and-gameplay-session-ownership.md). + The REALMS/JOIN consumer candidate carries the canonical tenant UUID from the exact namespace-qualified owner association in Account contexts and scope targets. Its lobby record retains the private Game Session catalog key separately as local routing metadata; JOIN rechecks that key's association against the stored UUID before forwarding. Missing, nil or changed association evidence denies without Account forwarding. This consumer is not the complete Account direct-text scope/JOIN producer, whose canonical caller/tenant and catalog-authority convergence remains open in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). Mocked consumer success does not prove enabled end-to-end JOIN, and activation gates remain closed. The dedicated `AccountIssuerAuthorityClient` is an unwired source-only consumer candidate for [Account's issuer readback](../account-service/api-contracts.md#account-owned-issuer-authority-advance-and-readback). It requires file-backed mutual TLS and the exact Account server workload identity, validates current and explicitly selected historical evidence with the shared issuer-event codec, and compares canonical decimal counters without narrowing them. Its transport result is not a recipient membership snapshot, admission or rebind authorization, an installed issuer projection, or a delivered revocation. Runtime activation remains denied until the complete producer, mutual peer authentication, projection and negative proof passes; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) records executed and unavailable proof. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index f67156ad10..cdd7101023 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,6 +10,10 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: +- The source-only issuer projection has an unwired decision layer and registered owner-local atomic Redis store. Its private, explicitly initialized Coordination client does not change the existing runtime client cohort or publish a bean; role/ACL deployment, authenticated event delivery and activation are unproved. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) records the precise component and proof boundary; [ADR 0022](../../decisions/adr-0022-account-authority-and-gameplay-session-ownership.md) owns the projection semantics. + +- Command ingress carries the canonical Account UUID unchanged into V9.1's `gameplay_command.account_uuid` slot; an absent Account identity does not invent either a UUID or private numeric selector. Existing numeric row evidence is retained without guessed mapping or backfill. Retained-command replay, complete owner/consumer handoff and activation remain unproved; component implementation and proof are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). + - The management-owner UUID candidate adds `game_instances.owner_account_uuid` for the exact canonical Account identity and keeps every retained `owner_account_id` BIGINT unchanged as internal historical evidence. Unmapped retained rows have no canonical owner and cannot satisfy owner-self checks; no UUID is derived from a numeric value. New owner requests reject numeric, nil or noncanonical Account selectors before dependency calls or mutation. Inside the owner transaction, `StartSession` locks tenant rows with no canonical UUID and any status other than exact `STOPPED`, then fails with `OWNER_ACCOUNT_IDENTITY_UNAVAILABLE` if such active or uncertain legacy-owner evidence exists; this conservative refusal does not assert that a row belongs to the requesting Account. `RestartSession` rejects a missing or noncanonical owner UUID before changing the row or Redis runtime state. Stop, readback, and pre-termination compensation remain available and preserve raw numeric evidence. This is app-layer containment, not owner mapping or activation: V10.1 still permits an older binary to insert numeric-only rows or reactivate retained rows, so deployment must quiesce or otherwise fence every pre-UUID numeric-owner writer before this path is enabled. Enablement also remains gated on the owner-run deployed migration-history inventory and exact retained-owner readback recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). UUID owner storage and DTO/readback convergence do not supply the missing Account operator authorization-reference, mutation-digest or durable operator-result contracts. Runtime catalog, membership and credential activation remain held back. The focused service and repository unit classes passed with 55 and 4 cases; both Docker-backed PostgreSQL cases were skipped locally, so guard execution, row preservation and lock behavior remain unverified against PostgreSQL. - The published [#2932 gameplay carrier](https://github.com/benhook1013/FireMUD/pull/2932) carries the canonical Account UUID unchanged into V9.1's `gameplay_command.account_uuid` slot. It preserves complete existing command rows and numeric `account_id` evidence without deriving or backfilling UUIDs; retained rows without authenticated mapping cannot become canonical identity evidence. This carrier and storage do not prove retained-command replay, complete owner/consumer handoff, or caller authorization, and do not activate the denied credential and membership paths. Component implementation and proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). diff --git a/design/architecture/repository-structure.md b/design/architecture/repository-structure.md index 546b249189..33ed4452ad 100644 --- a/design/architecture/repository-structure.md +++ b/design/architecture/repository-structure.md @@ -25,6 +25,7 @@ root │ ├── automation-scripting-service/ │ ├── common-data-runtime/ │ ├── common-platform-core/ +│ ├── common-redis-contracts/ │ ├── common-saga/ │ ├── common-security/ │ ├── common-temporal/ @@ -79,7 +80,7 @@ root - `gradle/` – Gradle version catalog, build conventions, and wrapper binaries. - `k8s/` – Kubernetes base manifests, Helm charts, overlays, monitoring configs, network policies, preview/prod support assets, storage/database helpers, Velero backup assets, and Terraform modules for local and production-like clusters. - `protos/` – Versioned gRPC definitions for every service, organized by service and version as described in this directory’s [gRPC API Style & Versioning Guidelines](./system-architecture-grpc.md). -- `services/` – Spring Boot microservices plus the narrowly scoped shared platform/library Gradle modules (`common-data-runtime`, `common-platform-core`, `common-saga`, `common-security`, `common-temporal`, `common-test-support`, and `common-web-support`), including Flyway database migration scripts under `services//src/main/resources/db/migration/` and shared saga migrations under `services/common-saga/src/main/resources/db/migration/saga`. SQL-backed services use one explicit `jOOQ + Flyway` persistence model rather than a mixed long-term ORM stack, and long-running durable control-plane workflows use the shared Temporal substrate rather than service-local workflow scaffolding. ADR 0176's future narrow Redis-contract foundation does not make owner-exclusive Redis execution a shared module concern. +- `services/` – Spring Boot microservices plus the narrowly scoped shared platform/library Gradle modules (`common-data-runtime`, `common-platform-core`, `common-redis-contracts`, `common-saga`, `common-security`, `common-temporal`, `common-test-support`, and `common-web-support`), including Flyway database migration scripts under `services//src/main/resources/db/migration/` and shared saga migrations under `services/common-saga/src/main/resources/db/migration/saga`. SQL-backed services use one explicit `jOOQ + Flyway` persistence model rather than a mixed long-term ORM stack, and long-running durable control-plane workflows use the shared Temporal substrate rather than service-local workflow scaffolding. The initial `common-redis-contracts` descriptor/validation foundation follows ADR 0176; owner-exclusive Redis builders, adapters and executable Lua remain in their service. Complete repository aggregation and legacy script coverage are still open. - `web-client/` – React web application. - `.editorconfig` – Consistent indentation and newline settings across editors. - `.env.sample` – Example environment variables loaded by `docker compose` and the test suites. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index bc9986a822..a2fde92bd6 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -18,7 +18,7 @@ Issuer-wide, account-wide, and tenant-wide publisher events use distinct closed, Game Session's derived issuer-generation projection bootstraps, advances, and verifies duplicates using Account-authenticated evidence for the exact issuer scope and source checkpoint. The evidence proves the exact issuer and stream identity, committed issuer generation and source version, sequence, and complete applicable source-event identity, payload, and digest. It does not require an individual recipient's `authorityTuple`, `issuanceFence`, or complete `outboxCheckpoints` set. An accepted bootstrap or next-sequence event atomically installs the projection watermark and matching source/checkpoint evidence. A conflicting, gapped, malformed, or ambiguous source/checkpoint is quarantined and fails closed; generation-only equality is not duplicate proof. This derived revocation projection grants no admission or rebind authority. -When source evidence is used to authorize or update an individual recipient, an Account-authenticated readback binds the consumed source event and checkpoint to that recipient's complete applicable `authorityTuple`, Account's actual `issuanceFence`, and complete `outboxCheckpoints` set in one Account snapshot. Consumers compare this complete binding for recipient authorization, admission, binding, refresh, rebind, retry, and duplicate handling. The Account readback composes source and recipient evidence without a distributed transaction or per-recipient event fanout. This recipient evidence remains required for admission and rebind even when the issuer projection is current. This distinction does not alter the closed `account-auth-authority-event/v1` membership event schema below, including its declared tuple and fence fields. +When source evidence is used to authorize or update an individual recipient, an Account-authenticated readback binds the consumed source event and checkpoint to that recipient's complete applicable `authorityTuple`, Account's actual `issuanceFence`, and complete `outboxCheckpoints` set in one Account snapshot. Consumers compare this complete binding for recipient authorization, admission, binding, refresh, rebind, retry, and duplicate handling. The Account readback composes source and recipient evidence without a distributed transaction or per-recipient event fanout. This recipient evidence remains required for admission and rebind even when the issuer projection is current. This distinction does not alter the closed `account-auth-authority-event/v1` membership event schema below, including its declared tuple and fence fields. A later issuer, account or tenant advance does not rewrite an immutable membership event: its original tuple, fence, bytes and digest remain historical evidence, while the separate current recipient carrier proves the applicable current source state, complete checkpoints and actual fence from one Account snapshot. Historical evidence must not lead or contradict that proved current state, and current membership lifecycle, roles, version and membership generation must remain bound to the exact committed membership event. #### Account Password-Reset Source Event @@ -26,6 +26,12 @@ When source evidence is used to authorize or update an individual recipient, an The digest preimage is the entire declared event object excluding **only** `eventDigest`, serialized as RFC 8785 canonical JSON UTF-8. `eventDigest` is `sha256:` plus 64 lowercase hexadecimal SHA-256 digits. Receivers reject duplicate properties, unknown/missing fields, noncanonical scope/counters, mismatched cutoff evidence, and a changed field paired with the original digest. Account stores the complete canonical event with the password mutation, token consumption, source generation/version and applicable local fence advance in one transaction. The separate Account-authenticated recipient snapshot binds this event to current recipient evidence; the event never creates gameplay admission. [Account API Contracts](./microservices/account-service/api-contracts.md) owns reset operation identity and exact-result retry. Other Account change types, issuer cutoffs and tenant billing changes require their own declared closed schemas before emission; this password-reset schema must not be aliased or fabricated for them. +#### Account Logout-All Source Event + +`account-auth-logout-all-event/v1` is the distinct closed source schema for an Account-committed account-wide logout cutoff. Its required preimage fields are `schemaVersion` (exactly `account-auth-logout-all-event/v1`), `eventType` (exactly `LOGOUT_ALL_COMMITTED`), `eventId`, `requestId`, `accountId`, `sourceScope`, `outboxStreamKey`, `outboxSequence`, `accountAuthorityGeneration`, `sourceVersion`, and `accountSecurityCutoff`; its sole additional wire field is `eventDigest`. `requestId` is the canonical lowercase non-nil operation UUID and `eventId` is exactly `account-logout-all-event-v1:`. `accountId` is a canonical lowercase non-nil Account UUID, `sourceScope` is exactly `account/`, and `outboxStreamKey` is exactly `account:auth-authority:v1:`. `accountSecurityCutoff` has exactly `accountAuthorityGeneration`, `outboxStreamKey`, and `outboxSequence`, identical to those source-event fields. Generation, source version and sequence, including nested values, are canonical positive decimal strings and are parsed with arbitrary precision. No fields are optional; arrays, nulls, raw credentials, presented-token identities, recipient tuples and recipient issuance fences are absent. + +The event digest binds the entire declared object excluding only `eventDigest`, using RFC 8785 canonical JSON UTF-8 and `sha256:` followed by 64 lowercase hexadecimal SHA-256 digits. Receivers reject duplicate/unknown/missing fields, noncanonical identities or counters, mismatched cutoff evidence and changed fields with the original digest. This event does not replace the password-reset schema or authorize another mutation. Account's immutable logout operation separately binds the original request digest, operation kind and exact presented-token identity for [ADR 0036's lifecycle-only retry](./decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md#lifecycle-only-logout-retry-exception); that evidence is not copied into a scope-wide source event. Account commits the authorized account-generation/source-version and local issuance-fence advance, exact outbox checkpoint, event and immutable lifecycle result atomically. The source event alone cannot authorize a recipient; the separate same-snapshot Account readback remains necessary. [Account API Contracts](./microservices/account-service/api-contracts.md) owns initial authorization and exact lifecycle-result recovery. Shared producer/consumer vectors cover every changed field and counters beyond signed 64-bit range; SQL source counters still fail closed on overflow. + #### Issuer Generation Source Event `account-auth-issuer-generation-event/v1` is the closed source schema for one Account-committed issuer-generation advance. Its required preimage fields are `schemaVersion` (exactly `account-auth-issuer-generation-event/v1`), `eventType` (exactly `ISSUER_GENERATION_ADVANCED`), `eventId`, `requestId`, `issuerId`, `sourceScope`, `outboxStreamKey`, `outboxSequence`, `issuerAuthGeneration`, and `sourceVersion`; its sole additional wire field is `eventDigest`. `issuerId` is the exact configured Account JWT issuer identity, not an Account or tenant selector, and is never normalized or inferred. `sourceScope` is exactly `issuer/` and `outboxStreamKey` is exactly `account:auth-authority:v1:`. Request and event identities are nonempty immutable strings. The sequence, generation and source version are canonical positive decimal strings; consumers parse arbitrary precision. There are no optional fields, arrays, recipient tuples, recipient issuance fences, account/tenant IDs, cutoff objects or `null` placeholders. @@ -34,6 +40,12 @@ The digest preimage is the entire declared object excluding only `eventDigest`, Issuer bootstrap readback requires a positive persisted issuer authority row and proved absence of committed events in that exact stream in the same fenced Account snapshot; a missing stream row alone is insufficient. Its checkpoint is then sequence zero with no event ID or digest, and grants no admission. Positive readback binds the current generation/source version to the exact latest immutable issuer event, payload/digest and stream checkpoint. Historical operation retry returns its original committed event rather than reapplying an advance; it is not current recipient authorization. The receiver still requires Account authentication and atomic projection/checkpoint installation. A local codec or unwired producer does not establish that authenticated handoff or complete projection proof. +#### Tenant Generation Source Event + +`account-auth-tenant-generation-event/v1` is the distinct closed source schema for an Account-owned bulk tenant-authority generation advance. Its required preimage fields are `schemaVersion` (exactly `account-auth-tenant-generation-event/v1`), `eventType` (exactly `TENANT_GENERATION_ADVANCED`), `eventId`, `requestId`, `tenantId`, `sourceScope`, `outboxStreamKey`, `outboxSequence`, `tenantAuthorityGeneration`, and `sourceVersion`; its sole additional wire field is `eventDigest`. `tenantId` is a canonical lowercase non-nil tenant UUID already enrolled through the authoritative tenant association; neither a numeric retained key nor a guessed UUID can select this source. `requestId` is a canonical lowercase non-nil operation UUID, `eventId` is exactly `account-tenant-generation-event-v1:`, `sourceScope` is exactly `tenant/` and `outboxStreamKey` is exactly `account:auth-authority:v1:`. Generation, source version and sequence are canonical positive decimal strings parsed with arbitrary precision. No fields are optional; arrays, nulls, recipient Account identities, recipient tuples, issuance fences and billing-cutoff fields are absent. + +The digest binds the entire declared event excluding only `eventDigest`, serialized as RFC 8785 canonical JSON UTF-8 and encoded as lowercase `sha256:` plus 64 hexadecimal digits. Receivers reject duplicate/unknown/missing fields, malformed scope/identities/counters and changed fields with the original digest. Account advances the exact existing tenant generation/source version and appends the immutable event/checkpoint atomically, without enrolling a missing source or advancing an Account fence. A stable request binds the original exact expected source generation/version; exact retry returns the original committed event after later advances, while a changed binding conflicts. Source readback proves the current fenced tenant row and exact latest or selected historical event/checkpoint together; sequence zero requires the original positive 1/1 baseline and proved absence of committed history, not merely a missing checkpoint. This source-only maintenance creates no recipient authorization or admission. It does not mutate subscription state, implement billing policy or replace the independent `tenantBillingSequence`/`tenantBillingCutoff` contract: billing mutations require their own closed payload and atomic billing-ledger composition. [Account API Contracts](./microservices/account-service/api-contracts.md) owns local operation/readback consequences; authenticated consumer, projection/delivery and recipient evidence remain separate requirements. + ### Playtest Grant Admission Consequence Account's explicit grant record, bounded expiry, revision/request replay, tombstone, tenant-admin authority, and audited platform-admin break-glass mutation path are canonical in [Account API Contracts](./microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract). Authentication owns only the caller-bound consequence: private/playtest discovery, connect-token issuance, `PLAY`, reconnect, and continued gameplay require the current Account grant in addition to `ACTIVE` membership, entitlement, and exact routing evidence. Effective expiry or revocation is an immediate authority cutoff, not a grace period; Game Session consumes Account's bounded authority change and terminates affected bindings. A friendly scheduled ending uses the separate close-and-drain lifecycle before grant revocation. No JWT role, cached discovery result, or grant projection creates gameplay authority by itself. @@ -61,7 +73,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - The current Account `Authenticate` proto path still lacks the target `requestId`/immutable-digest replay envelope and orphan-token retirement contract described below; those fields and recovery semantics remain implementation/proof gaps rather than implied current behavior. - **Current reauthentication boundary:** After a gameplay binding is terminated by an authority cutoff or the bounded cleanup path, current restoration requires fresh `LOGIN` plus `PLAY` and current authoritative checks. Token refresh, replacement, revocation, fencing, and logout are owned by [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md); gameplay binding continuity, reconnect, and resume orchestration remain in [Session Behavior](./system-architecture-session-behavior.md). Fresh `LOGIN` then `PLAY` remains the client-visible reauthentication path when required. - Account's JWKS endpoint and conditional secret watcher are implemented, while complete asymmetric-profile enforcement, non-exportable signer delegation for asymmetric signing, rotation/convergence and issued-token registry issuance/storage/consumer enforcement remain open. Account-local durable generations, outbox and source-operation components exist; their scoped implementation and execution proof are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md), not claimed as complete credential issuance, distributed propagation or current-authority consumption. -- **Scoped authority-source runtime status:** The current Account password-reset candidate composes a closed source event, atomic Account mutation, generation/fence advance and immutable retry receipt. This Account-local slice does not complete issuer/tenant publishers, Account-authenticated same-snapshot recipient readback, delivery or Game Session consumption; authority-event consumer activation remains closed. Execution evidence and remaining producer/consumer obligations are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). +- **Scoped authority-source runtime status:** Account source and recipient-carrier primitives remain bounded, unwired candidates; they do not establish authenticated runtime membership, delivered revocation or admission. Authority-event consumer activation remains closed. Execution evidence and remaining producer/consumer obligations are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). ## Contract Decisions (Normative) diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index f8e04c767c..73f17225f3 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -261,7 +261,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `IssueConnectToken` | `player_bootstrap_tenant` | **Target:** caller-bound `player-bootstrap` registry validation, Account membership/entitlement authority, the exact selected `tenantAuthorityGeneration` Account evidence entry, Game Session routing authority, and one-use replay protection are required before exposure. **Current drift:** the bootstrap path still uses the legacy Account session-key shape, target registry/evidence proof is incomplete, the required membership-authority-generation reread is missing, and lifecycle-qualified grant authority is unavailable. Fresh and cached-success private/playtest issuance remain denied until that grant authority exists; a retained four-field grant row does not authorize these targets. Existing membership is required for every realm; eligible public-production membership that is missing or `INACTIVE` returns `JOIN_REQUIRED` without membership, issuance record, or token, while `ACTIVE` membership does not require `JOIN`. Global roles alone do not grant gameplay admission. | | Account Service | `Authenticate` | `internal_workload` | Exact Game Session mTLS identity, no pre-existing issued token, and trusted server-derived credential source context | | Account Service | `RefreshGameplayServiceToken` | `internal_workload` | Exact Game Session mTLS identity plus current `game-session-account-delegation` authority with audience `account-service` | -| Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | Exact Game Session mTLS identity plus current Account-issued `game-session-account-delegation` authority with audience `account-service` and validated typed player/target context. Credential-bearing `LOGIN` obtains that private token from Account authentication; bare first-party `LOGIN` requires the separate Account-owned one-use exchange over proved committed connect issuance and verified signed context. Gateway context or a connect-token `jti` alone does not authorize the read, and Game Session never passes an end-user token as a substitute. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); the RPCs remain denied until the producer and consumer proof is complete. | +| Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | The declared machine-readable rows require exact Game Session mTLS identity, exact method permission, validated typed player/target context and each route's live domain checks. Those rows accept no JWT profile and do not require an issued-token registry record; neither a generic internal-service JWT, Gateway context nor a connect-token `jti` substitutes for authenticated workload identity or context/domain validation. The distinct private-delegation requirement for Game Session entitlement reads and refresh remains unchanged in their own rows. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority); the RPCs remain denied until the producer and consumer proof is complete. | | Account Service | `GetTenantEntitlementsForRuntime` | `internal_workload` | Exactly one complete caller-policy alternative: Game Session mTLS plus current private delegation and typed player context for player admission, or World Management mTLS plus tenant/operation-bound instance-lifecycle context without a player delegation. Constraints within the selected alternative are conjunctive; no `control-ui` or Logging and Admin caller; not edge exposed. The read assesses eligibility only and never commits capacity. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Account Service | `CommitTenantCapacityAdmission` | `internal_workload` | **Target; not currently routable.** Exactly one complete caller-policy alternative is required: Game Session presents its own exact Game Session caller workload mTLS identity to Account with typed `PlayerExecutionContext` and the live player-binding checks, or World Management presents its own exact World Management caller workload mTLS identity to Account with tenant/operation-bound instance-lifecycle context and the live lifecycle checks. Account remains the receiving authority; only those alternatives may call its exact receiving mTLS boundary. The request binds `tenantId`, stable `requestId`/`admissionId`, fresh `admissionAttemptId`, current `capacityRearmFence`, the complete Account evidence bundle including its applicable `authorityTuple`, `expected_billing_evidence`, and all `outboxCheckpoints[]`, plus a bounded `capacityDelta` whose protobuf field is `optional int64` encoded as a varint and whose canonical JSON/proto-JSON spelling is `capacityDelta` encoded as a base-10 decimal string. The machine contract explicitly distinguishes omitted (`absent`) from present zero (`present_zero`), rejects JSON `null` and boolean zero, and publishes both transport-specific golden vectors. The caller-supplied `capacity_rearm_fence` is the attempt-bound fence, while Account compares the live `capacity_admission_fence` at final commit alongside the applicable generation guards. It also carries versioned `mutationDigest` over the attempt identity, fence, and complete payload. The first attempt binds those fields without a rearm; an exact retry replays, while a changed field requires the Account-owned committed rearm CAS that advances the fence and binds the fresh attempt. Any change without that CAS is an idempotency conflict before reservation, usage, activation, or routing mutation. Account performs the final fenced reservation commit and returns the committed evidence or a canonical stale/quota/unavailable outcome; until this route is implemented, capacity-changing operations fail closed. | | Account Service | `GetTenantEntitlementsTenant` | `billing_safe_tenant` | `tenantAdmin` (tenant-scoped); live `current_operator_roles` and caller-bound membership checks | diff --git a/design/architecture/system-architecture-redis-lua-patterns.md b/design/architecture/system-architecture-redis-lua-patterns.md index a8cc68a8b4..02e4da8e8b 100644 --- a/design/architecture/system-architecture-redis-lua-patterns.md +++ b/design/architecture/system-architecture-redis-lua-patterns.md @@ -421,9 +421,9 @@ Script changes must be rolled out in a way that respects both AOF replay semanti - `schemaVersion` changes must support every caller and stored-payload version in the evidenced coexistence set; unknown or ambiguous versions, including unproven missing versions, must fail before mutation with `"UNSUPPORTED_SCHEMA_VERSION"` or the equivalent so AOF replay cannot apply effects with mismatched schemas. - When a reset-required change is introduced, operators follow the reset runbooks so that any surviving AOF history for old scripts is discarded for the relevant scope rather than replayed under incompatible semantics. -## Target-State Lua Script Registry and CI Expectations (Not Implemented) +## Target-State Lua Script Registry and CI Expectations (Partial Implementation) -The registry, validators, ownership enforcement, generic test harness, and CI checks in this section are target state and are not currently implemented. Once delivered, all coordination-related Lua scripts contribute entries to one aggregated **Lua Script Registry**. The shared Redis-contract foundation owns the registry schema and aggregation; each owning service contributes entries and retains executable Lua for exclusive key families. For each script, the registry records: +The initial `common-redis-contracts` foundation validates explicitly contributed descriptors and invocation handles, including owner/prefix, role/principal, identity/digest, arity and cluster-slot checks. It does not inventory or register legacy scripts automatically. Complete repository aggregation, ownership enforcement, the generic test harness, all-script CI and deployed role/ACL proof remain target-state gaps. Once delivered, all coordination-related Lua scripts contribute entries to one aggregated **Lua Script Registry**. The shared Redis-contract foundation owns the registry schema and aggregation; each owning service contributes entries and retains executable Lua for exclusive key families. For each script, the registry records: - Script identifier and file path. - Expected `KEYS` and `ARGV` ordering and allowed prefixes (including hash-tag rules). diff --git a/design/architecture/system-architecture-shared-libraries.md b/design/architecture/system-architecture-shared-libraries.md index 3d0d7daf9b..425a5b2dc7 100644 --- a/design/architecture/system-architecture-shared-libraries.md +++ b/design/architecture/system-architecture-shared-libraries.md @@ -6,7 +6,7 @@ FireMUD's microservices share a set of narrowly scoped modules so each service c ## Implementation Status -The current `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so shared code must not synthesize an absent epoch; exact tuple propagation and final enforcement remain implementation and focused-proof gaps at that boundary. The narrow shared Redis-contract foundation, owner-local descriptor contributions, repository aggregation, ownership enforcement, and descriptor-driven proof required by [ADR 0176](./decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md) are not implemented. See the [Automation and Scheduler Runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status) for current status and proof evidence. +The current `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so shared code must not synthesize an absent epoch; exact tuple propagation and final enforcement remain implementation and focused-proof gaps at that boundary. The initial `common-redis-contracts` descriptor/validation slice follows [ADR 0176](./decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md); it is opt-in and contains no owner-exclusive execution or automatic Redis client wiring. Complete owner contributions, repository aggregation, ownership enforcement, generic CI and deployed role/ACL proof remain incomplete. Shared proof status belongs to the [Shared Runtime tracker](../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#capability-status); scripting consequences remain in the [Automation and Scheduler Runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). - `common-saga` adoption is not currently explicit: base service conventions add the dependency broadly, and deployed service configurations expose the Saga Flyway location even for services without a Saga workflow. This can materialize shared Saga tables and repositories outside the adopter boundary; the explicit adopter allowlist and focused conformance proof remain incomplete. @@ -51,7 +51,7 @@ DTO records for common tasks (paging, IDs, basic metadata) live here so services ### Redis Key Naming & Lua Script Helpers -Target-state Redis helpers must follow the owner-local execution and aggregated-contract boundary in [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md); this boundary is not implemented in the current tree. +Target-state Redis helpers follow the owner-local execution and aggregated-contract boundary in [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md). The current foundation validates selected contributed descriptors and immutable invocation handles; the full aggregated boundary is not yet implemented. The target narrow shared Redis-contract module would own the descriptor schema, common outcome types, Redis-role and prefix-owner rules, hash-tag/cluster-slot validation, compatibility metadata rules, and repository registry/test aggregation. It would own executable key builders, invocation machinery, or Lua only for mutations genuinely executed by multiple independently deployed callers. @@ -85,7 +85,7 @@ Shared code is organized as the narrowly scoped Gradle modules currently include The versioned definitions under `protos/` remain the source for generated service stubs; they are not a replacement for the split Java modules. If a module is published for a supported distribution workflow, it retains its module-specific coordinates under the `net.firedevops.firemud` group rather than being folded into one shared runtime artifact. -Redis contracts follow [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md): a future narrow foundation such as `common-redis-contracts` may carry descriptor schemas, bounded outcomes, role/owner/slot validation, and repository aggregation. Owner-exclusive Redis builders, adapters, executable Lua, and semantic tests remain in the owning service. The foundation is not evidence that this target module or its registry has been implemented. +Redis contracts follow [ADR 0176](decisions/adr-0176-owner-local-redis-execution-with-aggregated-contracts.md). The narrow `common-redis-contracts` module carries the initial descriptor schema, bounded outcomes and role/owner/principal/slot invocation validation. Owner-exclusive Redis builders, adapters, executable Lua and semantic tests remain in the owning service. Repository aggregation, full legacy registration and deployed caller/ACL proof remain incomplete; presence of this module does not establish them. This split-module boundary aligns with the [Shared Runtime, Service Contracts, and Persistence implementation tracking](../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md) record and keeps reuse explicit without globalizing owner-exclusive execution. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index aad8217b2e..501d37b2be 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -342,3 +342,36 @@ Entry format: - `2026-10-02`: Keep helper file targets and validation inside the pinned assignment - Context: a helper assigned to the isolated Unit 1B worktree accidentally created an empty `DO_NOT_USE.java` in the default checkout, reported it, and removed its own disposable file; the orchestrator confirmed it was absent. Another helper ran an unrequested diff check despite a validation-none assignment. No user change or useful implementation was lost, and neither action supplied credited validation. - Expected pattern: verify the worktree identity before edits, use absolute patch targets, and treat validation-none as a closed boundary rather than permission for substitute checks. Report scope mistakes immediately and distinguish recovery from canonical proof; a successful helper handoff does not substitute for orchestrator inspection and validation. + +- `2026-10-02`: Distinguish caught service warnings from the exception that fails gameplay proof + - Context: the first CI36967764374 sentinel summary highlighted Game Design DNS failure as the WebSocket PLAY cause. The fixture helper followed the complete trace and found that warning was caught with defaults; the actual socket-closing exception was a null character-list response because the mock still selected a numeric Account ID after LOGIN returned the canonical UUID. + - Outcome: the fixture correction preserves production guards, uses the exact UUID selector and configures the existing fake service endpoint; exact CI36970584573 subsequently executed all sixteen WebSocket cases cleanly. The initial diagnosis was corrected in the private evidence and public checkpoint before claiming proof. + - Expected pattern: identify the fatal test/assertion path and distinguish caught warnings and secondary teardown failures. A prominent stack trace or a green component suite alone does not establish the root cause of broader gameplay failure. Likewise, select the exact matrix job before attributing conditional proof steps: a CI36969757041 sentinel inspected the non-Account job and reported skipped proof, while root's exact Account-job readback showed strict verification failed and XML upload succeeded. + +- `2026-10-02`: Bound PostgreSQL fixture identifiers before appending the full random nonce + - Context: all eight new logout-all PostgreSQL cases in CI36969757041 failed during Flyway setup because the descriptive schema prefix plus a full UUID exceeded PostgreSQL's 63-byte identifier limit. The physically truncated schema did not match the requested name, producing duplicate-schema creation errors before the operation assertions. + - Outcome: the fixture now uses the ASCII `logout_src` prefix and preserves its complete 128-bit nonce, keeping names at 43 bytes. Corrected database execution remains required; compiling or discovering the class locally did not expose this runtime setup error. + - Expected pattern: use a short ASCII prefix with a full unique nonce, verify the complete identifier length, and retain the same declared schema in JDBC/Flyway/readback. Do not fix this by weakening migration, isolation or transaction proof. + +- `2026-10-02`: Verify negative preservation scope as well as transferred split paths + - Context: while mechanically transferring the Redis projection from #2933 to its existing child, a helper patch briefly deleted the parent-owned PostgreSQL/socket-mTLS test outside the transfer allowlist. The helper reported the scope error and immediately restored that file byte-for-byte from the pinned commit with a patch; the resulting working diff leaves it unchanged. + - Expected pattern: explicitly check every parent-owned retained blob and the complete cumulative child tree, not just the moved path count. A reviewed transfer map does not make a generated deletion list safe by itself. Keep published history intact and verify no-loss before publication. + +- `2026-10-02`: Distinguish structural collaboration exhaustion from model capacity + - Context: dispatching the Account current-recipient helper failed with `agent thread limit reached` while two useful bounded workers and one CI sentinel were active. This was a structural slot error, not evidence that Luna was unavailable. + - Outcome: following the slot-recovery skill, the orchestrator closed out a completed split helper with a return-only continuation, checked agent state and retried the same fresh Luna xhigh assignment once. It succeeded without interrupting useful work or changing model/tier. The harness's precise reclamation timing remains unknown; the retry success does not prove that the close-out message alone released the slot. + - Expected pattern: preserve active work, distinguish the exact failure class and use a bounded structural recovery attempt. Do not substitute models or relabel a reused helper as a fresh independent review. + +- `2026-10-02`: Isolate delegated command text from prose punctuation + - Context: two focused Account/Game Session helper invocations treated a trailing prose period as a Gradle task named `.` and failed before the intended tasks ran. Corrected invocations without that argument succeeded; the failed invocations supplied no test proof. + - Expected pattern: put exact allowed commands on standalone fenced or explicitly delimited lines, with no sentence punctuation attached. Read back the actual invocation and task outcome before attributing validation; an intended command is not an executed gate. + +- `2026-10-02`: Check migrated constraints before manufacturing a missing-history failure + - Context: an Account outbox investigation initially treated a missing stream head with retained events as a possible runtime gap. Reading V33's immediate foreign key, immutable-event guards and unconditional head-delete rejection disproved that state under the intact schema. + - Outcome: the unnecessary local query and unit changes were removed before publication. Focused PostgreSQL tests instead exercise rejected deletion with unchanged evidence and exact-stream isolation without synthesizing authority; local Docker absence still requires executed runner proof. + - Expected pattern: inspect the complete owning migration before accepting a repository-level failure premise. Do not disable constraints or invent corrupted fixtures to justify a runtime repair; distinguish actual invariant proof from recovery for a separately specified corruption model. + +- `2026-10-03`: Script convenience APIs can widen a deliberately narrow Redis grant + - Context: the projection helpers' Spring Redis script convenience path can fall back from `EVALSHA` to raw `EVAL`. Giving the isolated fixture both commands masked the difference from the canonical owner-helper `SCRIPT LOAD`/`EVALSHA` grant. + - Outcome: the Account and issuer candidates use verified registered bytes, check the identity returned by `SCRIPT LOAD`, and invoke `EVALSHA` directly without fallback or a blind retry. Isolated Redis proof denies raw `EVAL`; local database/Redis skips still require executed runner evidence. + - Expected pattern: inspect convenience-API recovery behavior against the exact command grant, and test the forbidden command as well as the positive registered-helper path. Do not widen ACLs just to accommodate an implicit fallback. 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 91cf1f83f0..1c85c9f099 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,23 +6,73 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The source-to-cutoff reconciliation preserves Account's LEFT receipt migration at V42 and mechanically places the child logout-all receipt migration at V42.1, before the already-preserved downstream V43–V55 lineage. The logout SQL bytes and immutable receipt/event guards are unchanged; both behaviors remain present rather than selecting one duplicate version. This prepares a collision-free unapplied candidate, not permission to renumber an applied migration or repair retained Flyway history. Deployment still requires exact owning-environment migration inventory and retained-data readback; a conflicting applied history must remain a fail-closed rollout gate. Historical component executions below do not prove this newly composed migration sequence or enable any runtime path. + +The active prerequisite boundaries are [#2933](https://github.com/benhook1013/FireMUD/pull/2933) for Account reset/issuer source, retained UUID handoff and authenticated source transport proof, followed by [#2938](https://github.com/benhook1013/FireMUD/pull/2938) for Account logout-all/tenant source and the registered derived issuer projection. Normal regrouping preserved the complete cumulative pre-cut tree byte-for-byte; no authority, implementation or proof hunk was dropped. These are unwired prerequisite stages, not Unit 1B completion or admission authority. + +Composed PLAY validation exposed a cross-account denial that incorrectly cleared the caller's existing gameplay binding. The corrected denial preserves `WORLD_ACCESS_DENIED` but performs no binding, presence, actor or event mutation; bound and unbound complete cross-account carriers have explicit no-mutation assertions. Malformed current-recipient evidence remains `AUTH_UNAVAILABLE`, not a caller-bound denial that may clean up an existing binding. The affected Account/Game Session/Common Security/Core checks and both boot JARs passed locally in 2m15s (291 tasks: 37 executed, 254 up-to-date); Game Session's unit task executed 2,357 cases with 17 skipped and no failures/errors. Account's unchanged 759 unit results were reused in the final invocation; its 233 PostgreSQL cases all remain skipped locally. The subsequent source fixture merge retains those corrections and their separate execution limits below; no runtime path is enabled. + Exact source checkpoint `e10741ce7629d6c0117b2724d21feb6d456a6d56` [CI37199764787](https://github.com/benhook1013/FireMUD/actions/runs/37199764787) completed with aggregate failure. Its raw XML proves all ten Game Design association and seventeen Game Session retained-association PostgreSQL cases executed with zero skips, failures or errors, including the configured isolated owner-schema case, signature-tampering guard and repeated visible-but-private sandbox fixture. This closes those preceding fixture execution gaps. Four retained Game Session snapshot cases also passed the strict job-log verifier, without matching raw XML; its later broad task was canceled and receives no completion credit. Game Design's Entity-baseline test used an incorrect fully qualified selector, and the targeted invocation omitted the required fresh-tenant and authored-world suites. The workflow now selects all four actual owner suites before retaining raw XML and running the unchanged strict suite/case gates. Corrected-head execution of those previously missing suites remains required; successful association execution does not substitute for it. The same run's strict JUnit summaries prove Account JOIN 40, reconciliation 12, UUID storage migration 6, Social migration 8 and Logging migration 5 executed without skips, failures or errors; their jobs passed, but corresponding raw XML was not uploaded. Python lint exposed an unbound callback loop variable; ten tooling tests lacked the locked WebSocket client dependency. Both findings are routed to their #2853 owner in the controller. TCP's seventeen-case cross-service suite had thirteen expected-PLAY failures, including `PLAY_IDENTITY_UNAVAILABLE`; this does not prove an enabled canonical identity/admission path or that DNS alone caused the failures. No aggregate-green, complete producer, fresh-image/live proof or activation claim follows. The preceding local Game Design/Game Session full checks, boot JARs, formatting, analyzers, coverage and documentation gate passed in 1m11s (273 tasks: 30 executed, 243 up-to-date); unchanged unit results were reused, all 52 Game Design integration cases skipped without Docker, and Game Session executed 18 with 163 skipped. Runtime activation and the Account ring mount remain denied. -The active [#2933](https://github.com/benhook1013/FireMUD/pull/2933) boundary retains Account password-reset and issuer source authority, exact retained-tenant UUID handoff, Game Logic UUID preservation and authenticated current/historical source transport proof. Its coherent Redis foundation/derived projection has moved to the existing [#2938](https://github.com/benhook1013/FireMUD/pull/2938) Account source child; the cumulative child tree is preserved exactly through normal history. That earlier regrouping reduced the parent scope from100 to77paths without dropping source implementation or proof; current reconciliation scope and exact-head proof are recorded on the owning PR. - The reconciled REALMS/JOIN consumer candidate resolves only the exact namespace-qualified Game Session catalog-key association, sends its canonical tenant UUID unchanged in Account context and target, and stores the private catalog key separately. JOIN compares fresh association readback to the stored UUID before forwarding; absent, nil or changed evidence denies. Local mocked tests are component proof only. The Account direct-text scope/JOIN producer still parses private numeric caller/tenant fields and its runtime catalog reads do not yet prove canonical cross-owner tenant association. Canonical Account caller resolution, Account-owned tenant mapping, exact authenticated catalog evidence, durable scope/JOIN binding and composed positive/negative execution remain required before end-to-end availability. Do not forward a Game Session private key as an Account key, infer equality, or treat the consumer fixture as activation proof. Membership, credential/context/catalog/admission and ring gates remain unchanged. -Exact preceding checkpoint933d1f035 [CI36970584573](https://github.com/benhook1013/FireMUD/actions/runs/36970584573) passed Game Session/TCP. All16 WebSocket PostgreSQL cases executed cleanly, including the signed-context fail-closed case; this suite is strict-log evidence, not uploaded raw XML. Seven component XML suites prove62 clean cases without skips/failures/errors. Aggregate CI is still red on separately owned tooling/Automation/Game Design failures. The reduced parent full Game Session check/JAR and docs passed1m23s,131tasks(30executed/4from-cache/97up-to-date), with Docker-dependent cases skipped locally. Fresh regrouped-head CI and all complete recipient, deployment and runtime activation proof remain gates. Membership RPC and credential/context/catalog activation remain denied; the Account ring mount is unpublished. +Exact parent checkpoint933d1f035 [CI36970584573](https://github.com/benhook1013/FireMUD/actions/runs/36970584573) passed Game Session/TCP and executed all16 WebSocket PostgreSQL cases without skips/failures/errors, including the signed-context fail-closed case. That suite is strict-log evidence, not an uploaded XML. Seven uploaded component XMLs prove62 clean cases, including source/reset, retained association, real socket-mTLS/PostgreSQL and Redis components. Aggregate CI remained red on separately owned tooling/Automation/Game Design failures; regrouping needs its own exact-head evidence. + +The tenant-wide source primitive in #2938 has a closed shared codec, fixed/large-counter vectors, atomic already-enrolled tenant generation/version/event/checkpoint advancement, exact retry and selected historical/current same-fence readback. It neither enrolls sources nor changes Account fences or billing state. Missing or contradictory history, wrong scoped binding, gaps and overflow deny. Exact cumulative head `1b681b689876b1e83ca76ed3bd2420af4334bc36` [CI36974620808](https://github.com/benhook1013/FireMUD/actions/runs/36974620808) executed all12 Tenant-source cases cleanly, including fenced historical concurrency, rollback and committed-result recovery. All8 logout cases also executed: seven passed and the overflow case failed before assertions because its synthetic setup illegally jumped a monotonic source counter. The fixture correction seeds the maximum by INSERT with all database guards enabled; corrected execution remains required. Same-head raw XML proves reset6, AccountApplication9, issuer15, socket-mTLS6, PostgreSQL/socket3, RedisCAS6 and retained-association17 clean cases. Game Session passed, including strict-log WebSocket16 and ScriptPin25; aggregate CI remains red on the owned fixture and separately owned ancestor/tooling failures. Local Account/Core checks and JAR passed, with561 Account and152 Core unit results clean and all202 local PostgreSQL cases skipped without Docker. Initial registry/evidence-bundle authorization, complete same-snapshot current recipient composition and authenticated consumer, delivery, fresh-image/live proof and activation remain open. The membership RPC and credential/context/catalog paths stay denied; the Account ring mount remains unpublished. + +### Current recipient composition and unwired authenticated transport + +Exact preceding head `b33c81b45a4a51c474063593f8cffb1a4e792b0f` [CI36982818253](https://github.com/benhook1013/FireMUD/actions/runs/36982818253) passed Account, Game Session and TCP jobs. The repaired current-source composition case and all eleven fresh-UUID snapshot cases executed cleanly, as did logout8, Tenant12, issuer15 and reset6. Root parsed ten uploaded component XMLs; fresh-UUID11, WebSocket16 and ScriptPin25 are strict-log evidence without dedicated uploaded suite XML. Aggregate CI remains red on separately owned tooling/Automation/Game Design failures; it is not activation proof. Earlier fixture failures and local skips below retain their original attribution rather than overriding this corrected runner result. + +The consumer independently compares the returned Account UUID with the authenticated Game Session Account before using the carrier, even when the echoed request ID and the other Account's complete source content are valid. Its no-mutation negative passed with all 115 focused PLAY cases. The human-readable authz companion follows its expressly normative machine rows: runtime membership and the named grant reads require exact Game Session mTLS/method/context/domain validation, not an invented JWT profile; the distinct entitlement/refresh private-delegation requirements remain unchanged. Neither this convergence nor the transport candidate changes the live public-method allowlist, generic middleware or denied runtime handler. + +The current-recipient composition candidate in #2938 keeps each committed membership event's original tuple, fence, bytes and digest immutable while assembling the current issuer, Account, tenant and membership checkpoints under the Account owner fence. Shared content validation delegates positive evidence to each owning closed codec and verifies scope/checkpoint/identity/digest, lifecycle/roles/version/generation and non-regression. It is not caller authentication or independent absence proof. Account supplies durable pair and source readback. Unsupported grant/billing sources remain denied; retained LEFT remains nonadmitting after a later fence. + +An explicitly constructed, unregistered Account membership handler now checks the exact Game Session workload peer before request parsing or owner access, reads and encodes under one ordinary Account transaction, and returns only after commit. The explicitly initialized Game Session client requires file-backed mTLS and the exact Account server identity, complete typed request, recipient/request echoes, freshness and closed response content. PLAY reuses the same proto adapter without replacing its admission or lifecycle guards. Neither class is auto-wired; the live membership RPC still denies before invoking the producer. The transport requires a UUID Game Instance selector; converting or activating the legacy numeric gameplay path is not implied. + +Focused local proof executed 196 cases cleanly (Account handler6/encoder62, Game Session client8/adapter5/PLAY115). Eleven real socket/mTLS cases also executed cleanly, covering valid ACTIVE and nonadmitting MISSING carriers, wrong-service/wrong-namespace callers and servers, missing client certificate, malformed context and cross-bound/malformed responses. Their producer and transaction manager are mocked, not PostgreSQL proof. A separate real Account/PostgreSQL-through-mTLS case composes JOIN and immutable membership readback after issuer/Tenant/Account advances, durable sequence-zero absence and no-mutation wrong-peer/unmapped denials. It compiled but skipped locally without Docker; strict CI requires its exact case and captures raw XML. Its synthetic retained association and independent UUID Game Instance context are test fixtures, not live catalog or migration authority. + +The corrected Account full check/JAR passed1m4s,67tasks(17executed/50up-to-date), with568 clean unit cases and all203 PostgreSQL cases skipped locally. Game Session full check/JAR passed2m17s,131tasks(31executed/100up-to-date):1,872 unit, eighteen integration and eighteen cross-service cases executed cleanly, with17/149/36 skips respectively; cross-service execution includes the eleven physical membership mTLS cases, and the new PostgreSQL/socket case is one of the skips. Java formatting, Checkstyle, SpotBugs and JaCoCo passed; links/Markdown passed17s and actionlint/diff hygiene passed. + +Exact transport head `2c3cd707d62dad34e4009204b4a0ecf9f39dc672` [CI36987190469](https://github.com/benhook1013/FireMUD/actions/runs/36987190469) passed Account, Game Session and TCP jobs and executed the eleven physical membership mTLS cases plus the one real Account/PostgreSQL-through-mTLS composition case with zero skips/failures/errors. Root parsed twelve uploaded component XMLs, including composition1, logout8, Tenant12, issuer15, reset6, AccountApplication9, issuer socket6/PostgreSQL-socket3, Redis6 and retained-association17. Aggregate workflow failure remains separate: shared Python/dev-demo validation, a documentation-link504, Automation formatting and the already-routed Game Design duplicate fixture. This executed component proof establishes neither production wiring nor live admission. + +A follow-on second PostgreSQL/socket case exercises real JOIN→LEFT→reactivation, retained nonadmitting INACTIVE evidence, history/checkpoint sequence1→2→3 and exact historical LEFT replay without changing current ACTIVE evidence. It preserves the actual non-membership source baseline instead of assuming a pristine global issuer. Root aligned reactivation invalidation assertions with the existing generation-advancing owner transition and retained complete tuple/fence equality. Exact published head `902591a1e9201f19175bbe08efcf8020cdea28a6` [CI36990966974](https://github.com/benhook1013/FireMUD/actions/runs/36990966974) passed Account, Game Session and TCP jobs: both PostgreSQL/socket cases and all eleven physical membership mTLS cases executed with zero skips/failures/errors. Root parsed and rehashed the uploaded XML for those suites and the clean current-recipient composition1, logout8 and Tenant12 suites. Aggregate CI failed outside those passing jobs; detailed owner attribution remains separate from component proof. Local Docker remains unavailable, so both PostgreSQL/socket cases skipped in the local gate. Fresh-image/live identities, delivery, full grants/entitlements, credential/context/catalog activation and Account ring custody/readiness remain open; the ring mount remains unpublished. + +The logout-all source receipt now binds the explicit `control-ui` or `player-bootstrap` profile and recomputes ADR0035's byte-framed `requestDigest/v1` over the exact `ACCOUNT_LOGOUT_ALL` tuple before any initial source mutation. V42, receipt insertion/readback and historical source verification converge on that same operation identity and profile; exact retries preserve the original receipt after later authority advances, while changed profile/digest/hash/version/request bindings conflict without changing the receipt, event or counters. Bounded Account digest vectors also cover `TOKEN_LOGOUT`; this is serialization proof, not an implemented per-token revocation lifecycle. The producer remains unwired and these caller bindings are not authentication, an issued-token registry lookup or a complete authorization bundle. Exact4a2dd38dc runner proof below executes the strengthened eight-case PostgreSQL suite; later source-reader tests retain their own execution gate. + +V33's immediate event-to-stream foreign key and head-delete rejection guard prevent retained events from losing their stream head; an absent head is not a caller authorization or source-generation baseline. Focused new PostgreSQL cases check rejected deletion leaves the complete event/checkpoint and row counts unchanged, and reading a missing exact stream neither synthesizes a head nor confuses another stream's retained history. The six-case repository suite compiled and all six skipped locally without Docker; CI requires both new cases and captures raw XML. No schema guard is disabled and no unsupported orphaned-history fixture is fabricated. Accepted ADR0035/0036 decisions are unchanged; their implementation-status sections now link this tracker instead of repeating obsolete component-proof assertions. + +Exact canonical-digest/profile checkpoint `4a2dd38dcfa102baf5682b91580202d818bd7be1` [CI36994950206](https://github.com/benhook1013/FireMUD/actions/runs/36994950206) passed Account, Game Session and TCP jobs. Strengthened logout8, current-recipient composition1, PostgreSQL/mTLS2 and physical membership mTLS11 all executed without skips/failures/errors; root parsed and rehashed their four raw XMLs. The aggregate retained the Game Design tenant9301 duplicate fixture, Automation formatting and shared Ruff/dev-demo-validator failures. This proves the preceding source correction, not the later two outbox-history tests or live activation. + +The next ordinary credential prerequisite is distinct from this membership carrier: accepted ADR0035/0036 require durable Account provenance for the exact registry-backed issued token, a current token-identity fence and the complete immutable authorization bundle before connect issuance. Current player-bootstrap signing writes only a legacy Redis session key; V35 gameplay-connect storage and V42 logout-all receipts do not prove ordinary bootstrap issuance. The full bundle's token provenance, role-freshness and applicable billing-cutoff sources, immutable version/source reference and independently fenced registry postconditions remain unimplemented. A membership snapshot or a collection of source counters cannot be relabeled as that bundle. Initial issuance retry identity must be specified at its owning API before exact-retry recovery is claimed; no `jti`→request-ID equivalence is inferred. These are open implementation/source prerequisites, not evidence that current denied credential paths can activate. + +An unwired Account source reader now composes the persisted Account UUID association, locked Account generation/local issuance fence, current closed source event/checkpoint and an optional exact retained event in one owner transaction. It supports only the declared reset/logout-all schemas and original positive1/1 sequence-zero absence; it neither enrolls missing sources nor emits recipient authorization. Historical reset validation preserves the immutable receipt/event after a later reset without accepting its old password verifier as current or relaxing the superseded-reset retry guard. The corrected Account full check/JAR/docs gate passed56s/70tasks(22executed/48up-to-date), with584 unit cases executed cleanly, including reader8/readback7. All209 local PostgreSQL cases compiled and skipped without Docker, including the twelve-case expanded logout/source-reader suite. Its four new database cases cover pristine/unknown reads, mixed reset→logout→reset history, invalid and injected missing/foreign readback, and an actual PostgreSQL lock observation against a concurrent source writer. Mandatory CI selectors require all four; compilation or skips are not executed database evidence. Authentication/transport/delivery, ordinary credential provenance, complete bundles and activation remain separately open. + +Exact source-reader head `a54f8da2778b3a40a83a4623e00777aae5b9d9d7` [CI37000613624](https://github.com/benhook1013/FireMUD/actions/runs/37000613624) passed Account/Game Session/TCP and executed all twelve logout/source-reader PostgreSQL cases with zero skips/failures/errors, including the four new readback/history/lock cases. Outbox6, current-recipient composition1, membership PostgreSQL/mTLS2 and physical membership-mTLS11 also executed cleanly; root parsed/rehashed those raw XMLs and separate issuer6/3 evidence. Aggregate failed on shared dev-demo summary/Ruff validation, the already-routed Game Design duplicate fixture and Automation protobuf configuration-cache serialization. These component results do not prove the later local Account projection batch, live deployment or activation. + +Account now has an unwired owner-local [current-snapshot generation projection](../../architecture/microservices/account-service/runtime-and-data.md#account-generation-snapshot-projection), derived internally from its fenced SQL source reader. Its registered byte-exact CAS and private Coordination client refuse malformed/expiring/ahead/same-position conflicting Redis evidence; successful installation or exact replay requires exact Redis readback and a fresh matching durable source snapshot. This is source-owner reprojection, not delivery, enrollment, a full Account authorization bundle or admission. Root's full Account check/JAR/docs gate passed in 1m 9s (72 tasks, 23 executed/49 up-to-date): all 602 unit cases executed cleanly, including 6 closed-record and 12 store cases. All 216 PostgreSQL cases compiled but skipped locally without Docker. The seven new PostgreSQL/Redis cases cover proved pristine absence, actual reset/logout checkpoints and unchanged SQL history, unknown-source denial, valid higher-cache poison/malformed/TTL denial, concurrent source advances, and a narrow principal's direct `EVAL` rejection. CI must execute all seven; local skips do not establish database/Redis, deployed ACL/cohort, recovery-orchestration, fresh-image or activation proof. Owner-local helper invocation uses verified `SCRIPT LOAD` and `EVALSHA`, without the convenience API's raw `EVAL` fallback. + +The same narrow-command correction is applied to the existing issuer projection helper, preserving its source/transition/CAS semantics. Two added unit cases verify exact registered bytes, load/execute ordering and `NOSCRIPT` propagation without `EVAL` or a blind retry. Its isolated Redis principal now also denies `EVAL` and unused `SCRIPT EXISTS`; the new negative case complements all six existing positive/negative projection cases. Corrected composed Account/Game Session full checks, both boot JARs, shared Redis checks and docs passed in 2m 21s (166 tasks, 37 executed/129 up-to-date). Account's 602 clean unit cases executed again; Game Session executed 1,874 unit, 18 integration and 18 cross-service cases, with 17/150/37 respective skips. All seven issuer Redis cases skipped locally, as did the seven Account PostgreSQL/Redis cases. The unchanged 20-case shared Redis unit result was reused up-to-date, not newly executed. Exact-head runner proof, fresh images, live ACL/cohort verification and activation remain required; this is not Unit 1B completion. + +Exact preceding outbox-proof head `6bb37c4499cf54a6b396945a3a8414cfd48251d6` [CI36997795142](https://github.com/benhook1013/FireMUD/actions/runs/36997795142) executed all six outbox repository cases cleanly, including the rejected-delete/no-mutation and exact-stream/no-synthesis cases. Logout8, current-recipient composition1, membership PostgreSQL/mTLS2 and physical-mTLS11 also executed cleanly. Root parsed/rehashed their raw XMLs; aggregate shared tooling/Automation/Game Design failures remained separate. This earlier checkpoint is distinct from the expanded source-reader proof above. + +The corrected combined Account/Core/Game Session full checks, both service boot JARs and documentation gate passed in 1m29s: 171 tasks, 31 executed and 140 up-to-date. Account executed 562 unit cases cleanly; all 203 PostgreSQL cases skipped locally, including the new composition case and the corrected eight-case logout fixture. Core's same-code 165 clean unit results, including the thirteen validator cases, were reused; Game Session's corrected same-code 1,858 unit and eighteen integration results were reused with seventeen and 149 skips respectively, and its seven cross-service cases executed cleanly with 35 skips. Formatting, Checkstyle, SpotBugs and JaCoCo passed. Account's focused encoder proof also executed 62 clean cases before this full gate. Actionlint, Flyway sanity (twelve sets/130 files), all 25 CI-classifier cases, the new strict PostgreSQL selector and diff hygiene passed. Strict CI requires the new composition case to execute and captures its raw XML. No fresh-image boot, authenticated end-to-end membership, delivery, activation, provider-review or corpus-completion proof is claimed. ### Earlier component checkpoints -The issuer-source PostgreSQL-through-socket-mTLS cases remain focused source-handoff proof, not deployment or runtime activation. The derived issuer projection and owner-local Redis foundation, including their component proof, are assigned to [#2938](https://github.com/benhook1013/FireMUD/pull/2938). The projection grants no recipient, admission or rebind authority; exact recipient evidence remains required, and event delivery, role/ACL deployment, activation and active-binding revocation remain open. +Published #2933 head `9f1b75198b1f7cafd8d066dc271bf955484de4c7` has exact-head [CI 36964410034](https://github.com/benhook1013/FireMUD/actions/runs/36964410034) component execution: all six physical mTLS, three PostgreSQL/socket composition, six real Redis CAS, fifteen issuer PostgreSQL and seventeen retained-association cases passed with zero skips/failures/errors. TCP passed; aggregate CI remains red on other Game Session, Game Design and tooling/service checks under ownership diagnosis. Executed component proof does not establish live custody, deployed identity/ACL, delivered revocation, or recipient authorization. The local skips described below remain accurate local limits, not the best available runner proof. + +The next coherent Account-wide logout cutoff stage normally incorporates corrected #2933 `9d62089e5351ae3f2fe320697bab682bfc0f220a`, preserving its unique patch through a normal merge. Its closed source codec and shared vectors accompany an unwired, Account-owned producer: generation/source-version and issuance-fence advancement, immutable V42 request/token receipt, event and checkpoint commit together, followed by exact durable readback. Exact retry returns only its original lifecycle result; changed caller bindings conflict. Both password-reset → logout-all and logout-all → password-reset histories preserve their distinct immutable receipts and schemas. Present history at the pristine 1/1 baseline or single-counter progression remains denied before event lookup. + +The composed Account/Common Platform full checks, Account boot JAR, formatting, Checkstyle, SpotBugs, JaCoCo, links and Markdown passed 83 tasks (22 executed, 61 up-to-date). Account executed 551 unit cases without skips/failures/errors; all 190 PostgreSQL cases compiled/discovered but skipped without Docker, including eight new source/receipt/rollback/concurrency/mixed-history cases. Common Platform's same-code 145 clean unit cases, including six new codec cases, were reused from the preceding gate. Flyway sanity passed twelve sets/130 files, actionlint and all 25 CI-scope contract cases passed, and every new mandatory CI selector matches its method. Exact-head PostgreSQL execution, fresh-image boot and live proof remain required. Initial issued-token-registry/bundle authorization, authenticated recipient readback, delivery and activation remain unproved. No public logout-all route, membership RPC, credential path or ring mount is enabled by this source preparation. + +The projection correction, originally prepared in #2933 and now preserved in [#2938](https://github.com/benhook1013/FireMUD/pull/2938), adds an unwired Game Session issuer-projection transition engine and a registered owner-local byte-exact Redis compare-and-set store on an explicitly initialized Coordination connection. It accepts only the dedicated Account client's verified readback for the configured workload namespace, binds the exact issuer/stream/current or historical event evidence, denies gaps and conflicting progress, and atomically updates the projection and checkpoint without TTL. Duplicate verification is non-mutating; old events require Account's exact immutable historical lookup. This derived projection grants neither admission nor rebind authority. The narrow shared Redis descriptor foundation is partial; complete existing-script aggregation, descriptor-driven global CI, client-cohort cutover, deployed role/ACL proof, event delivery and active-binding revocation remain required. The new PostgreSQL-through-socket-mTLS and Redis integration cases are focused component proof, not deployment or runtime activation. Exact published [CI 36959528382](https://github.com/benhook1013/FireMUD/actions/runs/36959528382) at `58695d165a03f6004236a8a5e27b1a99f1b0eae4` completed with aggregate failure. Raw XML proved all fifteen issuer PostgreSQL, seventeen retained-association and four snapshot cases executed without skips, failures or errors, along with six reset-producer and both required reset-application methods. Five of six socket mTLS cases passed; the missing-client-certificate assertion lost its underlying throwable, so its cause cannot be established from that result. The corrected test observes the certificate rejection directly with explicit trust-only credentials, bounded timeouts, HTTP/2 negotiation and diagnostics. LOGIN/PLAY/LOOK passed; all four remaining TCP chat-output failures were the Game Logic numeric Account validator rejecting the canonical UUID. The local correction preserves exact UUIDs through Game Logic, but Social's numeric sender store still needs its owner migration; a Social stub does not prove persistence or end-to-end delivery. -At the combined pre-split checkpoint, Game Logic's 91 unit/five integration results and boot JAR passed; TCP executed 194 unit, seven integration and three cross-service cases, with fourteen skipped. All executed cases were clean, including the six physical socket mTLS cases. These Game Logic, TCP and source-transport results remain with #2933. Game Session and common Redis foundation/projection counts from that same run are tracked with #2938. The two PostgreSQL/socket composition methods skipped locally without Docker; strict CI requires their execution and captures raw XML. Fresh runner composition, fresh-image/live identity, membership RPC, credential/context/catalog activation and Account key-ring delivery/readiness remain gates; the RPC and credential paths stay denied and the ring mount remains unpublished. Unit 1B is provisional. +The corrected combined Redis foundation/Game Logic/Game Session/TCP full checks, Game Session/TCP boot JARs, links and Markdown passed 221 tasks (45 executed, 176 up-to-date), including formatting, Checkstyle, SpotBugs and JaCoCo. Foundation's twenty unit cases and Game Logic's 91 unit/five integration results were reused from their earlier same-code green gate; Game Logic's boot JAR also passed there. Game Session executed 1,850 unit, eighteen integration and seven cross-service cases, with 17/149/35 skipped; TCP executed 194 unit, seven integration and three cross-service cases, with fourteen skipped. All executed cases were clean, including fourteen transition, three descriptor, five store and six physical socket mTLS cases. Twenty-five CI-classifier cases and the lightweight scope contract passed. All six Redis integration cases and both PostgreSQL/socket test methods skipped locally without Docker; the latter defines three intended runner cases when parameterized execution is enabled. Strict CI requires their execution and captures raw XML. Fresh runner composition, fresh-image/live identity, membership RPC, credential/context/catalog activation and Account key-ring delivery/readiness remain gates; the RPC and credential paths stay denied and the ring mount remains unpublished. Unit 1B is provisional. ### Preceding local checkpoint evidence diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index c151b57d71..b434bf7fa0 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for shared runtime, service contr The implementation record below summarizes the shared runtime, service-contract, orchestration, persistence, and workflow boundaries represented by this tracker. It distinguishes live implementation from bounded follow-up work; it does not claim that every future service, runtime consumer, or workflow family has already adopted these conventions. +The initial `common-redis-contracts` module implements the ADR 0176 descriptor and selected-invocation validation boundary: explicit owner/principal/role prefix declarations, versioned identity/digest, ordered key/argument arity, immutable invocation handles and Redis Cluster tag/slot checks. It has no Redis client, automatic runtime wiring or shared owner-exclusive executable. Its focused unit tests executed locally; consolidated static checks and the owner adapter's runtime proof are recorded at their actual checkpoint rather than inferred from the descriptor. Full legacy prefix/script inventory, repository aggregation and all-script CI, rollout/coexistence evidence, role-qualified deployment and ACL proof remain required. Existing generic clients are not cut over by introducing this library. + Account V29 now persists one immutable canonical UUID per Account while preserving the numeric local primary key, with explicit migration/insertion provenance and source-row evidence. The Account repository returns and resolves that UUID using exact source-row readback, while external Account carriers and consumers remain numeric; this does not establish a tenant UUID mapping. `:account-service:spotlessJavaCheck` and the focused `AccountLoginAuthModesTest` executed successfully; the focused `AccountRepositoryIntegrationTest` compiled but all 13 cases, including the V29 retained-row, JOIN-operation, and membership-receipt no-loss proof, were skipped because Docker was unavailable. PostgreSQL runtime behavior is therefore not yet verified. The broader `SF-1.2` capability remains partial and its cross-service UUID convergence is still unproved. Account V25, Game Session V2, and Automation V2 schema activation now has a bounded quiescence slice: base/hosted workloads use non-rolling replacement, the trusted dev-demo path recognizes migration-bearing pushes, preserves that runtime database, stops the three Account, Game Session, and Automation writer Deployments, and verifies their Pods are absent; ordinary pushes retain the established clean namespace reset. Redispatch classification uses the exact namespace-manager deployed-head annotation and fails before mutation if the head or Git ancestry is unproven. The Game Session and Automation V2 migrations check their known V1 indexes plus service-specific active-claim/data prerequisites before changing indexes; this status does not claim equivalent migration validation for Account V25. Focused PostgreSQL failure-path tests are added but remain unverified until Docker-backed service tests run. Candidate PR previews that change Flyway migrations fail before namespace recreation because their scoped runtime path cannot prove Postgres PVC provenance or query migration history; trusted post-merge deployment is the activation path. Recovery is roll-forward only. This does not complete the separate retained-row identity and cross-instance PostgreSQL proof recorded below. @@ -83,7 +85,7 @@ The following current-state findings refine the existing partial/drift status; o | `SF-1.2` Identifiers, tenant context, and routing identity primitives | `partial`: Shared request/runtime identity validation and tenant-aware contexts are live, but durable cross-boundary identity still uses numeric forms instead of ADR 0020 scoped UUIDs, and gameplay delegation has not converged on canonical typed unsigned `PlayerExecutionContext`; legacy gameplay-attestation helpers remain wired into gameplay consumers pending removal. | `drift-found`: current context/scope tests prove useful fields but not the accepted workload/context boundary; `GameplaySessionAttestationServiceTest` proves helper token validation/matching only, and no focused consumer-level proof establishes that attestation values cannot authorize delegated work, establish workload identity, or serve as replay authority. | [identifier glossary](../../architecture/system-architecture-identifier-glossary.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0024](../../architecture/decisions/adr-0024-trusted-gameplay-workload-delegation.md) | [`RequestIdValidation.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/RequestIdValidation.java); [`RuntimeIdentity.java`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtime/RuntimeIdentity.java); [`SessionContext.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java); [`GameplaySessionAttestationService.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GameplaySessionAttestationService.java) | [`RequestIdValidationTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/RequestIdValidationTest.java); [`SessionContextTenantAccessTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionContextTenantAccessTest.java); [`GameplaySessionAttestationServiceTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java) | [Player Access](./player-access-and-session.md); [Realm Routing](./realm-routing-and-playable-state.md); [Game Session](./game-session-runtime-and-tick-coordination.md) | Migrate durable cross-boundary identifiers to scoped UUIDs with owner/scope validation; converge on one typed unsigned execution context, retain complete scoped validation, and prove it adds no authorization-store round trip; remove the deprecated gameplay-attestation debt, and add focused consumer proof before claiming that it cannot authorize delegated work. | | `SF-1.3` Authentication, authorization, trust, secrets, and certificates | `partial`: JWT propagation/claims, gRPC and HTTP auth interceptors, and mTLS configuration/reload are live, but signing still uses shared HMAC material and canonical certificate-derived workload identity, method caller allowlists, receiver-specific token profiles, issued-token/auth-generation enforcement, and rotation remain incomplete. Legacy gameplay attestations remain wired into gameplay consumers pending removal. | `drift-found`: current JWT/TLS tests prove bounded existing seams but do not prove Account-only asymmetric issuance and JWKS validation, concrete peer-certificate identity, exact per-method workload authorization, receiver-specific token enforcement, or Account-owned auth-generation enforcement; generic HMAC/internal-token behavior remains implementation debt, and no focused consumer-level proof establishes that legacy attestation values cannot authorize delegated work, establish workload identity, or serve as replay authority. | [JWT and token contracts](../../architecture/system-architecture-jwt-and-token-contracts.md); [security](../../architecture/system-architecture-security.md); [authentication](../../architecture/system-architecture-authentication.md); [ADR 0014](../../architecture/decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md); [ADR 0024](../../architecture/decisions/adr-0024-trusted-gameplay-workload-delegation.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0036](../../architecture/decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md); [ADR 0037](../../architecture/decisions/adr-0037-fail-closed-token-authority-outages-with-bounded-active-gameplay.md); [ADR 0038](../../architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md) | [`GrpcClientAuth.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcClientAuth.java); [`AuthTokenInterceptor.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java); [`ReloadableJwtUtil.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/ReloadableJwtUtil.java); [`CommonSecurityAutoConfiguration.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/config/CommonSecurityAutoConfiguration.java); [`apps.yaml`](../../../k8s/helm/firemud/templates/apps.yaml) | [`GrpcClientAuthTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/GrpcClientAuthTest.java); [`AuthTokenInterceptorTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [`GameplaySessionAttestationServiceTest.java`](../../../services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java); [`AuthConfigTest.java`](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AuthConfigTest.java) | [Player Access](./player-access-and-session.md); [Game Session](./game-session-runtime-and-tick-coordination.md); [Platform Operations](./platform-operations-and-delivery.md) | Shared signing material reaches workloads beyond Account and multiple workloads can mint locally; validators do not use Account JWKS. Certificate-bound workload identities, default-deny method allowlists, receiver-specific token enforcement, issued-token registry/auth-generation enforcement, generic internal-token removal, and rotation proof are absent. Consumer-level proof that deprecated gameplay-attestation values cannot authorize delegated calls, establish workload identity, or serve as replay authority is also absent; removal remains required. Player-facing readiness stays blocked pending Account-only private signing, asymmetric validator convergence, certificate-derived caller enforcement, monotonic generation projection/validation, phased rotation/compromise proof, and removal of the obsolete gameplay-attestation implementation debt. | | `SF-1.4` Clocks, timestamps, durations, and time semantics | `partial`: The proto time-field guard, explicit wall-clock fields, and tick-relative command/scheduler fields are live; a shared gameplay clock/state API and broad timed-state adoption are not. | `proven` for the naming guard and current tick/time contract seams, not runtime-wide time semantics. | [scheduler and timers](../../architecture/system-architecture-scripting-scheduler-and-timers.md); [runtime execution](../../architecture/system-architecture-scripting-runtime-execution.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [`check-proto-time-fields.py`](../../../dev-tools/validation/check-proto-time-fields.py); [`automation_scripting_service.proto`](../../../protos/automation-scripting/v1/automation_scripting_service.proto); [`TextCommandDefinition.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandDefinition.java); [`ActionStateCommandHandler.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandler.java) | [`test_check_proto_time_fields.py`](../../../dev-tools/validation/test_check_proto_time_fields.py); [`AuthoredActionCommandHandlerTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [`TickSchedulerTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java) | [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md); [Gameplay](./gameplay-rules-entities-and-effects.md) | Runtime cooldown state, common buff/condition timing, scheduled-effect execution, and richer gameplay-clock APIs remain gaps. The guard proves naming only; no scheduler design decision is made here. | -| `SF-1.5` Shared libraries, interceptors, and contract helpers | `partial`: Split shared platform, data, security, saga, and Temporal modules provide live auto-configuration, interceptors, identity, Redis, persistence, and workflow helpers; the broader shared-library substrate is not complete. | `drift-found`: current shared module/interceptor/helper implementation seams are proven, but the shared Redis descriptor/aggregation/helper foundation and descriptor-driven proof remain absent. | [shared libraries](../../architecture/system-architecture-shared-libraries.md); [gRPC](../../architecture/system-architecture-grpc.md); [transactions](../../architecture/system-architecture-transactions.md) | [`CommonGrpcServerConfiguration.java`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/CommonGrpcServerConfiguration.java); [`DatabaseAutoConfiguration.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java); [`CommonSecurityAutoConfiguration.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/config/CommonSecurityAutoConfiguration.java); [`CommonTemporalAutoConfiguration.java`](../../../services/common-temporal/src/main/java/net/firedevops/firemud/common/temporal/config/CommonTemporalAutoConfiguration.java) | [`GrpcTlsReloadPolicyTest.java`](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcTlsReloadPolicyTest.java); [`DatabaseAutoConfigurationTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java); [`CommonSecurityAutoConfigurationTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java); [`FiremudWorkflowIdsTest.java`](../../../services/common-temporal/src/test/java/unit/net/firedevops/firemud/common/temporal/FiremudWorkflowIdsTest.java) | [Player Access](./player-access-and-session.md); [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md) | Split `common-*` module ownership is converged in the canonical shared-libraries document. The shared Redis key/Lua descriptor, aggregation, and helper foundation required by ADR 0176 is not present in this tree; implement and prove that target boundary before completion. This row records no new design decision. | +| `SF-1.5` Shared libraries, interceptors, and contract helpers | `partial`: Split shared platform, data, security, saga and Temporal modules provide live helpers; the opt-in `common-redis-contracts` module adds initial descriptor and selected-invocation validation, not complete Redis adoption. | `drift-found`: focused descriptor tests execute, but repository aggregation, legacy coverage, generic CI and deployed caller/ACL proof remain incomplete. | [shared libraries](../../architecture/system-architecture-shared-libraries.md); [gRPC](../../architecture/system-architecture-grpc.md); [transactions](../../architecture/system-architecture-transactions.md) | [`CommonGrpcServerConfiguration.java`](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/CommonGrpcServerConfiguration.java); [`DatabaseAutoConfiguration.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java); [`CommonSecurityAutoConfiguration.java`](../../../services/common-security/src/main/java/net/firedevops/firemud/common/config/CommonSecurityAutoConfiguration.java); [`CommonTemporalAutoConfiguration.java`](../../../services/common-temporal/src/main/java/net/firedevops/firemud/common/temporal/config/CommonTemporalAutoConfiguration.java); [`RedisContractRegistry.java`](../../../services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java) | [`GrpcTlsReloadPolicyTest.java`](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcTlsReloadPolicyTest.java); [`DatabaseAutoConfigurationTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java); [`CommonSecurityAutoConfigurationTest.java`](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java); [`FiremudWorkflowIdsTest.java`](../../../services/common-temporal/src/test/java/unit/net/firedevops/firemud/common/temporal/FiremudWorkflowIdsTest.java); [`RedisContractRegistryTest.java`](../../../services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java) | [Player Access](./player-access-and-session.md); [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md) | Split `common-*` ownership follows the canonical shared-libraries document and ADR 0176. Complete the remaining aggregate catalog, ownership/role-client adoption and focused proof before claiming the shared boundary complete. This row records no new design decision. | | `SF-2.1` PostgreSQL ownership, schemas, migrations, and retention | `partial`: `jOOQ + Flyway`, owning service schemas, generated access, schema-qualified saga migrations, and several service-local retention sweeps are live. Shared retention-class declarations, cross-service horizon compatibility and blockers, safe-watermark cleanup, holds, and complete focused proof remain unimplemented; one gateway persistence surface also remains unresolved. | `drift-found`: current tests prove bounded jOOQ/Flyway/schema-qualified persistence and service-local retention seams only; they do not prove the SQL-only migration lineage, explicit Saga adopter wiring, historical migration mappings, shared retention contract, or cross-service cleanup safety. | [database migrations](../../architecture/system-architecture-database-migrations.md); [transactions](../../architecture/system-architecture-transactions.md); [scaling and retention](../../architecture/system-architecture-scaling-runbook.md#data-retention-and-high-churn-tables); [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) | [`FiremudJooqConventionsPlugin.kt`](../../../buildSrc/src/main/kotlin/net/firedevops/firemud/FiremudJooqConventionsPlugin.kt); [`JooqPersistenceSupport.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/persistence/jooq/JooqPersistenceSupport.java); [`DatabaseAutoConfiguration.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/DatabaseAutoConfiguration.java); [`application.yml`](../../../services/game-session-service/src/main/resources/application.yml); [`Game Session V1__baseline.sql`](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [`PlayerCommandHistoryRetentionSweepJob.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryRetentionSweepJob.java); [`DurableResumeTranscriptExpiryJob.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJob.java); [`ScriptOutboxCleanupJob.java`](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptOutboxCleanupJob.java); [`V1__init.sql`](../../../services/spring-cloud-gateway/src/main/resources/db/migration/V1__init.sql) | [`DatabaseAutoConfigurationTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/config/DatabaseAutoConfigurationTest.java); [`PostgresBackedServiceTestSupport.java`](../../../services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java); [`SagaPersistenceRepositoryIntegrationTest.java`](../../../services/common-saga/src/test/java/integration/net/firedevops/firemud/common/saga/persistence/SagaPersistenceRepositoryIntegrationTest.java); [`PlayerCommandHistoryRetentionSweepJobTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryRetentionSweepJobTest.java); [`DurableResumeTranscriptExpiryJobTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java); [`ScriptWorkItemServiceImplTest.java`](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java); [`check-flyway-versions.py`](../../../dev-tools/validation/check-flyway-versions.py) | [Game Session](./game-session-runtime-and-tick-coordination.md); [World Runtime](./world-runtime-and-movement.md); [Game Authoring](./game-authoring-publishing-and-activation.md); [Platform Operations](./platform-operations-and-delivery.md) | ADRs 0079-0082 accept the single persistence stack, adopter-local schema ownership, objective compatibility gates, and semantic identifier-migration boundary. The canonical retention contract and operational consequences are owned by ADR 0163 and the scaling runbook; current service-local sweeps do not establish the shared declarations, horizon inequalities and blockers, safe-watermark cleanup, hold handling, or required focused proof. Gateway `V1__init.sql` creates `route_config`, while runtime routes use [`GatewayRouteServiceImpl.java`](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/service/impl/GatewayRouteServiceImpl.java) with no jOOQ owner; migration compatibility evidence, shared-migration versioning, generic mapping/orchestration, and focused proof remain incomplete. | | `SF-2.2` Redis coordination, caching, rate limiting, and reset semantics | `partial`: Shared Redis configuration, atomic counters, bounded caches, session/presence coordination, rate limiting, replay guards, and tick Lua seams are live; cross-service reset and script conventions are incomplete. | `proven` for the current shared Redis primitives and named coordination/cache/replay adopters, not the whole reset contract. | [Redis](../../architecture/system-architecture-redis.md); [Redis cache](../../architecture/system-architecture-redis-cache.md); [Redis reset and recovery](../../architecture/system-architecture-redis-reset-and-recovery.md); [Redis Lua patterns](../../architecture/system-architecture-redis-lua-patterns.md) | [`RedisProperties.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/config/RedisProperties.java); [`RedisAtomicOperations.java`](../../../services/common-data-runtime/src/main/java/net/firedevops/firemud/common/redis/RedisAtomicOperations.java); [`RedisSessionContextService.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [`tick_commit.lua`](../../../services/game-session-service/src/main/resources/redis/tick_commit.lua); [`GameplayHandshakeFilter.java`](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java) | [`RedisAtomicOperationsTest.java`](../../../services/common-data-runtime/src/test/java/net/firedevops/firemud/common/redis/RedisAtomicOperationsTest.java); [`RedisSessionContextServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [`RedisMovementEffectIdempotencyServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [`GameplayHandshakeFilterTest.java`](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java) | [Player Access](./player-access-and-session.md); [Automation](./automation-and-scheduler-runtime.md); [Game Session](./game-session-runtime-and-tick-coordination.md); [Platform Operations](./platform-operations-and-delivery.md) | ADRs 0083-0087 accept the no-general-broker boundary, evidence-scoped Lua compatibility, evidence-gated replay/reset, owner-validated cache classes, and isolated-subject rate-limit semantics. Shared key/script descriptors, coexistence evidence, the durable recovery controller and external fence, room-cache validation, and repo-wide rate-limit/outage proof remain incomplete. Auth allowlist, issued-token registry, and authority-generation consumption are also absent; see `SF-1.3`. | | `SF-2.3` Idempotency, outbox, replay, and reconciliation | `partial`: Durable tick/effect ledgers, Redis idempotency/replay, remote-followup reconciliation, Entity nonblank-`effectId` replay and blank-ID denial, and Automation work-item/outbox paths are live; coverage is owner- and domain-bounded. | `drift-found` | [transactions](../../architecture/system-architecture-transactions.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [runtime execution](../../architecture/system-architecture-scripting-runtime-execution.md); [ADR 0083](../../architecture/decisions/adr-0083-no-general-event-broker-until-measured-adoption-gates.md); [ADR 0120](../../architecture/decisions/adr-0120-owner-read-first-control-plane-notifications.md); [scripting control-plane events](../../architecture/system-architecture-scripting-control-plane-events.md) | [`TickBatchExecutionService.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [`RedisDurableGameplayReplayService.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisDurableGameplayReplayService.java); [`RemoteFollowupRuntimeServiceImpl.java`](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [`EntityMutationEffectReplayService.java`](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java); [`ScriptWorkItemServiceImpl.java`](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java) | [`TickBatchExecutionServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [`RemoteFollowupRuntimeServiceImplTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [`RedisMovementEffectIdempotencyServiceTest.java`](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [`EntityMutationEffectReplayServiceTest.java`](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java); [`ScriptWorkItemExecutionServiceImplTest.java`](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java) | [Game Session](./game-session-runtime-and-tick-coordination.md); [Gameplay](./gameplay-rules-entities-and-effects.md); [Automation](./automation-and-scheduler-runtime.md); [World Runtime](./world-runtime-and-movement.md) | Entity service/gRPC unit proof covers blank-ID denial but not trusted caller identity, SQL/PostgreSQL uniqueness, concurrent first-apply, operation/target/request conflict rejection, or in-progress-marker recovery. The named tick, follow-up, and Automation work-item tests remain bounded and do not establish a repo-wide outbox contract. Target ownership remains in the linked transactions, scripting execution, and control-plane event documents. | 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/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index b6d248d0f0..d5172d7680 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -12,6 +12,8 @@ firemudJooq { } dependencies { + implementation(project(":common-redis-contracts")) + implementation("com.fasterxml.jackson.core:jackson-databind") implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java new file mode 100644 index 0000000000..029c6bf10f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; + +/** Canonical, bounded request digests for the two Account token-logout operations. */ +public final class AccountLogoutRequestDigest { + private static final String DOMAIN = "requestDigest/v1"; + private static final HexFormat HEX = HexFormat.of(); + + private AccountLogoutRequestDigest() {} + + public static String tokenLogout(UUID subjectAccountId, String tokenProfile, String tokenHash) { + return digest(OperationKind.TOKEN_LOGOUT, subjectAccountId, tokenProfile, tokenHash); + } + + public static String accountLogoutAll( + UUID subjectAccountId, String tokenProfile, String presentedTokenHash) { + return digest( + OperationKind.ACCOUNT_LOGOUT_ALL, subjectAccountId, tokenProfile, presentedTokenHash); + } + + /** Validates the exact closed token-profile vocabulary accepted by logout request bindings. */ + public static void validateTokenProfile(String tokenProfile) { + if (!"control-ui".equals(tokenProfile) && !"player-bootstrap".equals(tokenProfile)) { + throw new IllegalArgumentException( + "Logout request token profile must be control-ui or player-bootstrap"); + } + } + + /** Validates a SHA-256 token identity rendered as lowercase hexadecimal without a prefix. */ + public static void validateTokenHash(String tokenHash) { + if (tokenHash == null || !tokenHash.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Logout request token hash must be lowercase SHA-256 hex"); + } + } + + public static String tokenLogoutPreimageHex( + UUID subjectAccountId, String tokenProfile, String tokenHash) { + validateBindings(subjectAccountId, tokenProfile, tokenHash); + return HEX.formatHex( + preimage(OperationKind.TOKEN_LOGOUT, subjectAccountId, tokenProfile, tokenHash)); + } + + public static String accountLogoutAllPreimageHex( + UUID subjectAccountId, String tokenProfile, String presentedTokenHash) { + validateBindings(subjectAccountId, tokenProfile, presentedTokenHash); + return HEX.formatHex( + preimage( + OperationKind.ACCOUNT_LOGOUT_ALL, subjectAccountId, tokenProfile, presentedTokenHash)); + } + + private static String digest( + OperationKind operationKind, UUID subjectAccountId, String tokenProfile, String tokenHash) { + validateBindings(subjectAccountId, tokenProfile, tokenHash); + Objects.requireNonNull(operationKind, "A closed logout operation kind is required"); + byte[] preimage = preimage(operationKind, subjectAccountId, tokenProfile, tokenHash); + try { + return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(preimage)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void validateBindings( + UUID subjectAccountId, String tokenProfile, String tokenHash) { + if (subjectAccountId == null || new UUID(0L, 0L).equals(subjectAccountId)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + validateTokenProfile(tokenProfile); + validateTokenHash(tokenHash); + } + + private static byte[] preimage( + OperationKind operationKind, UUID subjectAccountId, String tokenProfile, String tokenHash) { + String tokenIdentityField = + operationKind == OperationKind.ACCOUNT_LOGOUT_ALL ? "presentedTokenHash" : "tokenHash"; + ByteArrayOutputStream output = new ByteArrayOutputStream(256); + appendSegment(output, DOMAIN); + appendStringField(output, "operationKind", operationKind.wireValue); + appendStringField(output, "subjectAccountId", subjectAccountId.toString()); + appendStringField(output, "tokenProfile", tokenProfile); + appendStringField(output, tokenIdentityField, tokenHash); + return output.toByteArray(); + } + + private static void appendStringField(ByteArrayOutputStream output, String name, String value) { + appendSegment(output, name); + appendSegment(output, "string"); + output.write('1'); + appendSegment(output, value); + } + + private static void appendSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private enum OperationKind { + TOKEN_LOGOUT("TOKEN_LOGOUT"), + ACCOUNT_LOGOUT_ALL("ACCOUNT_LOGOUT_ALL"); + + private final String wireValue; + + OperationKind(String wireValue) { + this.wireValue = wireValue; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java index 7ffb4e5855..55dfa0c8f8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeMembershipSnapshotDto.java @@ -4,11 +4,14 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; /** Same-fence Account snapshot candidate for the denied runtime membership RPC. */ public record RuntimeMembershipSnapshotDto( @@ -104,52 +107,48 @@ private static MembershipEvent requireConsistentSourceEvent( List outboxCheckpoints, List outboxSourceEvidence, MembershipEvent sourceEvent) { - if (!membershipExists) { - if (sourceEvent != null || !outboxSourceEvidence.isEmpty()) { - throw new IllegalArgumentException( - "Sequence-zero membership snapshot cannot carry an event source"); - } - return null; - } - - if (sourceEvent == null || outboxSourceEvidence.size() != 1) { - throw new IllegalArgumentException( - "Positive membership snapshot requires its exact source event"); - } - OutboxSourceEvidence source = outboxSourceEvidence.getFirst(); - MembershipEvent verified = MembershipAuthorityEventV1Codec.verify(source.canonicalEventJson()); - if (!verified.canonicalJson().equals(source.canonicalEventJson()) - || !sourceEvent.canonicalJson().equals(source.canonicalEventJson()) - || !verified.eventId().equals(source.eventId()) - || !verified.eventDigest().equals(source.eventDigest()) - || !verified.outboxStreamKey().equals(source.outboxStreamKey()) - || !verified.outboxSequence().equals(source.outboxSequence()) - || !verified.accountId().equals(accountUuid) - || !verified.tenantId().equals(tenantUuid) - || !verified - .membershipLifecycleState() - .equals(membershipBaseline.membershipLifecycleState()) - || !verified.membershipVersion().equals(membershipBaseline.membershipVersion()) - || !verified - .membershipAuthorityGeneration() - .equals(membershipBaseline.membershipAuthorityGeneration()) - || !verified.authorityTuple().equals(authorityTuple) - || !verified.issuanceFence().equals(issuanceFence) - || !verified.roles().equals(roles) - || verified.gameplayAdmissionAllowed() != gameplayAdmissionAllowed) { - throw new IllegalArgumentException( - "Positive membership source event differs from its exact Account snapshot"); + Optional validated = + RuntimeMembershipAuthorityEvidenceValidator.validate( + new Snapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + accountUuid, + tenantUuid, + membershipExists, + membershipBaseline.membershipLifecycleState(), + gameplayAdmissionAllowed, + membershipBaseline.membershipVersion(), + membershipBaseline.membershipAuthorityGeneration(), + roles, + authorityTuple, + issuanceFence, + outboxCheckpoints.stream() + .map( + checkpoint -> + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + checkpoint.outboxStreamKey(), checkpoint.outboxSequence())) + .toList(), + outboxSourceEvidence.stream() + .map( + source -> + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + source.outboxStreamKey(), + source.outboxSequence(), + source.eventId(), + source.eventDigest(), + source.canonicalEventJson())) + .toList())); + if (sourceEvent == null && validated.isPresent()) { + throw new IllegalArgumentException("Runtime membership source event is missing"); } - List matchingCheckpoints = - outboxCheckpoints.stream() - .filter(item -> item.outboxStreamKey().equals(verified.outboxStreamKey())) - .toList(); - if (matchingCheckpoints.size() != 1 - || !matchingCheckpoints.getFirst().outboxSequence().equals(verified.outboxSequence())) { + if (sourceEvent != null + && validated + .map(MembershipEvent::canonicalJson) + .filter(sourceEvent.canonicalJson()::equals) + .isEmpty()) { throw new IllegalArgumentException( - "Positive membership source event differs from its outbox checkpoint"); + "Runtime membership source event differs from its exact source evidence"); } - return verified; + return validated.orElse(null); } private static String requireCanonicalUuid(String value, String field) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java new file mode 100644 index 0000000000..0ce98e77e2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java @@ -0,0 +1,321 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Stores immutable source and lifecycle-result evidence for one Account logout-all operation. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountLogoutAllOperationRepository { + private static final String TABLE = "account_logout_all_operation_receipts"; + private static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + private static final String LIFECYCLE_RESULT = "LOGOUT_ALL_COMMITTED"; + private static final String SELECT_COLUMNS = + "request_id, account_id, account_uuid, operation_kind, request_digest_version, " + + "request_digest, presented_token_hash, token_profile, outbox_stream_key, outbox_sequence, " + + "event_id, event_digest, account_authority_generation, account_source_version, " + + "issuance_fence, issuance_fence_source_version, lifecycle_result"; + private static final HexFormat HEX = HexFormat.of(); + + private final DSLContext dsl; + + public AccountLogoutAllOperationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Exact request lookup; callers compare every immutable request binding before recovery. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByRequestId(UUID requestId) { + requireOwnerTransaction(); + requireRequestId(requestId); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE request_id = ?", requestId); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** + * Token identity lookup prevents an old presented token from being rebound to another request. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByPresentedTokenHash(String tokenHash) { + requireOwnerTransaction(); + byte[] hash = decodeDigest(tokenHash, "presented token hash"); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE presented_token_hash = ?", + hash); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** Inserts the one immutable lifecycle receipt for the source event. */ + @Transactional(propagation = Propagation.MANDATORY) + public LogoutAllReceipt insert(LogoutAllReceipt receipt) { + requireOwnerTransaction(); + validateReceipt(receipt); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, account_id, account_uuid, operation_kind, " + + "request_digest_version, request_digest, presented_token_hash, token_profile, " + + "outbox_stream_key, outbox_sequence, event_id, event_digest, " + + "account_authority_generation, account_source_version, issuance_fence, " + + "issuance_fence_source_version, lifecycle_result) " + + "VALUES (?, ?, ?, 'ACCOUNT_LOGOUT_ALL', 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'LOGOUT_ALL_COMMITTED')", + receipt.requestId(), + receipt.accountId(), + receipt.accountUuid(), + decodeDigest(receipt.requestDigest(), "request digest"), + decodeDigest(receipt.presentedTokenHash(), "presented token hash"), + receipt.tokenProfile(), + receipt.outboxStreamKey(), + receipt.outboxSequence(), + receipt.eventId(), + receipt.eventDigest(), + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion()); + if (inserted != 1) { + throw new IllegalStateException("Logout-all operation receipt was not inserted"); + } + return receipt; + } + + private LogoutAllReceipt toReceipt(Record row) { + return new LogoutAllReceipt( + requiredUuid(row.get("request_id", UUID.class), "request ID"), + requiredPositive(row.get("account_id", Long.class), "Account association"), + requiredUuid(row.get("account_uuid", UUID.class), "Account UUID"), + requireText(row.get("operation_kind", String.class), "operation kind"), + requiredPositive(row.get("request_digest_version", Integer.class), "digest version"), + encodeDigest(row.get("request_digest", byte[].class), "request digest"), + encodeDigest(row.get("presented_token_hash", byte[].class), "presented token hash"), + requireText(row.get("token_profile", String.class), "token profile"), + requireText(row.get("outbox_stream_key", String.class), "outbox stream key"), + requiredPositive(row.get("outbox_sequence", Long.class), "outbox sequence"), + requireText(row.get("event_id", String.class), "event ID"), + requireText(row.get("event_digest", String.class), "event digest"), + requiredPositive( + row.get("account_authority_generation", Long.class), "Account authority generation"), + requiredPositive(row.get("account_source_version", Long.class), "Account source version"), + requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"), + requiredPositive( + row.get("issuance_fence_source_version", Long.class), "issuance-fence source version"), + requireText(row.get("lifecycle_result", String.class), "lifecycle result")); + } + + private static void validateReceipt(LogoutAllReceipt receipt) { + Objects.requireNonNull(receipt, "logout-all receipt is required"); + requireRequestId(receipt.requestId()); + decodeDigest(receipt.requestDigest(), "request digest"); + decodeDigest(receipt.presentedTokenHash(), "presented token hash"); + AccountLogoutRequestDigest.validateTokenProfile(receipt.tokenProfile()); + if (receipt.accountId() <= 0L + || receipt.accountUuid() == null + || isNil(receipt.accountUuid()) + || receipt.requestDigestVersion() != 1 + || !AccountLogoutRequestDigest.accountLogoutAll( + receipt.accountUuid(), receipt.tokenProfile(), receipt.presentedTokenHash()) + .equals(receipt.requestDigest()) + || receipt.outboxSequence() <= 0L + || receipt.accountAuthorityGeneration() <= 0L + || receipt.accountSourceVersion() <= 0L + || receipt.issuanceFence() <= 0L + || receipt.issuanceFenceSourceVersion() <= 0L + || !accountStreamKey(receipt.accountUuid()).equals(receipt.outboxStreamKey()) + || !expectedEventId(receipt.requestId()).equals(receipt.eventId()) + || receipt.eventDigest() == null + || !receipt.eventDigest().matches("sha256:[0-9a-f]{64}") + || !LIFECYCLE_RESULT.equals(receipt.lifecycleResult())) { + throw new IllegalArgumentException("Logout-all operation receipt is malformed"); + } + requireBoundedText(receipt.operationKind(), "operation kind", 32); + if (!"ACCOUNT_LOGOUT_ALL".equals(receipt.operationKind())) { + throw new IllegalArgumentException("Logout-all operation kind is invalid"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Logout-all operation storage requires an active Account transaction"); + } + } + + private static UUID requiredUuid(UUID value, String field) { + if (value == null || isNil(value)) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static long requiredPositive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static int requiredPositive(Integer value, String field) { + if (value == null || value <= 0) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static String requireText(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static void requireBoundedText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + "Logout-all receipt " + field + " must contain 1 to " + maximumLength + " characters"); + } + } + + private static void requireRequestId(UUID requestId) { + if (requestId == null || isNil(requestId)) { + throw new IllegalArgumentException("A canonical non-nil logout-all request UUID is required"); + } + } + + private static byte[] decodeDigest(String value, String field) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Logout-all receipt " + field + " is malformed"); + } + return HEX.parseHex(value); + } + + private static String encodeDigest(byte[] value, String field) { + if (value == null || value.length != 32) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return HEX.formatHex(value); + } + + private static String accountStreamKey(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + private static String expectedEventId(UUID requestId) { + return EVENT_ID_PREFIX + requestId; + } + + private static boolean isNil(UUID value) { + return new UUID(0L, 0L).equals(value); + } + + /** Immutable committed request binding, source checkpoint and lifecycle-only result. */ + public record LogoutAllReceipt( + UUID requestId, + long accountId, + UUID accountUuid, + String operationKind, + int requestDigestVersion, + String requestDigest, + String presentedTokenHash, + String tokenProfile, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + long accountAuthorityGeneration, + long accountSourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + String lifecycleResult) { + public LogoutAllReceipt { + requireRequestId(requestId); + decodeDigest(requestDigest, "request digest"); + decodeDigest(presentedTokenHash, "presented token hash"); + AccountLogoutRequestDigest.validateTokenProfile(tokenProfile); + if (accountId <= 0L + || accountUuid == null + || isNil(accountUuid) + || requestDigestVersion != 1 + || !AccountLogoutRequestDigest.accountLogoutAll( + accountUuid, tokenProfile, presentedTokenHash) + .equals(requestDigest) + || outboxSequence <= 0L + || accountAuthorityGeneration <= 0L + || accountSourceVersion <= 0L + || issuanceFence <= 0L + || issuanceFenceSourceVersion <= 0L + || !accountStreamKey(accountUuid).equals(outboxStreamKey) + || !expectedEventId(requestId).equals(eventId) + || eventDigest == null + || !eventDigest.matches("sha256:[0-9a-f]{64}") + || !LIFECYCLE_RESULT.equals(lifecycleResult)) { + throw new IllegalArgumentException("Logout-all operation receipt is malformed"); + } + requireBoundedText(operationKind, "operation kind", 32); + if (!"ACCOUNT_LOGOUT_ALL".equals(operationKind)) { + throw new IllegalArgumentException("Logout-all operation kind is invalid"); + } + } + + public static LogoutAllReceipt committed( + UUID requestId, + long accountId, + UUID accountUuid, + String requestDigest, + String presentedTokenHash, + String tokenProfile, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + ScopeState accountAuthority, + IssuanceFence issuanceFence) { + if (accountAuthority == null + || issuanceFence == null + || accountAuthority.issuanceFence() == null + || !issuanceFence.equals(accountAuthority.issuanceFence())) { + throw new IllegalArgumentException( + "Committed logout-all authority and issuance fence must match exactly"); + } + return new LogoutAllReceipt( + requestId, + accountId, + accountUuid, + "ACCOUNT_LOGOUT_ALL", + 1, + requestDigest, + presentedTokenHash, + tokenProfile, + outboxStreamKey, + outboxSequence, + eventId, + eventDigest, + accountAuthority.generation(), + accountAuthority.sourceVersion(), + issuanceFence.value(), + issuanceFence.sourceVersion(), + LIFECYCLE_RESULT); + } + + public IssuanceFence issuanceFenceEvidence() { + return new IssuanceFence(accountUuid, issuanceFence, issuanceFenceSourceVersion); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java new file mode 100644 index 0000000000..9a8464b1a1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java @@ -0,0 +1,511 @@ +package net.firedevops.firemud.accountservice.service; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +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.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; + +/** + * Narrow validator for the two closed Account account-scope source-event schemas currently emitted. + * It does not authenticate a caller or turn source evidence into recipient authority. + */ +public final class AccountAuthoritySourceEventReadback { + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final String PASSWORD_RESET_REQUEST_ID_PREFIX = + "account-password-reset-request-v1:"; + private static final String PASSWORD_RESET_EVENT_ID_PREFIX = "account-password-reset-event-v1:"; + private static final String PASSWORD_RESET_REQUEST_DOMAIN = "account-password-reset-request/v1"; + private static final String LOGOUT_ALL_EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + private static final String PASSWORD_RESET_OPERATION_KIND = "PASSWORD_RESET"; + private static final String LOGOUT_ALL_OPERATION_KIND = "ACCOUNT_LOGOUT_ALL"; + private static final String LOGOUT_ALL_RESULT = "LOGOUT_ALL_COMMITTED"; + + private final AccountAuthorityOutboxRepository outboxRepository; + private final AccountPasswordResetOperationRepository passwordResetRepository; + private final AccountLogoutAllOperationRepository logoutAllRepository; + + public AccountAuthoritySourceEventReadback( + AccountAuthorityOutboxRepository outboxRepository, + AccountPasswordResetOperationRepository passwordResetRepository, + AccountLogoutAllOperationRepository logoutAllRepository) { + this.outboxRepository = + Objects.requireNonNull(outboxRepository, "Account authority outbox repository is required"); + this.passwordResetRepository = + Objects.requireNonNull( + passwordResetRepository, "Password-reset operation repository is required"); + this.logoutAllRepository = + Objects.requireNonNull(logoutAllRepository, "Logout-all operation repository is required"); + } + + /** + * Proves the exact current Account source generation, source version and shared outbox + * checkpoint. Sequence zero is valid only for the original positive 1/1 source baseline and + * absent history. + */ + public LatestSourceSnapshot requireCurrentLatest(Account account, ScopeState current) { + requireAccountAssociation(account); + AuthorityScope expectedScope = AuthorityScope.account(account.getAccountUuid()); + if (current == null + || !expectedScope.equals(current.scope()) + || current.generation() <= 0L + || current.sourceVersion() <= 0L) { + throw new IllegalStateException("Account source authority scope or counters are invalid"); + } + requireCurrentFence(current.issuanceFence(), account.getAccountUuid()); + + String streamKey = streamKey(account.getAccountUuid()); + Optional checkpoint = outboxRepository.readCheckpoint(streamKey); + if (checkpoint.isEmpty()) { + if (current.generation() != 1L || current.sourceVersion() != 1L) { + throw new IllegalStateException( + "Account source sequence zero is not the original positive 1/1 baseline"); + } + return new LatestSourceSnapshot(0L, Optional.empty()); + } + + Checkpoint latestCheckpoint = checkpoint.orElseThrow(); + if (current.generation() == 1L && current.sourceVersion() == 1L) { + throw new IllegalStateException("Pristine Account source has contradictory event history"); + } + if (current.generation() <= 1L || current.sourceVersion() <= 1L) { + throw new IllegalStateException("Account source history is not proven"); + } + Event latestEvent = + outboxRepository + .findEvent(streamKey, latestCheckpoint.outboxSequence()) + .orElseThrow(() -> new IllegalStateException("Latest Account source event is missing")); + requireCheckpointMatches(latestCheckpoint, latestEvent); + VerifiedSourceEvent verified = verifyEvent(latestEvent, account.getAccountUuid()); + if (!Long.toString(current.generation()).equals(verified.accountAuthorityGeneration()) + || !Long.toString(current.sourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException( + "Latest Account source event does not match its current generation and source version"); + } + + if (verified.passwordReset().isPresent()) { + PasswordResetReceipt receipt = + passwordResetRepository + .findByRequestId(verified.requestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Latest Account password-reset event has no immutable operation receipt")); + requirePasswordResetReceipt(account, receipt, latestEvent, verified, current); + } else { + UUID requestId = parseLogoutAllRequestId(verified.requestId()); + LogoutAllReceipt receipt = + logoutAllRepository + .findByRequestId(requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Latest Account logout-all event has no immutable operation receipt")); + requireLogoutAllReceipt(account, receipt, latestEvent, verified, current); + } + return new LatestSourceSnapshot(latestEvent.outboxSequence(), Optional.of(latestEvent)); + } + + /** Validates one retained logout-all receipt after the account stream has advanced further. */ + public void requireLogoutAllReceiptRetained( + Account account, LogoutAllReceipt receipt, Event event, ScopeState current) { + requireAccountAssociation(account); + if (current == null + || !AuthorityScope.account(account.getAccountUuid()).equals(current.scope())) { + throw new IllegalStateException("Logout-all current Account source scope is invalid"); + } + requireCurrentFence(current.issuanceFence(), account.getAccountUuid()); + VerifiedSourceEvent verified = verifyEvent(event, account.getAccountUuid()); + requireLogoutAllReceipt(account, receipt, event, verified, current); + if (event.outboxSequence() > currentSourceSequence(account)) { + throw new IllegalStateException( + "Logout-all operation event is ahead of its source checkpoint"); + } + } + + /** + * Validates one selected immutable Account event and its receipt against the current local + * authority fence. Historical password-reset evidence deliberately does not prove that the old + * password verifier remains current or make that reset operation recoverable. + */ + public void requireRetainedEvent(Account account, Event event, ScopeState current) { + requireAccountAssociation(account); + if (current == null + || !AuthorityScope.account(account.getAccountUuid()).equals(current.scope()) + || current.generation() <= 0L + || current.sourceVersion() <= 0L) { + throw new IllegalStateException("Retained Account source authority state is invalid"); + } + requireCurrentFence(current.issuanceFence(), account.getAccountUuid()); + VerifiedSourceEvent verified = verifyEvent(event, account.getAccountUuid()); + if (event.outboxSequence() > currentSourceSequence(account)) { + throw new IllegalStateException("Selected Account source event is ahead of its checkpoint"); + } + + if (verified.passwordReset().isPresent()) { + PasswordResetReceipt receipt = + passwordResetRepository + .findByRequestId(verified.requestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account password-reset event has no immutable operation receipt")); + requirePasswordResetReceiptBinding(account, receipt, event, verified, current); + return; + } + + UUID requestId = parseLogoutAllRequestId(verified.requestId()); + LogoutAllReceipt receipt = + logoutAllRepository + .findByRequestId(requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account logout-all event has no immutable operation receipt")); + requireLogoutAllReceipt(account, receipt, event, verified, current); + } + + private long currentSourceSequence(Account account) { + return outboxRepository + .readCheckpoint(streamKey(account.getAccountUuid())) + .map(Checkpoint::outboxSequence) + .orElse(0L); + } + + private void requirePasswordResetReceipt( + Account account, + PasswordResetReceipt receipt, + Event event, + VerifiedSourceEvent verified, + ScopeState current) { + requirePasswordResetReceiptBinding(account, receipt, event, verified, current); + requireCurrentPasswordVerifier(account, receipt); + } + + private void requirePasswordResetReceiptBinding( + Account account, + PasswordResetReceipt receipt, + Event event, + VerifiedSourceEvent verified, + ScopeState current) { + if (receipt.accountId() != account.getId() + || !account.getAccountUuid().equals(receipt.accountUuid()) + || !PASSWORD_RESET_OPERATION_KIND.equals(receipt.operationKind()) + || receipt.requestDigestVersion() != 1 + || !streamKey(account.getAccountUuid()).equals(receipt.outboxStreamKey()) + || receipt.outboxSequence() != event.outboxSequence() + || !receipt.requestId().equals(event.requestId()) + || !receipt.eventId().equals(event.eventId()) + || !receipt.eventDigest().equals(event.eventDigest()) + || !receipt.eventId().equals(PASSWORD_RESET_EVENT_ID_PREFIX + receipt.tokenHash()) + || !receipt.requestId().equals(PASSWORD_RESET_REQUEST_ID_PREFIX + receipt.tokenHash()) + || !Long.toString(receipt.accountAuthorityGeneration()) + .equals(verified.accountAuthorityGeneration()) + || !Long.toString(receipt.accountSourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException( + "Latest Account password-reset receipt does not match its source event"); + } + String expectedDigest = + passwordResetRequestDigest( + receipt.accountUuid(), + receipt.tokenHash(), + receipt.tokenExpiresAt().toString(), + receipt.passwordVerifierDigest()); + if (!constantTimeTextEquals(expectedDigest, receipt.requestDigest())) { + throw new IllegalStateException( + "Latest Account password-reset receipt request digest is inconsistent"); + } + requireReceiptNotAhead( + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion(), + current, + "Password-reset"); + } + + private void requireCurrentPasswordVerifier(Account account, PasswordResetReceipt receipt) { + String currentVerifier = account.getPasswordHash(); + if (currentVerifier == null + || currentVerifier.isBlank() + || !constantTimeTextEquals(sha256Hex(currentVerifier), receipt.passwordVerifierDigest())) { + throw new IllegalStateException( + "Latest Account password-reset event does not match the current password verifier"); + } + } + + private void requireLogoutAllReceipt( + Account account, + LogoutAllReceipt receipt, + Event event, + VerifiedSourceEvent verified, + ScopeState current) { + UUID requestId = parseLogoutAllRequestId(verified.requestId()); + if (!requestId.toString().equals(verified.requestId()) + || !requestId.equals(receipt.requestId()) + || receipt.accountId() != account.getId() + || !account.getAccountUuid().equals(receipt.accountUuid()) + || !LOGOUT_ALL_OPERATION_KIND.equals(receipt.operationKind()) + || receipt.requestDigestVersion() != 1 + || !receipt.lifecycleResult().equals(LOGOUT_ALL_RESULT) + || !streamKey(account.getAccountUuid()).equals(receipt.outboxStreamKey()) + || receipt.outboxSequence() != event.outboxSequence() + || !receipt.requestId().toString().equals(event.requestId()) + || !receipt.eventId().equals(event.eventId()) + || !receipt.eventDigest().equals(event.eventDigest()) + || !receipt.eventId().equals(LOGOUT_ALL_EVENT_ID_PREFIX + receipt.requestId()) + || !Long.toString(receipt.accountAuthorityGeneration()) + .equals(verified.accountAuthorityGeneration()) + || !Long.toString(receipt.accountSourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException("Latest Account logout-all receipt does not match its event"); + } + String expectedRequestDigest = + AccountLogoutRequestDigest.accountLogoutAll( + receipt.accountUuid(), receipt.tokenProfile(), receipt.presentedTokenHash()); + if (!constantTimeTextEquals(expectedRequestDigest, receipt.requestDigest())) { + throw new IllegalStateException( + "Account logout-all receipt request digest does not match its immutable caller bindings"); + } + requireReceiptNotAhead( + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion(), + current, + "Logout-all"); + } + + private UUID parseLogoutAllRequestId(String requestIdText) { + UUID requestId; + try { + requestId = UUID.fromString(requestIdText); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Logout-all source request ID is malformed", exception); + } + if (!requestId.toString().equals(requestIdText)) { + throw new IllegalStateException("Logout-all source request ID is not canonical"); + } + return requestId; + } + + private static VerifiedSourceEvent verifyEvent(Event event, UUID accountUuid) { + if (event == null) { + throw new IllegalStateException("Account source event is missing"); + } + String payload = new String(event.payload(), StandardCharsets.UTF_8); + try { + PasswordResetAuthorityEvent reset = PasswordResetAuthorityEventV1Codec.verify(payload); + if (!MessageDigest.isEqual(event.payload(), reset.canonicalJsonUtf8()) + || !event.outboxStreamKey().equals(reset.outboxStreamKey()) + || !event.requestId().equals(reset.requestId()) + || !event.eventId().equals(reset.eventId()) + || !event.eventDigest().equals(reset.eventDigest()) + || !accountUuid.toString().equals(reset.accountId()) + || !Long.toString(event.outboxSequence()).equals(reset.outboxSequence())) { + throw new IllegalStateException("Account password-reset event readback is inconsistent"); + } + return VerifiedSourceEvent.passwordReset(reset); + } catch (IllegalArgumentException resetFailure) { + try { + AccountLogoutAllAuthorityEvent logout = + AccountLogoutAllAuthorityEventV1Codec.verify(payload); + if (!MessageDigest.isEqual(event.payload(), logout.canonicalJsonUtf8()) + || !event.outboxStreamKey().equals(logout.outboxStreamKey()) + || !event.requestId().equals(logout.requestId()) + || !event.eventId().equals(logout.eventId()) + || !event.eventDigest().equals(logout.eventDigest()) + || !accountUuid.toString().equals(logout.accountId()) + || !Long.toString(event.outboxSequence()).equals(logout.outboxSequence())) { + throw new IllegalStateException("Account logout-all event readback is inconsistent"); + } + return VerifiedSourceEvent.logoutAll(logout); + } catch (IllegalArgumentException logoutFailure) { + logoutFailure.addSuppressed(resetFailure); + throw new IllegalStateException( + "Account source event is not a valid declared password-reset or logout-all event", + logoutFailure); + } + } + } + + /** Reuses the closed schema validator for immutable source-result constructor invariants. */ + static void requireEventMatchesSnapshot( + Event event, UUID accountUuid, ScopeState current, boolean mustBeCurrentLatest) { + if (accountUuid == null + || current == null + || !AuthorityScope.account(accountUuid).equals(current.scope()) + || current.generation() <= 0L + || current.sourceVersion() <= 0L) { + throw new IllegalStateException("Account source snapshot scope or counters are invalid"); + } + VerifiedSourceEvent verified = verifyEvent(event, accountUuid); + BigInteger eventGeneration = new BigInteger(verified.accountAuthorityGeneration()); + BigInteger eventSourceVersion = new BigInteger(verified.sourceVersion()); + BigInteger currentGeneration = BigInteger.valueOf(current.generation()); + BigInteger currentSourceVersion = BigInteger.valueOf(current.sourceVersion()); + boolean countersMatch = + mustBeCurrentLatest + ? eventGeneration.equals(currentGeneration) + && eventSourceVersion.equals(currentSourceVersion) + : eventGeneration.compareTo(currentGeneration) <= 0 + && eventSourceVersion.compareTo(currentSourceVersion) <= 0; + if (!countersMatch) { + throw new IllegalStateException( + "Account source event counters contradict or lead the current snapshot"); + } + } + + private void requireReceiptNotAhead( + long generation, + long sourceVersion, + long fence, + long fenceSourceVersion, + ScopeState current, + String operation) { + IssuanceFence currentFence = current.issuanceFence(); + if (generation > current.generation() + || sourceVersion > current.sourceVersion() + || fence > currentFence.value() + || fenceSourceVersion > currentFence.sourceVersion()) { + throw new IllegalStateException(operation + " receipt is ahead of current Account authority"); + } + } + + private void requireCurrentFence(IssuanceFence fence, UUID accountUuid) { + if (fence == null + || !accountUuid.equals(fence.accountId()) + || fence.value() <= 0L + || fence.sourceVersion() <= 0L) { + throw new IllegalStateException("Account source issuance fence is missing or invalid"); + } + } + + private void requireAccountAssociation(Account account) { + AccountIdentityProvenance provenance = + account == null ? null : account.getAccountUuidProvenance(); + if (account == null + || account.getId() == null + || account.getId() <= 0L + || account.getAccountUuid() == null + || new UUID(0L, 0L).equals(account.getAccountUuid()) + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION + && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT)) { + throw new IllegalStateException("Verified persisted Account association is required"); + } + } + + private void requireCheckpointMatches(Checkpoint checkpoint, Event event) { + if (!checkpoint.outboxStreamKey().equals(event.outboxStreamKey()) + || checkpoint.outboxSequence() != event.outboxSequence() + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new IllegalStateException("Account source checkpoint differs from its latest event"); + } + } + + private String streamKey(UUID accountUuid) { + return STREAM_PREFIX + accountUuid; + } + + private String passwordResetRequestDigest( + UUID accountUuid, String tokenHash, String tokenExpiresAt, String verifierDigest) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + updateLengthPrefixed(digest, PASSWORD_RESET_REQUEST_DOMAIN); + updateLengthPrefixed(digest, PASSWORD_RESET_OPERATION_KIND); + updateLengthPrefixed(digest, accountUuid.toString()); + updateLengthPrefixed(digest, tokenHash); + updateLengthPrefixed(digest, tokenExpiresAt); + updateLengthPrefixed(digest, verifierDigest); + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private void updateLengthPrefixed(MessageDigest digest, String value) { + if (value == null) { + throw new IllegalArgumentException("Password-reset request field is required"); + } + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } + + private String sha256Hex(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private boolean constantTimeTextEquals(String left, String right) { + return left != null + && right != null + && MessageDigest.isEqual( + left.getBytes(StandardCharsets.US_ASCII), right.getBytes(StandardCharsets.US_ASCII)); + } + + /** Current exact source checkpoint; empty event is legal only for the proven 1/1 baseline. */ + public record LatestSourceSnapshot(long outboxSequence, Optional latestEvent) { + public LatestSourceSnapshot { + latestEvent = Objects.requireNonNull(latestEvent, "latest source event optional is required"); + if (outboxSequence < 0L + || (outboxSequence == 0L && latestEvent.isPresent()) + || (outboxSequence > 0L + && (latestEvent.isEmpty() + || latestEvent.orElseThrow().outboxSequence() != outboxSequence))) { + throw new IllegalArgumentException("Account latest source snapshot is inconsistent"); + } + } + } + + private record VerifiedSourceEvent( + String requestId, + String accountAuthorityGeneration, + String sourceVersion, + Optional passwordReset) { + private static VerifiedSourceEvent passwordReset(PasswordResetAuthorityEvent event) { + return new VerifiedSourceEvent( + event.requestId(), + event.accountAuthorityGeneration(), + event.sourceVersion(), + Optional.of(event)); + } + + private static VerifiedSourceEvent logoutAll(AccountLogoutAllAuthorityEvent event) { + return new VerifiedSourceEvent( + event.requestId(), + event.accountAuthorityGeneration(), + event.sourceVersion(), + Optional.empty()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java new file mode 100644 index 0000000000..104217fe25 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java @@ -0,0 +1,237 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +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.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired owner-local reader for current and selected historical Account authority source events. + * Returned source evidence is not recipient authority. + */ +public final class AccountAuthoritySourceReader { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String ACCOUNT_STREAM_PREFIX = "account:auth-authority:v1:account/"; + + private final AccountRepository accountRepository; + private final AccountAuthorityGenerationRepository generationRepository; + private final AccountAuthorityOutboxRepository outboxRepository; + private final AccountAuthoritySourceEventReadback sourceEventReadback; + private final TransactionTemplate ownerTransaction; + + public AccountAuthoritySourceReader( + AccountRepository accountRepository, + AccountAuthorityGenerationRepository generationRepository, + AccountAuthorityOutboxRepository outboxRepository, + AccountAuthoritySourceEventReadback sourceEventReadback, + PlatformTransactionManager transactionManager) { + this.accountRepository = + Objects.requireNonNull(accountRepository, "Account repository is required"); + this.generationRepository = + Objects.requireNonNull(generationRepository, "authority generation repository is required"); + this.outboxRepository = + Objects.requireNonNull(outboxRepository, "authority outbox repository is required"); + this.sourceEventReadback = + Objects.requireNonNull(sourceEventReadback, "source event readback is required"); + + this.ownerTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** Reads the current positive Account source and its exact latest event, if one exists. */ + public AccountSourceSnapshot readCurrent(UUID accountId) { + requireCanonicalAccountId(accountId); + requireNoAmbientTransaction(); + return requireTransactionResult( + ownerTransaction.execute( + status -> readCurrentSnapshot(loadLockedAccount(accountId), accountId))); + } + + /** + * Reads one positive immutable event from this Account stream together with the current source + * snapshot that fences its use. + */ + public AccountSourceEventReadback readCommittedEvent(UUID accountId, long outboxSequence) { + requireCanonicalAccountId(accountId); + if (outboxSequence <= 0L) { + throw new IllegalArgumentException("A positive Account source event sequence is required"); + } + requireNoAmbientTransaction(); + return requireTransactionResult( + ownerTransaction.execute( + status -> { + Account account = loadLockedAccount(accountId); + AccountSourceSnapshot current = readCurrentSnapshot(account, accountId); + if (outboxSequence > current.outboxSequence()) { + throw new IllegalStateException( + "Selected Account source event is ahead of its current checkpoint"); + } + Event requested = + outboxRepository + .findEvent(current.outboxStreamKey(), outboxSequence) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account source event is missing")); + if (!current.outboxStreamKey().equals(requested.outboxStreamKey()) + || requested.outboxSequence() != outboxSequence) { + throw new IllegalStateException( + "Selected Account source event identity changed during readback"); + } + sourceEventReadback.requireRetainedEvent(account, requested, current.sourceState()); + return new AccountSourceEventReadback(current, requested); + })); + } + + private AccountSourceSnapshot readCurrentSnapshot(Account account, UUID accountId) { + AuthorityScope scope = AuthorityScope.account(accountId); + ScopeState state = generationRepository.read(scope); + if (state == null || !scope.equals(state.scope())) { + throw new IllegalStateException("Current Account authority scope changed during readback"); + } + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest = + sourceEventReadback.requireCurrentLatest(account, state); + return new AccountSourceSnapshot( + accountId, + state, + accountStreamKey(accountId), + latest.outboxSequence(), + latest.latestEvent()); + } + + private Account loadLockedAccount(UUID accountId) { + Account associated = + accountRepository + .findByAccountUuid(accountId) + .orElseThrow( + () -> new IllegalStateException("Persisted Account UUID association is missing")); + requirePersistedAssociation(associated, accountId); + + Account locked = + accountRepository + .findByIdForUpdate(associated.getId()) + .orElseThrow( + () -> new IllegalStateException("Persisted Account source row is missing")); + requirePersistedAssociation(locked, accountId); + if (!Objects.equals(associated.getId(), locked.getId()) + || !Objects.equals(associated.getAccountUuid(), locked.getAccountUuid()) + || associated.getAccountUuidProvenance() != locked.getAccountUuidProvenance() + || !Objects.equals( + associated.getAccountUuidSourceNumericId(), locked.getAccountUuidSourceNumericId())) { + throw new IllegalStateException( + "Locked Account row changed its exact UUID association or provenance"); + } + return locked; + } + + private void requirePersistedAssociation(Account account, UUID accountId) { + AccountIdentityProvenance provenance = + account == null ? null : account.getAccountUuidProvenance(); + if (account == null + || account.getId() == null + || account.getId() <= 0L + || !accountId.equals(account.getAccountUuid()) + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION + && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT)) { + throw new IllegalStateException("Verified persisted Account association is required"); + } + } + + private static void requireCanonicalAccountId(UUID accountId) { + if (accountId == null || NIL_UUID.equals(accountId)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account authority source reader must own its transaction without an ambient transaction"); + } + } + + private static T requireTransactionResult(T result) { + if (result == null) { + throw new IllegalStateException("Account authority source readback returned no result"); + } + return result; + } + + private static String accountStreamKey(UUID accountId) { + return ACCOUNT_STREAM_PREFIX + accountId; + } + + /** Immutable current owner-local source snapshot; it carries no credential or recipient tuple. */ + public record AccountSourceSnapshot( + UUID accountId, + ScopeState sourceState, + String outboxStreamKey, + long outboxSequence, + Optional latestEvent) { + public AccountSourceSnapshot { + requireCanonicalAccountId(accountId); + Objects.requireNonNull(sourceState, "Account source state is required"); + Objects.requireNonNull(outboxStreamKey, "Account source stream key is required"); + latestEvent = Objects.requireNonNull(latestEvent, "latest source event optional is required"); + AuthorityScope expectedScope = AuthorityScope.account(accountId); + if (!expectedScope.equals(sourceState.scope()) + || sourceState.generation() <= 0L + || sourceState.sourceVersion() <= 0L + || !outboxStreamKey.equals(accountStreamKey(accountId)) + || sourceState.issuanceFence() == null + || !accountId.equals(sourceState.issuanceFence().accountId()) + || sourceState.issuanceFence().value() <= 0L + || sourceState.issuanceFence().sourceVersion() <= 0L + || outboxSequence < 0L + || (outboxSequence == 0L + && (sourceState.generation() != 1L + || sourceState.sourceVersion() != 1L + || latestEvent.isPresent())) + || (outboxSequence > 0L + && (sourceState.generation() <= 1L + || sourceState.sourceVersion() <= 1L + || latestEvent.isEmpty() + || latestEvent.orElseThrow().outboxSequence() != outboxSequence + || !outboxStreamKey.equals(latestEvent.orElseThrow().outboxStreamKey())))) { + throw new IllegalArgumentException("Account source snapshot is inconsistent"); + } + latestEvent.ifPresent( + event -> + AccountAuthoritySourceEventReadback.requireEventMatchesSnapshot( + event, accountId, sourceState, true)); + } + } + + /** Immutable selected event paired with the current Account source fence. */ + public record AccountSourceEventReadback( + AccountSourceSnapshot currentSnapshot, Event requestedEvent) { + public AccountSourceEventReadback { + Objects.requireNonNull(currentSnapshot, "current Account source snapshot is required"); + Objects.requireNonNull(requestedEvent, "selected Account source event is required"); + if (requestedEvent.outboxSequence() <= 0L + || requestedEvent.outboxSequence() > currentSnapshot.outboxSequence() + || !currentSnapshot.outboxStreamKey().equals(requestedEvent.outboxStreamKey())) { + throw new IllegalArgumentException("Selected Account source event is inconsistent"); + } + AccountAuthoritySourceEventReadback.requireEventMatchesSnapshot( + requestedEvent, currentSnapshot.accountId(), currentSnapshot.sourceState(), false); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java new file mode 100644 index 0000000000..18844f4f3b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java @@ -0,0 +1,329 @@ +package net.firedevops.firemud.accountservice.service; + +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.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; + +/** Closed current-snapshot projection of one durable Account account-generation source. */ +public record AccountGenerationProjection( + String accountId, + String accountAuthorityGeneration, + String sourceVersion, + String outboxStreamKey, + String outboxSequence, + Optional sourceEvent) { + public static final String SCHEMA_VERSION = "account-auth-account-generation-projection/v1"; + public static final String KEY_PREFIX = "session:auth:generation:account:"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("0|[1-9][0-9]*"); + 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 REQUIRED_FIELDS = + Set.of( + "schemaVersion", + "accountId", + "accountAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence"); + private static final Set ALL_FIELDS = + Set.of( + "schemaVersion", + "accountId", + "accountAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent"); + + public AccountGenerationProjection { + requireCanonicalAccountId(accountId); + requirePositiveDecimal(accountAuthorityGeneration, "accountAuthorityGeneration"); + requirePositiveDecimal(sourceVersion, "sourceVersion"); + requireNonNegativeDecimal(outboxSequence, "outboxSequence"); + if (!streamKeyForAccount(accountId).equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Account generation projection stream key is not canonical"); + } + sourceEvent = Objects.requireNonNull(sourceEvent, "sourceEvent optional is required"); + BigInteger sequence = new BigInteger(outboxSequence); + if (sequence.signum() == 0) { + if (!"1".equals(accountAuthorityGeneration) + || !"1".equals(sourceVersion) + || sourceEvent.isPresent()) { + throw new IllegalArgumentException( + "Account sequence zero requires the original 1/1 source baseline and no event"); + } + } else { + if (new BigInteger(accountAuthorityGeneration).compareTo(BigInteger.ONE) <= 0 + || new BigInteger(sourceVersion).compareTo(BigInteger.ONE) <= 0 + || sourceEvent.isEmpty()) { + throw new IllegalArgumentException( + "Positive Account source sequence requires advanced counters and its exact event"); + } + validateSourceEvent( + sourceEvent.orElseThrow(), + accountId, + accountAuthorityGeneration, + sourceVersion, + outboxStreamKey, + outboxSequence); + } + } + + /** Builds projection evidence only from Account's owner-local current durable readback. */ + public static AccountGenerationProjection fromSource(AccountSourceSnapshot source) { + Objects.requireNonNull(source, "Account source snapshot is required"); + AuthorityScope scope = source.sourceState().scope(); + if (scope.kind() != ScopeKind.ACCOUNT || !source.accountId().equals(scope.accountId())) { + throw new IllegalArgumentException("Account source snapshot has a different authority scope"); + } + Optional event = + source.latestEvent().map(AccountGenerationProjection::decodeCanonicalEvent); + return new AccountGenerationProjection( + source.accountId().toString(), + Long.toString(source.sourceState().generation()), + Long.toString(source.sourceState().sourceVersion()), + source.outboxStreamKey(), + Long.toString(source.outboxSequence()), + event); + } + + /** + * Parses the closed wire shape and rejects noncanonical JSON and all alternate representations. + */ + public static AccountGenerationProjection parse(String json) { + Objects.requireNonNull(json, "projection JSON is required"); + final JsonNode root; + try { + root = JSON.readTree(json); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Account generation projection JSON is malformed", exception); + } + if (!(root instanceof ObjectNode object)) { + throw new IllegalArgumentException("Account generation projection must be a JSON object"); + } + Set fields = new HashSet<>(); + object.fieldNames().forEachRemaining(fields::add); + if (!fields.contains("sourceEvent") && !fields.equals(REQUIRED_FIELDS)) { + throw new IllegalArgumentException( + "Account generation projection has unknown or missing fields"); + } + if (fields.contains("sourceEvent") && !fields.equals(ALL_FIELDS)) { + throw new IllegalArgumentException( + "Account generation projection has unknown or missing fields"); + } + if (!SCHEMA_VERSION.equals(requireText(object, "schemaVersion"))) { + throw new IllegalArgumentException( + "Account generation projection schemaVersion is unsupported"); + } + Optional event = + fields.contains("sourceEvent") + ? Optional.of(requireText(object, "sourceEvent")) + : Optional.empty(); + AccountGenerationProjection projection = + new AccountGenerationProjection( + requireText(object, "accountId"), + requireText(object, "accountAuthorityGeneration"), + requireText(object, "sourceVersion"), + requireText(object, "outboxStreamKey"), + requireText(object, "outboxSequence"), + event); + if (!projection.toJson().equals(json)) { + throw new IllegalArgumentException("Account generation projection JSON is not canonical"); + } + return projection; + } + + public String key() { + return KEY_PREFIX + accountId; + } + + public String toJson() { + ObjectNode object = JSON.createObjectNode(); + object.put("schemaVersion", SCHEMA_VERSION); + object.put("accountId", accountId); + object.put("accountAuthorityGeneration", accountAuthorityGeneration); + object.put("sourceVersion", sourceVersion); + object.put("outboxStreamKey", outboxStreamKey); + object.put("outboxSequence", outboxSequence); + sourceEvent.ifPresent(value -> object.put("sourceEvent", value)); + try { + return JSON.writeValueAsString(object); + } catch (IOException exception) { + throw new IllegalStateException( + "Account generation projection cannot be serialized", exception); + } + } + + public BigInteger generationValue() { + return new BigInteger(accountAuthorityGeneration); + } + + public BigInteger sourceVersionValue() { + return new BigInteger(sourceVersion); + } + + public BigInteger outboxSequenceValue() { + return new BigInteger(outboxSequence); + } + + static String keyForAccount(UUID accountId) { + Objects.requireNonNull(accountId, "Account UUID is required"); + if (new UUID(0L, 0L).equals(accountId)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + return KEY_PREFIX + accountId; + } + + private static String streamKeyForAccount(String accountId) { + return STREAM_PREFIX + accountId; + } + + private static String decodeCanonicalEvent(Event event) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(event.payload())) + .toString(); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Account source event is not valid UTF-8", exception); + } + } + + private static void validateSourceEvent( + String eventJson, + String accountId, + String generation, + String sourceVersion, + String streamKey, + String sequence) { + String canonicalEvent; + try { + PasswordResetAuthorityEvent reset = PasswordResetAuthorityEventV1Codec.verify(eventJson); + canonicalEvent = new String(reset.canonicalJsonUtf8(), StandardCharsets.UTF_8); + requireEventBinding( + accountId, + generation, + sourceVersion, + streamKey, + sequence, + reset.accountId(), + reset.accountAuthorityGeneration(), + reset.sourceVersion(), + reset.outboxStreamKey(), + reset.outboxSequence()); + } catch (IllegalArgumentException resetFailure) { + try { + AccountLogoutAllAuthorityEvent logout = + AccountLogoutAllAuthorityEventV1Codec.verify(eventJson); + canonicalEvent = new String(logout.canonicalJsonUtf8(), StandardCharsets.UTF_8); + requireEventBinding( + accountId, + generation, + sourceVersion, + streamKey, + sequence, + logout.accountId(), + logout.accountAuthorityGeneration(), + logout.sourceVersion(), + logout.outboxStreamKey(), + logout.outboxSequence()); + } catch (IllegalArgumentException logoutFailure) { + logoutFailure.addSuppressed(resetFailure); + throw new IllegalArgumentException( + "Account source event is not one of the declared closed schemas", logoutFailure); + } + } + if (!canonicalEvent.equals(eventJson)) { + throw new IllegalArgumentException("Account source event JSON is not canonical"); + } + } + + private static void requireEventBinding( + String expectedAccount, + String expectedGeneration, + String expectedSourceVersion, + String expectedStream, + String expectedSequence, + String actualAccount, + String actualGeneration, + String actualSourceVersion, + String actualStream, + String actualSequence) { + if (!expectedAccount.equals(actualAccount) + || !expectedGeneration.equals(actualGeneration) + || !expectedSourceVersion.equals(actualSourceVersion) + || !expectedStream.equals(actualStream) + || !expectedSequence.equals(actualSequence)) { + throw new IllegalArgumentException( + "Account source event does not match its current projection checkpoint"); + } + } + + private static String requireText(ObjectNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Account generation projection " + field + " must be a string"); + } + return value.textValue(); + } + + private static void requireCanonicalAccountId(String value) { + Objects.requireNonNull(value, "accountId is required"); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException( + "Account generation projection accountId is not canonical"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Account generation projection accountId must be a lowercase canonical non-nil UUID", + malformed); + } + } + + private static void requirePositiveDecimal(String value, String field) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a positive canonical decimal string"); + } + } + + private static void requireNonNegativeDecimal(String value, String field) { + if (value == null || !NON_NEGATIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException( + field + " must be a non-negative canonical decimal string"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java new file mode 100644 index 0000000000..bf457b64e2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.PrefixDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisInvocationContract; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ArgumentSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.CompatibilityLevel; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.KeySpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.LossClass; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.MutationEffect; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.RedisRole; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ResetSensitivity; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ScriptCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.SupportedCoexistence; + +/** Registered Account-owned single-key compare-and-set for the account generation projection. */ +public final class AccountGenerationProjectionRedisContract { + public static final String SCRIPT_ID = "account.account-generation-projection.v1"; + public static final String RESOURCE_PATH = "redis/account_generation_projection_cas.lua"; + public static final String OWNER = "account-service"; + public static final String PRINCIPAL = "account_coord_app"; + public static final RedisRole ROLE = RedisRole.COORDINATION; + public static final String KEY_PREFIX = AccountGenerationProjection.KEY_PREFIX; + + private static final String RESOURCE_SHA256 = + "1c1df7fdf6edc42a9e3ad5dfd5a0db7c33295b41a9e5c28df2a65e98d9069c16"; + private static final RedisScriptDescriptor DESCRIPTOR = createDescriptor(); + private static final RedisContractRegistry REGISTRY = + new RedisContractRegistry( + List.of(new PrefixDeclaration(OWNER, ROLE, PRINCIPAL, KEY_PREFIX)), List.of(DESCRIPTOR)); + + private AccountGenerationProjectionRedisContract() {} + + public static RedisScriptDescriptor descriptor() { + return DESCRIPTOR; + } + + /** Declarative registry only; executable access stays private to the Account owner store. */ + public static RedisContractRegistry registry() { + return REGISTRY; + } + + static RedisInvocationContract prepareInvocation( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + Objects.requireNonNull(key, "Account generation key is required"); + requireCanonicalAccountKey(key); + return REGISTRY.prepareInvocation( + new InvocationRequest( + SCRIPT_ID, + RESOURCE_PATH, + RESOURCE_SHA256, + OWNER, + PRINCIPAL, + ROLE, + List.of(key), + List.of(expectedMode, expectedBytes, candidateBytes))); + } + + private static void requireCanonicalAccountKey(String key) { + if (!key.startsWith(KEY_PREFIX)) { + throw new IllegalArgumentException("Account generation key is outside its owner prefix"); + } + String accountId = key.substring(KEY_PREFIX.length()); + try { + UUID parsed = UUID.fromString(accountId); + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(accountId)) { + throw new IllegalArgumentException( + "Account generation key must use a canonical non-nil UUID"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Account generation key must use a canonical non-nil UUID", malformed); + } + } + + private static RedisScriptDescriptor createDescriptor() { + return new RedisScriptDescriptor( + SCRIPT_ID, + RESOURCE_PATH, + RESOURCE_SHA256, + OWNER, + PRINCIPAL, + ROLE, + List.of( + new KeySpec( + "accountGenerationProjection", KEY_PREFIX, HashTagDeclaration.NOT_REQUIRED)), + List.of( + new ArgumentSpec("expectedMode"), + new ArgumentSpec("expectedBytes"), + new ArgumentSpec("candidateBytes")), + ScriptCategory.SESSION_CAS, + List.of( + new OutcomeSpec("APPLIED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING), + new OutcomeSpec("REPLAY", OutcomeCategory.REPLAY, MutationEffect.NON_MUTATING), + new OutcomeSpec("STALE", OutcomeCategory.STALE, MutationEffect.NON_MUTATING), + new OutcomeSpec( + "INVALID", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING), + new OutcomeSpec( + "TTL_PRESENT", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING)), + ResetSensitivity.CLUSTER, + LossClass.EMPTY_REDIS_COLD_START_OR_RESET, + "On loss, fail closed and rebuild only from Account's exact current durable source snapshot.", + CompatibilityLevel.COMPATIBLE, + List.of(new SupportedCoexistence("v1", "v1")), + null); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java new file mode 100644 index 0000000000..3f2aa5ada4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java @@ -0,0 +1,587 @@ +package net.firedevops.firemud.accountservice.service; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +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.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired source-only Account logout-all mutation and immutable result readback. + * + *

This primitive does not authenticate a caller. Its caller must perform the initial exact token + * registry and Account evidence-bundle authorization required by ADR 0036 before invoking a new + * operation. It creates no authorization context and is not exposed through a REST, gRPC, or + * controller path. Exact committed retries return only the durable lifecycle result. + */ +public final class AccountLogoutAllAuthorityEventProducer { + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + private static final int DIGEST_VERSION = 1; + private static final String OPERATION_KIND = "ACCOUNT_LOGOUT_ALL"; + private static final HexFormat HEX = HexFormat.of(); + + private final AccountRepository accountRepository; + private final AccountAuthorityGenerationRepository generationRepository; + private final AccountAuthorityOutboxRepository outboxRepository; + private final AccountLogoutAllOperationRepository operationRepository; + private final AccountAuthoritySourceEventReadback sourceReadback; + private final TransactionTemplate ownerTransaction; + + public AccountLogoutAllAuthorityEventProducer( + AccountRepository accountRepository, + AccountAuthorityGenerationRepository generationRepository, + AccountAuthorityOutboxRepository outboxRepository, + AccountLogoutAllOperationRepository operationRepository, + AccountAuthoritySourceEventReadback sourceReadback, + DSLContext dsl, + PlatformTransactionManager transactionManager) { + this.accountRepository = + Objects.requireNonNull(accountRepository, "Account repository is required"); + this.generationRepository = + Objects.requireNonNull(generationRepository, "authority-generation repository is required"); + this.outboxRepository = + Objects.requireNonNull(outboxRepository, "authority outbox repository is required"); + this.operationRepository = + Objects.requireNonNull(operationRepository, "logout-all operation repository is required"); + this.sourceReadback = + Objects.requireNonNull(sourceReadback, "Account source-event readback is required"); + Objects.requireNonNull(dsl, "transaction-aware DSLContext is required"); + Objects.requireNonNull(transactionManager, "Account transaction manager is required"); + + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Commits one account-wide cutoff or recovers that request's exact original lifecycle result. + * + *

The request digest is recomputed from the exact closed operation tuple and compared with the + * supplied lowercase SHA-256 binding. The token profile and digest correlate the receipt; neither + * is proof of caller authorization. The supplied Account association and scope state are compared + * against locked persisted state. + */ + public LogoutAllResult commit( + UUID requestId, + int requestDigestVersion, + String requestDigest, + String tokenProfile, + String presentedTokenHash, + Account verifiedAccountAssociation, + ScopeState expectedAccountState) { + validateRequest( + requestId, requestDigestVersion, requestDigest, tokenProfile, presentedTokenHash); + validateExpectedInputs(verifiedAccountAssociation, expectedAccountState); + requireNoAmbientTransaction(); + + LogoutAllReceipt transactionResult = + ownerTransaction.execute( + status -> + commitInOwnerTransaction( + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + verifiedAccountAssociation, + expectedAccountState)); + if (transactionResult == null) { + throw new IllegalStateException("Logout-all source transaction returned no receipt"); + } + + LogoutAllReceipt committedResult = + readCommittedOperation( + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + verifiedAccountAssociation); + if (!transactionResult.equals(committedResult)) { + throw new IllegalStateException( + "Post-commit logout-all receipt differs from the source transaction result"); + } + return LogoutAllResult.valueOf(committedResult.lifecycleResult()); + } + + private LogoutAllReceipt commitInOwnerTransaction( + UUID requestId, + int requestDigestVersion, + String requestDigest, + String tokenProfile, + String presentedTokenHash, + Account requestedAccount, + ScopeState expectedAccountState) { + Account account = lockVerifiedAccount(requestedAccount); + String requestText = requestId.toString(); + + // The immutable request and token bindings take precedence over current server-derived + // counters. + Optional priorRequest = operationRepository.findByRequestId(requestId); + Optional priorToken = + operationRepository.findByPresentedTokenHash(presentedTokenHash); + if (priorRequest.isPresent()) { + LogoutAllReceipt receipt = priorRequest.orElseThrow(); + requireExactRetryBinding( + receipt, + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + account); + if (priorToken.isEmpty() || !receipt.equals(priorToken.orElseThrow())) { + throw new IllegalStateException("Logout-all token receipt index readback is inconsistent"); + } + return recoverReceipt(account, receipt); + } + if (priorToken.isPresent()) { + throw new OperationConflictException( + "Presented token identity is already bound to another logout-all request"); + } + + if (requestDigestVersion != DIGEST_VERSION) { + throw new IllegalArgumentException("Logout-all request digest version must be 1"); + } + String canonicalDigest = + AccountLogoutRequestDigest.accountLogoutAll( + account.getAccountUuid(), tokenProfile, presentedTokenHash); + if (!constantTimeTextEquals(canonicalDigest, requestDigest)) { + throw new IllegalArgumentException( + "Logout-all request digest does not match its canonical caller bindings"); + } + ScopeState current = + generationRepository.read(AuthorityScope.account(account.getAccountUuid())); + if (!current.equals(expectedAccountState)) { + throw new IllegalStateException("Logout-all Account source compare-and-advance is stale"); + } + AccountAuthoritySourceEventReadback.LatestSourceSnapshot source = + sourceReadback.requireCurrentLatest(account, current); + long nextGeneration = incrementExact(current.generation(), "Account authority generation"); + long nextSourceVersion = incrementExact(current.sourceVersion(), "Account source version"); + long nextIssuanceFence = + incrementExact(current.issuanceFence().value(), "Account issuance fence"); + incrementExact(current.issuanceFence().sourceVersion(), "issuance-fence source version"); + long nextSequence = incrementExact(source.outboxSequence(), "Account source outbox sequence"); + String streamKey = streamKey(account.getAccountUuid()); + String eventId = EVENT_ID_PREFIX + requestText; + + ScopeState advanced = generationRepository.advance(current, current.issuanceFence()); + requireAdvancedState(current, advanced, nextGeneration, nextSourceVersion, nextIssuanceFence); + + Event appended = + outboxRepository.append( + streamKey, + requestText, + sequence -> + eventEvidence( + account.getAccountUuid(), + requestId, + eventId, + sequence, + nextGeneration, + nextSourceVersion)); + if (appended.outboxSequence() != nextSequence) { + throw new IllegalStateException("Logout-all source outbox sequence did not advance once"); + } + AccountLogoutAllAuthorityEvent event = + requireEvent( + appended, + account.getAccountUuid(), + requestId, + eventId, + nextGeneration, + nextSourceVersion); + Checkpoint checkpoint = + outboxRepository + .readCheckpoint(streamKey) + .orElseThrow(() -> new IllegalStateException("Logout-all checkpoint is missing")); + requireCheckpointMatches(checkpoint, appended); + + LogoutAllReceipt receipt = + LogoutAllReceipt.committed( + requestId, + account.getId(), + account.getAccountUuid(), + requestDigest, + presentedTokenHash, + tokenProfile, + streamKey, + appended.outboxSequence(), + event.eventId(), + event.eventDigest(), + advanced, + advanced.issuanceFence()); + operationRepository.insert(receipt); + + Event requestReadback = + outboxRepository + .findEvent(streamKey, requestText) + .orElseThrow( + () -> new IllegalStateException("Logout-all request event readback is missing")); + Event sequenceReadback = + outboxRepository + .findEvent(streamKey, nextSequence) + .orElseThrow( + () -> new IllegalStateException("Logout-all sequence event readback is missing")); + if (!appended.equals(requestReadback) || !appended.equals(sequenceReadback)) { + throw new IllegalStateException("Logout-all immutable event readback differs from append"); + } + ScopeState sourceReadbackState = + generationRepository.read(AuthorityScope.account(account.getAccountUuid())); + if (!advanced.equals(sourceReadbackState)) { + throw new IllegalStateException("Logout-all source state readback differs from its commit"); + } + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest = + sourceReadback.requireCurrentLatest(account, sourceReadbackState); + if (latest.outboxSequence() != nextSequence + || latest.latestEvent().isEmpty() + || !appended.equals(latest.latestEvent().orElseThrow())) { + throw new IllegalStateException("Logout-all current source checkpoint readback differs"); + } + requireReceiptReadback( + receipt, + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + account); + return receipt; + } + + private LogoutAllReceipt recoverReceipt(Account account, LogoutAllReceipt receipt) { + ScopeState current = + generationRepository.read(AuthorityScope.account(account.getAccountUuid())); + sourceReadback.requireCurrentLatest(account, current); + Event event = + outboxRepository + .findEvent(receipt.outboxStreamKey(), receipt.outboxSequence()) + .orElseThrow(() -> new IllegalStateException("Logout-all historical event is missing")); + sourceReadback.requireLogoutAllReceiptRetained(account, receipt, event, current); + LogoutAllReceipt readback = + operationRepository + .findByRequestId(receipt.requestId()) + .orElseThrow(() -> new IllegalStateException("Logout-all retry receipt is missing")); + if (!receipt.equals(readback)) { + throw new IllegalStateException("Logout-all retry receipt changed during readback"); + } + Optional tokenReadback = + operationRepository.findByPresentedTokenHash(receipt.presentedTokenHash()); + if (tokenReadback.isEmpty() || !receipt.equals(tokenReadback.orElseThrow())) { + throw new IllegalStateException("Logout-all retry token receipt changed during readback"); + } + return readback; + } + + private LogoutAllReceipt readCommittedOperation( + UUID requestId, + int requestDigestVersion, + String requestDigest, + String tokenProfile, + String presentedTokenHash, + Account requestedAccount) { + requireNoAmbientTransaction(); + LogoutAllReceipt receipt = + ownerTransaction.execute( + status -> { + Account account = lockVerifiedAccount(requestedAccount); + LogoutAllReceipt committed = + operationRepository + .findByRequestId(requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Post-commit logout-all request receipt is missing")); + requireExactRetryBinding( + committed, + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + account); + return recoverReceipt(account, committed); + }); + if (receipt == null) { + throw new IllegalStateException("Post-commit logout-all receipt readback returned no result"); + } + return receipt; + } + + private LogoutAllReceipt requireReceiptReadback( + LogoutAllReceipt expected, + UUID requestId, + int requestDigestVersion, + String requestDigest, + String tokenProfile, + String presentedTokenHash, + Account account) { + LogoutAllReceipt byRequest = + operationRepository + .findByRequestId(requestId) + .orElseThrow(() -> new IllegalStateException("Logout-all receipt readback is missing")); + Optional byToken = + operationRepository.findByPresentedTokenHash(presentedTokenHash); + requireExactRetryBinding( + byRequest, + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + account); + if (!expected.equals(byRequest) + || byToken.isEmpty() + || !expected.equals(byToken.orElseThrow())) { + throw new IllegalStateException("Logout-all receipt readback differs from its insert"); + } + return byRequest; + } + + private void requireExactRetryBinding( + LogoutAllReceipt receipt, + UUID requestId, + int requestDigestVersion, + String requestDigest, + String tokenProfile, + String presentedTokenHash, + Account account) { + if (!receipt.requestId().equals(requestId) + || !OPERATION_KIND.equals(receipt.operationKind()) + || receipt.requestDigestVersion() != requestDigestVersion + || !constantTimeTextEquals(receipt.requestDigest(), requestDigest) + || !receipt.tokenProfile().equals(tokenProfile) + || !constantTimeTextEquals(receipt.presentedTokenHash(), presentedTokenHash) + || receipt.accountId() != account.getId() + || !receipt.accountUuid().equals(account.getAccountUuid())) { + throw new OperationConflictException( + "Logout-all request, digest, operation, token, or Account binding conflicts with its receipt"); + } + } + + private Account lockVerifiedAccount(Account requestedAccount) { + Account locked = + accountRepository + .findByIdForUpdate(requestedAccount.getId()) + .orElseThrow( + () -> new IllegalStateException("Verified Account association is missing")); + if (!Objects.equals(requestedAccount.getId(), locked.getId()) + || !Objects.equals(requestedAccount.getAccountUuid(), locked.getAccountUuid()) + || !Objects.equals( + requestedAccount.getAccountUuidSourceNumericId(), + locked.getAccountUuidSourceNumericId()) + || requestedAccount.getAccountUuidProvenance() != locked.getAccountUuidProvenance() + || !isVerifiedProvenance(locked.getAccountUuidProvenance())) { + throw new IllegalStateException("Verified Account association changed before logout-all"); + } + // The source readback enforces that this is an exact persisted UUID association. + if (locked.getId() == null + || locked.getId() <= 0L + || locked.getAccountUuid() == null + || new UUID(0L, 0L).equals(locked.getAccountUuid()) + || !locked.getId().equals(locked.getAccountUuidSourceNumericId())) { + throw new IllegalStateException("Verified persisted Account association is invalid"); + } + return locked; + } + + private EventEvidence eventEvidence( + UUID accountUuid, + UUID requestId, + String eventId, + long sequence, + long generation, + long sourceVersion) { + String streamKey = streamKey(accountUuid); + AccountLogoutAllAuthorityEvent event = + AccountLogoutAllAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", requestId.toString()), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", Long.toString(generation)), + Map.entry("sourceVersion", Long.toString(sourceVersion)), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", Long.toString(generation), + "outboxStreamKey", streamKey, + "outboxSequence", Long.toString(sequence))))); + return new EventEvidence(event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + } + + private AccountLogoutAllAuthorityEvent requireEvent( + Event event, + UUID accountUuid, + UUID requestId, + String eventId, + long generation, + long sourceVersion) { + AccountLogoutAllAuthorityEvent verified = + AccountLogoutAllAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + if (!MessageDigest.isEqual(event.payload(), verified.canonicalJsonUtf8()) + || !streamKey(accountUuid).equals(event.outboxStreamKey()) + || !requestId.toString().equals(event.requestId()) + || !eventId.equals(event.eventId()) + || !event.eventDigest().equals(verified.eventDigest()) + || !accountUuid.toString().equals(verified.accountId()) + || !Long.toString(event.outboxSequence()).equals(verified.outboxSequence()) + || !Long.toString(generation).equals(verified.accountAuthorityGeneration()) + || !Long.toString(sourceVersion).equals(verified.sourceVersion())) { + throw new IllegalStateException("Logout-all source event differs from its committed state"); + } + return verified; + } + + private void requireAdvancedState( + ScopeState previous, + ScopeState advanced, + long expectedGeneration, + long expectedSourceVersion, + long expectedFence) { + if (advanced == null + || !previous.scope().equals(advanced.scope()) + || advanced.generation() != expectedGeneration + || advanced.sourceVersion() != expectedSourceVersion + || advanced.issuanceFence() == null + || !previous.issuanceFence().accountId().equals(advanced.issuanceFence().accountId()) + || advanced.issuanceFence().value() != expectedFence + || advanced.issuanceFence().sourceVersion() + != incrementExact( + previous.issuanceFence().sourceVersion(), "issuance-fence source version")) { + throw new IllegalStateException( + "Logout-all Account source and issuance fence did not advance once"); + } + } + + private void requireCheckpointMatches(Checkpoint checkpoint, Event event) { + if (!checkpoint.outboxStreamKey().equals(event.outboxStreamKey()) + || checkpoint.outboxSequence() != event.outboxSequence() + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new IllegalStateException("Logout-all outbox checkpoint differs from its event"); + } + } + + private void validateRequest( + UUID requestId, + int requestDigestVersion, + String requestDigest, + String tokenProfile, + String presentedTokenHash) { + if (requestId == null || new UUID(0L, 0L).equals(requestId)) { + throw new IllegalArgumentException("A canonical non-nil logout-all request UUID is required"); + } + AccountLogoutRequestDigest.validateTokenProfile(tokenProfile); + if (requestDigestVersion <= 0) { + throw new IllegalArgumentException("Logout-all request digest version must be positive"); + } + decodeDigest(requestDigest, "request digest"); + AccountLogoutRequestDigest.validateTokenHash(presentedTokenHash); + } + + private void validateExpectedInputs(Account account, ScopeState expectedState) { + if (account == null + || account.getId() == null + || account.getId() <= 0L + || account.getAccountUuid() == null + || new UUID(0L, 0L).equals(account.getAccountUuid()) + || !isVerifiedProvenance(account.getAccountUuidProvenance()) + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId())) { + throw new IllegalArgumentException("Verified persisted Account association is required"); + } + if (expectedState == null + || !AuthorityScope.account(account.getAccountUuid()).equals(expectedState.scope()) + || expectedState.generation() <= 0L + || expectedState.sourceVersion() <= 0L + || expectedState.issuanceFence() == null + || !account.getAccountUuid().equals(expectedState.issuanceFence().accountId()) + || expectedState.issuanceFence().value() <= 0L + || expectedState.issuanceFence().sourceVersion() <= 0L) { + throw new IllegalArgumentException("Expected Account authority scope and fence are required"); + } + } + + private boolean isVerifiedProvenance(AccountIdentityProvenance provenance) { + return provenance == AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + || provenance == AccountIdentityProvenance.ACCOUNT_V29_MIGRATION + || provenance == AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT; + } + + private void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Logout-all source operations must own their Account transaction without an ambient transaction"); + } + } + + private String streamKey(UUID accountUuid) { + return STREAM_PREFIX + accountUuid; + } + + private static String decodeDigest(String value, String field) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Logout-all " + field + " must be lowercase SHA-256 hex"); + } + HEX.parseHex(value); + return value; + } + + private boolean constantTimeTextEquals(String left, String right) { + return left != null + && right != null + && MessageDigest.isEqual( + left.getBytes(StandardCharsets.US_ASCII), right.getBytes(StandardCharsets.US_ASCII)); + } + + private long incrementExact(long value, String field) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Logout-all " + field + " is exhausted", overflow); + } + } + + /** Caller bindings changed for an existing logout-all request or token identity. */ + public static final class OperationConflictException extends IllegalStateException { + public OperationConflictException(String message) { + super(message); + } + } + + /** The non-authorizing lifecycle outcome returned by both initial commit and exact retry. */ + public enum LogoutAllResult { + LOGOUT_ALL_COMMITTED + } +} 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 5661909bbc..41da470be0 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 @@ -27,6 +27,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition; @@ -34,6 +35,7 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -43,9 +45,15 @@ import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository.ApprovedAssociation; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; 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.MembershipAuthorityEventV1Codec.AuthorityTuple; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; @@ -70,6 +78,7 @@ public class AccountMembershipAuthorityEventProducer { private final FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository; private final AccountAuthorityGenerationRepository authorityGenerationRepository; private final AccountAuthorityOutboxRepository authorityOutboxRepository; + private final AccountAuthoritySourceEventReadback accountAuthoritySourceEventReadback; private final AccountMembershipTransitionReceiptRepository transitionReceiptRepository; private final AccountTenantMembershipRepository membershipRepository; private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; @@ -82,6 +91,8 @@ public AccountMembershipAuthorityEventProducer( FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository, AccountAuthorityGenerationRepository authorityGenerationRepository, AccountAuthorityOutboxRepository authorityOutboxRepository, + AccountPasswordResetOperationRepository passwordResetOperationRepository, + AccountLogoutAllOperationRepository logoutAllOperationRepository, AccountMembershipTransitionReceiptRepository transitionReceiptRepository, AccountTenantMembershipRepository membershipRepository, AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository) { @@ -92,6 +103,11 @@ public AccountMembershipAuthorityEventProducer( this.freshTenantIdentityAssociationRepository = freshTenantIdentityAssociationRepository; this.authorityGenerationRepository = authorityGenerationRepository; this.authorityOutboxRepository = authorityOutboxRepository; + this.accountAuthoritySourceEventReadback = + new AccountAuthoritySourceEventReadback( + authorityOutboxRepository, + passwordResetOperationRepository, + logoutAllOperationRepository); this.transitionReceiptRepository = transitionReceiptRepository; this.membershipRepository = membershipRepository; this.roleSnapshotRepository = roleSnapshotRepository; @@ -187,8 +203,9 @@ public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( throw new IllegalStateException( "Current Account membership differs from its V31 authority generation"); } - List upstreamCheckpoints = - readBaselineUpstreamCheckpoints(identity, authoritySnapshot); + CurrentSourceEvidence currentSources = + readCurrentUpstreamSourceEvidence( + identity.accountUuid(), identity.tenantUuid(), authoritySnapshot); String streamKey = membershipStreamKey(identity); Checkpoint checkpoint = @@ -227,11 +244,16 @@ public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( "MEMBERSHIP_REACTIVATED".equals(transitionReceipt.transitionType()), authoritySnapshot); - List checkpoints = new ArrayList<>(upstreamCheckpoints); + List checkpoints = new ArrayList<>(currentSources.checkpoints()); checkpoints.add( new OutboxCheckpointEntry( checkpoint.outboxStreamKey(), Long.toString(checkpoint.outboxSequence()))); + List sourceEvidence = new ArrayList<>(currentSources.sourceEvidence()); + sourceEvidence.add(sourceEvidence(checkpoint, event)); checkpoints = orderedCheckpoints(checkpoints); + sourceEvidence = orderedSourceEvidence(sourceEvidence); + AuthorityTuple currentTuple = + currentAuthorityTuple(identity.tenantUuid(), authoritySnapshot, currentSources); return new PositiveMembershipSnapshot( true, verified.accountId(), @@ -241,11 +263,11 @@ public PositiveMembershipSnapshot readCurrentPositiveMembershipSnapshot( membershipVersionMap(verified, identity), verified.membershipAuthorityGeneration(), verified.roles(), - verified.authorityTuple(), - verified.issuanceFence(), + currentTuple, + decimal(authoritySnapshot.issuanceFence().value()), Instant.now(), checkpoints, - List.of(sourceEvidence(checkpoint, event)), + sourceEvidence, transitionReceipt, verified); } @@ -391,8 +413,9 @@ public RuntimeMembershipSnapshotDto readCurrentPairBoundInactiveMembershipSnapsh throw new IllegalStateException( "Current inactive membership differs from its V31 authority generation"); } - List upstreamCheckpoints = - readBaselineUpstreamCheckpoints(identity, authoritySnapshot); + CurrentSourceEvidence currentSources = + readCurrentUpstreamSourceEvidence( + identity.accountUuid(), identity.tenantUuid(), authoritySnapshot); String streamKey = membershipStreamKey(identity); Checkpoint checkpoint = authorityOutboxRepository @@ -447,9 +470,11 @@ public RuntimeMembershipSnapshotDto readCurrentPairBoundInactiveMembershipSnapsh "Current inactive membership differs from its durable pair authority"); } - List checkpoints = new ArrayList<>(upstreamCheckpoints); + List checkpoints = new ArrayList<>(currentSources.checkpoints()); checkpoints.add( new OutboxCheckpointEntry(streamKey, Long.toString(checkpoint.outboxSequence()))); + List sourceEvidence = new ArrayList<>(currentSources.sourceEvidence()); + sourceEvidence.add(sourceEvidence(checkpoint, event)); return new RuntimeMembershipSnapshotDto( identity.accountUuid().toString(), identity.tenantUuid().toString(), @@ -462,11 +487,11 @@ public RuntimeMembershipSnapshotDto readCurrentPairBoundInactiveMembershipSnapsh membershipVersionMap(verified, identity), verified.membershipAuthorityGeneration()), exactRoles, - verified.authorityTuple(), - verified.issuanceFence(), + currentAuthorityTuple(identity.tenantUuid(), authoritySnapshot, currentSources), + decimal(authoritySnapshot.issuanceFence().value()), Instant.now(), orderedCheckpoints(checkpoints), - List.of(sourceEvidence(checkpoint, event)), + orderedSourceEvidence(sourceEvidence), verified); } @@ -795,7 +820,7 @@ public NeverJoinedMembershipSnapshot readFreshNeverJoinedMembershipSnapshot( // membership initializer takes its Account/tenant locks. The Account entity row remains the // outer owner fence, and the full composite snapshot is reread below after enrollment. CompositeSnapshot upstream = lockUpstreamAuthorityScopes(accountUuid, tenantUuid); - requireFreshUpstreamSequenceZeroBaseline(accountUuid, tenantUuid, upstream); + readCurrentUpstreamSourceEvidence(accountUuid, tenantUuid, upstream); String membershipStreamKey = membershipStreamKey(accountUuid, tenantUuid); Optional existingPair = @@ -834,8 +859,8 @@ private NeverJoinedMembershipSnapshot assembleNeverJoinedMembershipSnapshot( CompositeSnapshot authority = readSnapshot(accountUuid, tenantUuid); ScopeState member = only(authority.memberships(), "membership"); requireMatchingFence(authority, member, accountUuid); - List upstreamCheckpoints = - readBaselineUpstreamCheckpoints(accountUuid, tenantUuid, authority); + CurrentSourceEvidence currentSources = + readCurrentUpstreamSourceEvidence(accountUuid, tenantUuid, authority); String streamKey = membershipStreamKey(accountUuid, tenantUuid); OutboxCheckpointEntry membershipCheckpoint = requireSequenceZeroCheckpoint(streamKey, member, "membership"); @@ -847,48 +872,21 @@ private NeverJoinedMembershipSnapshot assembleNeverJoinedMembershipSnapshot( throw new IllegalStateException( "Never-joined Account membership differs from its positive pair baseline"); } - AuthorityTuple tuple = - new AuthorityTuple( - decimal(authority.issuer().generation()), - decimal(authority.account().generation()), - Map.of( - tenantUuid.toString(), decimal(only(authority.tenants(), "tenant").generation())), - Map.of(tenantUuid.toString(), decimal(member.generation())), - List.of(), - Optional.empty(), - Optional.empty()); - List checkpoints = new ArrayList<>(upstreamCheckpoints); + List checkpoints = new ArrayList<>(currentSources.checkpoints()); checkpoints.add(membershipCheckpoint); checkpoints = orderedCheckpoints(checkpoints); + AuthorityTuple currentTuple = currentAuthorityTuple(tenantUuid, authority, currentSources); return new NeverJoinedMembershipSnapshot( accountUuid.toString(), tenantUuid.toString(), Map.of(tenantUuid.toString(), decimal(pair.membershipVersion())), decimal(pair.membershipAuthorityGeneration()), - tuple, + currentTuple, decimal(authority.issuanceFence().value()), Instant.now(), streamKey, checkpoints, - List.of()); - } - - private void requireFreshUpstreamSequenceZeroBaseline( - UUID accountUuid, UUID tenantUuid, CompositeSnapshot snapshot) { - ScopeState tenant = only(snapshot.tenants(), "tenant"); - if (!AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER) - .equals(snapshot.issuer().scope()) - || !AuthorityScope.account(accountUuid).equals(snapshot.account().scope()) - || !AuthorityScope.tenant(tenantUuid).equals(tenant.scope()) - || !snapshot.memberships().isEmpty() - || !accountUuid.equals(snapshot.issuanceFence().accountId()) - || !snapshot.issuanceFence().equals(snapshot.account().issuanceFence())) { - throw new IllegalStateException( - "Fresh Account authority snapshot does not cover its exact issuer/account/tenant scopes"); - } - requireSequenceZeroCheckpoint(accountStreamKey(accountUuid), snapshot.account(), "account"); - requireSequenceZeroCheckpoint(issuerStreamKey(), snapshot.issuer(), "issuer"); - requireSequenceZeroCheckpoint(tenantStreamKey(tenantUuid), tenant, "tenant"); + orderedSourceEvidence(currentSources.sourceEvidence())); } private CompositeSnapshot lockUpstreamAuthorityScopes(UUID accountUuid, UUID tenantUuid) { @@ -1369,9 +1367,6 @@ private Checkpoint appendAndReadBack( } else { requireActiveMembership(membership); } - ScopeState issuer = snapshot.issuer(); - ScopeState account = snapshot.account(); - ScopeState tenant = only(snapshot.tenants(), "tenant"); ScopeState member = only(snapshot.memberships(), "membership"); requireMatchingFence(snapshot, member, identity.accountUuid()); if (membership.getMembershipAuthorityGeneration() != member.generation()) { @@ -1386,7 +1381,11 @@ private Checkpoint appendAndReadBack( throw new IllegalStateException( "Membership lifecycle transition must invalidate caller authority"); } - readBaselineUpstreamCheckpoints(identity, snapshot); + CurrentSourceEvidence currentSources = + readCurrentUpstreamSourceEvidence(identity.accountUuid(), identity.tenantUuid(), snapshot); + ScopeState issuer = snapshot.issuer(); + ScopeState account = snapshot.account(); + ScopeState tenant = only(snapshot.tenants(), "tenant"); RoleSnapshot roles = requireRoleSnapshot(identity, membership, inactiveMembership); String streamKey = membershipStreamKey(identity); String expectedEventId = eventIdForRequest(requestId); @@ -1409,6 +1408,7 @@ private Checkpoint appendAndReadBack( tenant, member, snapshot.issuanceFence().value(), + currentSources.accountSecurityCutoff(), membership, roles.roles(), callerBoundAuthorityInvalidated)); @@ -1504,23 +1504,9 @@ private Checkpoint requireCurrentMembershipEvent( throw new IllegalStateException("Current Account membership checkpoint identity differs"); } MembershipEvent verified = verifyStoredEvent(event, identity, event.requestId()); - ScopeState issuer = snapshot.issuer(); - ScopeState account = snapshot.account(); - ScopeState tenant = only(snapshot.tenants(), "tenant"); ScopeState member = only(snapshot.memberships(), "membership"); requireMatchingFence(snapshot, member, identity.accountUuid()); - var tuple = verified.authorityTuple(); - if (!Long.toString(issuer.generation()).equals(tuple.issuerAuthGeneration()) - || !Long.toString(account.generation()).equals(tuple.accountAuthorityGeneration()) - || !Map.of(identity.tenantUuid().toString(), Long.toString(tenant.generation())) - .equals(tuple.tenantAuthorityGeneration()) - || !Map.of(identity.tenantUuid().toString(), Long.toString(member.generation())) - .equals(tuple.membershipAuthorityGeneration()) - || !tuple.privateRealmGrantVersions().isEmpty() - || tuple.accountSecurityCutoff().isPresent() - || tuple.tenantBillingCutoff().isPresent() - || !Long.toString(snapshot.issuanceFence().value()).equals(verified.issuanceFence()) - || member.generation() != membershipAuthorityGeneration + if (member.generation() != membershipAuthorityGeneration || !lifecycleState.equals(verified.membershipLifecycleState()) || !Map.of(identity.tenantUuid().toString(), Long.toString(membershipVersion)) .equals(verified.membershipVersion()) @@ -1530,7 +1516,44 @@ private Checkpoint requireCurrentMembershipEvent( || gameplayAdmissionAllowed != verified.gameplayAdmissionAllowed() || callerBoundAuthorityInvalidated != verified.callerBoundAuthorityInvalidated()) { throw new IllegalStateException( - "Current Account membership differs from its canonical V33 event and V31 tuple"); + "Current Account membership differs from its canonical V33 event"); + } + + CurrentSourceEvidence currentSources = + readCurrentUpstreamSourceEvidence(identity.accountUuid(), identity.tenantUuid(), snapshot); + List checkpoints = new ArrayList<>(currentSources.checkpoints()); + checkpoints.add( + new OutboxCheckpointEntry(streamKey, Long.toString(checkpoint.outboxSequence()))); + List sourceEvidence = new ArrayList<>(currentSources.sourceEvidence()); + sourceEvidence.add(sourceEvidence(checkpoint, event)); + Optional carrierEvent; + try { + carrierEvent = + RuntimeMembershipAuthorityEvidenceValidator.validate( + validatorSnapshot( + identity.accountUuid().toString(), + identity.tenantUuid().toString(), + true, + lifecycleState, + gameplayAdmissionAllowed, + Map.of(identity.tenantUuid().toString(), Long.toString(membershipVersion)), + Long.toString(membershipAuthorityGeneration), + exactRoles, + currentAuthorityTuple(identity.tenantUuid(), snapshot, currentSources), + decimal(snapshot.issuanceFence().value()), + orderedCheckpoints(checkpoints), + orderedSourceEvidence(sourceEvidence))); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "Current Account membership source evidence does not bind to its recipient snapshot", + exception); + } + if (carrierEvent.isEmpty() + || !carrierEvent.orElseThrow().canonicalJson().equals(verified.canonicalJson()) + || (expectedRequestId != null && !expectedRequestId.equals(verified.requestId())) + || callerBoundAuthorityInvalidated != verified.callerBoundAuthorityInvalidated()) { + throw new IllegalStateException( + "Current Account membership source event differs from its recipient snapshot"); } return checkpoint; } @@ -1553,6 +1576,7 @@ private Map preimage( ScopeState tenant, ScopeState membershipState, long issuanceFence, + Optional accountSecurityCutoff, AccountTenantMembership membership, List roles, boolean callerBoundAuthorityInvalidated) { @@ -1566,6 +1590,14 @@ private Map preimage( "membershipAuthorityGeneration", Map.of(identity.tenantUuid().toString(), decimal(membershipState.generation()))); authorityTuple.put("privateRealmGrantVersions", List.of()); + accountSecurityCutoff.ifPresent( + cutoff -> + authorityTuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); Map event = new LinkedHashMap<>(); event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); @@ -1657,30 +1689,246 @@ private static int compareUnsignedUtf8(String left, String right) { return Integer.compare(leftBytes.length, rightBytes.length); } - private List readBaselineUpstreamCheckpoints( - Identity identity, CompositeSnapshot snapshot) { - return readBaselineUpstreamCheckpoints(identity.accountUuid(), identity.tenantUuid(), snapshot); - } - - private List readBaselineUpstreamCheckpoints( + private CurrentSourceEvidence readCurrentUpstreamSourceEvidence( UUID accountUuid, UUID tenantUuid, CompositeSnapshot snapshot) { ScopeState tenant = only(snapshot.tenants(), "tenant"); if (!AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER) .equals(snapshot.issuer().scope()) || !AuthorityScope.account(accountUuid).equals(snapshot.account().scope()) || !AuthorityScope.tenant(tenantUuid).equals(tenant.scope()) - || !AuthorityScope.membership(accountUuid, tenantUuid) - .equals(only(snapshot.memberships(), "membership").scope())) { + || !accountUuid.equals(snapshot.issuanceFence().accountId()) + || !snapshot.issuanceFence().equals(snapshot.account().issuanceFence()) + || (snapshot.memberships().size() == 1 + && !AuthorityScope.membership(accountUuid, tenantUuid) + .equals(snapshot.memberships().getFirst().scope())) + || snapshot.memberships().size() > 1) { throw new IllegalStateException( - "Account authority snapshot does not cover the exact issuer/account/tenant scopes"); + "Account authority snapshot does not cover its exact issuer/account/tenant scopes"); + } + + Account account = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Current Account source owner is absent")); + requirePersistedAccountIdentity(account, accountUuid); + + String accountStream = accountStreamKey(accountUuid); + AccountAuthoritySourceEventReadback.LatestSourceSnapshot accountReadback = + accountAuthoritySourceEventReadback.requireCurrentLatest(account, snapshot.account()); + CurrentSourceProof accountProof = + readCurrentScopeSourceProof( + accountStream, + snapshot.account(), + event -> verifyCurrentAccountSourceEvent(event, accountUuid, snapshot.account())); + if (!accountProof + .checkpoint() + .outboxSequence() + .equals(Long.toString(accountReadback.outboxSequence())) + || accountReadback.latestEvent().isPresent() != (accountReadback.outboxSequence() > 0L)) { + throw new IllegalStateException("Account source readback differs from its exact checkpoint"); + } + if (accountReadback.latestEvent().isPresent() + && !accountProof + .sourceEvidence() + .orElseThrow() + .canonicalEventJson() + .equals( + new String( + accountReadback.latestEvent().orElseThrow().payload(), + StandardCharsets.UTF_8))) { + throw new IllegalStateException("Account source readback event differs from its checkpoint"); + } + + CurrentSourceProof issuerProof = + readCurrentScopeSourceProof( + issuerStreamKey(), + snapshot.issuer(), + event -> verifyCurrentIssuerSourceEvent(event, snapshot.issuer())); + CurrentSourceProof tenantProof = + readCurrentScopeSourceProof( + tenantStreamKey(tenantUuid), + tenant, + event -> verifyCurrentTenantSourceEvent(event, tenantUuid, tenant)); + + List checkpoints = + orderedCheckpoints( + List.of(accountProof.checkpoint(), issuerProof.checkpoint(), tenantProof.checkpoint())); + List sourceEvidence = new ArrayList<>(); + accountProof.sourceEvidence().ifPresent(sourceEvidence::add); + issuerProof.sourceEvidence().ifPresent(sourceEvidence::add); + tenantProof.sourceEvidence().ifPresent(sourceEvidence::add); + return new CurrentSourceEvidence( + checkpoints, orderedSourceEvidence(sourceEvidence), currentAccountCutoff(accountProof)); + } + + private CurrentSourceProof readCurrentScopeSourceProof( + String streamKey, ScopeState scope, java.util.function.Consumer eventVerifier) { + Optional checkpoint = authorityOutboxRepository.readCheckpoint(streamKey); + if (checkpoint.isEmpty()) { + if (scope.generation() != 1L || scope.sourceVersion() != 1L) { + throw new IllegalStateException( + "Account " + scope.scope().kind().name().toLowerCase() + " source history is missing"); + } + return new CurrentSourceProof(new OutboxCheckpointEntry(streamKey, "0"), Optional.empty()); + } + + Checkpoint exactCheckpoint = checkpoint.orElseThrow(); + Event event = + authorityOutboxRepository + .findEvent(streamKey, exactCheckpoint.outboxSequence()) + .orElseThrow( + () -> new IllegalStateException("Current Account source event is missing")); + if (!checkpointMatches(exactCheckpoint, event)) { + throw new IllegalStateException("Current Account source checkpoint differs from its event"); } + eventVerifier.accept(event); + return new CurrentSourceProof( + new OutboxCheckpointEntry(streamKey, Long.toString(exactCheckpoint.outboxSequence())), + Optional.of(sourceEvidence(exactCheckpoint, event))); + } - return orderedCheckpoints( - List.of( - requireSequenceZeroCheckpoint( - accountStreamKey(accountUuid), snapshot.account(), "account"), - requireSequenceZeroCheckpoint(issuerStreamKey(), snapshot.issuer(), "issuer"), - requireSequenceZeroCheckpoint(tenantStreamKey(tenantUuid), tenant, "tenant"))); + private void verifyCurrentAccountSourceEvent(Event stored, UUID accountUuid, ScopeState current) { + String canonicalJson = new String(stored.payload(), StandardCharsets.UTF_8); + try { + var reset = PasswordResetAuthorityEventV1Codec.verify(canonicalJson); + requireCurrentStoredEvent( + stored, + reset.eventId(), + reset.requestId(), + reset.eventDigest(), + reset.canonicalJsonUtf8(), + reset.outboxStreamKey(), + reset.outboxSequence()); + if (!accountUuid.toString().equals(reset.accountId()) + || !decimal(current.generation()).equals(reset.accountAuthorityGeneration()) + || !decimal(current.sourceVersion()).equals(reset.sourceVersion())) { + throw new IllegalStateException("Current Account source event differs from its generation"); + } + return; + } catch (IllegalArgumentException resetSchemaMismatch) { + var logout = AccountLogoutAllAuthorityEventV1Codec.verify(canonicalJson); + requireCurrentStoredEvent( + stored, + logout.eventId(), + logout.requestId(), + logout.eventDigest(), + logout.canonicalJsonUtf8(), + logout.outboxStreamKey(), + logout.outboxSequence()); + if (!accountUuid.toString().equals(logout.accountId()) + || !decimal(current.generation()).equals(logout.accountAuthorityGeneration()) + || !decimal(current.sourceVersion()).equals(logout.sourceVersion())) { + throw new IllegalStateException("Current Account source event differs from its generation"); + } + } + } + + private void verifyCurrentIssuerSourceEvent(Event stored, ScopeState current) { + String canonicalJson = new String(stored.payload(), StandardCharsets.UTF_8); + var event = IssuerGenerationAuthorityEventV1Codec.verify(canonicalJson); + requireCurrentStoredEvent( + stored, + event.eventId(), + event.requestId(), + event.eventDigest(), + event.canonicalJsonUtf8(), + event.outboxStreamKey(), + event.outboxSequence()); + if (!AccountServiceImpl.ACCOUNT_JWT_ISSUER.equals(event.issuerId()) + || !decimal(current.generation()).equals(event.issuerAuthGeneration()) + || !decimal(current.sourceVersion()).equals(event.sourceVersion())) { + throw new IllegalStateException("Current issuer source event differs from its generation"); + } + } + + private void verifyCurrentTenantSourceEvent(Event stored, UUID tenantUuid, ScopeState current) { + String canonicalJson = new String(stored.payload(), StandardCharsets.UTF_8); + var event = TenantGenerationAuthorityEventV1Codec.verify(canonicalJson); + requireCurrentStoredEvent( + stored, + event.eventId(), + event.requestId(), + event.eventDigest(), + event.canonicalJsonUtf8(), + event.outboxStreamKey(), + event.outboxSequence()); + if (!tenantUuid.toString().equals(event.tenantId()) + || !decimal(current.generation()).equals(event.tenantAuthorityGeneration()) + || !decimal(current.sourceVersion()).equals(event.sourceVersion())) { + throw new IllegalStateException("Current tenant source event differs from its generation"); + } + } + + private void requireCurrentStoredEvent( + Event stored, + String eventId, + String requestId, + String digest, + byte[] canonicalBytes, + String streamKey, + String sequence) { + if (!streamKey.equals(stored.outboxStreamKey()) + || !requestId.equals(stored.requestId()) + || !eventId.equals(stored.eventId()) + || !digest.equals(stored.eventDigest()) + || !Long.toString(stored.outboxSequence()).equals(sequence) + || !Arrays.equals(stored.payload(), canonicalBytes)) { + throw new IllegalStateException( + "Current Account source event columns differ from its payload"); + } + } + + private Optional currentAccountCutoff( + CurrentSourceProof accountProof) { + if (accountProof.checkpoint().outboxSequence().equals("0")) { + return Optional.empty(); + } + String json = accountProof.sourceEvidence().orElseThrow().canonicalEventJson(); + try { + var reset = PasswordResetAuthorityEventV1Codec.verify(json); + var cutoff = reset.accountSecurityCutoff(); + return Optional.of( + new MembershipAuthorityEventV1Codec.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())); + } catch (IllegalArgumentException resetSchemaMismatch) { + var logout = AccountLogoutAllAuthorityEventV1Codec.verify(json); + var cutoff = logout.accountSecurityCutoff(); + return Optional.of( + new MembershipAuthorityEventV1Codec.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())); + } + } + + private AuthorityTuple currentAuthorityTuple( + UUID tenantUuid, CompositeSnapshot snapshot, CurrentSourceEvidence currentSources) { + ScopeState member = only(snapshot.memberships(), "membership"); + return new AuthorityTuple( + decimal(snapshot.issuer().generation()), + decimal(snapshot.account().generation()), + Map.of(tenantUuid.toString(), decimal(only(snapshot.tenants(), "tenant").generation())), + Map.of(tenantUuid.toString(), decimal(member.generation())), + List.of(), + currentSources.accountSecurityCutoff(), + Optional.empty()); + } + + private List orderedSourceEvidence( + List sourceEvidence) { + ArrayList ordered = new ArrayList<>(sourceEvidence); + ordered.sort( + Comparator.comparing( + OutboxSourceEvidence::outboxStreamKey, + AccountMembershipAuthorityEventProducer::compareUnsignedUtf8)); + for (int index = 1; index < ordered.size(); index++) { + if (ordered.get(index - 1).outboxStreamKey().equals(ordered.get(index).outboxStreamKey())) { + throw new IllegalArgumentException("Account authority source streams must be unique"); + } + } + return List.copyOf(ordered); } private OutboxCheckpointEntry requireSequenceZeroCheckpoint( @@ -1946,6 +2194,49 @@ private void requirePositive(String value, String field) { } } + private static Snapshot validatorSnapshot( + String accountId, + String tenantId, + boolean membershipExists, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + Map membershipVersion, + String membershipAuthorityGeneration, + List roles, + AuthorityTuple authorityTuple, + String issuanceFence, + List checkpoints, + List sourceEvidence) { + return new Snapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + accountId, + tenantId, + membershipExists, + membershipLifecycleState, + gameplayAdmissionAllowed, + membershipVersion, + membershipAuthorityGeneration, + roles, + authorityTuple, + issuanceFence, + checkpoints.stream() + .map( + checkpoint -> + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + checkpoint.outboxStreamKey(), checkpoint.outboxSequence())) + .toList(), + sourceEvidence.stream() + .map( + source -> + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + source.outboxStreamKey(), + source.outboxSequence(), + source.eventId(), + source.eventDigest(), + source.canonicalEventJson())) + .toList()); + } + /** Positive durable authority values committed before the first membership transition. */ public record NewMembershipBaseline(long membershipVersion, long membershipAuthorityGeneration) { public NewMembershipBaseline { @@ -1984,22 +2275,15 @@ public record OutboxSourceEvidence( throw new IllegalArgumentException("source event ID is required"); } Objects.requireNonNull(eventDigest, "source event digest is required"); + Objects.requireNonNull(canonicalEventJson, "canonical source event JSON is required"); if (!outboxStreamKey.startsWith(MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX) || !isPositiveCanonicalDecimal(outboxSequence) - || !eventDigest.matches("sha256:[0-9a-f]{64}")) { + || !eventDigest.matches("sha256:[0-9a-f]{64}") + || !canonicalEventJson.startsWith("{") + || !canonicalEventJson.endsWith("}")) { throw new IllegalArgumentException( "Account authority source event evidence is not canonical"); } - Objects.requireNonNull(canonicalEventJson, "canonical source event JSON is required"); - MembershipEvent event = MembershipAuthorityEventV1Codec.verify(canonicalEventJson); - if (!event.canonicalJson().equals(canonicalEventJson) - || !event.eventId().equals(eventId) - || !event.eventDigest().equals(eventDigest) - || !event.outboxStreamKey().equals(outboxStreamKey) - || !event.outboxSequence().equals(outboxSequence)) { - throw new IllegalArgumentException( - "Account authority source event JSON differs from its exact identity"); - } } } @@ -2037,18 +2321,11 @@ public record NeverJoinedMembershipSnapshot( outboxCheckpoints = requireOrderedCheckpointSet(outboxCheckpoints); outboxSourceEvidence = List.copyOf(outboxSourceEvidence); - if (!"1".equals(authorityTuple.issuerAuthGeneration()) - || !"1".equals(authorityTuple.accountAuthorityGeneration()) - || authorityTuple.tenantAuthorityGeneration().size() != 1 - || authorityTuple.membershipAuthorityGeneration().size() != 1 - || !authorityTuple.tenantAuthorityGeneration().containsKey(tenantId) - || !authorityTuple.membershipAuthorityGeneration().containsKey(tenantId) - || !"1".equals(authorityTuple.tenantAuthorityGeneration().get(tenantId)) + if (!"1".equals(membershipAuthorityGeneration) || !membershipAuthorityGeneration.equals( authorityTuple.membershipAuthorityGeneration().get(tenantId)) || !"1".equals(membershipVersion.get(tenantId)) || !authorityTuple.privateRealmGrantVersions().isEmpty() - || authorityTuple.accountSecurityCutoff().isPresent() || authorityTuple.tenantBillingCutoff().isPresent()) { throw new IllegalArgumentException( "Never-joined Account authority tuple is incomplete or mismatched"); @@ -2064,16 +2341,32 @@ public record NeverJoinedMembershipSnapshot( throw new IllegalArgumentException( "Never-joined Account membership stream key is not canonical"); } - List expectedCheckpoints = - requireOrderedCheckpointSet( - List.of( - new OutboxCheckpointEntry(accountStreamKey(accountId), "0"), - new OutboxCheckpointEntry(canonicalIssuerStreamKey(), "0"), - new OutboxCheckpointEntry(outboxStreamKey, "0"), - new OutboxCheckpointEntry(tenantStreamKey(tenantId), "0"))); - if (!expectedCheckpoints.equals(outboxCheckpoints) || !outboxSourceEvidence.isEmpty()) { + List membershipCheckpoints = + outboxCheckpoints.stream() + .filter(checkpoint -> checkpoint.outboxStreamKey().equals(expectedStreamKey)) + .toList(); + if (membershipCheckpoints.size() != 1 + || !"0".equals(membershipCheckpoints.getFirst().outboxSequence())) { throw new IllegalArgumentException( - "Never-joined Account snapshot must contain only four sequence-zero checkpoints"); + "Never-joined Account snapshot must retain a sequence-zero membership checkpoint"); + } + if (RuntimeMembershipAuthorityEvidenceValidator.validate( + validatorSnapshot( + accountId, + tenantId, + false, + "MISSING", + false, + membershipVersion, + membershipAuthorityGeneration, + List.of(), + authorityTuple, + issuanceFence, + outboxCheckpoints, + outboxSourceEvidence)) + .isPresent()) { + throw new IllegalArgumentException( + "Never-joined Account snapshot cannot contain a membership event"); } } @@ -2125,6 +2418,7 @@ public record PositiveMembershipSnapshot( membershipAuthorityGeneration = requirePositiveCanonicalDecimal( membershipAuthorityGeneration, "membership authority generation"); + String membershipStreamKey = membershipStreamKey(accountId, tenantId); roles = List.copyOf(roles); Objects.requireNonNull(authorityTuple, "complete authority tuple is required"); issuanceFence = requirePositiveCanonicalDecimal(issuanceFence, "Account issuance fence"); @@ -2134,28 +2428,6 @@ public record PositiveMembershipSnapshot( Objects.requireNonNull(transitionReceipt, "membership transition receipt is required"); Objects.requireNonNull(authorityEvent, "canonical membership authority event is required"); - String membershipStreamKey = membershipStreamKey(accountId, tenantId); - String membershipSequence = authorityEvent.outboxSequence(); - if (!isPositiveCanonicalDecimal(membershipSequence)) { - throw new IllegalArgumentException( - "Positive Account membership event sequence must be canonical and positive"); - } - List expectedCheckpoints = - requireOrderedCheckpointSet( - List.of( - new OutboxCheckpointEntry(accountStreamKey(accountId), "0"), - new OutboxCheckpointEntry(canonicalIssuerStreamKey(), "0"), - new OutboxCheckpointEntry(membershipStreamKey, membershipSequence), - new OutboxCheckpointEntry(tenantStreamKey(tenantId), "0"))); - List expectedSourceEvidence = - List.of( - new OutboxSourceEvidence( - membershipStreamKey, - membershipSequence, - authorityEvent.eventId(), - authorityEvent.eventDigest(), - authorityEvent.canonicalJson())); - if (!membershipExists || !"ACTIVE".equals(membershipLifecycleState) || !gameplayAdmissionAllowed @@ -2167,24 +2439,37 @@ public record PositiveMembershipSnapshot( || !membershipAuthorityGeneration.equals(authorityEvent.membershipAuthorityGeneration()) || !roles.equals(authorityEvent.roles()) || gameplayAdmissionAllowed != authorityEvent.gameplayAdmissionAllowed() - || !authorityTuple.equals(authorityEvent.authorityTuple()) - || !issuanceFence.equals(authorityEvent.issuanceFence()) - || !"1".equals(authorityTuple.issuerAuthGeneration()) - || !"1".equals(authorityTuple.accountAuthorityGeneration()) - || !Map.of(tenantId, "1").equals(authorityTuple.tenantAuthorityGeneration()) || !Map.of(tenantId, membershipAuthorityGeneration) .equals(authorityTuple.membershipAuthorityGeneration()) - || !membershipAuthorityGeneration.equals( - authorityTuple.membershipAuthorityGeneration().get(tenantId)) || !authorityTuple.privateRealmGrantVersions().isEmpty() - || authorityTuple.accountSecurityCutoff().isPresent() || authorityTuple.tenantBillingCutoff().isPresent() - || !expectedCheckpoints.equals(outboxCheckpoints) - || !expectedSourceEvidence.equals(outboxSourceEvidence) || !transitionReceipt.requestId().equals(authorityEvent.requestId())) { throw new IllegalArgumentException( "Positive Account membership snapshot evidence is internally inconsistent"); } + MembershipEvent verified = + RuntimeMembershipAuthorityEvidenceValidator.validate( + validatorSnapshot( + accountId, + tenantId, + true, + membershipLifecycleState, + gameplayAdmissionAllowed, + membershipVersion, + membershipAuthorityGeneration, + roles, + authorityTuple, + issuanceFence, + outboxCheckpoints, + outboxSourceEvidence)) + .orElseThrow( + () -> + new IllegalArgumentException( + "Positive Account snapshot is missing its membership event")); + if (!verified.canonicalJson().equals(authorityEvent.canonicalJson())) { + throw new IllegalArgumentException( + "Positive Account membership source differs from its exact event bytes"); + } } } @@ -2261,18 +2546,34 @@ private static String canonicalIssuerStreamKey() { + AccountServiceImpl.ACCOUNT_JWT_ISSUER; } - private static String accountStreamKey(String accountId) { - return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + accountId; - } - - private static String tenantStreamKey(String tenantId) { - return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantId; - } - private record Identity( long accountId, long legacyTenantId, UUID accountUuid, UUID tenantUuid, ApprovedAssociation association) {} + + private record CurrentSourceProof( + OutboxCheckpointEntry checkpoint, Optional sourceEvidence) { + private CurrentSourceProof { + Objects.requireNonNull(checkpoint, "current source checkpoint is required"); + sourceEvidence = + Objects.requireNonNull(sourceEvidence, "current source evidence is required"); + if ("0".equals(checkpoint.outboxSequence()) != sourceEvidence.isEmpty()) { + throw new IllegalArgumentException("Current source checkpoint and event evidence differ"); + } + } + } + + private record CurrentSourceEvidence( + List checkpoints, + List sourceEvidence, + Optional accountSecurityCutoff) { + private CurrentSourceEvidence { + checkpoints = List.copyOf(checkpoints); + sourceEvidence = List.copyOf(sourceEvidence); + accountSecurityCutoff = + Objects.requireNonNull(accountSecurityCutoff, "current Account cutoff is required"); + } + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducer.java new file mode 100644 index 0000000000..aff7b619c8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducer.java @@ -0,0 +1,746 @@ +package net.firedevops.firemud.accountservice.service; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired owner-local tenant-generation source mutation and readback. + * + *

This source-only primitive selects one canonical tenant UUID and requires its authority row to + * have already been enrolled by the authoritative tenant-association path. A caller-supplied tenant + * ID or authorization claim is not proof of enrollment or permission. This class does not + * initialize tenant authority, mutate billing state, advance an Account issuance fence, fan out to + * recipient Accounts, expose an endpoint, activate delivery, or establish authenticated consumer + * evidence. Each public operation owns a short writable READ_COMMITTED transaction and performs no + * network calls. + */ +public final class AccountTenantAuthorityEventProducer { + private static final String AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; + private static final String EVENT_ID_PREFIX = "account-tenant-generation-event-v1:"; + + private final AccountAuthorityGenerationRepository generationRepository; + private final AccountAuthorityOutboxRepository outboxRepository; + private final DSLContext dsl; + private final TransactionTemplate ownerTransaction; + + public AccountTenantAuthorityEventProducer( + AccountAuthorityGenerationRepository generationRepository, + AccountAuthorityOutboxRepository outboxRepository, + DSLContext dsl, + PlatformTransactionManager transactionManager) { + this.generationRepository = + Objects.requireNonNull(generationRepository, "authority-generation repository is required"); + this.outboxRepository = + Objects.requireNonNull(outboxRepository, "authority outbox repository is required"); + this.dsl = Objects.requireNonNull(dsl, "transaction-aware DSLContext is required"); + Objects.requireNonNull(transactionManager, "Account transaction manager is required"); + + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Advances the exact already-enrolled tenant source or recovers its original immutable event. + * + *

The request UUID is the stable operation identity within this exact tenant. The transaction + * locks the durable tenant source row before resolving request history. A separate post-commit + * locked read must prove the same event; if that read is unavailable, an exact retry recovers it + * without applying another advance. + */ + public TenantGenerationAuthorityEvent advance( + UUID tenantId, UUID requestId, long expectedGeneration, long expectedSourceVersion) { + AuthorityScope scope = tenantScope(tenantId); + requireRequestId(requestId); + if (expectedGeneration <= 0L || expectedSourceVersion <= 0L) { + throw new IllegalArgumentException( + "Expected tenant generation and source version must be positive"); + } + requireNoAmbientTransaction(); + + TenantGenerationAuthorityEvent transactionResult = + ownerTransaction.execute( + status -> + advanceInOwnerTransaction( + scope, requestId, expectedGeneration, expectedSourceVersion)); + if (transactionResult == null) { + throw new IllegalStateException("Tenant authority advance transaction returned no event"); + } + + TenantGenerationAuthorityEvent committedResult = + readCommittedOperation(scope, requestId, expectedGeneration, expectedSourceVersion); + if (!sameEvent(transactionResult, committedResult)) { + throw new IllegalStateException( + "Post-commit tenant event readback differs from its transaction result"); + } + return committedResult; + } + + /** + * Reads current positive tenant source state and the exact latest checkpoint in one row-fenced + * snapshot. + */ + public TenantAuthoritySnapshot readCurrent(UUID tenantId) { + AuthorityScope scope = tenantScope(tenantId); + requireNoAmbientTransaction(); + TenantAuthoritySnapshot snapshot = + ownerTransaction.execute(status -> readCurrentInTransaction(scope)); + if (snapshot == null) { + throw new IllegalStateException("Tenant authority snapshot transaction returned no state"); + } + return snapshot; + } + + /** + * Reads one exact retained immutable event together with current tenant source/checkpoint + * evidence, all while holding the tenant source row lock. + */ + public TenantAuthorityEventReadback readCommittedEvent(UUID tenantId, long outboxSequence) { + AuthorityScope scope = tenantScope(tenantId); + if (outboxSequence <= 0L) { + throw new IllegalArgumentException("Tenant outbox sequence must be positive"); + } + requireNoAmbientTransaction(); + + TenantAuthorityEventReadback readback = + ownerTransaction.execute(status -> readCommittedEventInTransaction(scope, outboxSequence)); + if (readback == null) { + throw new IllegalStateException( + "Tenant authority event readback transaction returned no state"); + } + return readback; + } + + private TenantGenerationAuthorityEvent advanceInOwnerTransaction( + AuthorityScope scope, UUID requestId, long expectedGeneration, long expectedSourceVersion) { + ScopeState current = readLockedTenantState(scope); + String streamKey = streamKey(scope); + + // Resolve an immutable request first so lost acknowledgements and later source advances return + // the original operation event rather than applying another increment. + Optional prior = outboxRepository.findEvent(streamKey, requestId.toString()); + if (prior.isPresent()) { + TenantGenerationAuthorityEvent historical = + verifyStoredEvent( + prior.get(), scope, requestId, expectedGeneration, expectedSourceVersion); + LatestEvidence currentHistory = requireCurrentHistoryMatches(scope, current); + requireHistoricalEventIsRetained(prior.get(), scope, current, currentHistory); + return historical; + } + + if (current.generation() != expectedGeneration + || current.sourceVersion() != expectedSourceVersion) { + throw new IllegalStateException("Tenant authority source compare-and-advance is stale"); + } + + long nextGeneration = incrementExact(expectedGeneration, "tenant generation"); + long nextSourceVersion = incrementExact(expectedSourceVersion, "tenant source version"); + LatestEvidence priorHistory = requireCurrentHistoryMatches(scope, current); + long nextSequence = incrementExact(priorHistory.sequence(), "tenant outbox sequence"); + String requestText = requestId.toString(); + String eventId = EVENT_ID_PREFIX + requestText; + + ScopeState advanced = generationRepository.advance(current, null); + requireScopeState(advanced, scope, nextGeneration, nextSourceVersion); + + Event appended = + outboxRepository.append( + streamKey, + requestText, + sequence -> + eventEvidence( + scope, requestText, eventId, sequence, nextGeneration, nextSourceVersion)); + if (appended.outboxSequence() != nextSequence) { + throw new IllegalStateException( + "Tenant authority outbox sequence did not advance exactly once"); + } + TenantGenerationAuthorityEvent appendedEvent = + verifyStoredEvent(appended, scope, requestId, expectedGeneration, expectedSourceVersion); + + // Exact in-transaction event, checkpoint, and current-source readback make any discrepancy + // abort the source advance and immutable outbox append together. + Event requestReadback = + outboxRepository + .findEvent(streamKey, requestText) + .orElseThrow( + () -> + new IllegalStateException( + "Tenant authority request event readback is missing")); + Event sequenceReadback = + outboxRepository + .findEvent(streamKey, nextSequence) + .orElseThrow( + () -> + new IllegalStateException( + "Tenant authority sequence event readback is missing")); + if (!appended.equals(requestReadback) || !appended.equals(sequenceReadback)) { + throw new IllegalStateException( + "Tenant authority immutable event readback differs from append"); + } + Checkpoint checkpoint = + outboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Tenant authority checkpoint readback is missing")); + requireCheckpointMatches(checkpoint, appended, streamKey); + ScopeState sourceReadback = readLockedTenantState(scope); + requireScopeState(sourceReadback, scope, nextGeneration, nextSourceVersion); + LatestEvidence currentHistory = requireCurrentHistoryMatches(scope, sourceReadback); + if (currentHistory.sequence() != nextSequence + || currentHistory.event().isEmpty() + || currentHistory.outboxEvent().isEmpty() + || !appended.equals(currentHistory.outboxEvent().orElseThrow())) { + throw new IllegalStateException( + "Tenant authority source and outbox readback differ from the advance"); + } + return appendedEvent; + } + + private TenantGenerationAuthorityEvent readCommittedOperation( + AuthorityScope scope, UUID requestId, long expectedGeneration, long expectedSourceVersion) { + requireNoAmbientTransaction(); + TenantGenerationAuthorityEvent event = + ownerTransaction.execute( + status -> { + ScopeState current = readLockedTenantState(scope); + String streamKey = streamKey(scope); + Event committed = + outboxRepository + .findEvent(streamKey, requestId.toString()) + .orElseThrow( + () -> + new IllegalStateException( + "Post-commit tenant authority request event is missing")); + TenantGenerationAuthorityEvent verified = + verifyStoredEvent( + committed, scope, requestId, expectedGeneration, expectedSourceVersion); + LatestEvidence currentHistory = requireCurrentHistoryMatches(scope, current); + requireHistoricalEventIsRetained(committed, scope, current, currentHistory); + if (committed.outboxSequence() > currentHistory.sequence()) { + throw new IllegalStateException( + "Post-commit tenant event is ahead of its checkpoint"); + } + return verified; + }); + if (event == null) { + throw new IllegalStateException("Post-commit tenant authority readback returned no event"); + } + return event; + } + + private TenantAuthoritySnapshot readCurrentInTransaction(AuthorityScope scope) { + ScopeState current = readLockedTenantState(scope); + LatestEvidence history = requireCurrentHistoryMatches(scope, current); + return new TenantAuthoritySnapshot( + scope.tenantId(), + current.generation(), + current.sourceVersion(), + streamKey(scope), + history.sequence(), + history.event()); + } + + private TenantAuthorityEventReadback readCommittedEventInTransaction( + AuthorityScope scope, long outboxSequence) { + ScopeState current = readLockedTenantState(scope); + LatestEvidence currentHistory = requireCurrentHistoryMatches(scope, current); + if (outboxSequence > currentHistory.sequence()) { + throw new IllegalStateException("Requested tenant event is ahead of the current checkpoint"); + } + String streamKey = streamKey(scope); + Event requested = + outboxRepository + .findEvent(streamKey, outboxSequence) + .orElseThrow( + () -> new IllegalStateException("Requested retained tenant event is missing")); + TenantGenerationAuthorityEvent verified = verifyStoredEventWithoutRequest(requested, scope); + requireHistoricalEventIsRetained(requested, scope, current, currentHistory); + if (requested.outboxSequence() != outboxSequence) { + throw new IllegalStateException( + "Requested tenant event sequence differs from its lookup key"); + } + + TenantAuthoritySnapshot currentSnapshot = + new TenantAuthoritySnapshot( + scope.tenantId(), + current.generation(), + current.sourceVersion(), + streamKey, + currentHistory.sequence(), + currentHistory.event()); + if (outboxSequence == currentHistory.sequence() + && (currentHistory.event().isEmpty() + || !sameEvent(verified, currentHistory.event().orElseThrow()))) { + throw new IllegalStateException( + "Requested latest tenant event differs from current source checkpoint evidence"); + } + return new TenantAuthorityEventReadback(currentSnapshot, verified); + } + + private ScopeState readLockedTenantState(AuthorityScope scope) { + ScopeState state = generationRepository.read(scope); + if (state == null + || !scope.equals(state.scope()) + || state.issuanceFence() != null + || state.generation() <= 0L + || state.sourceVersion() <= 0L) { + throw new IllegalStateException( + "Persisted Account tenant authority state is absent or malformed"); + } + return state; + } + + /** + * Validates the exact stream checkpoint and latest event while the tenant source row is locked. + * Sequence zero requires the original positive source baseline and proved absence of all event + * history; a missing stream row alone is not evidence of that baseline. + */ + private LatestEvidence requireCurrentHistoryMatches(AuthorityScope scope, ScopeState current) { + String streamKey = streamKey(scope); + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ? FOR SHARE", + streamKey); + if (stream == null) { + Record eventCountReadback = + dsl.fetchOne( + "SELECT COUNT(*) AS event_count FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + streamKey); + Long eventCount = + eventCountReadback == null ? null : eventCountReadback.get("event_count", Long.class); + if (eventCount == null || eventCount < 0L) { + throw new IllegalStateException("Tenant authority retained event count is malformed"); + } + if (eventCount != 0L) { + throw new IllegalStateException( + "Tenant authority event history has no matching stream head"); + } + requireOriginalBaseline(current); + return LatestEvidence.empty(); + } + + Long headValue = stream.get("last_sequence", Long.class); + if (headValue == null || headValue < 0L) { + throw new IllegalStateException("Tenant authority stream head is malformed"); + } + if (headValue == 0L) { + throw new IllegalStateException( + "Committed zero-sequence tenant stream head contradicts the authority checkpoint contract"); + } + + // Every canonical tenant source event advances generation and source version together from + // the initialized 1/1 baseline. Reject a pristine or one-sided source before looking up any + // positive event; a forged matching event cannot legitimize incomplete source progress. + if (current.generation() == 1L + || current.sourceVersion() == 1L + || current.generation() != current.sourceVersion()) { + throw new IllegalStateException( + "Positive tenant checkpoint requires both tenant generation and source version to have " + + "advanced together"); + } + + long headSequence = headValue; + if (headSequence != current.generation() - 1L || headSequence != current.sourceVersion() - 1L) { + throw new IllegalStateException( + "Tenant authority checkpoint sequence does not match uninterrupted source counters"); + } + Record eventRange = + dsl.fetchOne( + "SELECT COUNT(*) AS event_count, MIN(outbox_sequence) AS first_sequence, " + + "MAX(outbox_sequence) AS last_sequence FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + streamKey); + Long eventCount = eventRange == null ? null : eventRange.get("event_count", Long.class); + Long firstSequence = eventRange == null ? null : eventRange.get("first_sequence", Long.class); + Long lastSequence = eventRange == null ? null : eventRange.get("last_sequence", Long.class); + if (eventCount == null + || firstSequence == null + || lastSequence == null + || eventCount != headSequence + || firstSequence != 1L + || lastSequence != headSequence) { + throw new IllegalStateException( + "Tenant authority outbox event history contains a sequence gap or dangling head"); + } + + Checkpoint checkpoint = + outboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Tenant authority positive checkpoint is missing")); + Event latest = + outboxRepository + .findEvent(streamKey, headSequence) + .orElseThrow( + () -> new IllegalStateException("Tenant authority checkpoint event is missing")); + requireCheckpointMatches(checkpoint, latest, streamKey); + TenantGenerationAuthorityEvent verified = verifyStoredEventWithoutRequest(latest, scope); + if (!Long.toString(current.generation()).equals(verified.tenantAuthorityGeneration()) + || !Long.toString(current.sourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException( + "Latest tenant source event differs from current source counters"); + } + return new LatestEvidence(headSequence, Optional.of(verified), Optional.of(latest)); + } + + private void requireOriginalBaseline(ScopeState current) { + if (current.generation() != 1L || current.sourceVersion() != 1L) { + throw new IllegalStateException( + "Tenant sequence-zero readback requires the original positive 1/1 source baseline"); + } + } + + private void requireHistoricalEventIsRetained( + Event event, AuthorityScope scope, ScopeState current, LatestEvidence history) { + if (history.sequence() < event.outboxSequence()) { + throw new IllegalStateException("Historical tenant event is ahead of the current checkpoint"); + } + TenantGenerationAuthorityEvent verified = verifyStoredEventWithoutRequest(event, scope); + if (new BigInteger(verified.tenantAuthorityGeneration()) + .compareTo(BigInteger.valueOf(current.generation())) + > 0 + || new BigInteger(verified.sourceVersion()) + .compareTo(BigInteger.valueOf(current.sourceVersion())) + > 0) { + throw new IllegalStateException("Historical tenant event is ahead of current source state"); + } + } + + private EventEvidence eventEvidence( + AuthorityScope scope, + String requestId, + String eventId, + long sequence, + long tenantAuthorityGeneration, + long sourceVersion) { + String streamKey = streamKey(scope); + String sourceScope = sourceScope(scope); + TenantGenerationAuthorityEvent event = + TenantGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + TenantGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + eventId, + "requestId", + requestId, + "tenantId", + scope.tenantId().toString(), + "sourceScope", + sourceScope, + "outboxStreamKey", + streamKey, + "outboxSequence", + Long.toString(sequence), + "tenantAuthorityGeneration", + Long.toString(tenantAuthorityGeneration), + "sourceVersion", + Long.toString(sourceVersion))); + return new EventEvidence(event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + } + + private TenantGenerationAuthorityEvent verifyStoredEvent( + Event stored, + AuthorityScope scope, + UUID requestId, + long expectedGeneration, + long expectedSourceVersion) { + TenantGenerationAuthorityEvent verified = verifyStoredEventWithoutRequest(stored, scope); + String canonicalRequestId = requestId.toString(); + long resultingGeneration; + long resultingSourceVersion; + try { + resultingGeneration = Math.addExact(expectedGeneration, 1L); + resultingSourceVersion = Math.addExact(expectedSourceVersion, 1L); + } catch (ArithmeticException overflow) { + throw new AccountAuthorityOutboxRepository.IdempotencyConflictException( + "Tenant authority request identity was reused with different expected source state"); + } + if (!canonicalRequestId.equals(stored.requestId()) + || !canonicalRequestId.equals(verified.requestId()) + || !(EVENT_ID_PREFIX + canonicalRequestId).equals(stored.eventId()) + || !Long.toString(resultingGeneration).equals(verified.tenantAuthorityGeneration()) + || !Long.toString(resultingSourceVersion).equals(verified.sourceVersion())) { + throw new AccountAuthorityOutboxRepository.IdempotencyConflictException( + "Tenant authority request identity was reused with different expected source state"); + } + return verified; + } + + private TenantGenerationAuthorityEvent verifyStoredEventWithoutRequest( + Event stored, AuthorityScope scope) { + if (stored == null) { + throw new IllegalStateException("Tenant authority stored event is missing"); + } + TenantGenerationAuthorityEvent verified = + TenantGenerationAuthorityEventV1Codec.verify( + new String(stored.payload(), StandardCharsets.UTF_8)); + String streamKey = streamKey(scope); + String sourceScope = sourceScope(scope); + if (!MessageDigest.isEqual(stored.payload(), verified.canonicalJsonUtf8()) + || !streamKey.equals(stored.outboxStreamKey()) + || !streamKey.equals(verified.outboxStreamKey()) + || !sourceScope.equals(verified.sourceScope()) + || !scope.tenantId().toString().equals(verified.tenantId()) + || !stored.requestId().equals(verified.requestId()) + || !stored.eventId().equals(verified.eventId()) + || !stored.eventDigest().equals(verified.eventDigest()) + || !Long.toString(stored.outboxSequence()).equals(verified.outboxSequence()) + || !(EVENT_ID_PREFIX + stored.requestId()).equals(stored.eventId())) { + throw new IllegalStateException( + "Tenant authority stored event payload or database columns contradict"); + } + requireCanonicalStoredRequestId(stored.requestId()); + String expectedCounter = + BigInteger.valueOf(stored.outboxSequence()).add(BigInteger.ONE).toString(); + if (!expectedCounter.equals(verified.tenantAuthorityGeneration()) + || !expectedCounter.equals(verified.sourceVersion())) { + throw new IllegalStateException( + "Tenant authority event counters do not match their uninterrupted outbox sequence"); + } + return verified; + } + + private void requireCanonicalStoredRequestId(String requestId) { + try { + UUID parsed = UUID.fromString(requestId); + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(requestId)) { + throw new IllegalStateException("Tenant authority stored request ID is not canonical"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Tenant authority stored request ID is not a canonical UUID", malformed); + } + } + + private void requireScopeState( + ScopeState state, AuthorityScope scope, long generation, long sourceVersion) { + if (state == null + || !scope.equals(state.scope()) + || state.issuanceFence() != null + || state.generation() != generation + || state.sourceVersion() != sourceVersion) { + throw new IllegalStateException( + "Persisted Account tenant source did not match its expected advance"); + } + } + + private void requireCheckpointMatches(Checkpoint checkpoint, Event event, String streamKey) { + if (checkpoint == null + || event == null + || !streamKey.equals(checkpoint.outboxStreamKey()) + || !checkpoint.outboxStreamKey().equals(event.outboxStreamKey()) + || checkpoint.outboxSequence() != event.outboxSequence() + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new IllegalStateException( + "Tenant authority checkpoint differs from its immutable event"); + } + } + + private AuthorityScope tenantScope(UUID tenantId) { + if (tenantId == null || new UUID(0L, 0L).equals(tenantId)) { + throw new IllegalArgumentException("Canonical non-nil tenant UUID is required"); + } + return AuthorityScope.tenant(tenantId); + } + + private void requireRequestId(UUID requestId) { + if (requestId == null || new UUID(0L, 0L).equals(requestId)) { + throw new IllegalArgumentException( + "Tenant authority request ID must be a canonical non-nil UUID"); + } + } + + private String sourceScope(AuthorityScope scope) { + return "tenant/" + scope.tenantId(); + } + + private String streamKey(AuthorityScope scope) { + return AUTHORITY_STREAM_PREFIX + sourceScope(scope); + } + + private void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Tenant authority producer must own its Account transaction without an ambient transaction"); + } + } + + private static long incrementExact(long value, String field) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account " + field + " is exhausted", overflow); + } + } + + private static boolean sameEvent( + TenantGenerationAuthorityEvent first, TenantGenerationAuthorityEvent second) { + return first != null + && second != null + && first.schemaVersion().equals(second.schemaVersion()) + && first.eventType().equals(second.eventType()) + && first.eventId().equals(second.eventId()) + && first.requestId().equals(second.requestId()) + && first.tenantId().equals(second.tenantId()) + && first.sourceScope().equals(second.sourceScope()) + && first.outboxStreamKey().equals(second.outboxStreamKey()) + && first.outboxSequence().equals(second.outboxSequence()) + && first.tenantAuthorityGeneration().equals(second.tenantAuthorityGeneration()) + && first.sourceVersion().equals(second.sourceVersion()) + && first.eventDigest().equals(second.eventDigest()) + && first.canonicalJson().equals(second.canonicalJson()) + && MessageDigest.isEqual(first.canonicalJsonUtf8(), second.canonicalJsonUtf8()); + } + + /** Current exact source evidence; the event is omitted when the proven checkpoint is zero. */ + public record TenantAuthoritySnapshot( + UUID tenantId, + long tenantAuthorityGeneration, + long sourceVersion, + String outboxStreamKey, + long outboxSequence, + Optional latestEvent) { + public TenantAuthoritySnapshot { + if (tenantId == null + || new UUID(0L, 0L).equals(tenantId) + || tenantAuthorityGeneration <= 0L + || sourceVersion <= 0L + || outboxStreamKey == null + || outboxSequence < 0L) { + throw new IllegalArgumentException("Tenant authority snapshot fields are incomplete"); + } + String expectedScope = "tenant/" + tenantId; + String expectedStreamKey = AUTHORITY_STREAM_PREFIX + expectedScope; + if (!expectedStreamKey.equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Tenant authority snapshot stream does not bind its tenant"); + } + latestEvent = Objects.requireNonNull(latestEvent, "tenant latest event optional is required"); + if ((outboxSequence == 0L) != latestEvent.isEmpty()) { + throw new IllegalArgumentException("Tenant sequence-zero snapshot must omit its event"); + } + if (outboxSequence == 0L && (tenantAuthorityGeneration != 1L || sourceVersion != 1L)) { + throw new IllegalArgumentException( + "Tenant sequence-zero snapshot requires the positive 1/1 baseline"); + } + if (outboxSequence > 0L + && (tenantAuthorityGeneration == 1L + || sourceVersion == 1L + || tenantAuthorityGeneration != sourceVersion + || outboxSequence != tenantAuthorityGeneration - 1L)) { + throw new IllegalArgumentException( + "Positive tenant snapshot requires uninterrupted sequence and counter progression"); + } + latestEvent.ifPresent( + event -> { + if (!tenantId.toString().equals(event.tenantId()) + || !expectedScope.equals(event.sourceScope()) + || !outboxStreamKey.equals(event.outboxStreamKey()) + || !Long.toString(outboxSequence).equals(event.outboxSequence()) + || !Long.toString(tenantAuthorityGeneration) + .equals(event.tenantAuthorityGeneration()) + || !Long.toString(sourceVersion).equals(event.sourceVersion())) { + throw new IllegalArgumentException( + "Tenant authority snapshot event differs from its checkpoint"); + } + }); + } + } + + /** Exact retained source event tied to the current tenant checkpoint snapshot. */ + public record TenantAuthorityEventReadback( + TenantAuthoritySnapshot currentSnapshot, TenantGenerationAuthorityEvent requestedEvent) { + public TenantAuthorityEventReadback { + currentSnapshot = + Objects.requireNonNull(currentSnapshot, "current tenant authority snapshot is required"); + requestedEvent = + Objects.requireNonNull(requestedEvent, "requested tenant authority event is required"); + if (currentSnapshot.outboxSequence() <= 0L + || !currentSnapshot.tenantId().toString().equals(requestedEvent.tenantId()) + || !("tenant/" + currentSnapshot.tenantId()).equals(requestedEvent.sourceScope()) + || !currentSnapshot.outboxStreamKey().equals(requestedEvent.outboxStreamKey())) { + throw new IllegalArgumentException( + "Requested tenant event does not bind a positive current tenant snapshot"); + } + + BigInteger requestedSequence = parsePositiveCounter(requestedEvent.outboxSequence()); + BigInteger currentSequence = BigInteger.valueOf(currentSnapshot.outboxSequence()); + BigInteger requestedGeneration = + parsePositiveCounter(requestedEvent.tenantAuthorityGeneration()); + BigInteger requestedSourceVersion = parsePositiveCounter(requestedEvent.sourceVersion()); + if (requestedSequence.compareTo(currentSequence) > 0 + || requestedGeneration.compareTo( + BigInteger.valueOf(currentSnapshot.tenantAuthorityGeneration())) + > 0 + || requestedSourceVersion.compareTo(BigInteger.valueOf(currentSnapshot.sourceVersion())) + > 0) { + throw new IllegalArgumentException( + "Requested historical tenant event is ahead of the current snapshot"); + } + BigInteger expectedCounter = requestedSequence.add(BigInteger.ONE); + if (!expectedCounter.equals(requestedGeneration) + || !expectedCounter.equals(requestedSourceVersion)) { + throw new IllegalArgumentException( + "Requested historical tenant event counters do not match its outbox sequence"); + } + if (requestedSequence.equals(currentSequence) + && (currentSnapshot.latestEvent().isEmpty() + || !sameEvent(requestedEvent, currentSnapshot.latestEvent().orElseThrow()))) { + throw new IllegalArgumentException( + "Requested latest tenant event differs from the current snapshot checkpoint"); + } + } + + private static BigInteger parsePositiveCounter(String value) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "Tenant event counters must be canonical positive integers"); + } + return new BigInteger(value); + } + } + + private record LatestEvidence( + long sequence, Optional event, Optional outboxEvent) { + private LatestEvidence { + if (sequence < 0L) { + throw new IllegalArgumentException("Tenant authority history sequence cannot be negative"); + } + event = Objects.requireNonNull(event, "tenant history event optional is required"); + outboxEvent = Objects.requireNonNull(outboxEvent, "tenant outbox event optional is required"); + if ((sequence == 0L) != event.isEmpty() || event.isEmpty() != outboxEvent.isEmpty()) { + throw new IllegalArgumentException("Tenant authority history evidence is incomplete"); + } + } + + private static LatestEvidence empty() { + return new LatestEvidence(0L, Optional.empty(), Optional.empty()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/RedisAccountGenerationProjectionStore.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/RedisAccountGenerationProjectionStore.java new file mode 100644 index 0000000000..b405321f48 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/RedisAccountGenerationProjectionStore.java @@ -0,0 +1,451 @@ +package net.firedevops.firemud.accountservice.service; + +import java.io.IOException; +import java.nio.ByteBuffer; +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.time.Duration; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.common.redis.contracts.RedisInvocationContract; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.connection.RedisPassword; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; + +/** + * Explicitly initialized, unwired Account-owned store for the current account-generation + * projection. + */ +public final class RedisAccountGenerationProjectionStore implements AutoCloseable { + private static final Duration COMMAND_TIMEOUT = Duration.ofSeconds(3); + private static final byte[] CAS_SCRIPT_BYTES = scriptBytes(); + private static final String CAS_SCRIPT_SHA1 = scriptSha1(CAS_SCRIPT_BYTES); + private static final byte[] CAS_SCRIPT_SHA256 = scriptSha256(CAS_SCRIPT_BYTES); + + private final AccountAuthoritySourceReader sourceReader; + private final CoordinationEndpoint coordinationEndpoint; + + private LettuceConnectionFactory connectionFactory; + private StringRedisTemplate redisTemplate; + private boolean closed; + + /** Captures explicit role endpoints without creating a bean or opening a Redis connection. */ + public RedisAccountGenerationProjectionStore( + AccountAuthoritySourceReader reader, + CoordinationEndpoint coordination, + CacheRateLimitEndpoint cache) { + sourceReader = Objects.requireNonNull(reader, "Account source reader is required"); + coordinationEndpoint = + Objects.requireNonNull(coordination, "Coordination endpoint is required"); + Objects.requireNonNull(cache, "Cache/Rate-Limit endpoint is required"); + validateDistinctEndpoints(coordination, cache); + } + + /** Initializes this store's private Coordination-only Redis client. */ + public synchronized void init() { + if (closed) { + throw new IllegalStateException("Account generation projection store is closed"); + } + if (connectionFactory != null) { + return; + } + verifyScriptDigest(); + + RedisStandaloneConfiguration redisConfiguration = + new RedisStandaloneConfiguration(coordinationEndpoint.host(), coordinationEndpoint.port()); + redisConfiguration.setUsername(coordinationEndpoint.principal()); + redisConfiguration.setPassword(RedisPassword.of(coordinationEndpoint.password())); + LettuceClientConfiguration clientConfiguration = + LettuceClientConfiguration.builder().commandTimeout(COMMAND_TIMEOUT).build(); + + LettuceConnectionFactory newConnectionFactory = + new LettuceConnectionFactory(redisConfiguration, clientConfiguration); + newConnectionFactory.afterPropertiesSet(); + StringRedisTemplate newTemplate = new StringRedisTemplate(newConnectionFactory); + newTemplate.afterPropertiesSet(); + connectionFactory = newConnectionFactory; + redisTemplate = newTemplate; + } + + /** + * Reprojects one exact current Account snapshot. It reads source evidence before every attempt, + * performs at most one registered CAS, verifies exact Redis bytes, then rereads Account before + * reporting convergence. Source advancement never triggers an implicit retry. + */ + public synchronized ApplyResult refreshCurrent(UUID accountId) { + requireInitialized(); + String key = AccountGenerationProjection.keyForAccount(accountId); + AccountSourceSnapshot source = sourceReader.readCurrent(accountId); + AccountGenerationProjection candidate = AccountGenerationProjection.fromSource(source); + if (!key.equals(candidate.key())) { + return quarantined("ACCOUNT_SOURCE_IDENTITY_MISMATCH", Optional.empty()); + } + String candidateJson = candidate.toJson(); + byte[] candidateBytes = candidateJson.getBytes(StandardCharsets.UTF_8); + + StoredValue observed = readStoredValue(key); + if (observed.bytes() != null && observed.ttlMillis() != -1L) { + return quarantined("TTL_PRESENT", Optional.empty()); + } + + AccountGenerationProjection stored = null; + String storedJson = null; + if (observed.bytes() != null) { + try { + storedJson = decodeUtf8(observed.bytes()); + stored = AccountGenerationProjection.parse(storedJson); + } catch (IOException | IllegalArgumentException malformed) { + return quarantined("MALFORMED_STORED_PROJECTION", Optional.empty()); + } + if (!key.equals(stored.key())) { + return quarantined("STORED_ACCOUNT_ID_MISMATCH", Optional.empty()); + } + if (isRegression(candidate, stored)) { + return staleSource(key, storedJson); + } + if (candidate.outboxSequenceValue().equals(stored.outboxSequenceValue()) + && !candidate.equals(stored)) { + return quarantined( + "SAME_CHECKPOINT_DISAGREEMENT", Optional.of(new ProjectionSnapshot(key, storedJson))); + } + } + + String mode; + String expectedJson; + if (stored == null) { + mode = "ABSENT"; + expectedJson = ""; + } else if (candidate.equals(stored)) { + mode = "VERIFY"; + expectedJson = storedJson; + } else { + mode = "PRESENT"; + expectedJson = storedJson; + } + + String scriptResult = + executeRegistered(key, mode, expectedJson, "VERIFY".equals(mode) ? "" : candidateJson); + if ("STALE".equals(scriptResult)) { + return new ApplyResult(Outcome.STALE, Optional.empty(), Optional.of("REDIS_CAS_STALE")); + } + if ("TTL_PRESENT".equals(scriptResult)) { + return quarantined("TTL_PRESENT", Optional.empty()); + } + if ("INVALID".equals(scriptResult)) { + throw new IllegalStateException( + "Registered Account generation projection script rejected its invocation"); + } + if (!"APPLIED".equals(scriptResult) && !"REPLAY".equals(scriptResult)) { + throw new IllegalStateException( + "Unknown registered Account generation projection script result: " + + Objects.toString(scriptResult, "null")); + } + + StoredValue readback = readStoredValue(key); + if (readback.bytes() == null) { + return new ApplyResult( + Outcome.STALE, Optional.empty(), Optional.of("REDIS_READBACK_MISSING")); + } + if (readback.ttlMillis() != -1L) { + return quarantined("TTL_PRESENT", Optional.empty()); + } + if (!MessageDigest.isEqual(candidateBytes, readback.bytes())) { + return changedRedisReadback(key, readback.bytes()); + } + + AccountGenerationProjection current = + AccountGenerationProjection.fromSource(sourceReader.readCurrent(accountId)); + if (!candidate.equals(current)) { + return new ApplyResult( + Outcome.SOURCE_CHANGED, + Optional.of(new ProjectionSnapshot(key, candidateJson)), + Optional.of("ACCOUNT_SOURCE_ADVANCED_DURING_REPROJECTION")); + } + Outcome convergedOutcome = "APPLIED".equals(scriptResult) ? Outcome.APPLIED : Outcome.REPLAYED; + return new ApplyResult( + convergedOutcome, + Optional.of(new ProjectionSnapshot(key, candidateJson)), + Optional.empty()); + } + + @Override + public synchronized void close() { + closed = true; + if (connectionFactory != null) { + connectionFactory.destroy(); + connectionFactory = null; + redisTemplate = null; + } + } + + private ApplyResult changedRedisReadback(String key, byte[] bytes) { + try { + String json = decodeUtf8(bytes); + AccountGenerationProjection projection = AccountGenerationProjection.parse(json); + if (!key.equals(projection.key())) { + return quarantined("READBACK_ACCOUNT_ID_MISMATCH", Optional.empty()); + } + return new ApplyResult( + Outcome.STALE, + Optional.of(new ProjectionSnapshot(key, json)), + Optional.of("REDIS_READBACK_CHANGED")); + } catch (IOException | IllegalArgumentException malformed) { + return quarantined("MALFORMED_REDIS_READBACK", Optional.empty()); + } + } + + private static boolean isRegression( + AccountGenerationProjection candidate, AccountGenerationProjection stored) { + return candidate.generationValue().compareTo(stored.generationValue()) < 0 + || candidate.sourceVersionValue().compareTo(stored.sourceVersionValue()) < 0 + || candidate.outboxSequenceValue().compareTo(stored.outboxSequenceValue()) < 0; + } + + private String executeRegistered( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + RedisInvocationContract invocation = + AccountGenerationProjectionRedisContract.prepareInvocation( + key, expectedMode, expectedBytes, candidateBytes); + RedisScriptDescriptor descriptor = invocation.descriptor(); + if (descriptor != AccountGenerationProjectionRedisContract.descriptor() + || !AccountGenerationProjectionRedisContract.SCRIPT_ID.equals(descriptor.scriptId()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !AccountGenerationProjectionRedisContract.PRINCIPAL.equals(descriptor.principal()) + || !AccountGenerationProjectionRedisContract.OWNER.equals(descriptor.owner())) { + throw new IllegalStateException( + "Account generation projection invocation is not its registered owner contract"); + } + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + byte[] expectedModeBytes = expectedMode.getBytes(StandardCharsets.US_ASCII); + byte[] expectedBytesUtf8 = expectedBytes.getBytes(StandardCharsets.UTF_8); + byte[] candidateBytesUtf8 = candidateBytes.getBytes(StandardCharsets.UTF_8); + return redisTemplate.execute( + (RedisCallback) + connection -> { + String loadedSha = connection.scriptingCommands().scriptLoad(CAS_SCRIPT_BYTES); + if (!CAS_SCRIPT_SHA1.equals(loadedSha)) { + throw new IllegalStateException( + "Redis loaded a different Account generation projection script"); + } + Object result = + connection + .scriptingCommands() + .evalSha( + loadedSha, + ReturnType.VALUE, + 1, + keyBytes, + expectedModeBytes, + expectedBytesUtf8, + candidateBytesUtf8); + return decodeScriptResult(result); + }); + } + + private StoredValue readStoredValue(String key) { + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + return redisTemplate.execute( + (RedisCallback) + connection -> { + byte[] value = connection.stringCommands().get(keyBytes); + long ttlMillis = value == null ? -2L : connection.keyCommands().pTtl(keyBytes); + return new StoredValue(value, ttlMillis); + }); + } + + private void requireInitialized() { + if (closed || redisTemplate == null) { + throw new IllegalStateException( + "Account generation projection store requires explicit init()"); + } + } + + private static byte[] scriptBytes() { + try (var input = + new ClassPathResource(AccountGenerationProjectionRedisContract.RESOURCE_PATH) + .getInputStream()) { + return input.readAllBytes(); + } catch (IOException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + private static String scriptSha1(byte[] scriptBytes) { + try { + return java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-1").digest(scriptBytes)); + } catch (NoSuchAlgorithmException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + private static byte[] scriptSha256(byte[] scriptBytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(scriptBytes); + } catch (NoSuchAlgorithmException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + private static void verifyScriptDigest() { + String actual = java.util.HexFormat.of().formatHex(CAS_SCRIPT_SHA256); + if (!AccountGenerationProjectionRedisContract.descriptor().sha256().equals(actual)) { + throw new IllegalStateException( + "Account generation projection Lua resource digest differs from its registration"); + } + } + + private static String decodeUtf8(byte[] value) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } + + private static String decodeScriptResult(Object result) { + if (result instanceof byte[] bytes) { + try { + return StandardCharsets.US_ASCII + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalStateException( + "Registered Account projection script returned non-ASCII", malformed); + } + } + if (result instanceof String text) { + return text; + } + if (result == null) { + return null; + } + throw new IllegalStateException( + "Registered Account projection script returned an unsupported result type"); + } + + private static void validateDistinctEndpoints( + CoordinationEndpoint coordination, CacheRateLimitEndpoint cache) { + if (normalizeHost(coordination.host()).equals(normalizeHost(cache.host())) + && coordination.port() == cache.port()) { + throw new IllegalArgumentException( + "Coordination and Cache/Rate-Limit Redis endpoints must be distinct"); + } + } + + private static String normalizeHost(String host) { + String normalized = host.toLowerCase(Locale.ROOT); + if (normalized.startsWith("[") && normalized.endsWith("]")) { + normalized = normalized.substring(1, normalized.length() - 1); + } + while (normalized.endsWith(".")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + return normalized; + } + + private static ApplyResult staleSource(String key, String storedJson) { + return new ApplyResult( + Outcome.STALE_SOURCE, + Optional.of(new ProjectionSnapshot(key, storedJson)), + Optional.of("STORED_PROJECTION_AHEAD_OF_ACCOUNT_SOURCE")); + } + + private static ApplyResult quarantined(String detail, Optional snapshot) { + return new ApplyResult(Outcome.QUARANTINED, snapshot, Optional.of(detail)); + } + + private record StoredValue(byte[] bytes, long ttlMillis) {} + + public enum Outcome { + APPLIED, + REPLAYED, + SOURCE_CHANGED, + STALE_SOURCE, + STALE, + QUARANTINED + } + + /** Exact byte observation returned for inspection; it grants no authorization. */ + public record ProjectionSnapshot(String key, String json) { + public ProjectionSnapshot { + Objects.requireNonNull(key, "projection key is required"); + Objects.requireNonNull(json, "projection JSON is required"); + } + } + + public record ApplyResult( + Outcome outcome, Optional snapshot, Optional detail) { + public ApplyResult { + Objects.requireNonNull(outcome, "outcome is required"); + snapshot = Objects.requireNonNull(snapshot, "snapshot optional is required"); + detail = Objects.requireNonNull(detail, "detail optional is required"); + } + } + + /** Explicit Coordination endpoint and ACL identity; the principal is not caller-selectable. */ + public record CoordinationEndpoint(String host, int port, String principal, String password) { + public CoordinationEndpoint { + validateHost(host, "Coordination host"); + validatePort(port, "Coordination port"); + if (!AccountGenerationProjectionRedisContract.PRINCIPAL.equals(principal)) { + throw new IllegalArgumentException("Coordination principal must be account_coord_app"); + } + if (password == null || password.isBlank()) { + throw new IllegalArgumentException("Coordination ACL credential is required"); + } + } + + @Override + public String toString() { + return "CoordinationEndpoint[host=" + + host + + ", port=" + + port + + ", principal=" + + principal + + ", password=]"; + } + } + + /** Separate Cache/Rate-Limit endpoint used only to reject role endpoint collisions. */ + public record CacheRateLimitEndpoint(String host, int port) { + public CacheRateLimitEndpoint { + validateHost(host, "Cache/Rate-Limit host"); + validatePort(port, "Cache/Rate-Limit port"); + } + } + + private static void validateHost(String host, String label) { + if (host == null + || host.isBlank() + || !host.equals(host.trim()) + || host.contains("://") + || host.chars().anyMatch(Character::isWhitespace) + || host.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(label + " must be an explicit host or IP address"); + } + } + + private static void validatePort(int port, String label) { + if (port < 1 || port > 65535) { + throw new IllegalArgumentException(label + " must be between 1 and 65535"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index c5303d773a..41ab819481 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -4,10 +4,6 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Map; import java.util.TreeMap; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; @@ -65,7 +61,6 @@ import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.EmailCanonicalization; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -543,9 +538,10 @@ static GetTenantMembershipForRuntimeResponse encodeRuntimeMembershipCandidate( return response.build(); } - private static void requireCompleteRuntimePlayerContext( + static void requireCompleteRuntimePlayerContext( net.firedevops.firemud.shared.v1.PlayerExecutionContext playerContext) { if (playerContext == null + || !playerContext.getUnknownFields().asMap().isEmpty() || !hasText(playerContext.getAccountId()) || !hasText(playerContext.getTenantId()) || !hasText(playerContext.getRealmId()) @@ -572,96 +568,6 @@ private static void requireCompleteRuntimePlayerContext( private static void requireRuntimeMembershipEvidence(RuntimeMembershipSnapshotDto snapshot) { snapshot.requireConsistentSourceEvent(); - String tenantUuid = snapshot.tenantUuid(); - Map version = snapshot.membershipBaseline().membershipVersion(); - AuthorityTuple tuple = snapshot.authorityTuple(); - if (version.size() != 1 - || !version.containsKey(tenantUuid) - || !tuple.tenantAuthorityGeneration().keySet().equals(java.util.Set.of(tenantUuid)) - || !tuple.membershipAuthorityGeneration().keySet().equals(java.util.Set.of(tenantUuid)) - || !snapshot - .membershipBaseline() - .membershipAuthorityGeneration() - .equals(tuple.membershipAuthorityGeneration().get(tenantUuid)) - || !snapshot.issuanceFence().matches("[1-9][0-9]*")) { - throw new IllegalArgumentException("Runtime membership authority evidence is incomplete"); - } - ArrayList ordered = new ArrayList<>(snapshot.outboxCheckpoints()); - ordered.sort( - Comparator.comparing( - OutboxCheckpointEntry::outboxStreamKey, AccountGrpcService::compareUnsignedUtf8)); - if (!ordered.equals(snapshot.outboxCheckpoints()) || ordered.size() != 4) { - throw new IllegalArgumentException( - "Runtime membership checkpoints are not complete and ordered"); - } - - String membershipStreamKey = - MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX - + "membership/" - + snapshot.accountUuid() - + "/" - + tenantUuid; - String accountStreamKey = - MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + snapshot.accountUuid(); - String issuerStreamKey = - MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX - + "issuer/" - + AccountServiceImpl.ACCOUNT_JWT_ISSUER; - String tenantStreamKey = - MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantUuid; - List expectedZeroCheckpoints = - orderedCheckpoints( - List.of( - new OutboxCheckpointEntry(accountStreamKey, "0"), - new OutboxCheckpointEntry(issuerStreamKey, "0"), - new OutboxCheckpointEntry(membershipStreamKey, "0"), - new OutboxCheckpointEntry(tenantStreamKey, "0"))); - if (!snapshot.membershipExists()) { - if (!"MISSING".equals(snapshot.membershipBaseline().membershipLifecycleState()) - || snapshot.gameplayAdmissionAllowed() - || !snapshot.roles().isEmpty() - || !snapshot.outboxCheckpoints().equals(expectedZeroCheckpoints) - || !snapshot.outboxSourceEvidence().isEmpty()) { - throw new IllegalArgumentException("Sequence-zero membership snapshot is not nonadmitting"); - } - return; - } - - List expectedPositiveCheckpoints = - orderedCheckpoints( - List.of( - new OutboxCheckpointEntry(accountStreamKey, "0"), - new OutboxCheckpointEntry(issuerStreamKey, "0"), - new OutboxCheckpointEntry( - membershipStreamKey, - snapshot.outboxCheckpoints().stream() - .filter(item -> item.outboxStreamKey().equals(membershipStreamKey)) - .map(OutboxCheckpointEntry::outboxSequence) - .findFirst() - .orElse("0")), - new OutboxCheckpointEntry(tenantStreamKey, "0"))); - String lifecycleState = snapshot.membershipBaseline().membershipLifecycleState(); - boolean activeMembership = "ACTIVE".equals(lifecycleState); - if ((!activeMembership && !"INACTIVE".equals(lifecycleState)) - || snapshot.gameplayAdmissionAllowed() != activeMembership - || (activeMembership && !snapshot.roles().contains("player")) - || !snapshot.outboxCheckpoints().equals(expectedPositiveCheckpoints) - || snapshot.outboxSourceEvidence().size() != 1) { - throw new IllegalArgumentException("Positive runtime membership snapshot is incomplete"); - } - OutboxSourceEvidence source = snapshot.outboxSourceEvidence().getFirst(); - OutboxCheckpointEntry membershipCheckpoint = - expectedPositiveCheckpoints.stream() - .filter(item -> item.outboxStreamKey().equals(membershipStreamKey)) - .findFirst() - .orElseThrow(); - if (!membershipStreamKey.equals(source.outboxStreamKey()) - || !membershipCheckpoint.outboxSequence().equals(source.outboxSequence()) - || !source.eventId().matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") - || !source.eventDigest().matches("sha256:[0-9a-f]{64}")) { - throw new IllegalArgumentException( - "Runtime membership event source differs from its checkpoint"); - } } private static RuntimeAuthorityTuple toRuntimeAuthorityTuple(AuthorityTuple tuple) { @@ -714,29 +620,6 @@ private static RuntimeAuthorityTuple toRuntimeAuthorityTuple(AuthorityTuple tupl return result.build(); } - private static List orderedCheckpoints( - List checkpoints) { - return checkpoints.stream() - .sorted( - Comparator.comparing( - OutboxCheckpointEntry::outboxStreamKey, AccountGrpcService::compareUnsignedUtf8)) - .toList(); - } - - private static int compareUnsignedUtf8(String first, String second) { - byte[] left = first.getBytes(java.nio.charset.StandardCharsets.UTF_8); - byte[] right = second.getBytes(java.nio.charset.StandardCharsets.UTF_8); - int length = Math.min(left.length, right.length); - for (int index = 0; index < length; index++) { - int comparison = - Integer.compare(Byte.toUnsignedInt(left[index]), Byte.toUnsignedInt(right[index])); - if (comparison != 0) { - return comparison; - } - } - return Integer.compare(left.length, right.length); - } - private static long parseCanonicalPositiveId(String value, String field) { if (!hasText(value) || !value.matches("[1-9][0-9]*")) { throw new IllegalArgumentException("Runtime membership " + field + " is invalid"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountMembershipAuthorityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountMembershipAuthorityGrpcService.java new file mode 100644 index 0000000000..00177f7e2e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountMembershipAuthorityGrpcService.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.sql.SQLTransientException; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired transport candidate for Account-owned runtime membership readback. + * + *

This service is deliberately not a Spring component. The active Account service continues to + * deny {@code GetTenantMembershipForRuntime}; callers must explicitly construct this candidate with + * the Account-owned producer and transaction manager. + */ +public final class AccountMembershipAuthorityGrpcService + extends AccountServiceGrpc.AccountServiceImplBase { + private static final String GAME_SESSION_SERVICE = "game-session-service"; + + private final AccountMembershipAuthorityEventProducer producer; + private final TransactionTemplate ownerTransaction; + private final String expectedGameSessionPeerUri; + private final CandidateEncoder candidateEncoder; + + public AccountMembershipAuthorityGrpcService( + AccountMembershipAuthorityEventProducer producer, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this( + producer, + transactionManager, + workloadNamespace, + AccountGrpcService::encodeRuntimeMembershipCandidate); + } + + AccountMembershipAuthorityGrpcService( + AccountMembershipAuthorityEventProducer producer, + PlatformTransactionManager transactionManager, + String workloadNamespace, + CandidateEncoder candidateEncoder) { + this.producer = Objects.requireNonNull(producer, "membership authority producer is required"); + Objects.requireNonNull(transactionManager, "Account transaction manager is required"); + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalArgumentException("Account workload namespace is required"); + } + GrpcPeerIdentity expectedPeer = + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/" + GAME_SESSION_SERVICE) + .filter(identity -> workloadNamespace.equals(identity.namespace())) + .filter(identity -> identity.isService(GAME_SESSION_SERVICE)) + .orElseThrow( + () -> new IllegalArgumentException("Account workload namespace is invalid")); + this.expectedGameSessionPeerUri = expectedPeer.uri(); + this.candidateEncoder = + Objects.requireNonNull(candidateEncoder, "runtime membership encoder is required"); + + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + @Override + public void getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest request, + StreamObserver responseObserver) { + if (!hasExactGameSessionPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Game Session workload identity is required") + .asRuntimeException()); + return; + } + + final RequestSelection selection; + try { + selection = validateRequest(request); + } catch (IllegalArgumentException invalidRequest) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Runtime membership request is invalid") + .asRuntimeException()); + return; + } + + final GetTenantMembershipForRuntimeResponse response; + try { + response = + ownerTransaction.execute( + status -> { + RuntimeMembershipSnapshotDto snapshot = + producer.readRuntimeMembershipSnapshot( + selection.accountId(), selection.tenantId()); + return candidateEncoder.encode(selection.playerContext(), snapshot); + }); + if (response == null) { + throw new IllegalStateException("Runtime membership transaction returned no response"); + } + } catch (RuntimeException sourceFailure) { + Status.Code code = sourceFailureCode(sourceFailure); + String description = + code == Status.Code.UNAVAILABLE + ? "Runtime membership source is temporarily unavailable" + : "Runtime membership source evidence is unavailable or contradictory"; + responseObserver.onError( + Status.fromCode(code).withDescription(description).asRuntimeException()); + return; + } + + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean hasExactGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null && expectedGameSessionPeerUri.equals(peer.uri()); + } + + private static RequestSelection validateRequest(GetTenantMembershipForRuntimeRequest request) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Runtime membership request contains unknown fields"); + } + + PlayerExecutionContext playerContext = request.getPlayerContext(); + AccountGrpcService.requireCompleteRuntimePlayerContext(playerContext); + return new RequestSelection( + UUID.fromString(playerContext.getAccountId()), + UUID.fromString(playerContext.getTenantId()), + playerContext); + } + + private static Status.Code sourceFailureCode(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof TransientDataAccessException || cause instanceof SQLTransientException) { + return Status.Code.UNAVAILABLE; + } + } + return Status.Code.FAILED_PRECONDITION; + } + + @FunctionalInterface + interface CandidateEncoder { + GetTenantMembershipForRuntimeResponse encode( + PlayerExecutionContext playerContext, RuntimeMembershipSnapshotDto snapshot); + } + + private record RequestSelection( + UUID accountId, UUID tenantId, PlayerExecutionContext playerContext) { + private RequestSelection { + Objects.requireNonNull(accountId, "accountId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(playerContext, "playerContext"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 25abe33318..019a383e93 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -81,6 +81,7 @@ import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; @@ -95,6 +96,7 @@ import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.EmailService; @@ -155,6 +157,7 @@ public class AccountServiceImpl implements AccountService { private final AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; private final AccountAuthorityOutboxRepository accountAuthorityOutboxRepository; private final AccountPasswordResetOperationRepository passwordResetOperationRepository; + private final AccountAuthoritySourceEventReadback accountAuthoritySourceEventReadback; private final AccountAuditOutboxRepository accountAuditOutboxRepository; private final AccountConnectScopeRepository accountConnectScopeRepository; private final AccountJoinOperationRepository accountJoinOperationRepository; @@ -192,6 +195,7 @@ public AccountServiceImpl( AccountAuthorityGenerationRepository accountAuthorityGenerationRepository, AccountAuthorityOutboxRepository accountAuthorityOutboxRepository, AccountPasswordResetOperationRepository passwordResetOperationRepository, + AccountLogoutAllOperationRepository logoutAllOperationRepository, AccountAuditOutboxRepository accountAuditOutboxRepository, AccountConnectScopeRepository accountConnectScopeRepository, AccountJoinOperationRepository accountJoinOperationRepository, @@ -223,6 +227,11 @@ public AccountServiceImpl( this.accountAuthorityGenerationRepository = accountAuthorityGenerationRepository; this.accountAuthorityOutboxRepository = accountAuthorityOutboxRepository; this.passwordResetOperationRepository = passwordResetOperationRepository; + this.accountAuthoritySourceEventReadback = + new AccountAuthoritySourceEventReadback( + accountAuthorityOutboxRepository, + passwordResetOperationRepository, + logoutAllOperationRepository); this.accountAuditOutboxRepository = accountAuditOutboxRepository; this.accountConnectScopeRepository = accountConnectScopeRepository; this.accountJoinOperationRepository = accountJoinOperationRepository; @@ -2842,6 +2851,7 @@ private void completePasswordResetRetry( AuthorityScope accountScope = AuthorityScope.account(account.getAccountUuid()); ScopeState currentAuthority = readPasswordResetAccountAuthority(accountScope); + accountAuthoritySourceEventReadback.requireCurrentLatest(account, currentAuthority); requireReceiptAuthorityIsCurrentOrEarlier(receipt, currentAuthority); Event event = accountAuthorityOutboxRepository @@ -2863,58 +2873,7 @@ private void completePasswordResetRetry( } private void requireProvenPasswordResetSource(Account account, ScopeState state) { - AuthorityScope expectedScope = AuthorityScope.account(account.getAccountUuid()); - if (!expectedScope.equals(state.scope()) - || state.generation() <= 0L - || state.sourceVersion() <= 0L) { - throw new IllegalStateException("Account password-reset source scope is missing or invalid"); - } - requirePositiveAccountFence(state.issuanceFence(), account.getAccountUuid()); - - String streamKey = passwordResetStreamKey(account.getAccountUuid()); - Optional checkpoint = accountAuthorityOutboxRepository.readCheckpoint(streamKey); - if (state.generation() == 1L && state.sourceVersion() == 1L) { - if (checkpoint.isPresent()) { - throw new IllegalStateException( - "Pristine Account password-reset source has contradictory event history"); - } - return; - } - if (state.generation() <= 1L || state.sourceVersion() <= 1L || checkpoint.isEmpty()) { - throw new IllegalStateException("Account password-reset source history is not proven"); - } - - Checkpoint latestCheckpoint = checkpoint.get(); - Event latestEvent = - accountAuthorityOutboxRepository - .findEvent(streamKey, latestCheckpoint.outboxSequence()) - .orElseThrow( - () -> new IllegalStateException("Account password-reset source event is missing")); - requireCheckpointMatches(latestCheckpoint, latestEvent); - PasswordResetAuthorityEvent verified = - verifyPasswordResetEvent(latestEvent, account.getAccountUuid()); - if (!Long.toString(state.generation()).equals(verified.accountAuthorityGeneration()) - || !Long.toString(state.sourceVersion()).equals(verified.sourceVersion())) { - throw new IllegalStateException( - "Latest Account password-reset event does not match its progressed source state"); - } - PasswordResetReceipt priorReceipt = - passwordResetOperationRepository - .findByRequestId(latestEvent.requestId()) - .orElseThrow( - () -> - new IllegalStateException( - "Latest Account password-reset event has no immutable operation receipt")); - requireReceiptAccountBinding(priorReceipt, account); - requireReceiptEventBinding(priorReceipt, latestEvent); - requireReceiptAuthorityMatchesCurrent(priorReceipt, state); - String currentVerifier = account.getPasswordHash(); - if (currentVerifier == null - || !constantTimeTextEquals( - sha256Hex(currentVerifier), priorReceipt.passwordVerifierDigest())) { - throw new IllegalStateException( - "Latest Account password-reset event does not match the current password verifier"); - } + accountAuthoritySourceEventReadback.requireCurrentLatest(account, state); } private ScopeState readPasswordResetAccountAuthority(AuthorityScope accountScope) { @@ -2995,16 +2954,6 @@ private void requireReceiptEventBinding(PasswordResetReceipt receipt, Event even } } - private void requireReceiptAuthorityMatchesCurrent( - PasswordResetReceipt receipt, ScopeState state) { - if (receipt.accountAuthorityGeneration() != state.generation() - || receipt.accountSourceVersion() != state.sourceVersion()) { - throw new IllegalStateException( - "Latest password-reset receipt differs from Account authority"); - } - requireReceiptAuthorityIsCurrentOrEarlier(receipt, state); - } - private void requireReceiptAuthorityIsCurrentOrEarlier( PasswordResetReceipt receipt, ScopeState state) { AccountAuthorityGenerationRepository.IssuanceFence currentFence = state.issuanceFence(); diff --git a/services/account-service/src/main/resources/db/migration/V42.1__account_logout_all_operation_receipts.sql b/services/account-service/src/main/resources/db/migration/V42.1__account_logout_all_operation_receipts.sql new file mode 100644 index 0000000000..09ae1789ae --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V42.1__account_logout_all_operation_receipts.sql @@ -0,0 +1,90 @@ +-- Immutable lifecycle receipts bind one logout-all request and presented token to its source event. +CREATE TABLE account_logout_all_operation_receipts ( + request_id UUID NOT NULL, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL, + operation_kind VARCHAR(32) NOT NULL DEFAULT 'ACCOUNT_LOGOUT_ALL', + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + presented_token_hash BYTEA NOT NULL, + token_profile VARCHAR(32) NOT NULL, + outbox_stream_key VARCHAR(2048) NOT NULL, + outbox_sequence BIGINT NOT NULL, + event_id VARCHAR(128) NOT NULL, + event_digest VARCHAR(71) NOT NULL, + account_authority_generation BIGINT NOT NULL, + account_source_version BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + issuance_fence_source_version BIGINT NOT NULL, + lifecycle_result VARCHAR(32) NOT NULL DEFAULT 'LOGOUT_ALL_COMMITTED', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_logout_all_operation_identity_check + CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_kind = 'ACCOUNT_LOGOUT_ALL' + AND request_digest_version = 1 + AND octet_length(request_digest) = 32 + AND octet_length(presented_token_hash) = 32 + AND token_profile IN ('control-ui', 'player-bootstrap') + AND lifecycle_result = 'LOGOUT_ALL_COMMITTED'), + CONSTRAINT account_logout_all_operation_checkpoint_check + CHECK (outbox_stream_key = 'account:auth-authority:v1:account/' || account_uuid::TEXT + AND outbox_sequence > 0 + AND event_id = 'account-logout-all-event-v1:' || request_id::TEXT + AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_authority_generation > 0 + AND account_source_version > 0 + AND issuance_fence > 0 + AND issuance_fence_source_version > 0), + CONSTRAINT account_logout_all_operation_event_uq + UNIQUE (outbox_stream_key, event_id), + CONSTRAINT account_logout_all_operation_outbox_fk + FOREIGN KEY (outbox_stream_key, outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT +); + +-- [jooq ignore start] +ALTER TABLE account_logout_all_operation_receipts + ADD CONSTRAINT account_logout_all_operation_receipts_pk PRIMARY KEY (request_id); + +CREATE UNIQUE INDEX account_logout_all_operation_presented_token_uq + ON account_logout_all_operation_receipts (presented_token_hash); + +CREATE FUNCTION account_logout_all_operation_account_binding_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + persisted_uuid UUID; +BEGIN + SELECT account_uuid INTO persisted_uuid + FROM accounts + WHERE id = NEW.account_id; + IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN + RAISE EXCEPTION 'Logout-all receipt Account identity does not match its source row' + USING ERRCODE = '23514', CONSTRAINT = 'account_logout_all_operation_account_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_logout_all_operation_account_binding + BEFORE INSERT ON account_logout_all_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_logout_all_operation_account_binding_guard(); + +CREATE FUNCTION account_logout_all_operation_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Logout-all operation receipts are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_logout_all_operation_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_logout_all_operation_immutable + BEFORE UPDATE OR DELETE ON account_logout_all_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_logout_all_operation_immutable_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/redis/account_generation_projection_cas.lua b/services/account-service/src/main/resources/redis/account_generation_projection_cas.lua new file mode 100644 index 0000000000..a7b32ccc60 --- /dev/null +++ b/services/account-service/src/main/resources/redis/account_generation_projection_cas.lua @@ -0,0 +1,54 @@ +if #KEYS ~= 1 or #ARGV ~= 3 then + return 'INVALID' +end + +local mode = ARGV[1] +local expectedBytes = ARGV[2] +local candidateBytes = ARGV[3] + +if mode ~= 'ABSENT' and mode ~= 'PRESENT' and mode ~= 'VERIFY' then + return 'INVALID' +end + +if mode == 'VERIFY' then + if expectedBytes == '' or candidateBytes ~= '' then + return 'INVALID' + end +elseif mode == 'ABSENT' then + if expectedBytes ~= '' or candidateBytes == '' then + return 'INVALID' + end +elseif expectedBytes == '' or candidateBytes == '' then + return 'INVALID' +end + +local currentBytes = redis.call('GET', KEYS[1]) +if currentBytes ~= false and redis.call('PTTL', KEYS[1]) ~= -1 then + return 'TTL_PRESENT' +end + +if mode == 'VERIFY' then + if currentBytes == expectedBytes then + return 'REPLAY' + end + return 'STALE' +end + +if currentBytes == candidateBytes then + return 'REPLAY' +end + +if mode == 'ABSENT' then + if currentBytes ~= false then + return 'STALE' + end + redis.call('SET', KEYS[1], candidateBytes) + return 'APPLIED' +end + +if currentBytes ~= expectedBytes then + return 'STALE' +end + +redis.call('SET', KEYS[1], candidateBytes) +return 'APPLIED' 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 new file mode 100644 index 0000000000..991b713942 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java @@ -0,0 +1,574 @@ +package net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +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.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; +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.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountService; +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.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.v1.GameplayRealm; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = AccountServiceApplication.class, + properties = { + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, + GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.grpc.workload-namespace=account-current-authority-test" + }) +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 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:"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + @Autowired private AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; + @Autowired private AccountAuthorityGenerationRepository authorityGenerationRepository; + @Autowired private AccountAuthorityOutboxRepository authorityOutboxRepository; + @Autowired private AccountRepository accountRepository; + @Autowired private AccountLogoutAllOperationRepository logoutAllOperationRepository; + @Autowired private AccountPasswordResetOperationRepository passwordResetOperationRepository; + @Autowired private ApprovedLegacyTenantAssociationRepository tenantAssociationRepository; + @Autowired private LegacyTenantSourceEvidence legacyTenantSourceEvidence; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @Test + void postJoinSnapshotCarriesCurrentCompositeSourcesWithoutRewritingMembershipEvent() { + JoinFixture fixture = fixture(); + JoinPublicProductionResult joined = join(fixture); + assertThat(joined.success()).isTrue(); + + RuntimeMembershipSnapshotDto before = readRuntimeMembershipSnapshot(fixture); + var immutableMembershipEvent = before.sourceEvent(); + byte[] immutableMembershipBytes = immutableMembershipEvent.canonicalJsonUtf8(); + assertThat(before.membershipExists()).isTrue(); + assertThat(before.gameplayAdmissionAllowed()).isTrue(); + assertThat(before.authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(before.authorityTuple().accountAuthorityGeneration()).isEqualTo("1"); + assertThat(before.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(before.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(before.outboxCheckpoints()) + .containsExactly( + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + accountStreamKey(fixture.accountUuid()), "0"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + issuerStreamKey(), "0"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + membershipStreamKey(fixture), "1"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + tenantStreamKey(fixture.tenantUuid()), "0")); + assertThat(before.outboxSourceEvidence()).hasSize(1); + + UUID issuerRequestId = UUID.randomUUID(); + UUID tenantRequestId = UUID.randomUUID(); + UUID logoutRequestId = UUID.randomUUID(); + String presentedTokenHash = "b".repeat(64); + String tokenProfile = "control-ui"; + String requestDigest = + AccountLogoutRequestDigest.accountLogoutAll( + fixture.accountUuid(), tokenProfile, presentedTokenHash); + AccountIssuerAuthorityEventProducer issuerProducer = + new AccountIssuerAuthorityEventProducer( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + authorityGenerationRepository, + authorityOutboxRepository, + dsl, + transactionManager); + AccountTenantAuthorityEventProducer tenantProducer = + new AccountTenantAuthorityEventProducer( + authorityGenerationRepository, authorityOutboxRepository, dsl, transactionManager); + AccountLogoutAllAuthorityEventProducer logoutProducer = logoutProducer(); + + var issuerEvent = + issuerProducer.advance(AccountServiceImpl.ACCOUNT_JWT_ISSUER, issuerRequestId, 1L, 1L); + var tenantEvent = tenantProducer.advance(fixture.tenantUuid(), tenantRequestId, 1L, 1L); + ScopeState preLogoutAccountState = readAccountAuthority(fixture.accountUuid()); + Account account = readAccount(fixture.accountId()); + assertThat( + logoutProducer.commit( + logoutRequestId, + 1, + requestDigest, + tokenProfile, + presentedTokenHash, + account, + preLogoutAccountState)) + .isEqualTo(AccountLogoutAllAuthorityEventProducer.LogoutAllResult.LOGOUT_ALL_COMMITTED); + + RuntimeMembershipSnapshotDto current = readRuntimeMembershipSnapshot(fixture); + assertThat(current.membershipExists()).isTrue(); + assertThat(current.gameplayAdmissionAllowed()).isTrue(); + assertThat(current.membershipBaseline()).isEqualTo(before.membershipBaseline()); + assertThat(current.roles()).isEqualTo(before.roles()); + assertThat(current.authorityTuple().issuerAuthGeneration()).isEqualTo("2"); + assertThat(current.authorityTuple().accountAuthorityGeneration()).isEqualTo("2"); + assertThat(current.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(current.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(current.issuanceFence()).isEqualTo("2"); + assertThat(current.authorityTuple().accountSecurityCutoff()) + .hasValueSatisfying( + cutoff -> { + assertThat(cutoff.accountAuthorityGeneration()).isEqualTo("2"); + assertThat(cutoff.outboxStreamKey()) + .isEqualTo(accountStreamKey(fixture.accountUuid())); + assertThat(cutoff.outboxSequence()).isEqualTo("1"); + }); + assertThat(current.outboxCheckpoints()) + .containsExactly( + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + accountStreamKey(fixture.accountUuid()), "1"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + issuerStreamKey(), "1"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + membershipStreamKey(fixture), "1"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + tenantStreamKey(fixture.tenantUuid()), "1")); + assertThat(current.outboxSourceEvidence()) + .extracting(AccountMembershipAuthorityEventProducer.OutboxSourceEvidence::outboxStreamKey) + .containsExactly( + accountStreamKey(fixture.accountUuid()), + issuerStreamKey(), + membershipStreamKey(fixture), + tenantStreamKey(fixture.tenantUuid())); + var currentMembershipEvidence = + current.outboxSourceEvidence().stream() + .filter(evidence -> evidence.outboxStreamKey().equals(membershipStreamKey(fixture))) + .findFirst() + .orElseThrow(); + assertThat(currentMembershipEvidence.eventId()).isEqualTo(immutableMembershipEvent.eventId()); + assertThat(currentMembershipEvidence.eventDigest()) + .isEqualTo(immutableMembershipEvent.eventDigest()); + assertThat(currentMembershipEvidence.canonicalEventJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(immutableMembershipBytes); + assertThat(current.sourceEvent().eventId()).isEqualTo(immutableMembershipEvent.eventId()); + assertThat(current.sourceEvent().eventDigest()) + .isEqualTo(immutableMembershipEvent.eventDigest()); + assertThat(current.sourceEvent().canonicalJsonUtf8()).containsExactly(immutableMembershipBytes); + assertThat(current.sourceEvent().authorityTuple()) + .isEqualTo(immutableMembershipEvent.authorityTuple()); + assertThat(current.sourceEvent().issuanceFence()).isEqualTo("1"); + assertThat(current.sourceEvent().authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + + assertThat( + issuerProducer + .advance(AccountServiceImpl.ACCOUNT_JWT_ISSUER, issuerRequestId, 1L, 1L) + .eventDigest()) + .isEqualTo(issuerEvent.eventDigest()); + assertThat(tenantProducer.advance(fixture.tenantUuid(), tenantRequestId, 1L, 1L).eventDigest()) + .isEqualTo(tenantEvent.eventDigest()); + assertThat( + logoutProducer.commit( + logoutRequestId, + 1, + requestDigest, + tokenProfile, + presentedTokenHash, + account, + preLogoutAccountState)) + .isEqualTo(AccountLogoutAllAuthorityEventProducer.LogoutAllResult.LOGOUT_ALL_COMMITTED); + + RuntimeMembershipSnapshotDto readback = readRuntimeMembershipSnapshot(fixture); + assertThat(readback.authorityTuple()).isEqualTo(current.authorityTuple()); + assertThat(readback.issuanceFence()).isEqualTo(current.issuanceFence()); + assertThat(readback.outboxCheckpoints()).isEqualTo(current.outboxCheckpoints()); + assertThat(readback.outboxSourceEvidence()).isEqualTo(current.outboxSourceEvidence()); + assertThat(readback.sourceEvent().canonicalJsonUtf8()) + .containsExactly(immutableMembershipBytes); + + JoinFixture neverJoined = fixture(); + UUID neverJoinedTenantRequestId = UUID.randomUUID(); + var neverJoinedTenantEvent = + tenantProducer.advance(neverJoined.tenantUuid(), neverJoinedTenantRequestId, 1L, 1L); + RuntimeMembershipSnapshotDto absent = readRuntimeMembershipSnapshot(neverJoined); + assertThat(absent.membershipExists()).isFalse(); + assertThat(absent.gameplayAdmissionAllowed()).isFalse(); + assertThat(absent.membershipBaseline().membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(absent.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(neverJoined.tenantUuid().toString(), "1")); + assertThat(absent.authorityTuple().issuerAuthGeneration()).isEqualTo("2"); + assertThat(absent.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(neverJoined.tenantUuid().toString(), "2")); + assertThat(absent.outboxCheckpoints()) + .containsExactly( + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + accountStreamKey(neverJoined.accountUuid()), "0"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + issuerStreamKey(), "1"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + membershipStreamKey(neverJoined), "0"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + tenantStreamKey(neverJoined.tenantUuid()), "1")); + assertThat(absent.outboxSourceEvidence()) + .extracting(AccountMembershipAuthorityEventProducer.OutboxSourceEvidence::outboxStreamKey) + .containsExactly(issuerStreamKey(), tenantStreamKey(neverJoined.tenantUuid())); + assertThat(absent.outboxSourceEvidence().get(1).eventId()) + .isEqualTo(neverJoinedTenantEvent.eventId()); + assertThat(absent.outboxSourceEvidence().get(1).eventDigest()) + .isEqualTo(neverJoinedTenantEvent.eventDigest()); + assertThat(countMembershipRows(neverJoined)).isZero(); + assertThat(countStreamEvents(membershipStreamKey(neverJoined))).isZero(); + RuntimeMembershipSnapshotDto absentReadback = readRuntimeMembershipSnapshot(neverJoined); + assertThat(absentReadback.membershipExists()).isFalse(); + assertThat(absentReadback.authorityTuple()).isEqualTo(absent.authorityTuple()); + 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"); + assertThat(membershipEventBytes(fixture)).containsExactly(immutableMembershipBytes); + } + + private JoinFixture fixture() { + String suffix = UUID.randomUUID().toString(); + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "ca-" + suffix, + "current-authority-" + suffix + "@example.com", + "test-hash") + .fetchOne(0, Long.class)); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + seedAccountAuthorityState(accountUuid); + + long tenantId = positiveRandomLong(); + seedRetainedV26TenantEvidence(tenantId, suffix); + dsl.execute( + "INSERT INTO subscription (account_id, tenant_id, plan_id, status, entitlement_version) " + + "VALUES (?, ?, 'current-authority-proof', 'active', 1)", + accountId, + tenantId); + UUID tenantUuid = UUID.randomUUID(); + String evidenceDigest = legacyTenantSourceEvidence.digest(tenantId); + tenantAssociationRepository.importApproved( + tenantId, approvedTenantAssociation(tenantId, tenantUuid, evidenceDigest, suffix)); + var association = tenantAssociationRepository.findByLegacyTenantId(tenantId).orElseThrow(); + assertThat(association.canonicalTenantId()).isEqualTo(tenantUuid); + + GameplayRealm realm = + GameplayRealm.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + GameplayAdmissionPointer pointer = + GameplayAdmissionPointer.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(NAMESPACE_ID) + .setGameInstanceId(Long.toString(GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); + when(gameSessionClient.getAdmissionPointer(tenantId, WORLD_SLUG, REALM_SLUG)) + .thenReturn(pointer); + + String requestId = "current-authority-join-" + suffix; + DirectTextCallerContext caller = + new DirectTextCallerContext( + accountId, + tenantId, + REALM_ID, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "current-authority-session-" + suffix, + requestId); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + tenantId, + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + CATALOG_REVISION, + POINTER_VERSION); + DirectTextJoinScope scope = accountService.issueDirectTextConnectScope(caller, target); + return new JoinFixture(accountId, accountUuid, tenantId, tenantUuid, requestId, caller, scope); + } + + private JoinPublicProductionResult join(JoinFixture fixture) { + return accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.scope().connectScopeId(), fixture.requestId())); + } + + private RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot(JoinFixture fixture) { + return new TransactionTemplate(transactionManager) + .execute( + status -> + membershipAuthorityEventProducer.readRuntimeMembershipSnapshot( + fixture.accountUuid(), fixture.tenantUuid())); + } + + private ScopeState readAccountAuthority(UUID accountUuid) { + return new TransactionTemplate(transactionManager) + .execute(status -> authorityGenerationRepository.read(AuthorityScope.account(accountUuid))); + } + + private Account readAccount(long accountId) { + return new TransactionTemplate(transactionManager) + .execute(status -> accountRepository.findById(accountId).orElseThrow()); + } + + private AccountLogoutAllAuthorityEventProducer logoutProducer() { + return new AccountLogoutAllAuthorityEventProducer( + accountRepository, + authorityGenerationRepository, + authorityOutboxRepository, + logoutAllOperationRepository, + new AccountAuthoritySourceEventReadback( + authorityOutboxRepository, + passwordResetOperationRepository, + logoutAllOperationRepository), + dsl, + transactionManager); + } + + private byte[] membershipEventBytes(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT payload FROM account_authority_outbox_events WHERE outbox_stream_key = ? " + + "AND outbox_sequence = 1", + membershipStreamKey(fixture)) + .fetchOne()) + .get("payload", byte[].class); + } + + private long countMembershipRows(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? " + + "AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private long countStreamEvents(String streamKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class)); + } + + private void seedRetainedV26TenantEvidence(long tenantId, String suffix) { + long donorAccountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, ?, ?) RETURNING id", + "caspd-" + suffix, + "current-authority-donor-" + suffix + "@example.com", + "test-hash", + tenantId) + .fetchOne(0, Long.class)); + UUID donorAccountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", donorAccountId) + .fetchOne(0, UUID.class)); + seedAccountAuthorityState(donorAccountUuid); + long retainedMembershipId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED') " + + "RETURNING id", + donorAccountId, + tenantId) + .fetchOne(0, Long.class)); + dsl.execute( + "INSERT INTO account_legacy_tenant_sources " + + "(account_id, legacy_tenant_id, matching_membership_id, " + + "matching_membership_admission_allowed, profile_tenant_count, " + + "matching_profile_count, disposition) VALUES (?, ?, ?, FALSE, 0, 0, 'UNVERIFIED')", + donorAccountId, + tenantId, + retainedMembershipId); + dsl.execute( + "INSERT INTO account_legacy_membership_sources " + + "(membership_id, account_id, tenant_id, original_gameplay_admission_allowed, " + + "matches_account_legacy_tenant, disposition) " + + "VALUES (?, ?, ?, FALSE, TRUE, 'UNVERIFIED')", + retainedMembershipId, + donorAccountId, + tenantId); + } + + private void seedAccountAuthorityState(UUID accountUuid) { + 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); + } + + private ResolveLegacyAccountTenantAssociationResponse approvedTenantAssociation( + long legacyTenantId, UUID tenantUuid, String evidenceDigest, String suffix) { + String sourceLegacyGameTenantId = "legacy-game-" + suffix.replace("-", "").substring(0, 24); + return ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(legacyTenantId) + .setCanonicalTenantId(tenantUuid.toString()) + .setSourceLegacyGameTenantId(sourceLegacyGameTenantId) + .setSourceGameRowId(positiveRandomLong()) + .setAccountEvidenceDigest(evidenceDigest) + .setOperationId(UUID.randomUUID().toString()) + .setManifestDigest("sha256:" + "b".repeat(64)) + .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace(WORKLOAD_NAMESPACE) + .setSignerKeyId("game-design-owner-test") + .setApprovedBy("owner@example.test") + .setApprovalReference("unit-1b-current-authority-proof") + .setSignedAt("2026-09-26T00:00:00Z") + .setOperationEntryCount(1) + .setManifestSchemaVersion(1) + .build(); + } + + private long positiveRandomLong() { + long candidate = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return candidate == 0L ? 1L : candidate; + } + + private String accountStreamKey(UUID accountUuid) { + return AUTHORITY_STREAM_PREFIX + "account/" + accountUuid; + } + + private String issuerStreamKey() { + return AUTHORITY_STREAM_PREFIX + "issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER; + } + + private String tenantStreamKey(UUID tenantUuid) { + return AUTHORITY_STREAM_PREFIX + "tenant/" + tenantUuid; + } + + private String membershipStreamKey(JoinFixture fixture) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + fixture.accountUuid() + + "/" + + fixture.tenantUuid(); + } + + private record JoinFixture( + long accountId, + UUID accountUuid, + long tenantId, + UUID tenantUuid, + String requestId, + DirectTextCallerContext caller, + DirectTextJoinScope scope) {} +} 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 fedb879aea..c16fd9529d 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 @@ -470,8 +470,7 @@ void freshUuidSnapshotRejectsAdvancedTenantGenerationAndRollsBackBaselineWrites( assertThatThrownBy( () -> readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid)) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining( - "tenant authority generation cannot prove its sequence-zero baseline"); + .hasMessageContaining("tenant source history is missing"); assertThat(authorityGeneration("TENANT", null, tenantUuid)).isEqualTo(2L); assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isZero(); assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)).isZero(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountGenerationProjectionPostgresRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountGenerationProjectionPostgresRedisIntegrationTest.java new file mode 100644 index 0000000000..690192cddf --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountGenerationProjectionPostgresRedisIntegrationTest.java @@ -0,0 +1,814 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.HexFormat; +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 java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.PasswordResetToken; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer.LogoutAllResult; +import net.firedevops.firemud.accountservice.service.RedisAccountGenerationProjectionStore; +import net.firedevops.firemud.accountservice.service.RedisAccountGenerationProjectionStore.ApplyResult; +import net.firedevops.firemud.accountservice.service.RedisAccountGenerationProjectionStore.CacheRateLimitEndpoint; +import net.firedevops.firemud.accountservice.service.RedisAccountGenerationProjectionStore.CoordinationEndpoint; +import net.firedevops.firemud.accountservice.service.RedisAccountGenerationProjectionStore.Outcome; +import net.firedevops.firemud.accountservice.service.RedisAccountGenerationProjectionStore.ProjectionSnapshot; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.connection.RedisPassword; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Account-owned generation projection proof over real Account SQL and isolated Coordination Redis. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountGenerationProjectionPostgresRedisIntegrationTest { + private static final String SCHEMA_PREFIX = "account_gen_projection"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final String KEY_PREFIX = AccountGenerationProjection.KEY_PREFIX; + private static final String COORD_PASSWORD = "account-generation-projection-integration-secret"; + private static final String TOKEN_PROFILE = "control-ui"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--save", + "", + "--appendonly", + "no", + "--user", + "account_coord_app", + "on", + ">" + COORD_PASSWORD, + "~" + KEY_PREFIX + "*", + "+get", + "+set", + "+pttl", + "+evalsha", + "+script|load"); + + private final List stores = new ArrayList<>(); + private LettuceConnectionFactory adminConnectionFactory; + private StringRedisTemplate adminTemplate; + private LettuceConnectionFactory ownerConnectionFactory; + private StringRedisTemplate ownerTemplate; + + @BeforeEach + void startTestOnlyRedisAdminReadback() { + adminConnectionFactory = + new LettuceConnectionFactory( + new RedisStandaloneConfiguration(redis.getHost(), redis.getMappedPort(6379))); + adminConnectionFactory.afterPropertiesSet(); + adminTemplate = new StringRedisTemplate(adminConnectionFactory); + adminTemplate.afterPropertiesSet(); + + RedisStandaloneConfiguration ownerConfiguration = + new RedisStandaloneConfiguration(redis.getHost(), redis.getMappedPort(6379)); + ownerConfiguration.setUsername("account_coord_app"); + ownerConfiguration.setPassword(RedisPassword.of(COORD_PASSWORD)); + ownerConnectionFactory = new LettuceConnectionFactory(ownerConfiguration); + ownerConnectionFactory.afterPropertiesSet(); + ownerTemplate = new StringRedisTemplate(ownerConnectionFactory); + ownerTemplate.afterPropertiesSet(); + } + + @AfterEach + void closeConnections() { + stores.forEach(RedisAccountGenerationProjectionStore::close); + stores.clear(); + if (adminConnectionFactory != null) { + adminConnectionFactory.destroy(); + } + if (ownerConnectionFactory != null) { + ownerConnectionFactory.destroy(); + } + } + + @Test + void installsPristineAccountBaselineFromCurrentDurableSourceAndReadsItBackExactly() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + AccountAuthoritySourceReader reader = sourceReader(fixture); + AccountSourceSnapshot durableBaseline = reader.readCurrent(seed.accountUuid()); + + assertThat(durableBaseline.sourceState().generation()).isEqualTo(1L); + assertThat(durableBaseline.sourceState().sourceVersion()).isEqualTo(1L); + assertThat(durableBaseline.outboxSequence()).isZero(); + assertThat(durableBaseline.latestEvent()).isEmpty(); + + SqlState before = sqlState(fixture, seed); + ApplyResult result = store(reader).refreshCurrent(seed.accountUuid()); + + assertThat(result.outcome()).isEqualTo(Outcome.APPLIED); + ProjectionSnapshot projection = result.snapshot().orElseThrow(); + assertThat(projection.key()).isEqualTo(key(seed.accountUuid())); + JsonNode json = parse(projection.json()); + assertThat(json.path("schemaVersion").asText()) + .isEqualTo("account-auth-account-generation-projection/v1"); + assertThat(json.path("accountId").asText()).isEqualTo(seed.accountUuid().toString()); + assertThat(json.path("accountAuthorityGeneration").asText()).isEqualTo("1"); + assertThat(json.path("sourceVersion").asText()).isEqualTo("1"); + assertThat(json.path("outboxStreamKey").asText()).isEqualTo(streamKey(seed.accountUuid())); + assertThat(json.path("outboxSequence").asText()).isEqualTo("0"); + assertThat(json.has("sourceEvent")).isFalse(); + assertThat(fields(json)) + .containsExactlyInAnyOrder( + "schemaVersion", + "accountId", + "accountAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence"); + assertThat(adminTemplate.opsForValue().get(projection.key())).isEqualTo(projection.json()); + assertThat(adminTemplate.getExpire(projection.key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + assertThat(sqlState(fixture, seed)).isEqualTo(before); + } + + @Test + void accountCoordinationPrincipalCannotInvokeEvalDirectly() { + assertThatThrownBy( + () -> + ownerTemplate.execute( + (RedisCallback) + connection -> + connection + .scriptingCommands() + .eval( + "return 1".getBytes(StandardCharsets.UTF_8), + ReturnType.INTEGER, + 0))) + .satisfies(failure -> assertThat(exceptionMessageChain(failure)).contains("NOPERM")); + } + + @Test + void projectsActualPasswordResetAndLogoutAllCheckpointsWithoutRewritingSqlHistory() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + AccountAuthoritySourceReader reader = sourceReader(fixture); + RedisAccountGenerationProjectionStore store = store(reader); + + reset(fixture, seed.rawToken(), "after-reset-password"); + var resetEvent = event(fixture, seed.accountUuid(), 1L); + PasswordResetAuthorityEventV1Codec.verify( + new String(resetEvent.payload(), StandardCharsets.UTF_8)); + SqlState afterResetProducer = sqlState(fixture, seed); + ApplyResult resetProjection = store.refreshCurrent(seed.accountUuid()); + assertThat(resetProjection.outcome()).isEqualTo(Outcome.APPLIED); + assertThat( + parse(resetProjection.snapshot().orElseThrow().json()) + .path("accountAuthorityGeneration") + .asText()) + .isEqualTo("2"); + assertThat(sqlState(fixture, seed)).isEqualTo(afterResetProducer); + + ScopeState expected = readAuthority(fixture, seed.accountUuid()); + UUID requestId = UUID.randomUUID(); + String tokenHash = sha256Hex("presented-control-token:" + requestId); + String requestDigest = + AccountLogoutRequestDigest.accountLogoutAll(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + LogoutAllResult logoutResult = + logoutProducer(fixture) + .commit( + requestId, + 1, + requestDigest, + TOKEN_PROFILE, + tokenHash, + account(fixture, seed.accountId()), + expected); + assertThat(logoutResult).isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + + var logoutEvent = event(fixture, seed.accountUuid(), 2L); + AccountLogoutAllAuthorityEventV1Codec.verify( + new String(logoutEvent.payload(), StandardCharsets.UTF_8)); + SqlState afterBothProducers = sqlState(fixture, seed); + ApplyResult logoutProjection = store.refreshCurrent(seed.accountUuid()); + assertThat(logoutProjection.outcome()).isEqualTo(Outcome.APPLIED); + ProjectionSnapshot currentProjection = logoutProjection.snapshot().orElseThrow(); + assertThat(currentProjection.key()).isEqualTo(key(seed.accountUuid())); + JsonNode json = parse(currentProjection.json()); + assertThat(json.path("accountAuthorityGeneration").asText()).isEqualTo("3"); + assertThat(json.path("sourceVersion").asText()).isEqualTo("3"); + assertThat(json.path("outboxSequence").asText()).isEqualTo("2"); + assertThat(json.path("sourceEvent").asText()) + .isEqualTo(new String(logoutEvent.payload(), StandardCharsets.UTF_8)); + assertThat(fields(json)) + .containsExactlyInAnyOrder( + "schemaVersion", + "accountId", + "accountAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent"); + assertThat(adminTemplate.opsForValue().get(currentProjection.key())) + .isEqualTo(currentProjection.json()); + assertThat(sqlState(fixture, seed)).isEqualTo(afterBothProducers); + + ApplyResult duplicate = store.refreshCurrent(seed.accountUuid()); + assertThat(duplicate.outcome()).isEqualTo(Outcome.REPLAYED); + assertThat(duplicate.snapshot()).contains(currentProjection); + assertThat(adminTemplate.opsForValue().get(currentProjection.key())) + .isEqualTo(currentProjection.json()); + assertThat(sqlState(fixture, seed)).isEqualTo(afterBothProducers); + } + + @Test + void unknownAccountCannotSynthesizeProjectionOrChangeSourceRows() { + Fixture fixture = newFixture(); + UUID unknownAccount = UUID.randomUUID(); + AccountAuthoritySourceReader reader = sourceReader(fixture); + String key = key(unknownAccount); + + assertThatThrownBy(() -> store(reader).refreshCurrent(unknownAccount)) + .isInstanceOf(IllegalStateException.class); + assertThat(adminTemplate.opsForValue().get(key)).isNull(); + assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-2L); + assertThat(count(fixture, "accounts")).isZero(); + assertThat(count(fixture, "account_authority_generations")).isZero(); + assertThat(count(fixture, "account_authority_outbox_events")).isZero(); + assertThat(count(fixture, "account_authority_outbox_streams")).isZero(); + } + + @Test + void malformedExpiringAndAheadRedisValuesAreNeverOverwritten() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + AccountAuthoritySourceReader reader = sourceReader(fixture); + RedisAccountGenerationProjectionStore store = store(reader); + store.refreshCurrent(seed.accountUuid()); + + reset(fixture, seed.rawToken(), "after-reset-password"); + ProjectionSnapshot current = store.refreshCurrent(seed.accountUuid()).snapshot().orElseThrow(); + String key = current.key(); + + String malformed = "{\"schemaVersion\":\"unknown\",\"unexpected\":true}"; + adminTemplate.opsForValue().set(key, malformed); + ApplyResult malformedResult = store.refreshCurrent(seed.accountUuid()); + assertRefusedOverwrite(malformedResult); + assertThat(adminTemplate.opsForValue().get(key)).isEqualTo(malformed); + + adminTemplate.opsForValue().set(key, current.json()); + adminTemplate.expire(key, 30L, TimeUnit.SECONDS); + Long ttlBefore = adminTemplate.getExpire(key, TimeUnit.MILLISECONDS); + ApplyResult ttlResult = store.refreshCurrent(seed.accountUuid()); + assertRefusedOverwrite(ttlResult); + assertThat(adminTemplate.opsForValue().get(key)).isEqualTo(current.json()); + assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)) + .isPositive() + .isLessThanOrEqualTo(ttlBefore); + + // Poison Redis only: reseal an altered event projection without changing Account SQL evidence. + String aheadBytes = higherCachedProjection(current); + adminTemplate.opsForValue().set(key, aheadBytes); + SqlState beforeAheadRefresh = sqlState(fixture, seed); + ApplyResult aheadResult = store.refreshCurrent(seed.accountUuid()); + assertThat(aheadResult.outcome()).isEqualTo(Outcome.STALE_SOURCE); + assertThat(aheadResult.snapshot()).contains(new ProjectionSnapshot(key, aheadBytes)); + assertThat(adminTemplate.opsForValue().get(key)).isEqualTo(aheadBytes); + assertThat(sqlState(fixture, seed)).isEqualTo(beforeAheadRefresh); + } + + @Test + void staleSourceCandidateCannotReplaceAProjectionFromANewerAccountCommit() throws Exception { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + reset(fixture, seed.rawToken(), "after-reset-password"); + AccountAuthoritySourceReader delegate = sourceReader(fixture); + CountDownLatch staleReadReturned = new CountDownLatch(1); + CountDownLatch releaseStaleCandidate = new CountDownLatch(1); + AccountAuthoritySourceReader controlledReader = + controlledReader( + delegate, + 1, + () -> { + staleReadReturned.countDown(); + await(releaseStaleCandidate); + }, + false, + new AtomicInteger()); + RedisAccountGenerationProjectionStore staleStore = store(controlledReader); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + var staleRefresh = executor.submit(() -> staleStore.refreshCurrent(seed.accountUuid())); + assertThat(staleReadReturned.await(20, TimeUnit.SECONDS)).isTrue(); + + commitLogoutAll(fixture, seed); + RedisAccountGenerationProjectionStore currentStore = store(delegate); + ApplyResult current = currentStore.refreshCurrent(seed.accountUuid()); + assertThat(current.outcome()).isEqualTo(Outcome.APPLIED); + String newerBytes = current.snapshot().orElseThrow().json(); + assertThat(parse(newerBytes).path("outboxSequence").asText()).isEqualTo("2"); + + releaseStaleCandidate.countDown(); + ApplyResult staleResult = staleRefresh.get(45, TimeUnit.SECONDS); + assertRefusedOverwrite(staleResult); + assertThat(adminTemplate.opsForValue().get(key(seed.accountUuid()))).isEqualTo(newerBytes); + } finally { + releaseStaleCandidate.countDown(); + executor.shutdownNow(); + } + } + + @Test + void absentProjectionRacingAnAccountAdvanceReturnsSourceChanged() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + AccountAuthoritySourceReader delegate = sourceReader(fixture); + AtomicInteger reads = new AtomicInteger(); + AccountAuthoritySourceReader controlledReader = + controlledReader( + delegate, + 2, + () -> reset(fixture, seed.rawToken(), "racing-reset-password"), + true, + reads); + RedisAccountGenerationProjectionStore store = store(controlledReader); + String key = key(seed.accountUuid()); + + ApplyResult result = store.refreshCurrent(seed.accountUuid()); + + assertThat(reads.get()).isGreaterThanOrEqualTo(2); + assertThat(result.outcome()).isEqualTo(Outcome.SOURCE_CHANGED); + JsonNode stored = parse(adminTemplate.opsForValue().get(key)); + assertThat(stored.path("accountAuthorityGeneration").asText()).isEqualTo("1"); + assertThat(stored.path("sourceVersion").asText()).isEqualTo("1"); + assertThat(stored.path("outboxSequence").asText()).isEqualTo("0"); + assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-1L); + assertThat(sqlState(fixture, seed).generation()).isEqualTo(2L); + assertThat(eventHistory(fixture, seed.accountUuid())).hasSize(1); + } + + private void assertRefusedOverwrite(ApplyResult result) { + assertThat(result.outcome()).isNotIn(Outcome.APPLIED, Outcome.REPLAYED); + } + + private String higherCachedProjection(ProjectionSnapshot current) { + ObjectNode eventPreimage = + (ObjectNode) parse(parse(current.json()).path("sourceEvent").asText()); + eventPreimage.remove("eventDigest"); + eventPreimage.put("accountAuthorityGeneration", "999"); + eventPreimage.put("sourceVersion", "999"); + ((ObjectNode) eventPreimage.path("accountSecurityCutoff")) + .put("accountAuthorityGeneration", "999"); + Map preimage = + JSON.convertValue(eventPreimage, new TypeReference>() {}); + var sealed = PasswordResetAuthorityEventV1Codec.seal(preimage); + String canonicalSourceEvent = new String(sealed.canonicalJsonUtf8(), StandardCharsets.UTF_8); + var verifiedEvent = PasswordResetAuthorityEventV1Codec.verify(canonicalSourceEvent); + assertThat(verifiedEvent.accountAuthorityGeneration()).isEqualTo("999"); + assertThat(verifiedEvent.sourceVersion()).isEqualTo("999"); + assertThat(verifiedEvent.accountSecurityCutoff().accountAuthorityGeneration()).isEqualTo("999"); + + AccountGenerationProjection higherProjection = + new AccountGenerationProjection( + parse(current.json()).path("accountId").asText(), + "999", + "999", + parse(current.json()).path("outboxStreamKey").asText(), + parse(current.json()).path("outboxSequence").asText(), + Optional.of(canonicalSourceEvent)); + String json = higherProjection.toJson(); + assertThat(AccountGenerationProjection.parse(json)).isEqualTo(higherProjection); + return json; + } + + private AccountAuthoritySourceReader controlledReader( + AccountAuthoritySourceReader delegate, + int hookReadNumber, + Runnable hook, + boolean hookBeforeRead, + AtomicInteger reads) { + AccountAuthoritySourceReader reader = mock(AccountAuthoritySourceReader.class); + when(reader.readCurrent(any(UUID.class))) + .thenAnswer( + invocation -> { + UUID accountId = invocation.getArgument(0); + int read = reads.incrementAndGet(); + if (hookBeforeRead && read == hookReadNumber) { + hook.run(); + } + AccountSourceSnapshot current = delegate.readCurrent(accountId); + if (!hookBeforeRead && read == hookReadNumber) { + hook.run(); + } + return current; + }); + return reader; + } + + private void commitLogoutAll(Fixture fixture, Seed seed) { + ScopeState expected = readAuthority(fixture, seed.accountUuid()); + UUID requestId = UUID.randomUUID(); + String tokenHash = sha256Hex("presented-control-token:" + requestId); + String requestDigest = + AccountLogoutRequestDigest.accountLogoutAll(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + LogoutAllResult result = + logoutProducer(fixture) + .commit( + requestId, + 1, + requestDigest, + TOKEN_PROFILE, + tokenHash, + account(fixture, seed.accountId()), + expected); + assertThat(result).isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + } + + private Fixture newFixture() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + AccountRepository accounts = new AccountRepository(transactionDsl); + AccountAuthorityGenerationRepository authority = + new AccountAuthorityGenerationRepository(transactionDsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl); + AccountPasswordResetOperationRepository resetOperations = + new AccountPasswordResetOperationRepository(transactionDsl); + AccountLogoutAllOperationRepository logoutOperations = + new AccountLogoutAllOperationRepository(transactionDsl); + PasswordResetTokenRepository tokens = new PasswordResetTokenRepository(transactionDsl); + return new Fixture( + setupDsl, + transactionDsl, + transactionManager, + transaction, + accounts, + authority, + outbox, + resetOperations, + logoutOperations, + tokens); + } + + private Seed seedAccount(Fixture fixture) { + return transaction( + fixture.transaction(), + () -> { + Account account = new Account(); + String unique = UUID.randomUUID().toString(); + account.setUsername("projection-" + unique); + account.setEmail("account-projection-" + unique + "@example.test"); + account.setPasswordHash("initial-verifier"); + Account saved = fixture.accounts().save(account); + fixture.authority().initialize(AuthorityScope.account(saved.getAccountUuid())); + String rawToken = "reset-token-" + unique; + PasswordResetToken token = new PasswordResetToken(); + token.setAccount(saved); + token.setToken(rawToken); + token.setExpiresAt(LocalDateTime.now().plusHours(2)); + fixture.tokens().save(token); + return new Seed(saved.getId(), saved.getAccountUuid(), rawToken); + }); + } + + private AccountAuthoritySourceReader sourceReader(Fixture fixture) { + return new AccountAuthoritySourceReader( + fixture.accounts(), + fixture.authority(), + fixture.outbox(), + sourceReadback(fixture), + fixture.transactionManager()); + } + + private AccountAuthoritySourceEventReadback sourceReadback(Fixture fixture) { + return new AccountAuthoritySourceEventReadback( + fixture.outbox(), fixture.resetOperations(), fixture.logoutOperations()); + } + + private RedisAccountGenerationProjectionStore store(AccountAuthoritySourceReader reader) { + RedisAccountGenerationProjectionStore store = + new RedisAccountGenerationProjectionStore( + reader, + new CoordinationEndpoint( + redis.getHost(), redis.getMappedPort(6379), "account_coord_app", COORD_PASSWORD), + new CacheRateLimitEndpoint("cache.invalid.test", 6380)); + stores.add(store); + store.init(); + return store; + } + + private AccountLogoutAllAuthorityEventProducer logoutProducer(Fixture fixture) { + return new AccountLogoutAllAuthorityEventProducer( + fixture.accounts(), + fixture.authority(), + fixture.outbox(), + fixture.logoutOperations(), + sourceReadback(fixture), + fixture.transactionDsl(), + fixture.transactionManager()); + } + + private void reset(Fixture fixture, String rawToken, String password) { + AccountServiceImpl service = + new AccountServiceImpl( + fixture.accounts(), + fixture.authority(), + fixture.outbox(), + fixture.resetOperations(), + fixture.logoutOperations(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + fixture.tokens(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + fixture.transactionManager()); + transaction( + fixture.transaction(), + () -> { + service.completePasswordReset(new CompletePasswordResetRequest(rawToken, password)); + return null; + }); + } + + private Account account(Fixture fixture, long accountId) { + return transaction( + fixture.transaction(), () -> fixture.accounts().findById(accountId).orElseThrow()); + } + + private ScopeState readAuthority(Fixture fixture, UUID accountUuid) { + return transaction( + fixture.transaction(), () -> fixture.authority().read(AuthorityScope.account(accountUuid))); + } + + private AccountAuthorityOutboxRepository.Event event( + Fixture fixture, UUID accountUuid, long sequence) { + return transaction( + fixture.transaction(), + () -> fixture.outbox().findEvent(streamKey(accountUuid), sequence).orElseThrow()); + } + + private SqlState sqlState(Fixture fixture, Seed seed) { + Account account = account(fixture, seed.accountId()); + ScopeState source = readAuthority(fixture, seed.accountUuid()); + return new SqlState( + account.getPasswordHash(), + source.generation(), + source.sourceVersion(), + source.issuanceFence().value(), + source.issuanceFence().sourceVersion(), + count(fixture, "accounts"), + count(fixture, "account_authority_generations"), + count(fixture, "account_authority_issuance_fences"), + count(fixture, "account_password_reset_operation_receipts"), + count(fixture, "account_logout_all_operation_receipts"), + count(fixture, "account_authority_outbox_events"), + count(fixture, "account_authority_outbox_streams"), + eventHistory(fixture, seed.accountUuid())); + } + + private List eventHistory(Fixture fixture, UUID accountUuid) { + return fixture + .setupDsl() + .resultQuery( + "SELECT outbox_stream_key, outbox_sequence, request_id, event_id, event_digest, payload " + + "FROM account_authority_outbox_events WHERE outbox_stream_key = ? " + + "ORDER BY outbox_sequence", + streamKey(accountUuid)) + .fetch( + record -> + new EventEvidence( + record.get("outbox_stream_key", String.class), + record.get("outbox_sequence", Long.class), + record.get("request_id", String.class), + record.get("event_id", String.class), + record.get("event_digest", String.class), + record.get("payload", byte[].class))); + } + + private long count(Fixture fixture, String table) { + return Objects.requireNonNull( + fixture.setupDsl().resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class), + "Account projection source row count is missing"); + } + + private String key(UUID accountUuid) { + return KEY_PREFIX + accountUuid; + } + + private String streamKey(UUID accountUuid) { + return STREAM_PREFIX + accountUuid; + } + + private String sha256Hex(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private JsonNode parse(String json) { + try { + return JSON.readTree(json); + } catch (Exception exception) { + throw new IllegalStateException("Projection JSON could not be read", exception); + } + } + + private Set fields(JsonNode json) { + Set names = new HashSet<>(); + json.fieldNames().forEachRemaining(names::add); + return names; + } + + private String exceptionMessageChain(Throwable failure) { + StringBuilder messages = new StringBuilder(); + Throwable current = failure; + while (current != null) { + messages.append(current.getMessage()).append('\n'); + current = current.getCause(); + } + return messages.toString(); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Account projection race barrier timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Account projection race proof was interrupted", interrupted); + } + } + + private T transaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record Fixture( + DSLContext setupDsl, + DSLContext transactionDsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transaction, + AccountRepository accounts, + AccountAuthorityGenerationRepository authority, + AccountAuthorityOutboxRepository outbox, + AccountPasswordResetOperationRepository resetOperations, + AccountLogoutAllOperationRepository logoutOperations, + PasswordResetTokenRepository tokens) {} + + private record Seed(long accountId, UUID accountUuid, String rawToken) {} + + private record EventEvidence( + String streamKey, + long sequence, + String requestId, + String eventId, + String digest, + byte[] payload) { + private EventEvidence { + payload = payload.clone(); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof EventEvidence evidence)) { + return false; + } + return sequence == evidence.sequence + && streamKey.equals(evidence.streamKey) + && requestId.equals(evidence.requestId) + && eventId.equals(evidence.eventId) + && digest.equals(evidence.digest) + && java.util.Arrays.equals(payload, evidence.payload); + } + + @Override + public int hashCode() { + return Objects.hash( + streamKey, sequence, requestId, eventId, digest, java.util.Arrays.hashCode(payload)); + } + } + + private record SqlState( + String passwordHash, + long generation, + long sourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + long accountCount, + long generationCount, + long fenceCount, + long passwordResetReceiptCount, + long logoutReceiptCount, + long eventCount, + long streamCount, + List eventHistory) {} +} 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 a29e8d54e4..0f56baad43 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 @@ -2157,8 +2157,7 @@ void neverJoinedSnapshotRejectsAdvancedUpstreamGenerationWithoutSourceEvent() { .isZero(); assertThatThrownBy(() -> readNeverJoinedMembershipSnapshot(advancedTenant)) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining( - "tenant authority generation cannot prove its sequence-zero baseline"); + .hasMessageContaining("tenant source history is missing"); } private AccountMembershipAuthorityEventProducer.PositiveMembershipSnapshot diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java new file mode 100644 index 0000000000..8db75ac035 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java @@ -0,0 +1,1166 @@ +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.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.HexFormat; +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.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.PasswordResetToken; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer.LogoutAllResult; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class AccountLogoutAllAuthorityProducerPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "logout_src"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + private static final long MAX_COUNTER = Long.MAX_VALUE; + private static final String TOKEN_PROFILE = "control-ui"; + private static final UUID UNKNOWN_ACCOUNT_UUID = + UUID.fromString("90000000-0000-4000-8000-000000000001"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void commitsAccountGenerationFenceClosedEventCheckpointAndImmutableReceiptTogether() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("presented-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + + LogoutAllResult result = + commit(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + + ScopeState current = authority(fixture, seed); + LogoutAllReceipt receipt = logoutReceipt(fixture, requestId); + var event = + transaction( + fixture.transaction(), + () -> fixture.outbox().findEvent(streamKey(seed.accountUuid()), 1L).orElseThrow()); + var checkpoint = + transaction( + fixture.transaction(), + () -> fixture.outbox().readCheckpoint(streamKey(seed.accountUuid())).orElseThrow()); + var decoded = + AccountLogoutAllAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + + assertThat(result).isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + assertThat(current.generation()).isEqualTo(2L); + assertThat(current.sourceVersion()).isEqualTo(2L); + assertThat(current.issuanceFence().value()).isEqualTo(2L); + assertThat(current.issuanceFence().sourceVersion()).isEqualTo(2L); + assertThat(receipt.accountId()).isEqualTo(seed.accountId()); + assertThat(receipt.accountUuid()).isEqualTo(seed.accountUuid()); + assertThat(receipt.requestId()).isEqualTo(requestId); + assertThat(receipt.requestDigestVersion()).isEqualTo(1); + assertThat(receipt.requestDigest()).isEqualTo(requestDigest); + assertThat(receipt.presentedTokenHash()).isEqualTo(tokenHash); + assertThat(receipt.tokenProfile()).isEqualTo(TOKEN_PROFILE); + assertThat(receipt.operationKind()).isEqualTo("ACCOUNT_LOGOUT_ALL"); + assertThat(receipt.lifecycleResult()).isEqualTo("LOGOUT_ALL_COMMITTED"); + assertThat(receipt.accountAuthorityGeneration()).isEqualTo(2L); + assertThat(receipt.accountSourceVersion()).isEqualTo(2L); + assertThat(receipt.issuanceFence()).isEqualTo(2L); + assertThat(receipt.issuanceFenceSourceVersion()).isEqualTo(2L); + assertThat(receipt.outboxSequence()).isEqualTo(1L); + assertThat(receipt.eventId()).isEqualTo(EVENT_ID_PREFIX + requestId); + assertThat(checkpoint.outboxSequence()).isEqualTo(receipt.outboxSequence()); + assertThat(checkpoint.sourceEventId()).isEqualTo(receipt.eventId()); + assertThat(checkpoint.sourceEventDigest()).isEqualTo(receipt.eventDigest()); + assertThat(decoded.requestId()).isEqualTo(requestId.toString()); + assertThat(decoded.accountId()).isEqualTo(seed.accountUuid().toString()); + assertThat(decoded.accountAuthorityGeneration()).isEqualTo("2"); + assertThat(decoded.sourceVersion()).isEqualTo("2"); + assertThat(new String(event.payload(), StandardCharsets.UTF_8)).doesNotContain(tokenHash); + assertThat(count(fixture, "account_logout_all_operation_receipts")).isEqualTo(1L); + assertThat(count(fixture, "account_authority_outbox_events")).isEqualTo(1L); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_logout_all_operation_receipts " + + "SET request_digest = request_digest WHERE request_id = ?", + requestId)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_logout_all_operation_receipts WHERE request_id = ?", + requestId)) + .isInstanceOf(DataAccessException.class); + assertThat(logoutReceipt(fixture, requestId)).isEqualTo(receipt); + } + + @Test + void exactRetryRecoversOriginalResultAfterLaterSourceAdvanceWithoutRewritingCounters() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + UUID firstRequest = UUID.randomUUID(); + String firstTokenHash = digest("presented-token:" + firstRequest); + String firstDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, firstTokenHash); + LogoutAllResult firstResult = + commit(fixture, seed, firstRequest, firstDigest, firstTokenHash, seed.initialState()); + LogoutAllReceipt firstReceipt = logoutReceipt(fixture, firstRequest); + + UUID laterRequest = UUID.randomUUID(); + String laterTokenHash = digest("presented-token:" + laterRequest); + commit( + fixture, + seed, + laterRequest, + logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, laterTokenHash), + laterTokenHash, + authority(fixture, seed)); + StoredState afterLaterAdvance = snapshot(fixture, seed); + + LogoutAllResult retry = + commit(fixture, seed, firstRequest, firstDigest, firstTokenHash, seed.initialState()); + + assertThat(retry).isEqualTo(firstResult); + assertThat(logoutReceipt(fixture, firstRequest)).isEqualTo(firstReceipt); + assertThat(snapshot(fixture, seed)).isEqualTo(afterLaterAdvance); + } + + @Test + void changedRequestBindingsConflictWithoutMutation() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("presented-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + commit(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + StoredState committed = snapshot(fixture, seed); + LogoutAllReceipt committedReceipt = logoutReceipt(fixture, requestId); + var committedEvent = + transaction( + fixture.transaction(), + () -> fixture.outbox().findEvent(streamKey(seed.accountUuid()), 1L).orElseThrow()); + + assertThatThrownBy( + () -> + commit( + fixture, + seed, + requestId, + digest("changed-request:" + requestId), + tokenHash, + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + producer(fixture) + .commit( + requestId, + 2, + requestDigest, + TOKEN_PROFILE, + tokenHash, + account(fixture, seed), + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + requestId, + requestDigest, + digest("changed-token:" + requestId), + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + requestId, + logoutAllDigest(seed.accountUuid(), "player-bootstrap", tokenHash), + "player-bootstrap", + tokenHash, + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + UUID.randomUUID(), + digest("changed-request-id"), + tokenHash, + seed.initialState())) + .isInstanceOf(AccountLogoutAllAuthorityEventProducer.OperationConflictException.class); + UUID unboundRequestId = UUID.randomUUID(); + String unboundTokenHash = digest("unbound-token:" + unboundRequestId); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + unboundRequestId, + digest("unbound-request-digest"), + unboundTokenHash, + authority(fixture, seed))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical caller bindings"); + + assertThat(snapshot(fixture, seed)).isEqualTo(committed); + assertThat(logoutReceipt(fixture, requestId)).isEqualTo(committedReceipt); + assertThat( + transaction( + fixture.transaction(), + () -> fixture.outbox().findEvent(streamKey(seed.accountUuid()), 1L).orElseThrow())) + .isEqualTo(committedEvent); + } + + @Test + void concurrentExactRequestCommitsOnlyOneAuthorityAdvanceAndEvent() throws Exception { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("presented-token:" + requestId); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> + concurrentCommit( + fixture, seed, requestId, requestDigest, tokenHash, ready, start)); + var second = + executor.submit( + () -> + concurrentCommit( + fixture, seed, requestId, requestDigest, tokenHash, ready, start)); + assertThat(ready.await(20, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(first.get(45, TimeUnit.SECONDS)).isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + assertThat(second.get(45, TimeUnit.SECONDS)).isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + } finally { + start.countDown(); + executor.shutdownNow(); + } + + ScopeState current = authority(fixture, seed); + assertThat(current.generation()).isEqualTo(2L); + assertThat(current.sourceVersion()).isEqualTo(2L); + assertThat(current.issuanceFence().value()).isEqualTo(2L); + assertThat(count(fixture, "account_logout_all_operation_receipts")).isEqualTo(1L); + assertThat(count(fixture, "account_authority_outbox_events")).isEqualTo(1L); + } + + @Test + void eventInsertFailureRollsBackGenerationFenceCheckpointAndReceipt() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + fixture + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events " + + "ADD CONSTRAINT reject_logout_all_event " + + "CHECK (event_id NOT LIKE 'account-logout-all-event-v1:%')"); + + UUID rollbackRequest = UUID.randomUUID(); + String rollbackTokenHash = digest("rollback-token"); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + rollbackRequest, + logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, rollbackTokenHash), + rollbackTokenHash, + seed.initialState())) + .isInstanceOf(RuntimeException.class); + + assertThat(snapshot(fixture, seed)) + .isEqualTo(new StoredState(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L)); + assertThat(count(fixture, "account_authority_outbox_streams")).isZero(); + } + + @Test + void sourceCounterOverflowFailsBeforeAnyCutoffMutation() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture, MAX_COUNTER); + seedLatestLogoutReceiptAtMaximumCounter(fixture, seed); + ScopeState maximum = authority(fixture, seed); + StoredState before = snapshot(fixture, seed); + + UUID overflowRequest = UUID.randomUUID(); + String overflowTokenHash = digest("overflow-token"); + assertThatThrownBy( + () -> + commit( + fixture, + seed, + overflowRequest, + logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, overflowTokenHash), + overflowTokenHash, + maximum)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exhausted"); + + assertThat(snapshot(fixture, seed)).isEqualTo(before); + } + + @Test + void passwordResetThenLogoutAllPreservesBothReceiptsAndResetRetry() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + reset(fixture, seed, "reset-before-logout"); + PasswordResetReceipt resetReceipt = passwordResetReceipt(fixture, seed); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("presented-token:" + requestId); + + commit( + fixture, + seed, + requestId, + logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash), + tokenHash, + authority(fixture, seed)); + LogoutAllReceipt logoutReceipt = logoutReceipt(fixture, requestId); + + reset(fixture, seed, "reset-before-logout"); + + assertThat(passwordResetReceipt(fixture, seed)).isEqualTo(resetReceipt); + assertThat(logoutReceipt(fixture, requestId)).isEqualTo(logoutReceipt); + assertThat(authority(fixture, seed).generation()).isEqualTo(3L); + assertThat(authority(fixture, seed).sourceVersion()).isEqualTo(3L); + assertThat(count(fixture, "account_authority_outbox_events")).isEqualTo(2L); + } + + @Test + void logoutAllThenPasswordResetValidatesMixedLatestSourceAndPreservesLogoutReceipt() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + UUID requestId = UUID.randomUUID(); + String tokenHash = digest("presented-token:" + requestId); + + commit( + fixture, + seed, + requestId, + logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash), + tokenHash, + seed.initialState()); + LogoutAllReceipt logoutReceipt = logoutReceipt(fixture, requestId); + reset(fixture, seed, "reset-after-logout"); + + assertThat(logoutReceipt(fixture, requestId)).isEqualTo(logoutReceipt); + assertThat(passwordResetReceipt(fixture, seed).outboxSequence()).isEqualTo(2L); + assertThat(authority(fixture, seed).generation()).isEqualTo(3L); + assertThat(authority(fixture, seed).sourceVersion()).isEqualTo(3L); + assertThat(count(fixture, "account_authority_outbox_events")).isEqualTo(2L); + } + + @Test + void currentSourceReadbackProvesPristineAccountAndRejectsUnknownAccountWithoutMutation() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + StoredState before = snapshot(fixture, seed); + + AccountAuthoritySourceReader.AccountSourceSnapshot current = + sourceReader(fixture).readCurrent(seed.accountUuid()); + + assertThat(current.accountId()).isEqualTo(seed.accountUuid()); + assertThat(current.sourceState().scope()).isEqualTo(AuthorityScope.account(seed.accountUuid())); + assertThat(current.sourceState().generation()).isEqualTo(1L); + assertThat(current.sourceState().sourceVersion()).isEqualTo(1L); + assertThat(current.sourceState().issuanceFence().value()).isEqualTo(1L); + assertThat(current.sourceState().issuanceFence().sourceVersion()).isEqualTo(1L); + assertThat(current.outboxStreamKey()).isEqualTo(streamKey(seed.accountUuid())); + assertThat(current.outboxSequence()).isZero(); + assertThat(current.latestEvent()).isEmpty(); + + assertThatThrownBy(() -> sourceReader(fixture).readCurrent(UNKNOWN_ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class); + + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat(count(fixture, "account_authority_outbox_streams")).isZero(); + } + + @Test + void + historicalReadbackPreservesMixedEventsWhileReturningCurrentSourceAndResetRetryStaysSuperseded() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + String firstPassword = "historical-password-one"; + reset(fixture, seed, firstPassword); + PasswordResetReceipt firstResetReceipt = passwordResetReceipt(fixture, seed); + AccountAuthorityOutboxRepository.Event firstResetEvent = event(fixture, seed, 1L); + + UUID logoutRequestId = UUID.randomUUID(); + String tokenHash = digest("presented-token:" + logoutRequestId); + commit( + fixture, + seed, + logoutRequestId, + logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash), + tokenHash, + authority(fixture, seed)); + LogoutAllReceipt logoutReceipt = logoutReceipt(fixture, logoutRequestId); + AccountAuthorityOutboxRepository.Event logoutEvent = event(fixture, seed, 2L); + + String laterResetToken = addPasswordResetToken(fixture, seed); + String laterPassword = "historical-password-two"; + reset(fixture, laterResetToken, laterPassword); + PasswordResetReceipt laterResetReceipt = passwordResetReceipt(fixture, laterResetToken); + AccountAuthorityOutboxRepository.Event laterResetEvent = event(fixture, seed, 3L); + + AccountAuthoritySourceReader reader = sourceReader(fixture); + AccountAuthoritySourceReader.AccountSourceSnapshot current = + reader.readCurrent(seed.accountUuid()); + AccountAuthoritySourceReader.AccountSourceEventReadback historicalReset = + reader.readCommittedEvent(seed.accountUuid(), 1L); + AccountAuthoritySourceReader.AccountSourceEventReadback historicalLogout = + reader.readCommittedEvent(seed.accountUuid(), 2L); + + assertThat(current.sourceState().generation()).isEqualTo(4L); + assertThat(current.sourceState().sourceVersion()).isEqualTo(4L); + assertThat(current.sourceState().issuanceFence().value()).isEqualTo(4L); + assertThat(current.outboxSequence()).isEqualTo(3L); + assertThat(current.latestEvent()).isPresent(); + assertSameEvent(laterResetEvent, current.latestEvent().orElseThrow()); + assertThat(historicalReset.currentSnapshot().sourceState()).isEqualTo(current.sourceState()); + assertThat(historicalReset.currentSnapshot().outboxStreamKey()) + .isEqualTo(current.outboxStreamKey()); + assertThat(historicalReset.currentSnapshot().outboxSequence()).isEqualTo(3L); + assertSameEvent(laterResetEvent, historicalReset.currentSnapshot().latestEvent().orElseThrow()); + assertSameEvent(firstResetEvent, historicalReset.requestedEvent()); + assertThat(historicalLogout.currentSnapshot().sourceState()).isEqualTo(current.sourceState()); + assertThat(historicalLogout.currentSnapshot().outboxSequence()).isEqualTo(3L); + assertSameEvent( + laterResetEvent, historicalLogout.currentSnapshot().latestEvent().orElseThrow()); + assertSameEvent(logoutEvent, historicalLogout.requestedEvent()); + assertThat(passwordResetReceipt(fixture, seed)).isEqualTo(firstResetReceipt); + assertThat(passwordResetReceipt(fixture, laterResetToken)).isEqualTo(laterResetReceipt); + assertThat(logoutReceipt(fixture, logoutRequestId)).isEqualTo(logoutReceipt); + assertThat(new String(firstResetEvent.payload(), StandardCharsets.UTF_8)) + .doesNotContain(seed.rawToken(), firstPassword, laterPassword); + assertThat(new String(logoutEvent.payload(), StandardCharsets.UTF_8)) + .doesNotContain(seed.rawToken(), firstPassword, laterPassword, tokenHash); + assertThat(new String(laterResetEvent.payload(), StandardCharsets.UTF_8)) + .doesNotContain(laterResetToken, firstPassword, laterPassword); + for (Object evidence : List.of(current, historicalReset, historicalLogout)) { + assertThat(evidence.toString()) + .doesNotContain( + seed.rawToken(), laterResetToken, firstPassword, laterPassword, tokenHash); + } + + StoredState beforeSupersededRetry = snapshot(fixture, seed); + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), firstPassword)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("superseded"); + assertThat(snapshot(fixture, seed)).isEqualTo(beforeSupersededRetry); + assertThat(passwordResetReceipt(fixture, seed)).isEqualTo(firstResetReceipt); + assertThat(passwordResetReceipt(fixture, laterResetToken)).isEqualTo(laterResetReceipt); + assertThat(logoutReceipt(fixture, logoutRequestId)).isEqualTo(logoutReceipt); + assertSameEvent(firstResetEvent, event(fixture, seed, 1L)); + assertSameEvent(logoutEvent, event(fixture, seed, 2L)); + assertSameEvent(laterResetEvent, event(fixture, seed, 3L)); + } + + @Test + void invalidHistoricalSelectorsFailWithoutChangingAnyAccountSourceEvidence() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + reset(fixture, seed, "selector-test-password"); + UUID logoutRequestId = UUID.randomUUID(); + String tokenHash = digest("presented-token:" + logoutRequestId); + commit( + fixture, + seed, + logoutRequestId, + logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash), + tokenHash, + authority(fixture, seed)); + + StoredState before = snapshot(fixture, seed); + Account accountBefore = account(fixture, seed); + PasswordResetReceipt resetReceipt = passwordResetReceipt(fixture, seed); + LogoutAllReceipt logoutReceipt = logoutReceipt(fixture, logoutRequestId); + AccountAuthorityOutboxRepository.Event firstEvent = event(fixture, seed, 1L); + AccountAuthorityOutboxRepository.Event secondEvent = event(fixture, seed, 2L); + AccountAuthoritySourceReader reader = sourceReader(fixture); + + assertThatThrownBy(() -> reader.readCommittedEvent(seed.accountUuid(), 0L)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertAccountCredentialUnchanged(fixture, seed, accountBefore); + assertThat(passwordResetReceipt(fixture, seed)).isEqualTo(resetReceipt); + assertThat(logoutReceipt(fixture, logoutRequestId)).isEqualTo(logoutReceipt); + assertSameEvent(firstEvent, event(fixture, seed, 1L)); + assertSameEvent(secondEvent, event(fixture, seed, 2L)); + assertThatThrownBy(() -> reader.readCommittedEvent(seed.accountUuid(), -1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertAccountCredentialUnchanged(fixture, seed, accountBefore); + assertThat(passwordResetReceipt(fixture, seed)).isEqualTo(resetReceipt); + assertThat(logoutReceipt(fixture, logoutRequestId)).isEqualTo(logoutReceipt); + assertSameEvent(firstEvent, event(fixture, seed, 1L)); + assertSameEvent(secondEvent, event(fixture, seed, 2L)); + assertThatThrownBy(() -> reader.readCommittedEvent(seed.accountUuid(), 3L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ahead of its current checkpoint"); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat(passwordResetReceipt(fixture, seed)).isEqualTo(resetReceipt); + assertThat(logoutReceipt(fixture, logoutRequestId)).isEqualTo(logoutReceipt); + + AccountAuthorityOutboxRepository missingHistoricalEvent = + new AccountAuthorityOutboxRepository(fixture.transactionDsl()) { + @Override + public Optional findEvent( + String requestedStreamKey, long outboxSequence) { + if (streamKey(seed.accountUuid()).equals(requestedStreamKey) && outboxSequence == 1L) { + return Optional.empty(); + } + return super.findEvent(requestedStreamKey, outboxSequence); + } + }; + assertThatThrownBy( + () -> + sourceReader(fixture, fixture.accounts(), missingHistoricalEvent) + .readCommittedEvent(seed.accountUuid(), 1L)) + .isInstanceOf(IllegalStateException.class); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat(passwordResetReceipt(fixture, seed)).isEqualTo(resetReceipt); + assertThat(logoutReceipt(fixture, logoutRequestId)).isEqualTo(logoutReceipt); + assertSameEvent(firstEvent, event(fixture, seed, 1L)); + assertSameEvent(secondEvent, event(fixture, seed, 2L)); + + Seed otherAccount = seedAccount(fixture); + reset(fixture, otherAccount, "other-account-source-password"); + AccountAuthorityOutboxRepository.Event foreignEvent = event(fixture, seed, 1L); + AccountAuthorityOutboxRepository.Event otherAccountEvent = event(fixture, otherAccount, 1L); + ScopeState otherAccountBefore = authority(fixture, otherAccount); + Account otherAccountRowBefore = account(fixture, otherAccount); + PasswordResetReceipt otherAccountReceipt = passwordResetReceipt(fixture, otherAccount); + StoredState beforeCrossAccountRead = snapshot(fixture, seed); + AtomicInteger otherAccountEventReads = new AtomicInteger(); + AccountAuthorityOutboxRepository crossAccountReadback = + new AccountAuthorityOutboxRepository(fixture.transactionDsl()) { + @Override + public Optional findEvent( + String requestedStreamKey, long outboxSequence) { + if (streamKey(otherAccount.accountUuid()).equals(requestedStreamKey) + && outboxSequence == 1L) { + if (otherAccountEventReads.incrementAndGet() > 1) { + return Optional.of(foreignEvent); + } + } + return super.findEvent(requestedStreamKey, outboxSequence); + } + }; + assertThatThrownBy( + () -> + sourceReader(fixture, fixture.accounts(), crossAccountReadback) + .readCommittedEvent(otherAccount.accountUuid(), 1L)) + .isInstanceOf(IllegalStateException.class); + assertThat(snapshot(fixture, seed)).isEqualTo(beforeCrossAccountRead); + assertThat(authority(fixture, otherAccount)).isEqualTo(otherAccountBefore); + assertAccountCredentialUnchanged(fixture, otherAccount, otherAccountRowBefore); + assertThat(passwordResetReceipt(fixture, seed)).isEqualTo(resetReceipt); + assertThat(logoutReceipt(fixture, logoutRequestId)).isEqualTo(logoutReceipt); + assertThat(passwordResetReceipt(fixture, otherAccount)).isEqualTo(otherAccountReceipt); + assertSameEvent(firstEvent, event(fixture, seed, 1L)); + assertSameEvent(secondEvent, event(fixture, seed, 2L)); + assertSameEvent(otherAccountEvent, event(fixture, otherAccount, 1L)); + } + + @Test + void historicalReaderHoldsAccountFenceThroughSelectedAndCurrentSourceReadback() throws Exception { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + reset(fixture, seed, "fenced-source-password"); + AccountAuthorityOutboxRepository.Event firstEvent = event(fixture, seed, 1L); + ScopeState beforeAdvance = authority(fixture, seed); + Account verifiedAccount = account(fixture, seed); + + CountDownLatch readerLockedAccount = new CountDownLatch(1); + CountDownLatch releaseReader = new CountDownLatch(1); + CountDownLatch writerReachedAccountLock = new CountDownLatch(1); + AtomicInteger readerBackendPid = new AtomicInteger(); + AtomicInteger writerBackendPid = new AtomicInteger(); + AccountRepository readerAccounts = + new AccountRepository(fixture.transactionDsl()) { + @Override + public Optional findByIdForUpdate(Long id) { + Optional locked = super.findByIdForUpdate(id); + readerBackendPid.set(currentBackendPid(fixture.transactionDsl())); + readerLockedAccount.countDown(); + await(releaseReader); + return locked; + } + }; + AccountRepository writerAccounts = + new AccountRepository(fixture.transactionDsl()) { + @Override + public Optional findByIdForUpdate(Long id) { + writerBackendPid.set(currentBackendPid(fixture.transactionDsl())); + writerReachedAccountLock.countDown(); + return super.findByIdForUpdate(id); + } + }; + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var read = + executor.submit( + () -> + sourceReader(fixture, readerAccounts, fixture.outbox()) + .readCommittedEvent(seed.accountUuid(), 1L)); + assertThat(readerLockedAccount.await(20, TimeUnit.SECONDS)).isTrue(); + var write = + executor.submit( + () -> + producer(fixture, writerAccounts) + .commit( + UUID.randomUUID(), + 1, + logoutAllDigest( + seed.accountUuid(), TOKEN_PROFILE, digest("fenced-writer-token")), + TOKEN_PROFILE, + digest("fenced-writer-token"), + verifiedAccount, + beforeAdvance)); + assertThat(writerReachedAccountLock.await(20, TimeUnit.SECONDS)).isTrue(); + assertThat( + awaitAccountRowBlock( + fixture.setupDsl(), + readerBackendPid.get(), + writerBackendPid.get(), + Duration.ofSeconds(10))) + .as("the source mutation waits on the reader's locked Account row") + .isTrue(); + + releaseReader.countDown(); + AccountAuthoritySourceReader.AccountSourceEventReadback readback = + read.get(45, TimeUnit.SECONDS); + assertThat(write.get(45, TimeUnit.SECONDS)).isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); + + assertSameEvent(firstEvent, readback.requestedEvent()); + assertThat(readback.currentSnapshot().sourceState()).isEqualTo(beforeAdvance); + assertThat(readback.currentSnapshot().outboxSequence()).isEqualTo(1L); + assertSameEvent(firstEvent, readback.currentSnapshot().latestEvent().orElseThrow()); + ScopeState afterAdvance = authority(fixture, seed); + assertThat(afterAdvance.generation()).isEqualTo(3L); + assertThat(afterAdvance.sourceVersion()).isEqualTo(3L); + assertThat(afterAdvance.issuanceFence().value()).isEqualTo(3L); + assertThat(event(fixture, seed, 2L).outboxSequence()).isEqualTo(2L); + } finally { + releaseReader.countDown(); + executor.shutdownNow(); + } + } + + private LogoutAllResult concurrentCommit( + Fixture fixture, + Seed seed, + UUID requestId, + String requestDigest, + String tokenHash, + CountDownLatch ready, + CountDownLatch start) { + ready.countDown(); + await(start); + return commit(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + } + + private Fixture newFixture() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + AccountRepository accounts = new AccountRepository(transactionDsl); + AccountAuthorityGenerationRepository authority = + new AccountAuthorityGenerationRepository(transactionDsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl); + AccountPasswordResetOperationRepository passwordResetOperations = + new AccountPasswordResetOperationRepository(transactionDsl); + AccountLogoutAllOperationRepository logoutOperations = + new AccountLogoutAllOperationRepository(transactionDsl); + PasswordResetTokenRepository tokens = new PasswordResetTokenRepository(transactionDsl); + return new Fixture( + setupDsl, + transactionDsl, + transactionManager, + transaction, + accounts, + authority, + outbox, + passwordResetOperations, + logoutOperations, + tokens); + } + + private AccountAuthoritySourceReader sourceReader(Fixture fixture) { + return sourceReader(fixture, fixture.accounts(), fixture.outbox()); + } + + private AccountAuthoritySourceReader sourceReader( + Fixture fixture, AccountRepository accounts, AccountAuthorityOutboxRepository outbox) { + return new AccountAuthoritySourceReader( + accounts, + fixture.authority(), + outbox, + sourceReadback(fixture, outbox), + fixture.transactionManager()); + } + + private Seed seedAccount(Fixture fixture) { + return seedAccount(fixture, 1L); + } + + private Seed seedAccount(Fixture fixture, long initialCounter) { + return transaction( + fixture.transaction(), + () -> { + Account account = new Account(); + String unique = UUID.randomUUID().toString(); + account.setUsername("logout-all-" + unique); + account.setEmail("logout-all-" + unique + "@example.test"); + account.setPasswordHash("initial-verifier"); + Account saved = fixture.accounts().save(account); + if (initialCounter == 1L) { + fixture.authority().initialize(AuthorityScope.account(saved.getAccountUuid())); + } else { + // Seed a synthetic retained maximum by INSERT, not an illegal monotonic jump. + // All migration constraints and update triggers stay enabled for the whole test. + fixture + .transactionDsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) " + + "VALUES ('ACCOUNT', ?, ?, ?)", + saved.getAccountUuid(), + initialCounter, + initialCounter); + fixture + .transactionDsl() + .execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, ?, ?)", + saved.getAccountUuid(), + initialCounter, + initialCounter); + } + PasswordResetToken token = new PasswordResetToken(); + String rawToken = "reset-token-" + unique; + LocalDateTime deadline = LocalDateTime.now().plusHours(2); + token.setAccount(saved); + token.setToken(rawToken); + token.setExpiresAt(deadline); + fixture.tokens().save(token); + return new Seed( + saved.getId(), + saved.getAccountUuid(), + rawToken, + fixture.authority().read(AuthorityScope.account(saved.getAccountUuid()))); + }); + } + + private LogoutAllResult commit( + Fixture fixture, + Seed seed, + UUID requestId, + String requestDigest, + String tokenHash, + ScopeState expected) { + return commit(fixture, seed, requestId, requestDigest, TOKEN_PROFILE, tokenHash, expected); + } + + private LogoutAllResult commit( + Fixture fixture, + Seed seed, + UUID requestId, + String requestDigest, + String tokenProfile, + String tokenHash, + ScopeState expected) { + return producer(fixture) + .commit( + requestId, 1, requestDigest, tokenProfile, tokenHash, account(fixture, seed), expected); + } + + private AccountLogoutAllAuthorityEventProducer producer(Fixture fixture) { + return producer(fixture, fixture.accounts()); + } + + private AccountLogoutAllAuthorityEventProducer producer( + Fixture fixture, AccountRepository accounts) { + return new AccountLogoutAllAuthorityEventProducer( + accounts, + fixture.authority(), + fixture.outbox(), + fixture.logoutOperations(), + sourceReadback(fixture, fixture.outbox()), + fixture.transactionDsl(), + fixture.transactionManager()); + } + + private AccountAuthoritySourceEventReadback sourceReadback( + Fixture fixture, AccountAuthorityOutboxRepository outbox) { + return new AccountAuthoritySourceEventReadback( + outbox, fixture.passwordResetOperations(), fixture.logoutOperations()); + } + + private void reset(Fixture fixture, Seed seed, String password) { + reset(fixture, seed.rawToken(), password); + } + + private void reset(Fixture fixture, String rawToken, String password) { + AccountServiceImpl service = + new AccountServiceImpl( + fixture.accounts(), + fixture.authority(), + fixture.outbox(), + fixture.passwordResetOperations(), + fixture.logoutOperations(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + fixture.tokens(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + fixture.transactionManager()); + transaction( + fixture.transaction(), + () -> { + service.completePasswordReset(new CompletePasswordResetRequest(rawToken, password)); + return null; + }); + } + + private String addPasswordResetToken(Fixture fixture, Seed seed) { + return transaction( + fixture.transaction(), + () -> { + PasswordResetToken token = new PasswordResetToken(); + String rawToken = "reset-token-" + UUID.randomUUID(); + token.setAccount(fixture.accounts().findById(seed.accountId()).orElseThrow()); + token.setToken(rawToken); + token.setExpiresAt(LocalDateTime.now().plusHours(2)); + fixture.tokens().save(token); + return rawToken; + }); + } + + private void seedLatestLogoutReceiptAtMaximumCounter(Fixture fixture, Seed seed) { + UUID priorRequestId = UUID.randomUUID(); + String tokenHash = digest("prior-max-token"); + String requestDigest = logoutAllDigest(seed.accountUuid(), TOKEN_PROFILE, tokenHash); + String streamKey = streamKey(seed.accountUuid()); + String eventId = EVENT_ID_PREFIX + priorRequestId; + transaction( + fixture.transaction(), + () -> { + var event = + AccountLogoutAllAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", priorRequestId.toString()), + Map.entry("accountId", seed.accountUuid().toString()), + Map.entry("sourceScope", "account/" + seed.accountUuid()), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", "1"), + Map.entry("accountAuthorityGeneration", Long.toString(MAX_COUNTER)), + Map.entry("sourceVersion", Long.toString(MAX_COUNTER)), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + Long.toString(MAX_COUNTER), + "outboxStreamKey", + streamKey, + "outboxSequence", + "1")))); + var appended = + fixture + .outbox() + .append( + streamKey, + priorRequestId.toString(), + event.eventId(), + event.eventDigest(), + event.canonicalJsonUtf8()); + ScopeState maximum = fixture.authority().read(AuthorityScope.account(seed.accountUuid())); + fixture + .logoutOperations() + .insert( + LogoutAllReceipt.committed( + priorRequestId, + seed.accountId(), + seed.accountUuid(), + requestDigest, + tokenHash, + TOKEN_PROFILE, + streamKey, + appended.outboxSequence(), + eventId, + event.eventDigest(), + maximum, + maximum.issuanceFence())); + return null; + }); + } + + private Account account(Fixture fixture, Seed seed) { + return transaction( + fixture.transaction(), () -> fixture.accounts().findById(seed.accountId()).orElseThrow()); + } + + private ScopeState authority(Fixture fixture, Seed seed) { + return transaction( + fixture.transaction(), + () -> fixture.authority().read(AuthorityScope.account(seed.accountUuid()))); + } + + private LogoutAllReceipt logoutReceipt(Fixture fixture, UUID requestId) { + return transaction( + fixture.transaction(), + () -> fixture.logoutOperations().findByRequestId(requestId).orElseThrow()); + } + + private PasswordResetReceipt passwordResetReceipt(Fixture fixture, Seed seed) { + return passwordResetReceipt(fixture, seed.rawToken()); + } + + private PasswordResetReceipt passwordResetReceipt(Fixture fixture, String rawToken) { + return transaction( + fixture.transaction(), + () -> fixture.passwordResetOperations().findByTokenHash(digest(rawToken)).orElseThrow()); + } + + private AccountAuthorityOutboxRepository.Event event( + Fixture fixture, Seed seed, long outboxSequence) { + return transaction( + fixture.transaction(), + () -> + fixture + .outbox() + .findEvent(streamKey(seed.accountUuid()), outboxSequence) + .orElseThrow()); + } + + private StoredState snapshot(Fixture fixture, Seed seed) { + ScopeState state = authority(fixture, seed); + return new StoredState( + state.generation(), + state.sourceVersion(), + state.issuanceFence().value(), + state.issuanceFence().sourceVersion(), + count(fixture, "accounts"), + count(fixture, "account_authority_generations"), + count(fixture, "account_authority_issuance_fences"), + count(fixture, "password_reset_token"), + count(fixture, "account_logout_all_operation_receipts"), + count(fixture, "account_password_reset_operation_receipts"), + count(fixture, "account_authority_outbox_events"), + count(fixture, "account_authority_outbox_streams")); + } + + private long count(Fixture fixture, String table) { + return Objects.requireNonNull( + fixture.setupDsl().resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class), + "Logout-all source row count is missing"); + } + + private String streamKey(UUID accountUuid) { + return STREAM_PREFIX + accountUuid; + } + + private String digest(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private String logoutAllDigest(UUID accountUuid, String tokenProfile, String tokenHash) { + return AccountLogoutRequestDigest.accountLogoutAll(accountUuid, tokenProfile, tokenHash); + } + + private void assertSameEvent( + AccountAuthorityOutboxRepository.Event expected, + AccountAuthorityOutboxRepository.Event actual) { + assertThat(actual.outboxStreamKey()).isEqualTo(expected.outboxStreamKey()); + assertThat(actual.requestId()).isEqualTo(expected.requestId()); + assertThat(actual.outboxSequence()).isEqualTo(expected.outboxSequence()); + assertThat(actual.eventId()).isEqualTo(expected.eventId()); + assertThat(actual.eventDigest()).isEqualTo(expected.eventDigest()); + assertThat(actual.payload()).containsExactly(expected.payload()); + } + + private void assertAccountCredentialUnchanged(Fixture fixture, Seed seed, Account before) { + Account after = account(fixture, seed); + assertThat(after.getId()).isEqualTo(before.getId()); + assertThat(after.getAccountUuid()).isEqualTo(before.getAccountUuid()); + assertThat(after.getPasswordHash()).isEqualTo(before.getPasswordHash()); + } + + private int currentBackendPid(DSLContext dsl) { + return Objects.requireNonNull( + dsl.resultQuery("SELECT pg_backend_pid()").fetchOne(0, Integer.class), + "PostgreSQL did not return the Account row-lock holder backend PID"); + } + + private boolean awaitAccountRowBlock( + DSLContext observerDsl, int readerBackendPid, int writerBackendPid, Duration timeout) + throws InterruptedException { + long deadline = System.nanoTime() + timeout.toNanos(); + while (System.nanoTime() < deadline) { + Boolean blocked = + observerDsl + .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)))", + writerBackendPid, + readerBackendPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent logout-all barrier timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent logout-all proof was interrupted", interrupted); + } + } + + private T transaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record Fixture( + DSLContext setupDsl, + DSLContext transactionDsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transaction, + AccountRepository accounts, + AccountAuthorityGenerationRepository authority, + AccountAuthorityOutboxRepository outbox, + AccountPasswordResetOperationRepository passwordResetOperations, + AccountLogoutAllOperationRepository logoutOperations, + PasswordResetTokenRepository tokens) {} + + private record Seed(long accountId, UUID accountUuid, String rawToken, ScopeState initialState) {} + + private record StoredState( + long generation, + long sourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + long accountRowCount, + long generationRowCount, + long issuanceFenceRowCount, + long passwordResetTokenCount, + long logoutReceiptCount, + long passwordResetReceiptCount, + long eventCount, + long streamCount) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java index fb1c191e99..0475c5bb0e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.OperationConflictException; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; @@ -319,6 +320,8 @@ private Fixture newFixture() { AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl); AccountPasswordResetOperationRepository operations = new AccountPasswordResetOperationRepository(transactionDsl); + AccountLogoutAllOperationRepository logoutAllOperations = + new AccountLogoutAllOperationRepository(transactionDsl); PasswordResetTokenRepository tokens = new PasswordResetTokenRepository(transactionDsl); return new Fixture( setupDsl, @@ -329,6 +332,7 @@ private Fixture newFixture() { authority, outbox, operations, + logoutAllOperations, tokens); } @@ -365,6 +369,7 @@ private AccountServiceImpl newService( fixture.authority(), fixture.outbox(), operations, + fixture.logoutAllOperations(), null, // audit outbox null, // connect scopes null, // join operations @@ -515,6 +520,7 @@ private record Fixture( AccountAuthorityGenerationRepository authority, AccountAuthorityOutboxRepository outbox, AccountPasswordResetOperationRepository operations, + AccountLogoutAllOperationRepository logoutAllOperations, PasswordResetTokenRepository tokens) {} private record Seed( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java new file mode 100644 index 0000000000..97a653e14c --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java @@ -0,0 +1,880 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Duration; +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 net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountTenantAuthorityEventProducer; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.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.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class TenantAuthorityProducerPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "tenant_authority_source_proof"; + private static final String TEST_NAMESPACE = "account-service"; + private static final String REQUEST_DIGEST = "sha256:" + "a".repeat(64); + private static final UUID TENANT_ID = UUID.fromString("10000000-0000-4000-8000-000000000001"); + private static final UUID UNKNOWN_TENANT_ID = + UUID.fromString("10000000-0000-4000-8000-000000000002"); + private static final String SOURCE_SCOPE = "tenant/" + TENANT_ID; + private static final String STREAM_KEY = "account:auth-authority:v1:" + SOURCE_SCOPE; + private static final String EVENT_ID_PREFIX = "account-tenant-generation-event-v1:"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void + atomicallyAdvancesEnrolledTenantSourceAndReadsBackExactCheckpointWithoutAccountFenceChange() { + Fixture fixture = newFixture(); + seed(fixture); + ScopeState accountBefore = readAccountState(fixture); + AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot baseline = + fixture.producer().readCurrent(TENANT_ID); + assertThat(baseline.tenantAuthorityGeneration()).isEqualTo(1L); + assertThat(baseline.sourceVersion()).isEqualTo(1L); + assertThat(baseline.outboxSequence()).isZero(); + assertThat(baseline.latestEvent()).isEmpty(); + + UUID requestId = UUID.randomUUID(); + TenantGenerationAuthorityEvent event = fixture.producer().advance(TENANT_ID, requestId, 1L, 1L); + AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot current = + fixture.producer().readCurrent(TENANT_ID); + + assertThat(event.eventId()).isEqualTo(EVENT_ID_PREFIX + requestId); + assertThat(event.requestId()).isEqualTo(requestId.toString()); + assertThat(event.tenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(event.sourceScope()).isEqualTo(SOURCE_SCOPE); + assertThat(event.outboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(event.outboxSequence()).isEqualTo("1"); + assertThat(event.tenantAuthorityGeneration()).isEqualTo("2"); + assertThat(event.sourceVersion()).isEqualTo("2"); + assertThat(event.eventDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(event.canonicalJson()) + .doesNotContain("issuanceFence", "recipientAccount", "billing"); + assertThat(current.tenantAuthorityGeneration()).isEqualTo(2L); + assertThat(current.sourceVersion()).isEqualTo(2L); + assertThat(current.outboxSequence()).isEqualTo(1L); + assertThat(current.latestEvent()).isPresent(); + assertSameEvent(event, current.latestEvent().orElseThrow()); + assertThat(countEvents(fixture, STREAM_KEY)).isEqualTo(1L); + assertThat(readAccountState(fixture)).isEqualTo(accountBefore); + } + + @Test + void exactRetryRecoversOriginalEventAfterLaterTenantAdvances() { + Fixture fixture = newFixture(); + seed(fixture); + UUID firstRequest = UUID.randomUUID(); + TenantGenerationAuthorityEvent first = + fixture.producer().advance(TENANT_ID, firstRequest, 1L, 1L); + TenantGenerationAuthorityEvent exactRetry = + fixture.producer().advance(TENANT_ID, firstRequest, 1L, 1L); + assertSameEvent(first, exactRetry); + + TenantGenerationAuthorityEvent second = + fixture.producer().advance(TENANT_ID, UUID.randomUUID(), 2L, 2L); + TenantGenerationAuthorityEvent historicalRetry = + fixture.producer().advance(TENANT_ID, firstRequest, 1L, 1L); + + assertSameEvent(first, historicalRetry); + assertThat(second.outboxSequence()).isEqualTo("2"); + assertThat(fixture.producer().readCurrent(TENANT_ID).tenantAuthorityGeneration()).isEqualTo(3L); + assertThat(countEvents(fixture, STREAM_KEY)).isEqualTo(2L); + } + + @Test + void historicalReadbackReturnsRequestedEventAndCurrentSourceFromOneTenantFence() { + Fixture fixture = newFixture(); + seed(fixture); + TenantGenerationAuthorityEvent first = + fixture.producer().advance(TENANT_ID, UUID.randomUUID(), 1L, 1L); + TenantGenerationAuthorityEvent second = + fixture.producer().advance(TENANT_ID, UUID.randomUUID(), 2L, 2L); + + AccountTenantAuthorityEventProducer.TenantAuthorityEventReadback readback = + fixture.producer().readCommittedEvent(TENANT_ID, 1L); + + assertSameEvent(first, readback.requestedEvent()); + assertThat(readback.currentSnapshot().tenantAuthorityGeneration()).isEqualTo(3L); + assertThat(readback.currentSnapshot().sourceVersion()).isEqualTo(3L); + assertThat(readback.currentSnapshot().outboxSequence()).isEqualTo(2L); + assertThat(readback.currentSnapshot().latestEvent()).isPresent(); + assertSameEvent(second, readback.currentSnapshot().latestEvent().orElseThrow()); + } + + @Test + void concurrentHistoricalReadWaitsForTenantFenceAndReturnsConsistentCurrentEvidence() + throws Exception { + Fixture fixture = newFixture(); + seed(fixture); + TenantGenerationAuthorityEvent first = + fixture.producer().advance(TENANT_ID, UUID.randomUUID(), 1L, 1L); + UUID secondRequest = UUID.randomUUID(); + CountDownLatch sourceLocked = new CountDownLatch(1); + CountDownLatch releaseAdvance = new CountDownLatch(1); + CountDownLatch readStarted = new CountDownLatch(1); + AtomicInteger holderBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future advance = + executor.submit( + () -> + transaction( + fixture.transaction(), + () -> { + holderBackendPid.set( + Objects.requireNonNull( + fixture + .transactionDsl() + .resultQuery("SELECT pg_backend_pid()") + .fetchOne(0, Integer.class), + "PostgreSQL did not return the tenant row-lock holder backend PID")); + ScopeState current = + fixture.generations().read(AuthorityScope.tenant(TENANT_ID)); + sourceLocked.countDown(); + await(releaseAdvance); + ScopeState advanced = fixture.generations().advance(current, null); + appendSeedEvent( + fixture, + secondRequest, + advanced.generation(), + advanced.sourceVersion()); + return null; + })); + assertThat(sourceLocked.await(20, TimeUnit.SECONDS)).isTrue(); + Future read = + executor.submit( + () -> { + readStarted.countDown(); + return fixture.producer().readCommittedEvent(TENANT_ID, 1L); + }); + assertThat(readStarted.await(20, TimeUnit.SECONDS)).isTrue(); + assertThat( + awaitTenantAuthorityRowBlock( + fixture.setupDsl(), holderBackendPid.get(), Duration.ofSeconds(10))) + .as("the historical reader is blocked by the exact tenant source-row transaction") + .isTrue(); + + releaseAdvance.countDown(); + advance.get(45, TimeUnit.SECONDS); + AccountTenantAuthorityEventProducer.TenantAuthorityEventReadback readback = + read.get(45, TimeUnit.SECONDS); + assertSameEvent(first, readback.requestedEvent()); + assertThat(readback.currentSnapshot().tenantAuthorityGeneration()).isEqualTo(3L); + assertThat(readback.currentSnapshot().sourceVersion()).isEqualTo(3L); + assertThat(readback.currentSnapshot().outboxSequence()).isEqualTo(2L); + } finally { + releaseAdvance.countDown(); + executor.shutdownNow(); + } + } + + @Test + void concurrentExactRequestSerializesAndCommitsOneTenantEvent() throws Exception { + Fixture fixture = newFixture(); + seed(fixture); + UUID requestId = UUID.randomUUID(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> concurrentAdvance(fixture, requestId, ready, start)); + Future second = + executor.submit(() -> concurrentAdvance(fixture, requestId, ready, start)); + assertThat(ready.await(20, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertSameEvent(first.get(45, TimeUnit.SECONDS), second.get(45, TimeUnit.SECONDS)); + } finally { + start.countDown(); + executor.shutdownNow(); + } + + assertThat(readTenantState(fixture).generation()).isEqualTo(2L); + assertThat(readTenantState(fixture).sourceVersion()).isEqualTo(2L); + assertThat(countEvents(fixture, STREAM_KEY)).isEqualTo(1L); + assertThat(countTenantStreams(fixture)).isEqualTo(1L); + } + + @Test + void unknownTenantStaleBindingAndChangedRetryFailWithoutEnrollmentOrMutation() { + Fixture fixture = newFixture(); + seed(fixture); + StoredState baseline = snapshot(fixture); + UUID requestId = UUID.randomUUID(); + + assertThatThrownBy(() -> fixture.producer().readCurrent(UNKNOWN_TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("generation is missing"); + assertThatThrownBy(() -> fixture.producer().advance(UNKNOWN_TENANT_ID, requestId, 1L, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("generation is missing"); + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, requestId, 2L, 2L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("compare-and-advance is stale"); + fixture.producer().advance(TENANT_ID, requestId, 1L, 1L); + StoredState committed = snapshot(fixture); + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, requestId, 2L, 2L)) + .isInstanceOf(AccountAuthorityOutboxRepository.IdempotencyConflictException.class); + + assertThat(countTenantStreams(fixture)).isEqualTo(1L); + assertThat(countEvents(fixture, "account:auth-authority:v1:tenant/" + UNKNOWN_TENANT_ID)) + .isZero(); + assertThat(snapshot(fixture)).isEqualTo(committed); + assertThat(committed).isNotEqualTo(baseline); + } + + @Test + void sequenceZeroRequiresOriginalBaselineAndPositiveHistoryRequiresBothCountersToProgress() { + Fixture pristine = newFixture(); + seed(pristine); + AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot zero = + pristine.producer().readCurrent(TENANT_ID); + assertThat(zero.tenantAuthorityGeneration()).isEqualTo(1L); + assertThat(zero.sourceVersion()).isEqualTo(1L); + assertThat(zero.outboxSequence()).isZero(); + + Fixture advancedWithoutEvents = newFixture(); + seed(advancedWithoutEvents); + transaction( + advancedWithoutEvents.transaction(), + () -> { + ScopeState current = + advancedWithoutEvents.generations().read(AuthorityScope.tenant(TENANT_ID)); + advancedWithoutEvents.generations().advance(current, null); + return null; + }); + assertThatThrownBy(() -> advancedWithoutEvents.producer().readCurrent(TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("original positive 1/1"); + + Fixture contradictory = newFixture(); + seed(contradictory); + transaction( + contradictory.transaction(), + () -> { + appendSeedEvent(contradictory, UUID.randomUUID(), 1L, 1L); + return null; + }); + assertThatThrownBy(() -> contradictory.producer().readCurrent(TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("advanced together"); + } + + @Test + void persistedNumericTenantScopeEvidenceIsRejectedWithoutChangingSourceState() { + Fixture fixture = newFixture(); + seed(fixture); + UUID requestId = UUID.randomUUID(); + String requestText = requestId.toString(); + String eventId = EVENT_ID_PREFIX + requestText; + String digest = "sha256:" + "0".repeat(64); + String payload = + "{\"schemaVersion\":\"" + + TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION + + "\",\"eventType\":\"" + + TenantGenerationAuthorityEventV1Codec.EVENT_TYPE + + "\",\"eventId\":\"" + + eventId + + "\",\"requestId\":\"" + + requestText + + "\",\"tenantId\":\"" + + TENANT_ID + + "\",\"sourceScope\":\"tenant/731\",\"outboxStreamKey\":" + + "\"account:auth-authority:v1:tenant/731\",\"outboxSequence\":\"1\"," + + "\"tenantAuthorityGeneration\":\"2\",\"sourceVersion\":\"2\"," + + "\"eventDigest\":\"" + + digest + + "\"}"; + transaction( + fixture.transaction(), + () -> { + ScopeState current = fixture.generations().read(AuthorityScope.tenant(TENANT_ID)); + fixture.generations().advance(current, null); + fixture + .outbox() + .append( + STREAM_KEY, + requestText, + eventId, + digest, + payload.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return null; + }); + StoredState committed = snapshot(fixture); + + assertThatThrownBy(() -> fixture.producer().readCurrent(TENANT_ID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("event.sourceScope must equal tenant/" + TENANT_ID); + assertThat(snapshot(fixture)).isEqualTo(committed); + } + + @Test + void historicalReadRejectsMissingRetainedPayloadAndCurrentReadRejectsChangedDigestEvidence() { + Fixture missing = newFixture(); + seed(missing); + missing.producer().advance(TENANT_ID, UUID.randomUUID(), 1L, 1L); + missing.producer().advance(TENANT_ID, UUID.randomUUID(), 2L, 2L); + AccountAuthorityOutboxRepository hideHistoricalEvent = + new AccountAuthorityOutboxRepository(missing.transactionDsl()) { + @Override + public Optional findEvent(String streamKey, long outboxSequence) { + if (STREAM_KEY.equals(streamKey) && outboxSequence == 1L) { + return Optional.empty(); + } + return super.findEvent(streamKey, outboxSequence); + } + }; + StoredState beforeMissingRead = snapshot(missing); + + assertThatThrownBy( + () -> missing.producer(hideHistoricalEvent).readCommittedEvent(TENANT_ID, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("retained tenant event is missing"); + assertThat(snapshot(missing)).isEqualTo(beforeMissingRead); + + Fixture missingLatest = newFixture(); + seed(missingLatest); + missingLatest.producer().advance(TENANT_ID, UUID.randomUUID(), 1L, 1L); + AccountAuthorityOutboxRepository hideLatestEvent = + new AccountAuthorityOutboxRepository(missingLatest.transactionDsl()) { + @Override + public Optional findEvent(String streamKey, long outboxSequence) { + if (STREAM_KEY.equals(streamKey) && outboxSequence == 1L) { + return Optional.empty(); + } + return super.findEvent(streamKey, outboxSequence); + } + }; + StoredState beforeMissingLatestRead = snapshot(missingLatest); + + assertThatThrownBy(() -> missingLatest.producer(hideLatestEvent).readCurrent(TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("checkpoint has no matching event evidence"); + assertThat(snapshot(missingLatest)).isEqualTo(beforeMissingLatestRead); + + Fixture changedPayload = newFixture(); + seed(changedPayload); + changedPayload.producer().advance(TENANT_ID, UUID.randomUUID(), 1L, 1L); + AccountAuthorityOutboxRepository malformedEventReadback = + new AccountAuthorityOutboxRepository(changedPayload.transactionDsl()) { + @Override + public Optional findEvent(String streamKey, long outboxSequence) { + Optional stored = super.findEvent(streamKey, outboxSequence); + if (STREAM_KEY.equals(streamKey) && outboxSequence == 1L && stored.isPresent()) { + Event event = stored.orElseThrow(); + return Optional.of( + new Event( + event.outboxStreamKey(), + event.requestId(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + "not-json".getBytes(java.nio.charset.StandardCharsets.UTF_8))); + } + return stored; + } + }; + StoredState beforeMalformedRead = snapshot(changedPayload); + + assertThatThrownBy(() -> changedPayload.producer(malformedEventReadback).readCurrent(TENANT_ID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("event JSON is malformed"); + assertThat(snapshot(changedPayload)).isEqualTo(beforeMalformedRead); + + Fixture changedScope = newFixture(); + seed(changedScope); + UUID requestId = UUID.randomUUID(); + changedScope.producer().advance(TENANT_ID, requestId, 1L, 1L); + TenantGenerationAuthorityEvent otherScopeEvent = + TenantGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + TenantGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + EVENT_ID_PREFIX + requestId, + "requestId", + requestId.toString(), + "tenantId", + UNKNOWN_TENANT_ID.toString(), + "sourceScope", + "tenant/" + UNKNOWN_TENANT_ID, + "outboxStreamKey", + "account:auth-authority:v1:tenant/" + UNKNOWN_TENANT_ID, + "outboxSequence", + "1", + "tenantAuthorityGeneration", + "2", + "sourceVersion", + "2")); + AccountAuthorityOutboxRepository otherScopeReadback = + new AccountAuthorityOutboxRepository(changedScope.transactionDsl()) { + @Override + public Optional findEvent(String streamKey, long outboxSequence) { + Optional stored = super.findEvent(streamKey, outboxSequence); + if (STREAM_KEY.equals(streamKey) && outboxSequence == 1L && stored.isPresent()) { + Event event = stored.orElseThrow(); + return Optional.of( + new Event( + event.outboxStreamKey(), + event.requestId(), + event.outboxSequence(), + event.eventId(), + otherScopeEvent.eventDigest(), + otherScopeEvent.canonicalJsonUtf8())); + } + return stored; + } + }; + StoredState beforeChangedScopeRead = snapshot(changedScope); + + assertThatThrownBy(() -> changedScope.producer(otherScopeReadback).readCurrent(TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stored event payload or database columns contradict"); + assertThat(snapshot(changedScope)).isEqualTo(beforeChangedScopeRead); + + Fixture changedCounters = newFixture(); + seed(changedCounters); + changedCounters.producer().advance(TENANT_ID, UUID.randomUUID(), 1L, 1L); + TenantGenerationAuthorityEvent actualLatest = + changedCounters.producer().advance(TENANT_ID, UUID.randomUUID(), 2L, 2L); + TenantGenerationAuthorityEvent staleCountersEvent = + TenantGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + TenantGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + actualLatest.eventId(), + "requestId", + actualLatest.requestId(), + "tenantId", + TENANT_ID.toString(), + "sourceScope", + SOURCE_SCOPE, + "outboxStreamKey", + STREAM_KEY, + "outboxSequence", + actualLatest.outboxSequence(), + "tenantAuthorityGeneration", + "2", + "sourceVersion", + "2")); + AccountAuthorityOutboxRepository staleCounterReadback = + new AccountAuthorityOutboxRepository(changedCounters.transactionDsl()) { + @Override + public Optional findEvent(String streamKey, long outboxSequence) { + Optional stored = super.findEvent(streamKey, outboxSequence); + if (STREAM_KEY.equals(streamKey) && outboxSequence == 2L && stored.isPresent()) { + Event event = stored.orElseThrow(); + return Optional.of( + new Event( + event.outboxStreamKey(), + event.requestId(), + event.outboxSequence(), + event.eventId(), + staleCountersEvent.eventDigest(), + staleCountersEvent.canonicalJsonUtf8())); + } + return stored; + } + }; + StoredState beforeChangedCounterRead = snapshot(changedCounters); + + assertThatThrownBy(() -> changedCounters.producer(staleCounterReadback).readCurrent(TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("counters do not match their uninterrupted outbox sequence"); + assertThat(snapshot(changedCounters)).isEqualTo(beforeChangedCounterRead); + } + + @Test + void appendFailureRollsBackTenantSourceAndOutboxTogether() { + Fixture fixture = newFixture(); + seed(fixture); + ScopeState accountBefore = readAccountState(fixture); + fixture + .setupDsl() + .execute( + "ALTER TABLE account_authority_outbox_events " + + "ADD CONSTRAINT reject_tenant_source_event " + + "CHECK (event_id NOT LIKE 'account-tenant-generation-event-v1:%')"); + + assertThatThrownBy(() -> fixture.producer().advance(TENANT_ID, UUID.randomUUID(), 1L, 1L)) + .isInstanceOf(RuntimeException.class); + + assertTenantCountersAndOutbox(fixture, 1L, 1L, 0L, 0L); + assertThat(readAccountState(fixture)).isEqualTo(accountBefore); + } + + @Test + void transactionLocalReadbackFailureRollsBackTenantAdvance() { + Fixture fixture = newFixture(); + seed(fixture); + AccountAuthorityOutboxRepository hideSecondRequestRead = + new AccountAuthorityOutboxRepository(fixture.transactionDsl()) { + private final AtomicInteger requestLookups = new AtomicInteger(); + + @Override + public Optional findEvent(String streamKey, String requestId) { + if (requestLookups.incrementAndGet() >= 2) { + return Optional.empty(); + } + return super.findEvent(streamKey, requestId); + } + }; + AccountTenantAuthorityEventProducer producer = fixture.producer(hideSecondRequestRead); + + assertThatThrownBy(() -> producer.advance(TENANT_ID, UUID.randomUUID(), 1L, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("request event readback is missing"); + + assertTenantCountersAndOutbox(fixture, 1L, 1L, 0L, 0L); + } + + @Test + void unavailablePostCommitReadLeavesDurableEventAndExactRetryRecoversIt() { + Fixture fixture = newFixture(); + seed(fixture); + AtomicInteger requestLookups = new AtomicInteger(); + AccountAuthorityOutboxRepository hidePostCommitRead = + new AccountAuthorityOutboxRepository(fixture.transactionDsl()) { + @Override + public Optional findEvent(String streamKey, String requestId) { + if (requestLookups.incrementAndGet() == 3) { + return Optional.empty(); + } + return super.findEvent(streamKey, requestId); + } + }; + UUID requestId = UUID.randomUUID(); + AccountTenantAuthorityEventProducer firstAttempt = fixture.producer(hidePostCommitRead); + + assertThatThrownBy(() -> firstAttempt.advance(TENANT_ID, requestId, 1L, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Post-commit tenant authority request event is missing"); + + assertTenantCountersAndOutbox(fixture, 2L, 2L, 1L, 1L); + TenantGenerationAuthorityEvent recovered = + fixture.producer().advance(TENANT_ID, requestId, 1L, 1L); + assertThat(recovered.eventId()).isEqualTo(EVENT_ID_PREFIX + requestId); + assertThat(recovered.outboxSequence()).isEqualTo("1"); + assertTenantCountersAndOutbox(fixture, 2L, 2L, 1L, 1L); + } + + private TenantGenerationAuthorityEvent concurrentAdvance( + Fixture fixture, UUID requestId, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + return fixture.producer().advance(TENANT_ID, requestId, 1L, 1L); + } + + private Fixture newFixture() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + String suffix = UUID.randomUUID().toString().replace("-", ""); + Record account = + setupDsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES (?, ?, ?) RETURNING account_uuid", + "tenant-proof-" + suffix, + "tenant-proof-" + suffix + "@example.test", + "integration-proof-hash"); + if (account == null || account.get("account_uuid", UUID.class) == null) { + throw new IllegalStateException("Account authority-fence fixture UUID was not persisted"); + } + UUID accountUuid = account.get("account_uuid", UUID.class); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(transactionDsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl); + FreshTenantIdentityAssociationRepository associations = + new FreshTenantIdentityAssociationRepository(transactionDsl, TEST_NAMESPACE); + return new Fixture( + setupDsl, + transactionDsl, + transactionManager, + transaction, + generations, + outbox, + associations, + accountUuid); + } + + private void seed(Fixture fixture) { + FreshTenantCreationEvidence association = + tenantEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + TENANT_ID, + 731L, + "tn-" + UUID.randomUUID().toString().replace("-", "")); + transaction( + fixture.transaction(), + () -> { + fixture.associations().importVerified(association); + fixture.generations().initializeTenantIfAbsent(TENANT_ID); + fixture.generations().initialize(AuthorityScope.account(fixture.accountUuid())); + return null; + }); + } + + private FreshTenantCreationEvidence tenantEvidence( + UUID requestId, + UUID operationId, + UUID tenantId, + long sourceGameRowId, + String sourceGameTenantKey) { + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + REQUEST_DIGEST, + tenantId, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + REQUEST_DIGEST, + tenantId, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private void appendSeedEvent( + Fixture fixture, UUID requestId, long generation, long sourceVersion) { + String requestText = requestId.toString(); + String eventId = EVENT_ID_PREFIX + requestText; + fixture + .outbox() + .append( + STREAM_KEY, + requestText, + sequence -> { + TenantGenerationAuthorityEvent event = + TenantGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + TenantGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + eventId, + "requestId", + requestText, + "tenantId", + TENANT_ID.toString(), + "sourceScope", + SOURCE_SCOPE, + "outboxStreamKey", + STREAM_KEY, + "outboxSequence", + Long.toString(sequence), + "tenantAuthorityGeneration", + Long.toString(generation), + "sourceVersion", + Long.toString(sourceVersion))); + return new AccountAuthorityOutboxRepository.EventEvidence( + event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + }); + } + + private void assertTenantCountersAndOutbox( + Fixture fixture, + long generation, + long sourceVersion, + long expectedEventCount, + long expectedStreamCount) { + ScopeState tenant = readTenantState(fixture); + assertThat(tenant.generation()).isEqualTo(generation); + assertThat(tenant.sourceVersion()).isEqualTo(sourceVersion); + assertThat(countEvents(fixture, STREAM_KEY)).isEqualTo(expectedEventCount); + assertThat(countTenantStreams(fixture)).isEqualTo(expectedStreamCount); + } + + private ScopeState readTenantState(Fixture fixture) { + return transaction( + fixture.transaction(), () -> fixture.generations().read(AuthorityScope.tenant(TENANT_ID))); + } + + private ScopeState readAccountState(Fixture fixture) { + return transaction( + fixture.transaction(), + () -> fixture.generations().read(AuthorityScope.account(fixture.accountUuid()))); + } + + private StoredState snapshot(Fixture fixture) { + ScopeState tenant = readTenantState(fixture); + ScopeState account = readAccountState(fixture); + return new StoredState( + tenant.generation(), + tenant.sourceVersion(), + countEvents(fixture, STREAM_KEY), + countTenantStreams(fixture), + account); + } + + private long countEvents(Fixture fixture, String streamKey) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class), + "Tenant event count readback is missing"); + } + + private long countTenantStreams(Fixture fixture) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key LIKE 'account:auth-authority:v1:tenant/%'") + .fetchOne(0, Long.class), + "Tenant stream count readback is missing"); + } + + private boolean awaitTenantAuthorityRowBlock( + DSLContext observerDsl, int holderBackendPid, Duration timeout) throws InterruptedException { + long deadline = System.nanoTime() + timeout.toNanos(); + while (System.nanoTime() < deadline) { + Boolean blocked = + observerDsl + .resultQuery( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity waiting " + + "WHERE waiting.wait_event_type = 'Lock' " + + "AND waiting.query ILIKE '%account_authority_generations%' " + + "AND waiting.query ILIKE '%tenant_uuid IS NOT DISTINCT FROM%' " + + "AND ? = ANY(pg_blocking_pids(waiting.pid)))", + holderBackendPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + + private void assertSameEvent( + TenantGenerationAuthorityEvent expected, TenantGenerationAuthorityEvent actual) { + assertThat(actual.schemaVersion()).isEqualTo(expected.schemaVersion()); + assertThat(actual.eventType()).isEqualTo(expected.eventType()); + assertThat(actual.eventId()).isEqualTo(expected.eventId()); + assertThat(actual.requestId()).isEqualTo(expected.requestId()); + assertThat(actual.tenantId()).isEqualTo(expected.tenantId()); + assertThat(actual.sourceScope()).isEqualTo(expected.sourceScope()); + assertThat(actual.outboxStreamKey()).isEqualTo(expected.outboxStreamKey()); + assertThat(actual.outboxSequence()).isEqualTo(expected.outboxSequence()); + assertThat(actual.tenantAuthorityGeneration()).isEqualTo(expected.tenantAuthorityGeneration()); + assertThat(actual.sourceVersion()).isEqualTo(expected.sourceVersion()); + assertThat(actual.eventDigest()).isEqualTo(expected.eventDigest()); + assertThat(actual.canonicalJson()).isEqualTo(expected.canonicalJson()); + assertThat(actual.canonicalJsonUtf8()).containsExactly(expected.canonicalJsonUtf8()); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent tenant authority barrier timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent tenant authority proof was interrupted", interrupted); + } + } + + private T transaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record Fixture( + DSLContext setupDsl, + DSLContext transactionDsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transaction, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox, + FreshTenantIdentityAssociationRepository associations, + UUID accountUuid) { + private AccountTenantAuthorityEventProducer producer() { + return producer(outbox); + } + + private AccountTenantAuthorityEventProducer producer( + AccountAuthorityOutboxRepository override) { + return new AccountTenantAuthorityEventProducer( + generations, override, transactionDsl, transactionManager); + } + } + + private record StoredState( + long generation, + long sourceVersion, + long eventCount, + long streamCount, + ScopeState accountAuthority) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryIntegrationTest.java index 469965abec..bf6f4b14e8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryIntegrationTest.java @@ -18,6 +18,7 @@ import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; @@ -91,6 +92,118 @@ void appendsContiguousPerStreamAndReplaysOnlyExactRequestEvidence() { assertThat(inTransaction(transaction, () -> repository.findEvent(stream, 2L))).contains(second); } + @Test + void missingHeadWithNoExactHistoryIsEmptyDespiteAnotherStreamsRetainedEvent() { + TestContext context = newTestContext(); + AccountAuthorityOutboxRepository repository = context.repository(); + TransactionTemplate transaction = context.transaction(); + DSLContext dsl = context.dsl(); + String missingStream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); + String retainedStream = "account:auth-authority:v1:tenant/" + UUID.randomUUID(); + byte[] retainedPayload = new byte[] {4, 5, 6}; + + Event retained = + inTransaction( + transaction, + () -> + repository.append( + retainedStream, + "retained-request", + "retained-event", + "retained-digest", + retainedPayload)); + + assertThat(inTransaction(transaction, () -> repository.readCheckpoint(missingStream))) + .isEmpty(); + + assertThat(inTransaction(transaction, () -> repository.readCheckpoint(retainedStream))) + .contains(new Checkpoint(retainedStream, 1L, "retained-event", "retained-digest")); + Event retainedAfterRead = + inTransaction(transaction, () -> repository.findEvent(retainedStream, 1L)).orElseThrow(); + assertThat(retainedAfterRead).isEqualTo(retained); + assertThat(retainedAfterRead.eventId()).isEqualTo(retained.eventId()); + assertThat(retainedAfterRead.eventDigest()).isEqualTo(retained.eventDigest()); + assertThat(retainedAfterRead.payload()).containsExactly(retainedPayload); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + missingStream) + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + missingStream) + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + retainedStream) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void databaseRejectsDeletingAHeadWithRetainedHistoryWithoutChangingEvidence() { + TestContext context = newTestContext(); + AccountAuthorityOutboxRepository repository = context.repository(); + TransactionTemplate transaction = context.transaction(); + DSLContext dsl = context.dsl(); + String stream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); + byte[] retainedPayload = new byte[] {7, 8, 9}; + Event retained = + inTransaction( + transaction, + () -> + repository.append( + stream, + "retained-request", + "retained-event", + "retained-digest", + retainedPayload)); + + assertThatThrownBy( + () -> + inTransaction( + transaction, + () -> { + dsl.execute( + "DELETE FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + stream); + return null; + })) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Account authority outbox stream history cannot be deleted"); + + assertThat(inTransaction(transaction, () -> repository.readCheckpoint(stream))) + .contains(new Checkpoint(stream, 1L, retained.eventId(), retained.eventDigest())); + Event retainedAfterDelete = + inTransaction(transaction, () -> repository.findEvent(stream, 1L)).orElseThrow(); + assertThat(retainedAfterDelete).isEqualTo(retained); + assertThat(retainedAfterDelete.eventId()).isEqualTo(retained.eventId()); + assertThat(retainedAfterDelete.eventDigest()).isEqualTo(retained.eventDigest()); + assertThat(retainedAfterDelete.payload()).containsExactly(retainedPayload); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + stream) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + stream) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + @Test void callerRollbackRemovesAppendAndConcurrentExactRetriesShareOneSequence() throws Exception { TestContext context = newTestContext(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java new file mode 100644 index 0000000000..fc0fd83b27 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java @@ -0,0 +1,105 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import org.junit.jupiter.api.Test; + +class AccountLogoutRequestDigestTest { + private static final UUID LOGOUT_ALL_ACCOUNT = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TOKEN_LOGOUT_ACCOUNT = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void accountLogoutAllMatchesFixedRequestDigestV1PreimageAndDigestVector() { + String tokenHash = "a".repeat(64); + + assertThat( + AccountLogoutRequestDigest.accountLogoutAllPreimageHex( + LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isEqualTo( + compactHex( + """ + 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131383a4143434f554e545f4c4f474f55545f414c4c31363a7375626a6563744163636f756e744964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d31313131313131313131313131323a746f6b656e50726f66696c65363a737472696e673131303a636f6e74726f6c2d756931383a70726573656e746564546f6b656e48617368363a737472696e673136343a61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161 + """)); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isEqualTo("78f999be5a5bdb0a5bc4517336ad6899b2383c8058b0bb8f76fe67eb67dea020"); + } + + @Test + void tokenLogoutMatchesFixedRequestDigestV1PreimageAndDigestVector() { + String tokenHash = "b".repeat(64); + + assertThat( + AccountLogoutRequestDigest.tokenLogoutPreimageHex( + TOKEN_LOGOUT_ACCOUNT, "player-bootstrap", tokenHash)) + .isEqualTo( + compactHex( + """ + 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131323a544f4b454e5f4c4f474f555431363a7375626a6563744163636f756e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231323a746f6b656e50726f66696c65363a737472696e673131363a706c617965722d626f6f747374726170393a746f6b656e48617368363a737472696e673136343a62626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262 + """)); + assertThat( + AccountLogoutRequestDigest.tokenLogout( + TOKEN_LOGOUT_ACCOUNT, "player-bootstrap", tokenHash)) + .isEqualTo("21c085ddf384d4ab3d32c04f37601e710240d11ffe1be64531ee780cf2fcdee0"); + } + + @Test + void eachClosedTupleFieldChangesTheDigest() { + String tokenHash = "a".repeat(64); + String original = + AccountLogoutRequestDigest.accountLogoutAll(LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash); + + assertThat(AccountLogoutRequestDigest.tokenLogout(LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + TOKEN_LOGOUT_ACCOUNT, "control-ui", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "player-bootstrap", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "control-ui", "b".repeat(64))) + .isNotEqualTo(original); + } + + @Test + void rejectsUnsupportedProfilesNoncanonicalAccountIdentityAndMalformedTokenHashes() { + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "private-player-delegation", "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("token profile"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.accountLogoutAll( + new UUID(0L, 0L), "control-ui", "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil Account UUID"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.tokenLogout( + LOGOUT_ALL_ACCOUNT, "control-ui", "A".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase SHA-256 hex"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.tokenLogout( + LOGOUT_ALL_ACCOUNT, "control-ui", "a".repeat(63))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase SHA-256 hex"); + } + + private static String compactHex(String hex) { + return hex.replaceAll("\\s+", ""); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java index cfe16f83f1..b4f39e8215 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMigrationVersionTest.java @@ -36,14 +36,16 @@ void accountMigrationsHaveDistinctFlywayVersionsWithoutRequiringDocker() throws "V40__account_membership_transition_receipts.sql", "V41__protect_account_membership_transition_receipts.sql", "V41.1__account_password_reset_operation_receipts.sql", - "V42__account_membership_left_transition_receipts.sql") + "V42__account_membership_left_transition_receipts.sql", + "V42.1__account_logout_all_operation_receipts.sql") .doesNotContain( "V28__account_join_reconciliation.sql", "V28__account_membership_transition_receipts.sql", "V28.1__account_membership_transition_receipts.sql", "V37__account_bare_login_exchange_storage.sql", "V38__fresh_tenant_identity_associations.sql", - "V40__account_membership_left_transition_receipts.sql"); + "V40__account_membership_left_transition_receipts.sql", + "V42__account_logout_all_operation_receipts.sql"); assertThat(migrations.stream().map(AccountMigrationVersionTest::version).toList()) .as("Flyway rejects two different migration descriptions with the same version") .doesNotHaveDuplicates(); @@ -74,6 +76,9 @@ void accountMigrationsHaveDistinctFlywayVersionsWithoutRequiringDocker() throws assertThat(version("V42__account_membership_left_transition_receipts.sql")) .isGreaterThan(version("V40__account_membership_transition_receipts.sql")) .isGreaterThan(version("V41__protect_account_membership_transition_receipts.sql")); + assertThat(version("V42.1__account_logout_all_operation_receipts.sql")) + .isGreaterThan(version("V42__account_membership_left_transition_receipts.sql")) + .isLessThan(MigrationVersion.fromVersion("43")); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java new file mode 100644 index 0000000000..8531750d36 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java @@ -0,0 +1,475 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.HexFormat; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +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.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountAuthoritySourceEventReadbackTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + + @Test + void sequenceZeroRequiresTheOriginalPositiveBaselineAndNoCheckpoint() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + when(outbox.readCheckpoint("account:auth-authority:v1:account/" + ACCOUNT_UUID)) + .thenReturn(Optional.empty()); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + var snapshot = + readback.requireCurrentLatest( + account(), + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + 1L, + 1L, + new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 4L, 3L))); + + assertThat(snapshot.outboxSequence()).isZero(); + assertThat(snapshot.latestEvent()).isEmpty(); + verifyNoInteractions(resets, logouts); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void sequenceZeroNeverRepairsAProgressedSourceWithoutHistory() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + outbox, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class)); + when(outbox.readCheckpoint("account:auth-authority:v1:account/" + ACCOUNT_UUID)) + .thenReturn(Optional.empty()); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + assertThatThrownBy( + () -> + readback.requireCurrentLatest( + account(), + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + 2L, + 2L, + new AccountAuthorityGenerationRepository.IssuanceFence( + ACCOUNT_UUID, 5L, 4L)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("original positive 1/1 baseline"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void presentCheckpointIsContradictoryAtPristineBaselineAndSingleCounterProgression() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 1L, "event-id", "sha256:" + "a".repeat(64)))); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + assertRejectedCheckpoint(readback, 1L, 1L, "contradictory event history"); + assertRejectedCheckpoint(readback, 2L, 1L, "history is not proven"); + assertRejectedCheckpoint(readback, 1L, 2L, "history is not proven"); + + verify(outbox, never()).findEvent(streamKey, 1L); + verifyNoInteractions(resets, logouts); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void retainedPasswordResetUsesImmutableReceiptWithoutMakingItsVerifierCurrent() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + Account account = account(); + account.setPasswordHash("a-later-password-verifier"); + Event retained = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "a".repeat(64)); + PasswordResetReceipt receipt = passwordResetReceipt(retained, 7L, 6L); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 2L, "later-event", "sha256:" + "c".repeat(64)))); + when(resets.findByRequestId(receipt.requestId())).thenReturn(Optional.of(receipt)); + AccountAuthorityGenerationRepository.ScopeState current = accountState(3L, 3L, 8L, 7L); + + readback.requireRetainedEvent(account, retained, current); + + verify(resets).findByRequestId(receipt.requestId()); + verifyNoInteractions(logouts); + } + + @Test + void latestPasswordResetStillRequiresItsRecordedVerifierToBeCurrent() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + Account account = account(); + account.setPasswordHash("a-later-password-verifier"); + Event latest = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "b".repeat(64)); + PasswordResetReceipt receipt = passwordResetReceipt(latest, 7L, 6L); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 1L, latest.eventId(), latest.eventDigest()))); + when(outbox.findEvent(streamKey, 1L)).thenReturn(Optional.of(latest)); + when(resets.findByRequestId(receipt.requestId())).thenReturn(Optional.of(receipt)); + + assertThatThrownBy(() -> readback.requireCurrentLatest(account, accountState(2L, 2L, 7L, 6L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match the current password verifier"); + } + + @Test + void retainedLogoutAllEventRequiresItsExactImmutableReceipt() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + Event retained = + logoutAllEvent( + ACCOUNT_UUID, UUID.fromString("a980fa44-619e-4ca4-8ad6-75b0538a66a3"), 1L, 2L, 2L); + LogoutAllReceipt receipt = logoutReceipt(retained, 7L, 6L); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 2L, "later-event", "sha256:" + "d".repeat(64)))); + when(logouts.findByRequestId(receipt.requestId())).thenReturn(Optional.of(receipt)); + + readback.requireRetainedEvent(account(), retained, accountState(3L, 3L, 8L, 7L)); + + verify(logouts).findByRequestId(receipt.requestId()); + verifyNoInteractions(resets); + } + + @Test + void retainedReadRejectsChangedEventBytesAndMissingReceipts() { + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository resets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + Event valid = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "e".repeat(64)); + String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + when(outbox.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 2L, "later-event", "sha256:" + "f".repeat(64)))); + byte[] changedPayload = valid.payload(); + changedPayload[changedPayload.length - 2] ^= 1; + Event changedBytes = + new Event( + valid.outboxStreamKey(), + valid.requestId(), + valid.outboxSequence(), + valid.eventId(), + valid.eventDigest(), + changedPayload); + + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), changedBytes, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not a valid declared"); + + Event changedDigest = + new Event( + valid.outboxStreamKey(), + valid.requestId(), + valid.outboxSequence(), + valid.eventId(), + "sha256:" + "0".repeat(64), + valid.payload()); + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), changedDigest, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback is inconsistent"); + + Event unsupportedSchema = + new Event( + valid.outboxStreamKey(), + "unsupported-request", + 1L, + "unsupported-event", + "sha256:" + "1".repeat(64), + "{}".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), unsupportedSchema, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not a valid declared"); + + Event wrongAccount = + passwordResetEvent( + UUID.fromString("d980fa44-619e-4ca4-8ad6-75b0538a66a3"), 1L, 2L, 2L, "f".repeat(64)); + assertThatThrownBy( + () -> + readback.requireRetainedEvent( + account(), wrongAccount, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback is inconsistent"); + + PasswordResetReceipt receipt = passwordResetReceipt(valid, 7L, 6L); + PasswordResetReceipt mismatchedReceipt = + new PasswordResetReceipt( + receipt.accountId(), + receipt.accountUuid(), + receipt.tokenHash(), + receipt.operationKind(), + receipt.requestId(), + receipt.requestDigestVersion(), + receipt.requestDigest(), + receipt.tokenExpiresAt(), + receipt.passwordVerifierDigest(), + receipt.outboxStreamKey(), + receipt.outboxSequence(), + receipt.eventId(), + "sha256:" + "2".repeat(64), + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion()); + when(resets.findByRequestId(valid.requestId())) + .thenReturn(Optional.empty(), Optional.of(mismatchedReceipt)); + assertThatThrownBy( + () -> readback.requireRetainedEvent(account(), valid, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no immutable operation receipt"); + assertThatThrownBy( + () -> readback.requireRetainedEvent(account(), valid, accountState(3L, 3L, 8L, 7L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("receipt does not match its source event"); + } + + private void assertRejectedCheckpoint( + AccountAuthoritySourceEventReadback readback, + long generation, + long sourceVersion, + String expectedMessage) { + assertThatThrownBy( + () -> + readback.requireCurrentLatest( + account(), + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + generation, + sourceVersion, + new AccountAuthorityGenerationRepository.IssuanceFence( + ACCOUNT_UUID, 4L, 3L)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(expectedMessage); + } + + private Account account() { + Account account = new Account(); + account.setId(11L); + account.setAccountUuid(ACCOUNT_UUID); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + account.setAccountUuidSourceNumericId(11L); + account.setPasswordHash("unused-on-sequence-zero"); + return account; + } + + private AccountAuthorityGenerationRepository.ScopeState accountState( + long generation, long sourceVersion, long fence, long fenceSourceVersion) { + return new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + generation, + sourceVersion, + new AccountAuthorityGenerationRepository.IssuanceFence( + ACCOUNT_UUID, fence, fenceSourceVersion)); + } + + private Event passwordResetEvent( + UUID accountUuid, long sequence, long generation, long sourceVersion, String tokenHash) { + String streamKey = "account:auth-authority:v1:account/" + accountUuid; + String requestId = "account-password-reset-request-v1:" + tokenHash; + String eventId = "account-password-reset-event-v1:" + tokenHash; + var sealed = + PasswordResetAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", requestId), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", Long.toString(generation)), + Map.entry("sourceVersion", Long.toString(sourceVersion)), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", Long.toString(generation), + "outboxStreamKey", streamKey, + "outboxSequence", Long.toString(sequence))))); + return new Event( + streamKey, requestId, sequence, eventId, sealed.eventDigest(), sealed.canonicalJsonUtf8()); + } + + private PasswordResetReceipt passwordResetReceipt( + Event event, long fence, long fenceSourceVersion) { + String tokenHash = event.requestId().substring("account-password-reset-request-v1:".length()); + LocalDateTime tokenDeadline = LocalDateTime.of(2030, 1, 2, 3, 4, 5); + String verifierDigest = "b".repeat(64); + return new PasswordResetReceipt( + 11L, + ACCOUNT_UUID, + tokenHash, + "PASSWORD_RESET", + event.requestId(), + 1, + passwordResetRequestDigest( + ACCOUNT_UUID, tokenHash, tokenDeadline.toString(), verifierDigest), + tokenDeadline, + verifierDigest, + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + 2L, + 2L, + fence, + fenceSourceVersion); + } + + private Event logoutAllEvent( + UUID accountUuid, UUID requestId, long sequence, long generation, long sourceVersion) { + String streamKey = "account:auth-authority:v1:account/" + accountUuid; + String eventId = "account-logout-all-event-v1:" + requestId; + var sealed = + AccountLogoutAllAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", requestId.toString()), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", Long.toString(generation)), + Map.entry("sourceVersion", Long.toString(sourceVersion)), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", Long.toString(generation), + "outboxStreamKey", streamKey, + "outboxSequence", Long.toString(sequence))))); + return new Event( + streamKey, + requestId.toString(), + sequence, + eventId, + sealed.eventDigest(), + sealed.canonicalJsonUtf8()); + } + + private LogoutAllReceipt logoutReceipt(Event event, long fence, long fenceSourceVersion) { + UUID requestId = UUID.fromString(event.requestId()); + String tokenHash = "c".repeat(64); + String tokenProfile = "control-ui"; + return new LogoutAllReceipt( + requestId, + 11L, + ACCOUNT_UUID, + "ACCOUNT_LOGOUT_ALL", + 1, + AccountLogoutRequestDigest.accountLogoutAll(ACCOUNT_UUID, tokenProfile, tokenHash), + tokenHash, + tokenProfile, + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + 2L, + 2L, + fence, + fenceSourceVersion, + "LOGOUT_ALL_COMMITTED"); + } + + private String passwordResetRequestDigest( + UUID accountUuid, String tokenHash, String tokenDeadline, String verifierDigest) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + updateLengthPrefixed(digest, "account-password-reset-request/v1"); + updateLengthPrefixed(digest, "PASSWORD_RESET"); + updateLengthPrefixed(digest, accountUuid.toString()); + updateLengthPrefixed(digest, tokenHash); + updateLengthPrefixed(digest, tokenDeadline); + updateLengthPrefixed(digest, verifierDigest); + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private void updateLengthPrefixed(MessageDigest digest, String value) { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReaderTest.java new file mode 100644 index 0000000000..fbeaff2b59 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReaderTest.java @@ -0,0 +1,314 @@ +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.ArgumentMatchers.any; +import static org.mockito.Mockito.anyLong; +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.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +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.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountAuthoritySourceReaderTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + private static final String STREAM_KEY = "account:auth-authority:v1:account/" + ACCOUNT_UUID; + + @Test + void currentReadLocksAndRechecksThePersistedAssociationBeforeReadingAuthority() { + Collaborators collaborators = collaborators(); + Account account = account(11L, ACCOUNT_UUID); + ScopeState state = state(1L, 1L, 7L, 4L); + when(collaborators.accounts.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account)); + when(collaborators.accounts.findByIdForUpdate(11L)).thenReturn(Optional.of(account)); + when(collaborators.generations.read(AuthorityScope.account(ACCOUNT_UUID))).thenReturn(state); + when(collaborators.sourceReadback.requireCurrentLatest(account, state)) + .thenReturn( + new AccountAuthoritySourceEventReadback.LatestSourceSnapshot(0L, Optional.empty())); + + AccountSourceSnapshot snapshot = newReader(collaborators).readCurrent(ACCOUNT_UUID); + + assertThat(snapshot.accountId()).isEqualTo(ACCOUNT_UUID); + assertThat(snapshot.sourceState()).isEqualTo(state); + assertThat(snapshot.outboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(snapshot.outboxSequence()).isZero(); + assertThat(snapshot.latestEvent()).isEmpty(); + var order = + inOrder(collaborators.accounts, collaborators.generations, collaborators.sourceReadback); + order.verify(collaborators.accounts).findByAccountUuid(ACCOUNT_UUID); + order.verify(collaborators.accounts).findByIdForUpdate(11L); + order.verify(collaborators.generations).read(AuthorityScope.account(ACCOUNT_UUID)); + order.verify(collaborators.sourceReadback).requireCurrentLatest(account, state); + assertTransactionDefinitionIsWritableReadCommitted(collaborators.transactionManager); + } + + @Test + void currentSequenceZeroAllowsAnAdvancedPositiveFenceAtTheOriginalSourceBaseline() { + Collaborators collaborators = collaborators(); + Account account = account(11L, ACCOUNT_UUID); + ScopeState baseline = state(1L, 1L, 7L, 4L); + when(collaborators.accounts.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account)); + when(collaborators.accounts.findByIdForUpdate(11L)).thenReturn(Optional.of(account)); + when(collaborators.generations.read(AuthorityScope.account(ACCOUNT_UUID))).thenReturn(baseline); + when(collaborators.sourceReadback.requireCurrentLatest(account, baseline)) + .thenReturn( + new AccountAuthoritySourceEventReadback.LatestSourceSnapshot(0L, Optional.empty())); + + AccountSourceSnapshot snapshot = newReader(collaborators).readCurrent(ACCOUNT_UUID); + + assertThat(snapshot.sourceState().generation()).isEqualTo(1L); + assertThat(snapshot.sourceState().sourceVersion()).isEqualTo(1L); + assertThat(snapshot.sourceState().issuanceFence()) + .isEqualTo(new IssuanceFence(ACCOUNT_UUID, 7L, 4L)); + assertThat(snapshot.outboxSequence()).isZero(); + } + + @Test + void selectedReadReturnsTheExactHistoricalEventWithTheCurrentSnapshot() { + Collaborators collaborators = collaborators(); + Account account = account(11L, ACCOUNT_UUID); + ScopeState state = state(3L, 3L, 8L, 7L); + Event latest = event(2L); + Event selected = event(1L); + when(collaborators.accounts.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account)); + when(collaborators.accounts.findByIdForUpdate(11L)).thenReturn(Optional.of(account)); + when(collaborators.generations.read(AuthorityScope.account(ACCOUNT_UUID))).thenReturn(state); + when(collaborators.sourceReadback.requireCurrentLatest(account, state)) + .thenReturn( + new AccountAuthoritySourceEventReadback.LatestSourceSnapshot(2L, Optional.of(latest))); + when(collaborators.outbox.findEvent(STREAM_KEY, 1L)).thenReturn(Optional.of(selected)); + + AccountSourceEventReadback result = + newReader(collaborators).readCommittedEvent(ACCOUNT_UUID, 1L); + + assertThat(result.currentSnapshot().outboxSequence()).isEqualTo(2L); + assertThat(result.currentSnapshot().latestEvent()).contains(latest); + assertThat(result.requestedEvent()).isEqualTo(selected); + var order = inOrder(collaborators.sourceReadback, collaborators.outbox); + order.verify(collaborators.sourceReadback).requireCurrentLatest(account, state); + order.verify(collaborators.outbox).findEvent(STREAM_KEY, 1L); + order.verify(collaborators.sourceReadback).requireRetainedEvent(account, selected, state); + } + + @Test + void resultRecordsRejectLatestOrSelectedEventsWhosePayloadLeadsCurrentCounters() { + ScopeState currentState = state(3L, 3L, 8L, 7L); + Event latest = event(2L); + AccountSourceSnapshot current = + new AccountSourceSnapshot(ACCOUNT_UUID, currentState, STREAM_KEY, 2L, Optional.of(latest)); + + assertThatThrownBy( + () -> + new AccountSourceSnapshot( + ACCOUNT_UUID, currentState, STREAM_KEY, 2L, Optional.of(event(2L, 2L, 3L)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("contradict"); + assertThatThrownBy(() -> new AccountSourceEventReadback(current, event(1L, 4L, 2L))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("lead the current snapshot"); + } + + @Test + void selectedReadRejectsAnEventAheadOfTheCurrentCheckpointBeforeLookingItUp() { + Collaborators collaborators = collaborators(); + Account account = account(11L, ACCOUNT_UUID); + ScopeState state = state(2L, 2L, 5L, 4L); + when(collaborators.accounts.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account)); + when(collaborators.accounts.findByIdForUpdate(11L)).thenReturn(Optional.of(account)); + when(collaborators.generations.read(AuthorityScope.account(ACCOUNT_UUID))).thenReturn(state); + when(collaborators.sourceReadback.requireCurrentLatest(account, state)) + .thenReturn( + new AccountAuthoritySourceEventReadback.LatestSourceSnapshot( + 1L, Optional.of(event(1L)))); + + assertThatThrownBy(() -> newReader(collaborators).readCommittedEvent(ACCOUNT_UUID, 2L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ahead of its current checkpoint"); + + verify(collaborators.outbox, never()).findEvent(any(String.class), anyLong()); + } + + @Test + void selectedReadRejectsMissingRetainedEventEvidence() { + Collaborators collaborators = collaborators(); + Account account = account(11L, ACCOUNT_UUID); + ScopeState state = state(2L, 2L, 5L, 4L); + when(collaborators.accounts.findByAccountUuid(ACCOUNT_UUID)).thenReturn(Optional.of(account)); + when(collaborators.accounts.findByIdForUpdate(11L)).thenReturn(Optional.of(account)); + when(collaborators.generations.read(AuthorityScope.account(ACCOUNT_UUID))).thenReturn(state); + when(collaborators.sourceReadback.requireCurrentLatest(account, state)) + .thenReturn( + new AccountAuthoritySourceEventReadback.LatestSourceSnapshot( + 1L, Optional.of(event(1L)))); + when(collaborators.outbox.findEvent(STREAM_KEY, 1L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> newReader(collaborators).readCommittedEvent(ACCOUNT_UUID, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Selected Account source event is missing"); + + verify(collaborators.sourceReadback, never()) + .requireRetainedEvent(any(Account.class), any(Event.class), any(ScopeState.class)); + } + + @Test + void nilIdentityAndAmbientTransactionsFailBeforeRepositoryAccess() { + Collaborators collaborators = collaborators(); + AccountAuthoritySourceReader reader = newReader(collaborators); + + assertThatThrownBy(() -> reader.readCurrent(new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> reader.readCommittedEvent(ACCOUNT_UUID, 0L)) + .isInstanceOf(IllegalArgumentException.class); + + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> reader.readCurrent(ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + verifyNoInteractions(collaborators.accounts, collaborators.generations, collaborators.outbox); + verify(collaborators.transactionManager, never()) + .getTransaction(any(TransactionDefinition.class)); + } + + @Test + void lockedAccountMustRetainTheExactUuidAndProvenance() { + Collaborators collaborators = collaborators(); + Account associated = account(11L, ACCOUNT_UUID); + Account changed = account(12L, ACCOUNT_UUID); + when(collaborators.accounts.findByAccountUuid(ACCOUNT_UUID)) + .thenReturn(Optional.of(associated)); + when(collaborators.accounts.findByIdForUpdate(11L)).thenReturn(Optional.of(changed)); + + assertThatThrownBy(() -> newReader(collaborators).readCurrent(ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact UUID association or provenance"); + + verifyNoInteractions( + collaborators.generations, collaborators.outbox, collaborators.sourceReadback); + } + + private void assertTransactionDefinitionIsWritableReadCommitted( + PlatformTransactionManager transactionManager) { + var definition = org.mockito.ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactionManager).getTransaction(definition.capture()); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + } + + private AccountAuthoritySourceReader newReader(Collaborators collaborators) { + return new AccountAuthoritySourceReader( + collaborators.accounts, + collaborators.generations, + collaborators.outbox, + collaborators.sourceReadback, + collaborators.transactionManager); + } + + private Collaborators collaborators() { + AccountRepository accounts = mock(AccountRepository.class); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountAuthoritySourceEventReadback sourceReadback = + mock(AccountAuthoritySourceEventReadback.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + return new Collaborators(accounts, generations, outbox, sourceReadback, transactionManager); + } + + private Account account(long id, UUID uuid) { + Account account = new Account(); + account.setId(id); + account.setAccountUuid(uuid); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + account.setAccountUuidSourceNumericId(id); + account.setPasswordHash("credential-verifier-is-not-returned"); + return account; + } + + private ScopeState state( + long generation, long sourceVersion, long fence, long fenceSourceVersion) { + return new ScopeState( + AuthorityScope.account(ACCOUNT_UUID), + generation, + sourceVersion, + new IssuanceFence(ACCOUNT_UUID, fence, fenceSourceVersion)); + } + + private Event event(long sequence) { + long generation = sequence + 1L; + return event(sequence, generation, generation); + } + + private Event event(long sequence, long generation, long sourceVersion) { + UUID requestId = + UUID.nameUUIDFromBytes(("request-" + sequence).getBytes(StandardCharsets.UTF_8)); + String eventId = "account-logout-all-event-v1:" + requestId; + String generationCounter = Long.toString(generation); + String sourceVersionCounter = Long.toString(sourceVersion); + var sealed = + AccountLogoutAllAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", requestId.toString()), + Map.entry("accountId", ACCOUNT_UUID.toString()), + Map.entry("sourceScope", "account/" + ACCOUNT_UUID), + Map.entry("outboxStreamKey", STREAM_KEY), + Map.entry("outboxSequence", Long.toString(sequence)), + Map.entry("accountAuthorityGeneration", generationCounter), + Map.entry("sourceVersion", sourceVersionCounter), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", generationCounter, + "outboxStreamKey", STREAM_KEY, + "outboxSequence", Long.toString(sequence))))); + return new Event( + STREAM_KEY, + requestId.toString(), + sequence, + eventId, + sealed.eventDigest(), + sealed.canonicalJsonUtf8()); + } + + private record Collaborators( + AccountRepository accounts, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox, + AccountAuthoritySourceEventReadback sourceReadback, + PlatformTransactionManager transactionManager) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionTest.java new file mode 100644 index 0000000000..45381b6c0b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionTest.java @@ -0,0 +1,205 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +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.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; + +class AccountGenerationProjectionTest { + private static final UUID ACCOUNT_ID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + private static final String ACCOUNT_TEXT = ACCOUNT_ID.toString(); + private static final String STREAM_KEY = "account:auth-authority:v1:account/" + ACCOUNT_TEXT; + + @Test + void emitsExactSequenceZeroBaselineWithoutAnEvent() { + AccountGenerationProjection projection = + projection(ACCOUNT_TEXT, "1", "1", "0", Optional.empty()); + + assertThat(projection.key()).isEqualTo("session:auth:generation:account:" + ACCOUNT_TEXT); + assertThat(projection.toJson()) + .isEqualTo( + "{\"schemaVersion\":\"account-auth-account-generation-projection/v1\"," + + "\"accountId\":\"" + + ACCOUNT_TEXT + + "\",\"accountAuthorityGeneration\":\"1\",\"sourceVersion\":\"1\"," + + "\"outboxStreamKey\":\"" + + STREAM_KEY + + "\",\"outboxSequence\":\"0\"}"); + assertThat(AccountGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + } + + @Test + void preservesCanonicalClosedPasswordResetAndLogoutAllEventsAsStrings() { + AccountGenerationProjection resetProjection = + projection(ACCOUNT_TEXT, "4", "5", "3", Optional.of(resetEvent("4", "5", "3"))); + AccountGenerationProjection logoutProjection = + projection(ACCOUNT_TEXT, "6", "8", "5", Optional.of(logoutEvent("6", "8", "5"))); + + assertThat(AccountGenerationProjection.parse(resetProjection.toJson())) + .isEqualTo(resetProjection); + assertThat(AccountGenerationProjection.parse(logoutProjection.toJson())) + .isEqualTo(logoutProjection); + assertThat(resetProjection.sourceEvent()).contains(resetEvent("4", "5", "3")); + assertThat(logoutProjection.sourceEvent()).contains(logoutEvent("6", "8", "5")); + } + + @Test + void acceptsLargeCanonicalCountersWithoutLongConversion() { + String large = "922337203685477580812345678901234567890"; + AccountGenerationProjection projection = + projection( + ACCOUNT_TEXT, large, large, large, Optional.of(logoutEvent(large, large, large))); + + assertThat(projection.generationValue()).isEqualTo(new BigInteger(large)); + assertThat(projection.sourceVersionValue()).isEqualTo(new BigInteger(large)); + assertThat(projection.outboxSequenceValue()).isEqualTo(new BigInteger(large)); + assertThat(AccountGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + } + + @Test + void closesTheProjectionShapeAndRejectsDuplicateUnknownNullAndNoncanonicalEvidence() { + String baseline = projection(ACCOUNT_TEXT, "1", "1", "0", Optional.empty()).toJson(); + String duplicateAccountId = + baseline.replace( + "\"accountId\":\"" + ACCOUNT_TEXT + "\"", + "\"accountId\":\"" + ACCOUNT_TEXT + "\",\"accountId\":\"" + ACCOUNT_TEXT + "\""); + String unknownField = + baseline.substring(0, baseline.length() - 1) + ",\"issuanceFence\":\"1\"}"; + String nullEvent = baseline.substring(0, baseline.length() - 1) + ",\"sourceEvent\":null}"; + String noncanonicalSequence = + baseline.replace("\"outboxSequence\":\"0\"", "\"outboxSequence\":\"00\""); + String reordered = + baseline.replace( + "\"schemaVersion\":\"account-auth-account-generation-projection/v1\"," + + "\"accountId\":\"" + + ACCOUNT_TEXT + + "\",", + "\"accountId\":\"" + + ACCOUNT_TEXT + + "\",\"schemaVersion\":\"account-auth-account-generation-projection/v1\","); + + assertThatThrownBy(() -> AccountGenerationProjection.parse(duplicateAccountId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountGenerationProjection.parse(unknownField)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountGenerationProjection.parse(nullEvent)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountGenerationProjection.parse(noncanonicalSequence)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountGenerationProjection.parse(reordered)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedEventCheckpointAndInvalidSequenceZeroRepresentations() { + String event = logoutEvent("2", "2", "1"); + + assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "3", "2", "1", Optional.of(event))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("declared closed schemas") + .cause() + .hasMessageContaining("does not match"); + assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "2", "2", "0", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence zero"); + assertThatThrownBy(() -> projection(ACCOUNT_TEXT, "2", "2", "1", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires advanced counters"); + } + + @Test + void localIssuanceFenceIsNotSerializedOrComparedAsProjectionEvidence() { + AccountGenerationProjection first = + AccountGenerationProjection.fromSource(source(1L, 1L, 0L, Optional.empty(), 4L)); + AccountGenerationProjection withNewerLocalFence = + AccountGenerationProjection.fromSource(source(1L, 1L, 0L, Optional.empty(), 99L)); + + assertThat(withNewerLocalFence).isEqualTo(first); + assertThat(first.toJson()).doesNotContain("issuanceFence"); + } + + private static AccountGenerationProjection projection( + String accountId, + String generation, + String sourceVersion, + String sequence, + Optional sourceEvent) { + return new AccountGenerationProjection( + accountId, generation, sourceVersion, STREAM_KEY, sequence, sourceEvent); + } + + private static String resetEvent(String generation, String sourceVersion, String sequence) { + var evidence = + PasswordResetAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "account-password-reset-event-v1:sample"), + Map.entry("requestId", "account-password-reset-request-v1:sample"), + Map.entry("accountId", ACCOUNT_TEXT), + Map.entry("sourceScope", "account/" + ACCOUNT_TEXT), + Map.entry("outboxStreamKey", STREAM_KEY), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", generation, + "outboxStreamKey", STREAM_KEY, + "outboxSequence", sequence)))); + return new String(evidence.canonicalJsonUtf8(), StandardCharsets.UTF_8); + } + + private static String logoutEvent(String generation, String sourceVersion, String sequence) { + String requestId = "11111111-1111-4111-8111-111111111111"; + var evidence = + AccountLogoutAllAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", AccountLogoutAllAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId), + Map.entry("accountId", ACCOUNT_TEXT), + Map.entry("sourceScope", "account/" + ACCOUNT_TEXT), + Map.entry("outboxStreamKey", STREAM_KEY), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", generation, + "outboxStreamKey", STREAM_KEY, + "outboxSequence", sequence)))); + return new String(evidence.canonicalJsonUtf8(), StandardCharsets.UTF_8); + } + + private static AccountSourceSnapshot source( + long generation, long sourceVersion, long sequence, Optional event, long fenceValue) { + return new AccountSourceSnapshot( + ACCOUNT_ID, + new ScopeState( + AuthorityScope.account(ACCOUNT_ID), + generation, + sourceVersion, + new IssuanceFence(ACCOUNT_ID, fenceValue, 1L)), + STREAM_KEY, + sequence, + event); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java new file mode 100644 index 0000000000..95f27d4b56 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java @@ -0,0 +1,222 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +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.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountLogoutAllAuthorityEventProducerTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("7439d275-a8bd-4ad2-8993-3c9d30e86472"); + private static final String TOKEN_PROFILE = "control-ui"; + private static final String TOKEN_HASH = "b".repeat(64); + private static final String REQUEST_DIGEST = + AccountLogoutRequestDigest.accountLogoutAll(ACCOUNT_UUID, TOKEN_PROFILE, TOKEN_HASH); + + @Test + void rejectsMalformedRequestEvidenceBeforeDatabaseOrTransactionInteraction() { + Collaborators collaborators = new Collaborators(); + AccountLogoutAllAuthorityEventProducer producer = newProducer(collaborators); + Account account = account(); + var expected = + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + 1L, + 1L, + new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L)); + + assertThatThrownBy( + () -> + producer.commit( + new UUID(0L, 0L), + 1, + REQUEST_DIGEST, + TOKEN_PROFILE, + TOKEN_HASH, + account, + expected)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil"); + assertThatThrownBy( + () -> + producer.commit( + UUID.randomUUID(), + 0, + REQUEST_DIGEST, + TOKEN_PROFILE, + TOKEN_HASH, + account, + expected)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive"); + assertThatThrownBy( + () -> + producer.commit( + UUID.randomUUID(), + 1, + "A".repeat(64), + TOKEN_PROFILE, + TOKEN_HASH, + account, + expected)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase SHA-256"); + assertThatThrownBy( + () -> + producer.commit( + UUID.randomUUID(), + 1, + REQUEST_DIGEST, + TOKEN_PROFILE, + "b".repeat(63), + account, + expected)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("token hash"); + assertThatThrownBy( + () -> + producer.commit( + UUID.randomUUID(), + 1, + REQUEST_DIGEST, + "private-player-delegation", + TOKEN_HASH, + account, + expected)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("token profile"); + + collaborators.verifyUnused(); + } + + @Test + void rejectsAmbientTransactionAndDoesNotUseExpectedStateAsCallerAuthorization() { + Collaborators collaborators = new Collaborators(); + AccountLogoutAllAuthorityEventProducer producer = newProducer(collaborators); + Account account = account(); + var expected = + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID), + 1L, + 1L, + new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L)); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + assertThatThrownBy( + () -> + producer.commit( + UUID.randomUUID(), + 1, + REQUEST_DIGEST, + TOKEN_PROFILE, + TOKEN_HASH, + account, + expected)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient transaction"); + collaborators.verifyUnused(); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void rejectsMismatchedExpectedSourceScopeBeforeDatabaseInteraction() { + Collaborators collaborators = new Collaborators(); + AccountLogoutAllAuthorityEventProducer producer = newProducer(collaborators); + Account account = account(); + var wrongScope = + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.account(UUID.randomUUID()), + 1L, + 1L, + new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L)); + + assertThatThrownBy( + () -> + producer.commit( + UUID.randomUUID(), + 1, + REQUEST_DIGEST, + TOKEN_PROFILE, + TOKEN_HASH, + account, + wrongScope)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Expected Account authority scope"); + + collaborators.verifyUnused(); + } + + private AccountLogoutAllAuthorityEventProducer newProducer(Collaborators collaborators) { + AccountAuthoritySourceEventReadback readback = + new AccountAuthoritySourceEventReadback( + collaborators.outboxRepository(), + collaborators.passwordResetRepository(), + collaborators.logoutAllRepository()); + return new AccountLogoutAllAuthorityEventProducer( + collaborators.accountRepository(), + collaborators.generationRepository(), + collaborators.outboxRepository(), + collaborators.logoutAllRepository(), + readback, + collaborators.dsl(), + collaborators.transactionManager()); + } + + private Account account() { + Account account = new Account(); + account.setId(7L); + account.setAccountUuid(ACCOUNT_UUID); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + account.setAccountUuidSourceNumericId(7L); + return account; + } + + private record Collaborators( + AccountRepository accountRepository, + AccountAuthorityGenerationRepository generationRepository, + AccountAuthorityOutboxRepository outboxRepository, + AccountPasswordResetOperationRepository passwordResetRepository, + AccountLogoutAllOperationRepository logoutAllRepository, + DSLContext dsl, + PlatformTransactionManager transactionManager) { + private Collaborators() { + this( + mock(AccountRepository.class), + mock(AccountAuthorityGenerationRepository.class), + mock(AccountAuthorityOutboxRepository.class), + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), + mock(DSLContext.class), + mock(PlatformTransactionManager.class)); + } + + private void verifyUnused() { + verifyNoInteractions( + accountRepository, + generationRepository, + outboxRepository, + passwordResetRepository, + logoutAllRepository, + dsl, + transactionManager); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java index 2089ad9b83..90e1c8b826 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java @@ -8,8 +8,10 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -49,6 +51,8 @@ void inactiveMembershipSnapshotRequiresOwnerTransactionBeforeRepositoryReads() { freshAssociationRepository, generationRepository, outboxRepository, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), receiptRepository, membershipRepository, rolesRepository); @@ -94,6 +98,8 @@ void freshSnapshotRequiresOwnerTransactionBeforeRepositoryReads() { freshAssociationRepository, mock(AccountAuthorityGenerationRepository.class), mock(AccountAuthorityOutboxRepository.class), + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), mock(AccountMembershipTransitionReceiptRepository.class), mock(AccountTenantMembershipRepository.class), mock(AccountTenantMembershipRoleSnapshotRepository.class)); @@ -125,6 +131,8 @@ void canonicalRuntimeSnapshotRequiresOwnerTransactionBeforeIdentityReads() { freshAssociationRepository, mock(AccountAuthorityGenerationRepository.class), mock(AccountAuthorityOutboxRepository.class), + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), mock(AccountMembershipTransitionReceiptRepository.class), mock(AccountTenantMembershipRepository.class), mock(AccountTenantMembershipRoleSnapshotRepository.class)); @@ -170,6 +178,8 @@ void existingPositiveSnapshotRequiresOwnerTransactionBeforeIdentityReads() { freshAssociationRepository, authorityGenerationRepository, authorityOutboxRepository, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), transitionReceiptRepository, membershipRepository, roleSnapshotRepository); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducerTest.java new file mode 100644 index 0000000000..5076a08e1b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantAuthorityEventProducerTest.java @@ -0,0 +1,411 @@ +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.service.AccountTenantAuthorityEventProducer; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.Test; +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 AccountTenantAuthorityEventProducerTest { + private static final UUID TENANT_ID = UUID.fromString("10000000-0000-0000-0000-000000000001"); + private static final UUID OTHER_TENANT_ID = + UUID.fromString("10000000-0000-0000-0000-000000000002"); + private static final String STREAM_KEY = "account:auth-authority:v1:tenant/" + TENANT_ID; + + @Test + void nilTenantAndRequestIdentitiesAreRejectedBeforePersistence() { + Collaborators collaborators = new Collaborators(); + AccountTenantAuthorityEventProducer producer = newProducer(collaborators); + + assertThatThrownBy(() -> producer.advance(null, UUID.randomUUID(), 1L, 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenant UUID"); + assertThatThrownBy(() -> producer.readCurrent(new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenant UUID"); + assertThatThrownBy(() -> producer.advance(TENANT_ID, new UUID(0L, 0L), 1L, 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + assertThatThrownBy(() -> producer.advance(TENANT_ID, UUID.randomUUID(), 0L, 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be positive"); + assertThatThrownBy(() -> producer.advance(TENANT_ID, UUID.randomUUID(), 1L, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be positive"); + assertThatThrownBy(() -> producer.readCommittedEvent(TENANT_ID, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence must be positive"); + + collaborators.verifyUnused(); + } + + @Test + void missingConstructorCollaboratorsAreRejectedBeforeOtherInteractions() { + Collaborators collaborators = new Collaborators(); + + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer( + null, + collaborators.outboxRepository(), + collaborators.dsl(), + collaborators.transactionManager())) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("authority-generation repository"); + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer( + collaborators.generationRepository(), + null, + collaborators.dsl(), + collaborators.transactionManager())) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("authority outbox repository"); + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer( + collaborators.generationRepository(), + collaborators.outboxRepository(), + null, + collaborators.transactionManager())) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("transaction-aware DSLContext"); + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer( + collaborators.generationRepository(), + collaborators.outboxRepository(), + collaborators.dsl(), + null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Account transaction manager"); + + collaborators.verifyUnused(); + } + + @Test + void ambientTransactionIsRejectedForEveryPublicOperation() { + Collaborators collaborators = new Collaborators(); + AccountTenantAuthorityEventProducer producer = newProducer(collaborators); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + assertThatThrownBy(() -> producer.readCurrent(TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient transaction"); + assertThatThrownBy(() -> producer.readCommittedEvent(TENANT_ID, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient transaction"); + assertThatThrownBy(() -> producer.advance(TENANT_ID, UUID.randomUUID(), 1L, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient transaction"); + collaborators.verifyUnused(); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void sequenceZeroSnapshotRequiresThePositiveOriginalBaselineAndExactStream() { + AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot snapshot = + new AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot( + TENANT_ID, 1L, 1L, STREAM_KEY, 0L, Optional.empty()); + + assertThat(snapshot.latestEvent()).isEmpty(); + assertThat(snapshot.outboxSequence()).isZero(); + + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot( + TENANT_ID, + 1L, + 1L, + "account:auth-authority:v1:tenant/" + OTHER_TENANT_ID, + 0L, + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not bind its tenant"); + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot( + TENANT_ID, 2L, 1L, STREAM_KEY, 0L, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive 1/1 baseline"); + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot( + TENANT_ID, 1L, 2L, STREAM_KEY, 0L, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive 1/1 baseline"); + } + + @Test + void positiveSnapshotRequiresTheExactLatestEventAndCurrentCounters() { + UUID requestId = UUID.randomUUID(); + TenantGenerationAuthorityEvent matchingEvent = event(TENANT_ID, requestId, 1L, 2L, 2L); + TenantGenerationAuthorityEvent wrongCounterEvent = + event(TENANT_ID, UUID.randomUUID(), 1L, 2L, 3L); + + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot( + TENANT_ID, 2L, 2L, STREAM_KEY, 1L, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must omit its event"); + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot( + TENANT_ID, 2L, 2L, STREAM_KEY, 1L, Optional.of(wrongCounterEvent))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from its checkpoint"); + + AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot valid = + new AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot( + TENANT_ID, 2L, 2L, STREAM_KEY, 1L, Optional.of(matchingEvent)); + assertThat(valid.latestEvent()).containsSame(matchingEvent); + } + + @Test + void positiveHeadRejectsPristineOrOneSidedCountersBeforeAnyEventLookup() { + for (long[] counters : new long[][] {{1L, 1L}, {2L, 1L}, {1L, 2L}}) { + Collaborators collaborators = new Collaborators(); + TransactionStatus status = new SimpleTransactionStatus(); + when(collaborators.transactionManager().getTransaction(any(TransactionDefinition.class))) + .thenReturn(status); + doNothing().when(collaborators.transactionManager()).commit(status); + AccountAuthorityGenerationRepository.ScopeState scopeState = + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.tenant(TENANT_ID), + counters[0], + counters[1], + null); + when(collaborators.generationRepository().read(scopeState.scope())).thenReturn(scopeState); + Record stream = mock(Record.class); + when(stream.get("last_sequence", Long.class)).thenReturn(1L); + when(collaborators.dsl().fetchOne(contains("SELECT last_sequence"), eq(STREAM_KEY))) + .thenReturn(stream); + AccountTenantAuthorityEventProducer producer = newProducer(collaborators); + + assertThatThrownBy(() -> producer.readCurrent(TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("advanced together"); + verify(collaborators.outboxRepository(), never()).readCheckpoint(any()); + verify(collaborators.outboxRepository(), never()).findEvent(anyString(), anyLong()); + verify(collaborators.outboxRepository(), never()).findEvent(anyString(), anyString()); + } + } + + @Test + void tenantGenerationAndSourceVersionOverflowFailBeforeMutation() { + for (long[] counters : + new long[][] { + {Long.MAX_VALUE, 1L}, + {1L, Long.MAX_VALUE}, + {Long.MAX_VALUE, Long.MAX_VALUE} + }) { + Collaborators collaborators = new Collaborators(); + TransactionStatus status = new SimpleTransactionStatus(); + when(collaborators.transactionManager().getTransaction(any(TransactionDefinition.class))) + .thenReturn(status); + doNothing().when(collaborators.transactionManager()).commit(status); + AccountAuthorityGenerationRepository.ScopeState scopeState = + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.tenant(TENANT_ID), + counters[0], + counters[1], + null); + when(collaborators.generationRepository().read(scopeState.scope())).thenReturn(scopeState); + UUID requestId = UUID.randomUUID(); + when(collaborators.outboxRepository().findEvent(STREAM_KEY, requestId.toString())) + .thenReturn(Optional.empty()); + AccountTenantAuthorityEventProducer producer = newProducer(collaborators); + + assertThatThrownBy(() -> producer.advance(TENANT_ID, requestId, counters[0], counters[1])) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("is exhausted"); + + verify(collaborators.generationRepository(), never()) + .advance(any(AccountAuthorityGenerationRepository.ScopeState.class), isNull()); + verify(collaborators.outboxRepository(), never()) + .append(eq(STREAM_KEY), eq(requestId.toString()), any()); + verify(collaborators.outboxRepository(), never()).readCheckpoint(anyString()); + verify(collaborators.outboxRepository(), never()).findEvent(eq(STREAM_KEY), anyLong()); + } + } + + @Test + void outboxSequenceGapIsRejectedBeforeEventReadbackOrMutation() { + Collaborators collaborators = new Collaborators(); + TransactionStatus status = new SimpleTransactionStatus(); + when(collaborators.transactionManager().getTransaction(any(TransactionDefinition.class))) + .thenReturn(status); + doNothing().when(collaborators.transactionManager()).commit(status); + AccountAuthorityGenerationRepository.ScopeState scopeState = + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.tenant(TENANT_ID), 3L, 3L, null); + when(collaborators.generationRepository().read(scopeState.scope())).thenReturn(scopeState); + Record stream = mock(Record.class); + when(stream.get("last_sequence", Long.class)).thenReturn(2L); + when(collaborators.dsl().fetchOne(contains("SELECT last_sequence"), eq(STREAM_KEY))) + .thenReturn(stream); + Record eventRange = mock(Record.class); + when(eventRange.get("event_count", Long.class)).thenReturn(1L); + when(eventRange.get("first_sequence", Long.class)).thenReturn(2L); + when(eventRange.get("last_sequence", Long.class)).thenReturn(2L); + when(collaborators.dsl().fetchOne(contains("COUNT(*) AS event_count"), eq(STREAM_KEY))) + .thenReturn(eventRange); + UUID requestId = UUID.randomUUID(); + when(collaborators.outboxRepository().findEvent(STREAM_KEY, requestId.toString())) + .thenReturn(Optional.empty()); + AccountTenantAuthorityEventProducer producer = newProducer(collaborators); + + assertThatThrownBy(() -> producer.advance(TENANT_ID, requestId, 3L, 3L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("sequence gap or dangling head"); + + verify(collaborators.generationRepository(), never()) + .advance(any(AccountAuthorityGenerationRepository.ScopeState.class), isNull()); + verify(collaborators.outboxRepository(), never()) + .append(eq(STREAM_KEY), eq(requestId.toString()), any()); + verify(collaborators.outboxRepository(), never()).readCheckpoint(anyString()); + verify(collaborators.outboxRepository(), never()).findEvent(anyString(), anyLong()); + } + + @Test + void historicalReadbackBindsAnOlderExactEventToTheCurrentTenantSnapshot() { + TenantGenerationAuthorityEvent historical = event(TENANT_ID, UUID.randomUUID(), 1L, 2L, 2L); + TenantGenerationAuthorityEvent latest = event(TENANT_ID, UUID.randomUUID(), 3L, 4L, 4L); + AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot current = + new AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot( + TENANT_ID, 4L, 4L, STREAM_KEY, 3L, Optional.of(latest)); + + AccountTenantAuthorityEventProducer.TenantAuthorityEventReadback readback = + new AccountTenantAuthorityEventProducer.TenantAuthorityEventReadback(current, historical); + + assertThat(readback.currentSnapshot()).isSameAs(current); + assertThat(readback.requestedEvent()).isSameAs(historical); + } + + @Test + void historicalReadbackRejectsAnotherTenantAheadEventOrChangedLatestPayload() { + TenantGenerationAuthorityEvent latest = event(TENANT_ID, UUID.randomUUID(), 2L, 3L, 3L); + TenantGenerationAuthorityEvent differentLatest = + event(TENANT_ID, UUID.randomUUID(), 2L, 3L, 3L); + AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot current = + new AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot( + TENANT_ID, 3L, 3L, STREAM_KEY, 2L, Optional.of(latest)); + + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer.TenantAuthorityEventReadback( + current, event(OTHER_TENANT_ID, UUID.randomUUID(), 1L, 2L, 2L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not bind"); + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer.TenantAuthorityEventReadback( + current, event(TENANT_ID, UUID.randomUUID(), 3L, 3L, 4L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ahead of the current snapshot"); + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer.TenantAuthorityEventReadback( + current, event(TENANT_ID, UUID.randomUUID(), 1L, 4L, 4L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ahead of the current snapshot"); + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer.TenantAuthorityEventReadback( + current, event(TENANT_ID, UUID.randomUUID(), 1L, 3L, 3L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("counters do not match its outbox sequence"); + assertThatThrownBy( + () -> + new AccountTenantAuthorityEventProducer.TenantAuthorityEventReadback( + current, differentLatest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from the current snapshot checkpoint"); + } + + private AccountTenantAuthorityEventProducer newProducer(Collaborators collaborators) { + return new AccountTenantAuthorityEventProducer( + collaborators.generationRepository(), + collaborators.outboxRepository(), + collaborators.dsl(), + collaborators.transactionManager()); + } + + private TenantGenerationAuthorityEvent event( + UUID tenantId, UUID requestId, long sequence, long generation, long sourceVersion) { + String requestText = requestId.toString(); + String sourceScope = "tenant/" + tenantId; + String streamKey = "account:auth-authority:v1:" + sourceScope; + return TenantGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + TenantGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + "account-tenant-generation-event-v1:" + requestText, + "requestId", + requestText, + "tenantId", + tenantId.toString(), + "sourceScope", + sourceScope, + "outboxStreamKey", + streamKey, + "outboxSequence", + Long.toString(sequence), + "tenantAuthorityGeneration", + Long.toString(generation), + "sourceVersion", + Long.toString(sourceVersion))); + } + + private record Collaborators( + AccountAuthorityGenerationRepository generationRepository, + AccountAuthorityOutboxRepository outboxRepository, + DSLContext dsl, + PlatformTransactionManager transactionManager) { + private Collaborators() { + this( + mock(AccountAuthorityGenerationRepository.class), + mock(AccountAuthorityOutboxRepository.class), + mock(DSLContext.class), + mock(PlatformTransactionManager.class)); + } + + private void verifyUnused() { + verifyNoInteractions(generationRepository, outboxRepository, dsl, transactionManager); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java index 5f1317e874..a2bf9da43a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/NeverJoinedMembershipSnapshotTest.java @@ -7,13 +7,16 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; 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.IssuerGenerationAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; 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.TenantGenerationAuthorityEventV1Codec; import org.junit.jupiter.api.Test; class NeverJoinedMembershipSnapshotTest { @@ -59,6 +62,107 @@ void retainsAnAdvancedAccountIssuanceFenceWithoutInventingUpstreamEvents() { assertThat(snapshot.outboxSourceEvidence()).isEmpty(); } + @Test + void neverJoinedMembershipMayKeepZeroMembershipCheckpointWithAdvancedUpstreamSources() { + String issuerStream = + "account:auth-authority:v1:issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER; + String tenantStream = "account:auth-authority:v1:tenant/" + TENANT_ID; + var issuerEvent = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + "issuer-event-1", + "requestId", + "issuer-request-1", + "issuerId", + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + "sourceScope", + "issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + "outboxStreamKey", + issuerStream, + "outboxSequence", + "1", + "issuerAuthGeneration", + "2", + "sourceVersion", + "2")); + UUID tenantRequest = UUID.fromString("018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a"); + var tenantEvent = + TenantGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + TenantGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + TenantGenerationAuthorityEventV1Codec.EVENT_ID_PREFIX + tenantRequest, + "requestId", + tenantRequest.toString(), + "tenantId", + TENANT_ID, + "sourceScope", + "tenant/" + TENANT_ID, + "outboxStreamKey", + tenantStream, + "outboxSequence", + "1", + "tenantAuthorityGeneration", + "2", + "sourceVersion", + "2")); + AuthorityTuple currentTuple = + new AuthorityTuple( + "2", + "1", + Map.of(TENANT_ID, "2"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.empty(), + Optional.empty()); + List checkpoints = + List.of( + new OutboxCheckpointEntry("account:auth-authority:v1:account/" + ACCOUNT_ID, "0"), + new OutboxCheckpointEntry(issuerStream, "1"), + new OutboxCheckpointEntry(STREAM_KEY, "0"), + new OutboxCheckpointEntry(tenantStream, "1")); + List evidence = + List.of( + new OutboxSourceEvidence( + issuerStream, + "1", + issuerEvent.eventId(), + issuerEvent.eventDigest(), + issuerEvent.canonicalJson()), + new OutboxSourceEvidence( + tenantStream, + "1", + tenantEvent.eventId(), + tenantEvent.eventDigest(), + tenantEvent.canonicalJson())); + + var snapshot = + new AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot( + ACCOUNT_ID, + TENANT_ID, + Map.of(TENANT_ID, "1"), + "1", + currentTuple, + "7", + Instant.parse("2026-09-27T00:00:00Z"), + STREAM_KEY, + checkpoints, + evidence); + + assertThat(snapshot.membershipExists()).isFalse(); + assertThat(snapshot.gameplayAdmissionAllowed()).isFalse(); + assertThat(snapshot.outboxCheckpoints()).isEqualTo(checkpoints); + assertThat(snapshot.outboxSourceEvidence()).isEqualTo(evidence); + } + @Test void rejectsNonCanonicalIdsAndNonPositiveCounters() { assertThatThrownBy( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisAccountGenerationProjectionStoreTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisAccountGenerationProjectionStoreTest.java new file mode 100644 index 0000000000..216fbdae52 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisAccountGenerationProjectionStoreTest.java @@ -0,0 +1,468 @@ +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +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.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.RedisAccountGenerationProjectionStore; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisKeyCommands; +import org.springframework.data.redis.connection.RedisScriptingCommands; +import org.springframework.data.redis.connection.RedisStringCommands; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; + +class RedisAccountGenerationProjectionStoreTest { + private static final String PASSWORD = "coordination-secret"; + private static final UUID ACCOUNT_ID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + private static final String ACCOUNT_TEXT = ACCOUNT_ID.toString(); + private static final String KEY = "session:auth:generation:account:" + ACCOUNT_TEXT; + private static final String STREAM_KEY = "account:auth-authority:v1:account/" + ACCOUNT_TEXT; + + @Test + void requiresAccountCoordinationPrincipalAndSeparateCacheEndpoint() { + assertThatThrownBy( + () -> + new RedisAccountGenerationProjectionStore.CoordinationEndpoint( + "coordination.internal", 6379, "gamesession_coord_app", PASSWORD)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("account_coord_app"); + assertThatThrownBy( + () -> + new RedisAccountGenerationProjectionStore.CoordinationEndpoint( + "coordination.internal", 6379, "account_coord_app", " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("credential"); + + var coordination = coordination("coordination.internal", 6379); + var cache = + new RedisAccountGenerationProjectionStore.CacheRateLimitEndpoint( + "COORDINATION.INTERNAL.", 6379); + assertThatThrownBy( + () -> newStore(mock(AccountAuthoritySourceReader.class), coordination, cache)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("endpoints must be distinct"); + assertThat(coordination.toString()).contains("password=").doesNotContain(PASSWORD); + } + + @Test + void constructorDoesNotAcceptAmbientRedisTemplatesOrOpenRedis() { + RedisAccountGenerationProjectionStore store = + newStore( + mock(AccountAuthoritySourceReader.class), + coordination("coord.internal", 6379), + cache()); + + assertThatThrownBy(() -> store.refreshCurrent(ACCOUNT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("explicit init()"); + boolean acceptsAmbientTemplate = + Arrays.stream(RedisAccountGenerationProjectionStore.class.getConstructors()) + .anyMatch( + constructor -> + Arrays.stream(constructor.getParameterTypes()) + .anyMatch(StringRedisTemplate.class::isAssignableFrom)); + assertThat(acceptsAmbientTemplate).isFalse(); + store.close(); + } + + @Test + void rebuildsMissingProjectionOnlyFromOwnerCurrentSnapshotAndVerifiesExactBytes() + throws Exception { + AccountSourceSnapshot baseline = source(1L, 1L, 0L, null, 1L); + Harness harness = harness(new FakeRedis(), baseline, baseline); + + RedisAccountGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID); + + assertThat(result.outcome()).isEqualTo(RedisAccountGenerationProjectionStore.Outcome.APPLIED); + assertThat(result.snapshot()).isPresent(); + assertThat(result.snapshot().orElseThrow().key()).isEqualTo(KEY); + assertThat(result.snapshot().orElseThrow().json()).contains("\"outboxSequence\":\"0\""); + assertThat(harness.redis().bytes) + .isEqualTo(result.snapshot().orElseThrow().json().getBytes(StandardCharsets.UTF_8)); + verify(harness.reader(), times(2)).readCurrent(ACCOUNT_ID); + harness.store().close(); + } + + @Test + void exactSnapshotUsesNonMutatingVerificationAndReturnsReplay() throws Exception { + AccountSourceSnapshot baseline = source(1L, 1L, 0L, null, 1L); + AccountGenerationProjection projection = AccountGenerationProjection.fromSource(baseline); + FakeRedis redis = new FakeRedis(projection.toJson().getBytes(StandardCharsets.UTF_8)); + Harness harness = harness(redis, baseline, baseline); + + RedisAccountGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID); + + assertThat(result.outcome()).isEqualTo(RedisAccountGenerationProjectionStore.Outcome.REPLAYED); + assertThat(redis.lastMode).isEqualTo("VERIFY"); + assertThat(redis.scriptCalls).isEqualTo(1); + verify(harness.reader(), times(2)).readCurrent(ACCOUNT_ID); + harness.store().close(); + } + + @Test + void ttlBearingProjectionIsQuarantinedWithoutMutation() throws Exception { + AccountSourceSnapshot baseline = source(1L, 1L, 0L, null, 1L); + AccountGenerationProjection projection = AccountGenerationProjection.fromSource(baseline); + FakeRedis redis = new FakeRedis(projection.toJson().getBytes(StandardCharsets.UTF_8)); + redis.ttlMillis = 10_000L; + Harness harness = harness(redis, baseline); + + RedisAccountGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisAccountGenerationProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains("TTL_PRESENT"); + assertThat(redis.scriptCalls).isZero(); + verify(harness.reader(), times(1)).readCurrent(ACCOUNT_ID); + harness.store().close(); + } + + @Test + void sourceRegressionNeverOverwritesAnExistingHigherProjection() throws Exception { + AccountSourceSnapshot baseline = source(1L, 1L, 0L, null, 1L); + AccountGenerationProjection newer = + AccountGenerationProjection.fromSource( + source(2L, 2L, 1L, logoutEvent("2", "2", "1", null), 2L)); + FakeRedis redis = new FakeRedis(newer.toJson().getBytes(StandardCharsets.UTF_8)); + Harness harness = harness(redis, baseline); + + RedisAccountGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisAccountGenerationProjectionStore.Outcome.STALE_SOURCE); + assertThat(result.snapshot()).isPresent(); + assertThat(result.snapshot().orElseThrow().json()).isEqualTo(newer.toJson()); + assertThat(redis.scriptCalls).isZero(); + assertThat(redis.bytes).isEqualTo(newer.toJson().getBytes(StandardCharsets.UTF_8)); + harness.store().close(); + } + + @Test + void sameCheckpointDisagreementFailsClosed() throws Exception { + Event storedEvent = logoutEvent("2", "2", "1", "11111111-1111-4111-8111-111111111111"); + Event sourceEvent = logoutEvent("2", "2", "1", "22222222-2222-4222-8222-222222222222"); + AccountGenerationProjection stored = + AccountGenerationProjection.fromSource(source(2L, 2L, 1L, storedEvent, 2L)); + AccountSourceSnapshot candidate = source(2L, 2L, 1L, sourceEvent, 3L); + FakeRedis redis = new FakeRedis(stored.toJson().getBytes(StandardCharsets.UTF_8)); + Harness harness = harness(redis, candidate); + + RedisAccountGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisAccountGenerationProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains("SAME_CHECKPOINT_DISAGREEMENT"); + assertThat(redis.scriptCalls).isZero(); + harness.store().close(); + } + + @Test + void staleCasReturnsWithoutBlindRetry() throws Exception { + AccountSourceSnapshot baseline = source(1L, 1L, 0L, null, 1L); + AccountSourceSnapshot advanced = source(2L, 2L, 1L, logoutEvent("2", "2", "1", null), 2L); + FakeRedis redis = + new FakeRedis( + AccountGenerationProjection.fromSource(baseline) + .toJson() + .getBytes(StandardCharsets.UTF_8)); + redis.forcedScriptResult = "STALE"; + Harness harness = harness(redis, advanced); + + RedisAccountGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID); + + assertThat(result.outcome()).isEqualTo(RedisAccountGenerationProjectionStore.Outcome.STALE); + assertThat(redis.scriptCalls).isEqualTo(1); + verify(harness.reader(), times(1)).readCurrent(ACCOUNT_ID); + harness.store().close(); + } + + @Test + void postWriteReadbackChangedByNewerWriterCannotReturnSuccess() throws Exception { + AccountSourceSnapshot baseline = source(1L, 1L, 0L, null, 1L); + AccountSourceSnapshot candidateSource = + source(2L, 2L, 1L, logoutEvent("2", "2", "1", null), 2L); + AccountGenerationProjection newer = + AccountGenerationProjection.fromSource( + source( + 3L, + 3L, + 2L, + logoutEvent("3", "3", "2", "33333333-3333-4333-8333-333333333333"), + 3L)); + FakeRedis redis = + new FakeRedis( + AccountGenerationProjection.fromSource(baseline) + .toJson() + .getBytes(StandardCharsets.UTF_8)); + redis.afterWriteBytes = newer.toJson().getBytes(StandardCharsets.UTF_8); + Harness harness = harness(redis, candidateSource); + + RedisAccountGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID); + + assertThat(result.outcome()).isEqualTo(RedisAccountGenerationProjectionStore.Outcome.STALE); + assertThat(result.snapshot()).isPresent(); + assertThat(result.snapshot().orElseThrow().json()).isEqualTo(newer.toJson()); + assertThat(redis.bytes).isEqualTo(newer.toJson().getBytes(StandardCharsets.UTF_8)); + verify(harness.reader(), times(1)).readCurrent(ACCOUNT_ID); + harness.store().close(); + } + + @Test + void sourceAdvanceAfterSuccessfulRedisReadbackReturnsSourceChangedWithObservation() + throws Exception { + AccountSourceSnapshot baseline = source(1L, 1L, 0L, null, 1L); + AccountSourceSnapshot advanced = source(2L, 2L, 1L, logoutEvent("2", "2", "1", null), 2L); + FakeRedis redis = new FakeRedis(); + Harness harness = harness(redis, baseline, advanced); + + RedisAccountGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisAccountGenerationProjectionStore.Outcome.SOURCE_CHANGED); + assertThat(result.snapshot()).isPresent(); + assertThat(result.snapshot().orElseThrow().json()) + .isEqualTo(AccountGenerationProjection.fromSource(baseline).toJson()); + assertThat(redis.bytes) + .isEqualTo( + AccountGenerationProjection.fromSource(baseline) + .toJson() + .getBytes(StandardCharsets.UTF_8)); + assertThat(redis.scriptCalls).isEqualTo(1); + verify(harness.reader(), times(2)).readCurrent(ACCOUNT_ID); + harness.store().close(); + } + + @Test + void malformedStoredProjectionIsQuarantined() throws Exception { + AccountSourceSnapshot baseline = source(1L, 1L, 0L, null, 1L); + FakeRedis redis = new FakeRedis("{\"unknown\":true}".getBytes(StandardCharsets.UTF_8)); + Harness harness = harness(redis, baseline); + + RedisAccountGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisAccountGenerationProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains("MALFORMED_STORED_PROJECTION"); + assertThat(redis.scriptCalls).isZero(); + harness.store().close(); + } + + @Test + void redisConnectionFailureRemainsVisibleToTheCaller() throws Exception { + AccountSourceSnapshot baseline = source(1L, 1L, 0L, null, 1L); + FakeRedis redis = new FakeRedis(); + redis.readFailure = new DataAccessResourceFailureException("Coordination Redis unavailable"); + Harness harness = harness(redis, baseline); + + assertThatThrownBy(() -> harness.store().refreshCurrent(ACCOUNT_ID)) + .isSameAs(redis.readFailure); + harness.store().close(); + } + + private static Harness harness(FakeRedis redis, AccountSourceSnapshot... sources) + throws Exception { + AccountAuthoritySourceReader reader = mock(AccountAuthoritySourceReader.class); + AtomicInteger sourceIndex = new AtomicInteger(); + doAnswer(ignored -> sources[Math.min(sourceIndex.getAndIncrement(), sources.length - 1)]) + .when(reader) + .readCurrent(ACCOUNT_ID); + + RedisConnection connection = mock(RedisConnection.class); + RedisStringCommands stringCommands = mock(RedisStringCommands.class); + RedisKeyCommands keyCommands = mock(RedisKeyCommands.class); + RedisScriptingCommands scriptingCommands = mock(RedisScriptingCommands.class); + org.mockito.Mockito.when(connection.stringCommands()).thenReturn(stringCommands); + org.mockito.Mockito.when(connection.keyCommands()).thenReturn(keyCommands); + org.mockito.Mockito.when(connection.scriptingCommands()).thenReturn(scriptingCommands); + org.mockito.Mockito.when(stringCommands.get(any(byte[].class))) + .thenAnswer( + ignored -> { + if (redis.readFailure != null) { + throw redis.readFailure; + } + return redis.bytes == null ? null : redis.bytes.clone(); + }); + org.mockito.Mockito.when(keyCommands.pTtl(any(byte[].class))) + .thenAnswer(ignored -> redis.ttlMillis); + org.mockito.Mockito.when(scriptingCommands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + + StringRedisTemplate template = mock(StringRedisTemplate.class); + doAnswer( + invocation -> { + RedisCallback callback = invocation.getArgument(0); + return callback.doInRedis(connection); + }) + .when(template) + .execute(any(RedisCallback.class)); + doAnswer( + invocation -> { + redis.scriptCalls++; + byte[][] keysAndArgs = (byte[][]) invocation.getRawArguments()[3]; + String mode = new String(keysAndArgs[1], StandardCharsets.US_ASCII); + String expected = new String(keysAndArgs[2], StandardCharsets.UTF_8); + String candidate = new String(keysAndArgs[3], StandardCharsets.UTF_8); + redis.lastMode = mode; + if (redis.forcedScriptResult != null) { + return redis.forcedScriptResult.getBytes(StandardCharsets.US_ASCII); + } + if (redis.bytes != null && redis.ttlMillis != -1L) { + return "TTL_PRESENT".getBytes(StandardCharsets.US_ASCII); + } + String current = + redis.bytes == null ? null : new String(redis.bytes, StandardCharsets.UTF_8); + if ("VERIFY".equals(mode)) { + return (expected.equals(current) ? "REPLAY" : "STALE") + .getBytes(StandardCharsets.US_ASCII); + } + if (candidate.equals(current)) { + return "REPLAY".getBytes(StandardCharsets.US_ASCII); + } + if ("ABSENT".equals(mode) ? current != null : !expected.equals(current)) { + return "STALE".getBytes(StandardCharsets.US_ASCII); + } + redis.bytes = candidate.getBytes(StandardCharsets.UTF_8); + if (redis.afterWriteBytes != null) { + redis.bytes = redis.afterWriteBytes.clone(); + } + return "APPLIED".getBytes(StandardCharsets.US_ASCII); + }) + .when(scriptingCommands) + .evalSha(any(String.class), eq(ReturnType.VALUE), eq(1), any(byte[][].class)); + + RedisAccountGenerationProjectionStore store = + newStore( + reader, + coordination("coordination.internal", 6379), + new RedisAccountGenerationProjectionStore.CacheRateLimitEndpoint( + "cache.internal", 6380)); + Field templateField = + RedisAccountGenerationProjectionStore.class.getDeclaredField("redisTemplate"); + templateField.setAccessible(true); + templateField.set(store, template); + return new Harness(store, reader, redis); + } + + private static RedisAccountGenerationProjectionStore newStore( + AccountAuthoritySourceReader reader, + RedisAccountGenerationProjectionStore.CoordinationEndpoint coordination, + RedisAccountGenerationProjectionStore.CacheRateLimitEndpoint cache) { + return new RedisAccountGenerationProjectionStore(reader, coordination, cache); + } + + private static RedisAccountGenerationProjectionStore.CoordinationEndpoint coordination( + String host, int port) { + return new RedisAccountGenerationProjectionStore.CoordinationEndpoint( + host, port, "account_coord_app", PASSWORD); + } + + private static RedisAccountGenerationProjectionStore.CacheRateLimitEndpoint cache() { + return new RedisAccountGenerationProjectionStore.CacheRateLimitEndpoint("cache.internal", 6380); + } + + private static String sha1(byte[] script) throws NoSuchAlgorithmException { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(script)); + } + + private static AccountSourceSnapshot source( + long generation, long sourceVersion, long sequence, Event event, long fenceValue) { + return new AccountSourceSnapshot( + ACCOUNT_ID, + new ScopeState( + AuthorityScope.account(ACCOUNT_ID), + generation, + sourceVersion, + new IssuanceFence(ACCOUNT_ID, fenceValue, fenceValue)), + STREAM_KEY, + sequence, + java.util.Optional.ofNullable(event)); + } + + private static Event logoutEvent( + String generation, String sourceVersion, String sequence, String requestId) { + String exactRequestId = requestId == null ? "11111111-1111-4111-8111-111111111111" : requestId; + var evidence = + AccountLogoutAllAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + AccountLogoutAllAuthorityEventV1Codec.EVENT_ID_PREFIX + exactRequestId), + Map.entry("requestId", exactRequestId), + Map.entry("accountId", ACCOUNT_TEXT), + Map.entry("sourceScope", "account/" + ACCOUNT_TEXT), + Map.entry("outboxStreamKey", STREAM_KEY), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", generation, + "outboxStreamKey", STREAM_KEY, + "outboxSequence", sequence)))); + return new Event( + STREAM_KEY, + exactRequestId, + Long.parseLong(sequence), + evidence.eventId(), + evidence.eventDigest(), + evidence.canonicalJsonUtf8()); + } + + private record Harness( + RedisAccountGenerationProjectionStore store, + AccountAuthoritySourceReader reader, + FakeRedis redis) {} + + private static final class FakeRedis { + private byte[] bytes; + private long ttlMillis = -1L; + private String forcedScriptResult; + private byte[] afterWriteBytes; + private RuntimeException readFailure; + private int scriptCalls; + private String lastMode; + + private FakeRedis() {} + + private FakeRedis(byte[] bytes) { + this.bytes = bytes.clone(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index decb435d0e..763bb76963 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -2582,17 +2582,14 @@ void encodeRuntimeMembershipCandidateRejectsNumericAndNoncanonicalUuidInputs() { @Test void encodeRuntimeMembershipCandidateRejectsIncompleteCheckpointOrSourceEvidence() { List completeCheckpoints = runtimeMembershipCheckpoints("1"); - RuntimeMembershipSnapshotDto missingCheckpoint = - runtimeMembershipSnapshot( - ACCOUNT_UUID, - true, - completeCheckpoints.subList(0, completeCheckpoints.size() - 1), - runtimeMembershipSourceEvidence()); assertThrows( IllegalArgumentException.class, () -> - AccountGrpcService.encodeRuntimeMembershipCandidate( - validRuntimeMembershipContext(), missingCheckpoint)); + runtimeMembershipSnapshot( + ACCOUNT_UUID, + true, + completeCheckpoints.subList(0, completeCheckpoints.size() - 1), + runtimeMembershipSourceEvidence())); assertThrows( IllegalArgumentException.class, () -> runtimeMembershipSnapshot(ACCOUNT_UUID, true, completeCheckpoints, List.of())); @@ -2651,30 +2648,48 @@ void runtimeOutboxSourceEvidenceRejectsChangedContentOrDigest() { assertThrows( IllegalArgumentException.class, () -> - new OutboxSourceEvidence( - event.outboxStreamKey(), - event.outboxSequence(), - event.eventId(), - event.eventDigest(), - changedContent)); + runtimeMembershipSnapshot( + ACCOUNT_UUID, + true, + runtimeMembershipCheckpoints("1"), + List.of( + new OutboxSourceEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + changedContent)), + event)); assertThrows( IllegalArgumentException.class, () -> - new OutboxSourceEvidence( - event.outboxStreamKey(), - event.outboxSequence(), - event.eventId(), - event.eventDigest(), - changedDigest)); + runtimeMembershipSnapshot( + ACCOUNT_UUID, + true, + runtimeMembershipCheckpoints("1"), + List.of( + new OutboxSourceEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + changedDigest)), + event)); assertThrows( IllegalArgumentException.class, () -> - new OutboxSourceEvidence( - event.outboxStreamKey(), - "2", - event.eventId(), - event.eventDigest(), - event.canonicalJson())); + runtimeMembershipSnapshot( + ACCOUNT_UUID, + true, + runtimeMembershipCheckpoints("1"), + List.of( + new OutboxSourceEvidence( + event.outboxStreamKey(), + "2", + event.eventId(), + event.eventDigest(), + event.canonicalJson())), + event)); } private static final class RecordingObserver implements StreamObserver { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountMembershipAuthorityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountMembershipAuthorityGrpcServiceTest.java new file mode 100644 index 0000000000..88dc438bef --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountMembershipAuthorityGrpcServiceTest.java @@ -0,0 +1,429 @@ +package net.firedevops.firemud.accountservice.service.impl; + +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +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 java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto.MembershipBaseline; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.Test; +import org.springframework.dao.TransientDataAccessResourceException; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountMembershipAuthorityGrpcServiceTest { + private static final String NAMESPACE = "firemud-test"; + private static final String GAME_SESSION_URI = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final String ACCOUNT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72001"; + private static final String TENANT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72002"; + private static final String REALM_UUID = "4c4b57d8-e3a2-48fe-9977-e7df0fdce901"; + private static final String PLAYABLE_NAMESPACE_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72005"; + private static final String GAME_INSTANCE_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72006"; + private static final GrpcPeerIdentity GAME_SESSION_PEER = + new GrpcPeerIdentity(GAME_SESSION_URI, NAMESPACE, "game-session-service"); + + @Test + void constructorRequiresProducerTransactionManagerAndValidatedNamespace() { + TestTransactionManager transactionManager = new TestTransactionManager(); + assertThatThrownBy( + () -> new AccountMembershipAuthorityGrpcService(null, transactionManager, NAMESPACE)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("producer"); + assertThatThrownBy( + () -> + new AccountMembershipAuthorityGrpcService( + mockProducer(), transactionManager, "Invalid_Namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + } + + @Test + void exactCertificateDerivedGameSessionPeerIsRequiredBeforeRequestValidationOrProducerAccess() { + AccountMembershipAuthorityEventProducer producer = mockProducer(); + AccountMembershipAuthorityGrpcService service = newService(producer); + GetTenantMembershipForRuntimeRequest malformed = + GetTenantMembershipForRuntimeRequest.getDefaultInstance(); + + List> rejected = + List.of( + invokeWithoutPeer(service, malformed), + invoke( + service, + malformed, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", + NAMESPACE, + "account-service")), + invoke( + service, + malformed, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other-namespace/sa/game-session-service", + "other-namespace", + "game-session-service"))); + + for (Outcome outcome : rejected) { + assertFailure(outcome, Status.Code.PERMISSION_DENIED); + } + verifyNoInteractions(producer); + } + + @Test + void malformedCrossboundAndUnknownRequestOrContextFieldsFailBeforeProducerAccess() { + AccountMembershipAuthorityEventProducer producer = mockProducer(); + AccountMembershipAuthorityGrpcService service = newService(producer); + GetTenantMembershipForRuntimeRequest valid = validRequest(); + PlayerExecutionContext context = valid.getPlayerContext(); + + List invalidRequests = + List.of( + GetTenantMembershipForRuntimeRequest.getDefaultInstance(), + valid.toBuilder() + .setUnknownFields( + unknownLengthDelimitedFields( + Map.of(1, ACCOUNT_UUID, 2, TENANT_UUID, 3, "crossbound-request"))) + .build(), + valid.toBuilder() + .setPlayerContext( + context.toBuilder().setUnknownFields(unknownVarintField(99, 1L)).build()) + .build(), + valid.toBuilder() + .setPlayerContext(context.toBuilder().setAccountId("10").build()) + .build(), + valid.toBuilder() + .setPlayerContext( + context.toBuilder() + .setAccountId("00000000-0000-0000-0000-000000000000") + .build()) + .build(), + valid.toBuilder() + .setPlayerContext( + context.toBuilder().setTenantId(TENANT_UUID.toUpperCase()).build()) + .build(), + valid.toBuilder() + .setPlayerContext(context.toBuilder().setRealmId("10").build()) + .build(), + valid.toBuilder() + .setPlayerContext( + context.toBuilder().setPlayableStateNamespaceId("numeric-namespace").build()) + .build(), + valid.toBuilder() + .setPlayerContext(context.toBuilder().setGameInstanceId("40").build()) + .build(), + valid.toBuilder() + .setPlayerContext(context.toBuilder().setPlayableStateScope("realm:10").build()) + .build(), + valid.toBuilder() + .setPlayerContext(context.toBuilder().setSessionId("01").build()) + .build(), + valid.toBuilder() + .setPlayerContext(context.toBuilder().setSessionId("0").build()) + .build(), + valid.toBuilder() + .setPlayerContext(context.toBuilder().setRequestId(" ").build()) + .build()); + + for (GetTenantMembershipForRuntimeRequest invalidRequest : invalidRequests) { + Outcome outcome = + invoke(service, invalidRequest, GAME_SESSION_PEER); + assertFailure(outcome, Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(producer); + } + + @Test + void validRequestReturnsExactCanonicalTargetAndRequestEchoesFromOneProducerRead() { + AccountMembershipAuthorityEventProducer producer = mockProducer(); + RuntimeMembershipSnapshotDto snapshot = neverJoinedSnapshot(); + when(producer.readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID))) + .thenReturn(snapshot); + AccountMembershipAuthorityGrpcService service = newService(producer); + + Outcome outcome = + invoke(service, validRequest(), GAME_SESSION_PEER); + + GetTenantMembershipForRuntimeResponse response = assertSuccess(outcome); + assertThat(response.getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getTenantId()).isEqualTo(TENANT_UUID); + assertThat(response.getRequestAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getRequestTenantId()).isEqualTo(TENANT_UUID); + assertThat(response.getRequestId()).isEqualTo("membership-read-1"); + assertThat(response.getAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(response.getMembershipExists()).isFalse(); + assertThat(response.getGameplayAdmissionAllowed()).isFalse(); + verify(producer) + .readRuntimeMembershipSnapshot(UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID)); + } + + @Test + void producerAndActualCandidateEncodingRunInsideWritableOwnerTransaction() { + AccountMembershipAuthorityEventProducer producer = mockProducer(); + TestTransactionManager transactionManager = new TestTransactionManager(); + RuntimeMembershipSnapshotDto snapshot = neverJoinedSnapshot(); + AtomicBoolean producerSawTransaction = new AtomicBoolean(); + AtomicBoolean encoderSawTransaction = new AtomicBoolean(); + when(producer.readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID))) + .thenAnswer( + invocation -> { + producerSawTransaction.set( + TransactionSynchronizationManager.isActualTransactionActive()); + return snapshot; + }); + AccountMembershipAuthorityGrpcService service = + new AccountMembershipAuthorityGrpcService( + producer, + transactionManager, + NAMESPACE, + (playerContext, candidate) -> { + encoderSawTransaction.set( + TransactionSynchronizationManager.isActualTransactionActive()); + return AccountGrpcService.encodeRuntimeMembershipCandidate(playerContext, candidate); + }); + + Outcome outcome = + invoke(service, validRequest(), GAME_SESSION_PEER); + + assertSuccess(outcome); + assertThat(producerSawTransaction).isTrue(); + assertThat(encoderSawTransaction).isTrue(); + assertThat(transactionManager.lastDefinition.isReadOnly()).isFalse(); + assertThat(transactionManager.lastDefinition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(outcome.observerSawActiveTransaction()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + @Test + void contradictoryOrUnavailableSourceAndFailedCommitNeverEmitResponse() { + AccountMembershipAuthorityEventProducer contradictoryProducer = mockProducer(); + when(contradictoryProducer.readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID))) + .thenThrow(new IllegalStateException("contradictory source internals")); + Outcome contradictory = + invoke(newService(contradictoryProducer), validRequest(), GAME_SESSION_PEER); + assertFailure(contradictory, Status.Code.FAILED_PRECONDITION); + assertThat(contradictory.error().getDescription()) + .doesNotContain("contradictory source internals"); + + AccountMembershipAuthorityEventProducer unavailableProducer = mockProducer(); + when(unavailableProducer.readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID))) + .thenThrow(new TransientDataAccessResourceException("database details")); + Outcome unavailable = + invoke(newService(unavailableProducer), validRequest(), GAME_SESSION_PEER); + assertFailure(unavailable, Status.Code.UNAVAILABLE); + assertThat(unavailable.error().getDescription()).doesNotContain("database details"); + + AccountMembershipAuthorityEventProducer commitProducer = mockProducer(); + when(commitProducer.readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID))) + .thenReturn(neverJoinedSnapshot()); + TestTransactionManager failedCommitManager = new TestTransactionManager(); + failedCommitManager.failCommit = true; + Outcome failedCommit = + invoke( + new AccountMembershipAuthorityGrpcService( + commitProducer, failedCommitManager, NAMESPACE), + validRequest(), + GAME_SESSION_PEER); + assertFailure(failedCommit, Status.Code.FAILED_PRECONDITION); + } + + private static AccountMembershipAuthorityGrpcService newService( + AccountMembershipAuthorityEventProducer producer) { + return new AccountMembershipAuthorityGrpcService( + producer, new TestTransactionManager(), NAMESPACE); + } + + private static AccountMembershipAuthorityEventProducer mockProducer() { + return mock(AccountMembershipAuthorityEventProducer.class); + } + + private static GetTenantMembershipForRuntimeRequest validRequest() { + return GetTenantMembershipForRuntimeRequest.newBuilder() + .setPlayerContext( + PlayerExecutionContext.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId(TENANT_UUID) + .setRealmId(REALM_UUID) + .setPlayableStateNamespaceId(PLAYABLE_NAMESPACE_UUID) + .setPlayableStateScope("SHARED") + .setGameInstanceId(GAME_INSTANCE_UUID) + .setSessionId("50") + .setRequestId("membership-read-1")) + .build(); + } + + private static RuntimeMembershipSnapshotDto neverJoinedSnapshot() { + String membershipStream = + "account:auth-authority:v1:membership/" + ACCOUNT_UUID + "/" + TENANT_UUID; + return new RuntimeMembershipSnapshotDto( + ACCOUNT_UUID, + TENANT_UUID, + ACCOUNT_UUID, + TENANT_UUID, + false, + false, + new MembershipBaseline("MISSING", Map.of(TENANT_UUID, "1"), "1"), + List.of(), + new AuthorityTuple( + "1", + "1", + Map.of(TENANT_UUID, "1"), + Map.of(TENANT_UUID, "1"), + List.of(), + Optional.empty(), + Optional.empty()), + "7", + Instant.parse("2026-09-27T00:00:00Z"), + List.of( + new OutboxCheckpointEntry("account:auth-authority:v1:account/" + ACCOUNT_UUID, "0"), + new OutboxCheckpointEntry( + "account:auth-authority:v1:issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER, "0"), + new OutboxCheckpointEntry(membershipStream, "0"), + new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + TENANT_UUID, "0")), + List.of(), + null); + } + + private static UnknownFieldSet unknownVarintField(int fieldNumber, long value) { + return UnknownFieldSet.newBuilder() + .addField(fieldNumber, UnknownFieldSet.Field.newBuilder().addVarint(value).build()) + .build(); + } + + private static UnknownFieldSet unknownLengthDelimitedFields(Map values) { + UnknownFieldSet.Builder fields = UnknownFieldSet.newBuilder(); + values.forEach( + (number, value) -> + fields.addField( + number, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited(ByteString.copyFromUtf8(value)) + .build())); + return fields.build(); + } + + private static Outcome invoke( + AccountMembershipAuthorityGrpcService service, + GetTenantMembershipForRuntimeRequest request, + GrpcPeerIdentity peerIdentity) { + Context peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peerIdentity); + Context previous = peerContext.attach(); + try { + RecordingObserver observer = new RecordingObserver<>(); + service.getTenantMembershipForRuntime(request, observer); + return observer.outcome(); + } finally { + peerContext.detach(previous); + } + } + + private static Outcome invokeWithoutPeer( + AccountMembershipAuthorityGrpcService service, GetTenantMembershipForRuntimeRequest request) { + RecordingObserver observer = new RecordingObserver<>(); + service.getTenantMembershipForRuntime(request, observer); + return observer.outcome(); + } + + private static T assertSuccess(Outcome outcome) { + assertThat(outcome.error()).isNull(); + assertThat(outcome.completed()).isTrue(); + assertThat(outcome.responses()).hasSize(1); + return outcome.responses().get(0); + } + + private static void assertFailure(Outcome outcome, Status.Code expectedCode) { + assertThat(outcome.error()).isNotNull(); + assertThat(outcome.error().getCode()).isEqualTo(expectedCode); + assertThat(outcome.responses()).isEmpty(); + assertThat(outcome.completed()).isFalse(); + } + + private record Outcome( + List responses, Status error, boolean completed, boolean observerSawActiveTransaction) {} + + private static final class RecordingObserver implements StreamObserver { + private final List responses = new ArrayList<>(); + private Status error; + private boolean completed; + private boolean observerSawActiveTransaction; + + @Override + public void onNext(T value) { + responses.add(value); + observerSawActiveTransaction = TransactionSynchronizationManager.isActualTransactionActive(); + } + + @Override + public void onError(Throwable throwable) { + error = Status.fromThrowable(throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + + private Outcome outcome() { + return new Outcome<>(List.copyOf(responses), error, completed, observerSawActiveTransaction); + } + } + + private static final class TestTransactionManager extends AbstractPlatformTransactionManager { + private TransactionDefinition lastDefinition; + private boolean failCommit; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected boolean isExistingTransaction(Object transaction) { + return false; + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + lastDefinition = definition; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + if (failCommit) { + throw new IllegalStateException("synthetic commit failure"); + } + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index f91b331098..2d5088adbf 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -75,6 +75,7 @@ import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipTransitionReceiptRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.OperationConflictException; @@ -131,6 +132,7 @@ class AccountServiceImplTest { @Mock private AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; @Mock private AccountAuthorityOutboxRepository accountAuthorityOutboxRepository; @Mock private AccountPasswordResetOperationRepository passwordResetOperationRepository; + @Mock private AccountLogoutAllOperationRepository logoutAllOperationRepository; @Mock private AccountAuditOutboxRepository accountAuditOutboxRepository; @Mock private AccountConnectScopeRepository accountConnectScopeRepository; @Mock private AccountJoinOperationRepository accountJoinOperationRepository; @@ -277,6 +279,7 @@ void setup() { accountAuthorityGenerationRepository, accountAuthorityOutboxRepository, passwordResetOperationRepository, + logoutAllOperationRepository, accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, @@ -3154,6 +3157,7 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { accountAuthorityGenerationRepository, accountAuthorityOutboxRepository, passwordResetOperationRepository, + logoutAllOperationRepository, accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, @@ -8120,8 +8124,13 @@ private PasswordResetRetryHarness preparePasswordResetRetry( when(passwordResetOperationRepository.findByTokenHash(tokenHash)) .thenAnswer(ignored -> Optional.ofNullable(receiptReadback.get())); + when(passwordResetOperationRepository.findByRequestId(requestId)) + .thenAnswer(ignored -> Optional.ofNullable(receiptReadback.get())); when(accountRepository.findByIdForUpdate(accountId)).thenReturn(Optional.of(account)); when(accountAuthorityGenerationRepository.read(scope)).thenReturn(committedAuthority); + when(accountAuthorityOutboxRepository.readCheckpoint(streamKey)) + .thenReturn( + Optional.of(new Checkpoint(streamKey, 1L, event.eventId(), event.eventDigest()))); when(accountAuthorityOutboxRepository.findEvent(streamKey, 1L)).thenReturn(Optional.of(event)); return new PasswordResetRetryHarness(account, receipt, receiptReadback); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java new file mode 100644 index 0000000000..a9234264b4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java @@ -0,0 +1,355 @@ +package net.firedevops.firemud.common.account.authority; + +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.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Strict codec for committed Account logout-all authority events. */ +public final class AccountLogoutAllAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-logout-all-event/v1"; + public static final String EVENT_TYPE = "LOGOUT_ALL_COMMITTED"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + public static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "accountId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "accountAuthorityGeneration", + "sourceVersion", + "accountSecurityCutoff"); + private static final Set WIRE_FIELDS; + private static final Set ACCOUNT_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); + wireFields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(wireFields); + } + + private AccountLogoutAllAuthorityEventV1Codec() {} + + /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */ + public static AccountLogoutAllAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "preimage must not be null"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event", "must be a JSON object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return toEvidence(wire, digest, canonicalJson(wire)); + } + + /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */ + public static AccountLogoutAllAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "wireJson must not be null"); + final JsonNode tree; + try { + // Canonicalization rejects duplicate JSON object properties before Jackson builds a tree. + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + private static AccountLogoutAllAuthorityEvent verifyWireNode(ObjectNode wire) { + requireExactFields(wire, WIRE_FIELDS, "event"); + String suppliedDigest = requireText(wire, "eventDigest", "event"); + if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + String expectedDigest = digest(preimage); + if (!MessageDigest.isEqual( + suppliedDigest.getBytes(StandardCharsets.US_ASCII), + expectedDigest.getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest", "does not match the canonical event preimage"); + } + return toEvidence(wire, suppliedDigest, canonicalJson(wire)); + } + + private static void validatePreimage(ObjectNode event) { + requireExactFields(event, PREIMAGE_FIELDS, "event preimage"); + requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event"); + requireExactText(event, "eventType", EVENT_TYPE, "event"); + + String requestId = requireUuid(event, "requestId", "event"); + requireExactText(event, "eventId", EVENT_ID_PREFIX + requestId, "event"); + String accountId = requireUuid(event, "accountId", "event"); + String sourceScope = "account/" + accountId; + String streamKey = EVENT_STREAM_PREFIX + sourceScope; + requireExactText(event, "sourceScope", sourceScope, "event"); + requireExactText(event, "outboxStreamKey", streamKey, "event"); + + String outboxSequence = requirePositiveDecimal(event, "outboxSequence", "event"); + String accountAuthorityGeneration = + requirePositiveDecimal(event, "accountAuthorityGeneration", "event"); + requirePositiveDecimal(event, "sourceVersion", "event"); + + JsonNode cutoffNode = event.get("accountSecurityCutoff"); + if (!(cutoffNode instanceof ObjectNode cutoff)) { + throw invalid("accountSecurityCutoff", "must be a required JSON object"); + } + requireExactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, "accountSecurityCutoff"); + String cutoffGeneration = + requirePositiveDecimal(cutoff, "accountAuthorityGeneration", "accountSecurityCutoff"); + String cutoffStream = requireText(cutoff, "outboxStreamKey", "accountSecurityCutoff"); + String cutoffSequence = + requirePositiveDecimal(cutoff, "outboxSequence", "accountSecurityCutoff"); + if (!accountAuthorityGeneration.equals(cutoffGeneration)) { + throw invalid( + "accountSecurityCutoff.accountAuthorityGeneration", + "must equal event.accountAuthorityGeneration"); + } + if (!streamKey.equals(cutoffStream)) { + throw invalid("accountSecurityCutoff.outboxStreamKey", "must equal event.outboxStreamKey"); + } + if (!outboxSequence.equals(cutoffSequence)) { + throw invalid("accountSecurityCutoff.outboxSequence", "must equal event.outboxSequence"); + } + } + + private static AccountLogoutAllAuthorityEvent toEvidence( + ObjectNode wire, String digest, String canonicalJson) { + ObjectNode cutoff = (ObjectNode) wire.get("accountSecurityCutoff"); + return new AccountLogoutAllAuthorityEvent( + wire.path("schemaVersion").textValue(), + wire.path("eventType").textValue(), + wire.path("eventId").textValue(), + wire.path("requestId").textValue(), + wire.path("accountId").textValue(), + wire.path("sourceScope").textValue(), + wire.path("outboxStreamKey").textValue(), + wire.path("outboxSequence").textValue(), + wire.path("accountAuthorityGeneration").textValue(), + wire.path("sourceVersion").textValue(), + new AccountSecurityCutoff( + cutoff.path("accountAuthorityGeneration").textValue(), + cutoff.path("outboxStreamKey").textValue(), + cutoff.path("outboxSequence").textValue()), + digest, + canonicalJson); + } + + private static void requireExactFields(ObjectNode object, Set required, String path) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(required)) { + Set missing = new java.util.HashSet<>(required); + missing.removeAll(actual); + Set unexpected = new java.util.HashSet<>(actual); + unexpected.removeAll(required); + StringBuilder message = new StringBuilder("must contain exactly the declared fields"); + if (!missing.isEmpty()) { + message.append("; missing ").append(missing); + } + if (!unexpected.isEmpty()) { + message.append("; unexpected ").append(unexpected); + } + throw invalid(path, message.toString()); + } + } + + private static String requireExactText( + ObjectNode object, String field, String expected, String path) { + String value = requireText(object, field, path); + if (!expected.equals(value)) { + throw invalid(path + "." + field, "must equal " + expected); + } + return value; + } + + private static String requireText(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(path + "." + field, "must be a required string"); + } + return value.textValue(); + } + + private static String requireUuid(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(path + "." + field, "must be a canonical lowercase non-nil UUID"); + } + return value; + } + + private static String requirePositiveDecimal(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!POSITIVE_DECIMAL_PATTERN.matcher(value).matches()) { + throw invalid(path + "." + field, "must be a positive canonical decimal string"); + } + return value; + } + + private static String digest(ObjectNode preimage) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString()); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical); + return "sha256:" + java.util.HexFormat.of().formatHex(hash); + } catch (IOException exception) { + throw new IllegalArgumentException("event preimage cannot be canonicalized", exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String canonicalJson(ObjectNode wire) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(wire.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + /** Immutable verified or producer-sealed logout-all event evidence. */ + public static final class AccountLogoutAllAuthorityEvent { + private final String schemaVersion; + private final String eventType; + private final String eventId; + private final String requestId; + private final String accountId; + private final String sourceScope; + private final String outboxStreamKey; + private final String outboxSequence; + private final String accountAuthorityGeneration; + private final String sourceVersion; + private final AccountSecurityCutoff accountSecurityCutoff; + private final String eventDigest; + private final String canonicalJson; + + private AccountLogoutAllAuthorityEvent( + String schemaVersion, + String eventType, + String eventId, + String requestId, + String accountId, + String sourceScope, + String outboxStreamKey, + String outboxSequence, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + String eventDigest, + String canonicalJson) { + this.schemaVersion = schemaVersion; + this.eventType = eventType; + this.eventId = eventId; + this.requestId = requestId; + this.accountId = accountId; + this.sourceScope = sourceScope; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.accountAuthorityGeneration = accountAuthorityGeneration; + this.sourceVersion = sourceVersion; + this.accountSecurityCutoff = accountSecurityCutoff; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return schemaVersion; + } + + public String eventType() { + return eventType; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return accountId; + } + + public String sourceScope() { + return sourceScope; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String accountAuthorityGeneration() { + return accountAuthorityGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public AccountSecurityCutoff accountSecurityCutoff() { + return accountSecurityCutoff; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a caller-owned copy of the canonical complete wire event bytes. */ + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } + + /** Immutable Account security cutoff checkpoint. */ + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {} +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java new file mode 100644 index 0000000000..c0f1e9a0ee --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java @@ -0,0 +1,663 @@ +package net.firedevops.firemud.common.account.authority; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +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.MembershipEvent; + +/** + * Validates the content and cross-binding of one current runtime membership evidence snapshot. + * + *

This does not authenticate the source or authorize gameplay admission. The membership event is + * immutable historical evidence; a caller supplies the separate current tuple, fence and + * checkpoints. Private-realm grant and tenant-billing tuple evidence are not supported by this + * candidate and are rejected until their source contracts are available. An empty result for a + * missing membership is only a local statement about the supplied snapshot, not proof that the + * account has never joined. + */ +public final class RuntimeMembershipAuthorityEvidenceValidator { + private static final String EVENT_STREAM_PREFIX = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]*)"); + private static final Set MEMBERSHIP_LIFECYCLES = Set.of("ACTIVE", "INACTIVE"); + + private RuntimeMembershipAuthorityEvidenceValidator() {} + + /** + * Verifies every supplied source event and binds the immutable membership event to the current + * recipient carrier. Returns empty only for a well-formed snapshot whose membership checkpoint is + * zero and whose current membership state is explicitly missing and nonadmitting. + * + * @throws IllegalArgumentException if the snapshot is malformed, incomplete, inconsistent, or + * contains unsupported authority evidence + */ + public static Optional validate(Snapshot evidence) { + Objects.requireNonNull(evidence, "evidence must not be null"); + + requireCanonicalUuid(evidence.accountId(), "accountId"); + requireCanonicalUuid(evidence.tenantId(), "tenantId"); + requireNonBlank(evidence.issuerId(), "issuerId"); + requirePositiveDecimal( + evidence.membershipAuthorityGeneration(), "membershipAuthorityGeneration"); + requirePositiveDecimal(evidence.issuanceFence(), "issuanceFence"); + requireExactTenantValue(evidence.membershipVersion(), evidence.tenantId(), "membershipVersion"); + + AuthorityTuple currentTuple = evidence.authorityTuple(); + requireTupleShape( + currentTuple, + evidence.accountId(), + evidence.tenantId(), + evidence.membershipAuthorityGeneration(), + "authorityTuple"); + + String issuerStream = EVENT_STREAM_PREFIX + "issuer/" + evidence.issuerId(); + String accountStream = EVENT_STREAM_PREFIX + "account/" + evidence.accountId(); + String tenantStream = EVENT_STREAM_PREFIX + "tenant/" + evidence.tenantId(); + String membershipStream = + EVENT_STREAM_PREFIX + "membership/" + evidence.accountId() + "/" + evidence.tenantId(); + List expectedStreams = + new ArrayList<>(List.of(issuerStream, accountStream, tenantStream, membershipStream)); + expectedStreams.sort(RuntimeMembershipAuthorityEvidenceValidator::compareUtf8); + + Map checkpoints = + validateCheckpoints(evidence.checkpoints(), expectedStreams); + Map sources = + validateSourceInventory(evidence.sourceEvidence(), checkpoints); + + verifyIssuerSource( + sources.get(issuerStream), + checkpoints.get(issuerStream), + evidence.issuerId(), + currentTuple.issuerAuthGeneration()); + AccountSource accountSource = + verifyAccountSource( + sources.get(accountStream), + checkpoints.get(accountStream), + evidence.accountId(), + currentTuple.accountAuthorityGeneration()); + verifyTenantSource( + sources.get(tenantStream), + checkpoints.get(tenantStream), + evidence.tenantId(), + currentTuple.tenantAuthorityGeneration().get(evidence.tenantId())); + + validateCurrentAccountCutoff( + currentTuple, accountSource, checkpoints.get(accountStream), accountStream); + + Checkpoint membershipCheckpoint = checkpoints.get(membershipStream); + if (membershipCheckpoint.outboxSequence().equals("0")) { + validateMissingMembership(evidence); + return Optional.empty(); + } + + MembershipEvent membershipEvent = + verifyMembershipSource( + sources.get(membershipStream), + membershipCheckpoint, + evidence.accountId(), + evidence.tenantId()); + validateMembershipCarrier(evidence, membershipEvent, currentTuple, accountSource); + + return Optional.of(membershipEvent); + } + + private static Map validateCheckpoints( + List supplied, List expectedStreams) { + if (supplied.size() != expectedStreams.size()) { + throw invalid("checkpoints", "must contain exactly the four authority streams"); + } + Map checkpoints = new HashMap<>(); + String previousStream = null; + for (Checkpoint checkpoint : supplied) { + if (!expectedStreams.contains(checkpoint.outboxStreamKey())) { + throw invalid("checkpoints", "contains an unexpected authority stream"); + } + if (previousStream != null + && compareUtf8(previousStream, checkpoint.outboxStreamKey()) >= 0) { + throw invalid("checkpoints", "must be sorted by stream key and contain no duplicates"); + } + if (checkpoints.putIfAbsent(checkpoint.outboxStreamKey(), checkpoint) != null) { + throw invalid("checkpoints", "contains a duplicate authority stream"); + } + requireNonNegativeDecimal(checkpoint.outboxSequence(), "checkpoint.outboxSequence"); + previousStream = checkpoint.outboxStreamKey(); + } + if (!checkpoints.keySet().equals(Set.copyOf(expectedStreams))) { + throw invalid("checkpoints", "must cover each expected authority stream exactly once"); + } + return Map.copyOf(checkpoints); + } + + private static Map validateSourceInventory( + List supplied, Map checkpoints) { + Map sources = new HashMap<>(); + String previousStream = null; + for (SourceEvidence source : supplied) { + if (previousStream != null && compareUtf8(previousStream, source.outboxStreamKey()) >= 0) { + throw invalid("sourceEvidence", "must be sorted by stream key and contain no duplicates"); + } + Checkpoint checkpoint = checkpoints.get(source.outboxStreamKey()); + if (checkpoint == null || checkpoint.outboxSequence().equals("0")) { + throw invalid("sourceEvidence", "contains evidence without a positive checkpoint"); + } + if (!checkpoint.outboxSequence().equals(source.outboxSequence())) { + throw invalid("sourceEvidence", "sequence must equal its exact current checkpoint"); + } + if (sources.putIfAbsent(source.outboxStreamKey(), source) != null) { + throw invalid("sourceEvidence", "contains a duplicate authority stream"); + } + previousStream = source.outboxStreamKey(); + } + + for (Checkpoint checkpoint : checkpoints.values()) { + boolean hasSource = sources.containsKey(checkpoint.outboxStreamKey()); + if (checkpoint.outboxSequence().equals("0") == hasSource) { + throw invalid( + "sourceEvidence", "must contain one source for each positive checkpoint only"); + } + } + return Map.copyOf(sources); + } + + private static void verifyIssuerSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedIssuerId, + String currentGeneration) { + if (checkpoint.outboxSequence().equals("0")) { + requireEquals("1", currentGeneration, "authorityTuple.issuerAuthGeneration baseline"); + return; + } + var event = IssuerGenerationAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + requireSourceIdentity( + supplied, + checkpoint, + event.eventId(), + event.eventDigest(), + event.canonicalJson(), + event.outboxSequence(), + event.outboxStreamKey()); + requireEquals(expectedIssuerId, event.issuerId(), "issuer source issuerId"); + requireEquals(currentGeneration, event.issuerAuthGeneration(), "current issuer generation"); + } + + private static void verifyTenantSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedTenantId, + String currentGeneration) { + if (checkpoint.outboxSequence().equals("0")) { + requireEquals("1", currentGeneration, "authorityTuple.tenantAuthorityGeneration baseline"); + return; + } + var event = TenantGenerationAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + requireSourceIdentity( + supplied, + checkpoint, + event.eventId(), + event.eventDigest(), + event.canonicalJson(), + event.outboxSequence(), + event.outboxStreamKey()); + requireEquals(expectedTenantId, event.tenantId(), "tenant source tenantId"); + requireEquals( + currentGeneration, event.tenantAuthorityGeneration(), "current tenant generation"); + } + + private static AccountSource verifyAccountSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedAccountId, + String currentGeneration) { + if (checkpoint.outboxSequence().equals("0")) { + requireEquals("1", currentGeneration, "authorityTuple.accountAuthorityGeneration baseline"); + return null; + } + + AccountSource event; + try { + var reset = PasswordResetAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + event = + new AccountSource( + reset.eventId(), + reset.eventDigest(), + reset.canonicalJson(), + reset.outboxStreamKey(), + reset.outboxSequence(), + reset.accountId(), + reset.accountAuthorityGeneration(), + reset.accountSecurityCutoff().accountAuthorityGeneration(), + reset.accountSecurityCutoff().outboxStreamKey(), + reset.accountSecurityCutoff().outboxSequence()); + } catch (IllegalArgumentException resetFailure) { + try { + var logout = AccountLogoutAllAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + event = + new AccountSource( + logout.eventId(), + logout.eventDigest(), + logout.canonicalJson(), + logout.outboxStreamKey(), + logout.outboxSequence(), + logout.accountId(), + logout.accountAuthorityGeneration(), + logout.accountSecurityCutoff().accountAuthorityGeneration(), + logout.accountSecurityCutoff().outboxStreamKey(), + logout.accountSecurityCutoff().outboxSequence()); + } catch (IllegalArgumentException logoutFailure) { + logoutFailure.addSuppressed(resetFailure); + throw invalid( + "account source", "must use the declared password-reset or logout-all schema"); + } + } + + requireSourceIdentity( + supplied, + checkpoint, + event.eventId(), + event.eventDigest(), + event.canonicalJson(), + event.outboxSequence(), + event.outboxStreamKey()); + requireEquals(expectedAccountId, event.accountId(), "account source accountId"); + requireEquals( + currentGeneration, event.accountAuthorityGeneration(), "current account generation"); + requireEquals( + event.accountAuthorityGeneration(), event.cutoffGeneration(), "account cutoff generation"); + requireEquals(event.outboxStreamKey(), event.cutoffStream(), "account cutoff stream key"); + requireEquals(event.outboxSequence(), event.cutoffSequence(), "account cutoff sequence"); + return event; + } + + private static MembershipEvent verifyMembershipSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedAccountId, + String expectedTenantId) { + MembershipEvent event = MembershipAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + requireSourceIdentity( + supplied, + checkpoint, + event.eventId(), + event.eventDigest(), + event.canonicalJson(), + event.outboxSequence(), + event.outboxStreamKey()); + requireEquals(expectedAccountId, event.accountId(), "membership source accountId"); + requireEquals(expectedTenantId, event.tenantId(), "membership source tenantId"); + return event; + } + + private static void requireSourceIdentity( + SourceEvidence supplied, + Checkpoint checkpoint, + String eventId, + String eventDigest, + String canonicalJson, + String eventSequence, + String eventStreamKey) { + requireEquals(checkpoint.outboxStreamKey(), eventStreamKey, "source event stream key"); + requireEquals( + checkpoint.outboxStreamKey(), supplied.outboxStreamKey(), "source carrier stream key"); + requireEquals( + checkpoint.outboxSequence(), supplied.outboxSequence(), "source carrier sequence"); + requireEquals(checkpoint.outboxSequence(), eventSequence, "source event sequence"); + requireEquals(eventId, supplied.eventId(), "source carrier eventId"); + requireEquals(eventDigest, supplied.eventDigest(), "source carrier eventDigest"); + requireEquals( + canonicalJson, supplied.canonicalEventJson(), "source carrier canonical event bytes"); + } + + private static void validateCurrentAccountCutoff( + AuthorityTuple tuple, + AccountSource source, + Checkpoint checkpoint, + String expectedAccountStream) { + Optional cutoff = tuple.accountSecurityCutoff(); + if (checkpoint.outboxSequence().equals("0")) { + if (cutoff.isPresent()) { + throw invalid( + "authorityTuple.accountSecurityCutoff", "must be absent at the account baseline"); + } + return; + } + if (cutoff.isEmpty() || source == null) { + throw invalid( + "authorityTuple.accountSecurityCutoff", "must bind the current account source event"); + } + AccountSecurityCutoff current = cutoff.orElseThrow(); + requireEquals( + tuple.accountAuthorityGeneration(), + current.accountAuthorityGeneration(), + "current account cutoff generation"); + requireEquals( + expectedAccountStream, current.outboxStreamKey(), "current account cutoff stream key"); + requireEquals( + checkpoint.outboxSequence(), current.outboxSequence(), "current account cutoff sequence"); + requireEquals( + source.cutoffGeneration(), + current.accountAuthorityGeneration(), + "current account cutoff source generation"); + requireEquals( + source.cutoffStream(), current.outboxStreamKey(), "current account cutoff source stream"); + requireEquals( + source.cutoffSequence(), + current.outboxSequence(), + "current account cutoff source sequence"); + } + + private static void validateMissingMembership(Snapshot evidence) { + if (evidence.membershipExists() + || !"MISSING".equals(evidence.membershipLifecycleState()) + || evidence.gameplayAdmissionAllowed() + || !evidence.roles().isEmpty()) { + throw invalid( + "membership", "zero checkpoint requires MISSING, absent, empty-role, nonadmitting state"); + } + // The absent-row representation still carries positive persisted defaults. This check is + // content validation only and cannot establish that a prior membership never existed. + requirePositiveDecimal( + evidence.membershipVersion().get(evidence.tenantId()), "membershipVersion"); + requirePositiveDecimal( + evidence.membershipAuthorityGeneration(), "membershipAuthorityGeneration"); + requirePositiveDecimal(evidence.issuanceFence(), "issuanceFence"); + } + + private static void validateMembershipCarrier( + Snapshot evidence, + MembershipEvent event, + AuthorityTuple currentTuple, + AccountSource currentAccountSource) { + if (!evidence.membershipExists()) { + throw invalid("membershipExists", "must be true for a positive membership checkpoint"); + } + if (!MEMBERSHIP_LIFECYCLES.contains(evidence.membershipLifecycleState())) { + throw invalid( + "membershipLifecycleState", "must be ACTIVE or INACTIVE for an existing membership"); + } + requireEquals( + event.membershipLifecycleState(), + evidence.membershipLifecycleState(), + "membershipLifecycleState"); + requireEquals( + event.gameplayAdmissionAllowed(), + evidence.gameplayAdmissionAllowed(), + "gameplayAdmissionAllowed"); + requireEquals(event.roles(), evidence.roles(), "roles"); + requireEquals(event.membershipVersion(), evidence.membershipVersion(), "membershipVersion"); + requireEquals( + event.membershipAuthorityGeneration(), + evidence.membershipAuthorityGeneration(), + "membershipAuthorityGeneration"); + requireEquals( + event.membershipAuthorityGeneration(), + currentTuple.membershipAuthorityGeneration().get(evidence.tenantId()), + "current membership authority generation"); + + AuthorityTuple eventTuple = event.authorityTuple(); + requireSupportedTupleExtensions(eventTuple, "membership source authorityTuple"); + requireAtMost( + eventTuple.issuerAuthGeneration(), + currentTuple.issuerAuthGeneration(), + "membership source issuerAuthGeneration"); + requireAtMost( + eventTuple.accountAuthorityGeneration(), + currentTuple.accountAuthorityGeneration(), + "membership source accountAuthorityGeneration"); + requireAtMost( + eventTuple.tenantAuthorityGeneration().get(evidence.tenantId()), + currentTuple.tenantAuthorityGeneration().get(evidence.tenantId()), + "membership source tenantAuthorityGeneration"); + requireAtMost( + event.issuanceFence(), evidence.issuanceFence(), "membership source issuanceFence"); + validateHistoricalAccountCutoff(eventTuple, currentTuple, currentAccountSource); + } + + private static void validateHistoricalAccountCutoff( + AuthorityTuple eventTuple, AuthorityTuple currentTuple, AccountSource currentAccountSource) { + Optional historicalCutoff = eventTuple.accountSecurityCutoff(); + Optional currentCutoff = currentTuple.accountSecurityCutoff(); + int accountGenerationOrder = + compareDecimal( + eventTuple.accountAuthorityGeneration(), currentTuple.accountAuthorityGeneration()); + if (accountGenerationOrder == 0) { + if (historicalCutoff.isPresent() != currentCutoff.isPresent()) { + throw invalid( + "membership source accountSecurityCutoff", + "must match cutoff presence at the same generation"); + } + if (historicalCutoff.isPresent() + && !historicalCutoff.orElseThrow().equals(currentCutoff.orElseThrow())) { + throw invalid( + "membership source accountSecurityCutoff", + "must equal the current cutoff at the same generation"); + } + } + if (historicalCutoff.isEmpty()) { + requireEquals( + "1", + eventTuple.accountAuthorityGeneration(), + "membership source accountAuthorityGeneration without a cutoff"); + return; + } + if (currentCutoff.isEmpty() || currentAccountSource == null) { + throw invalid( + "membership source accountSecurityCutoff", + "cannot exceed or outlive current account cutoff evidence"); + } + AccountSecurityCutoff historical = historicalCutoff.orElseThrow(); + AccountSecurityCutoff current = currentCutoff.orElseThrow(); + requireEquals( + current.outboxStreamKey(), + historical.outboxStreamKey(), + "historical account cutoff stream key"); + requireAtMost( + historical.accountAuthorityGeneration(), + current.accountAuthorityGeneration(), + "historical account cutoff generation"); + requireAtMost( + historical.outboxSequence(), + current.outboxSequence(), + "historical account cutoff sequence"); + } + + private static void requireTupleShape( + AuthorityTuple tuple, + String accountId, + String tenantId, + String membershipGeneration, + String path) { + requirePositiveDecimal(tuple.issuerAuthGeneration(), path + ".issuerAuthGeneration"); + requirePositiveDecimal( + tuple.accountAuthorityGeneration(), path + ".accountAuthorityGeneration"); + requireExactTenantValue( + tuple.tenantAuthorityGeneration(), tenantId, path + ".tenantAuthorityGeneration"); + requireExactTenantValue( + tuple.membershipAuthorityGeneration(), tenantId, path + ".membershipAuthorityGeneration"); + requireEquals( + membershipGeneration, + tuple.membershipAuthorityGeneration().get(tenantId), + path + ".membershipAuthorityGeneration"); + requireSupportedTupleExtensions(tuple, path); + tuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> { + requirePositiveDecimal( + cutoff.accountAuthorityGeneration(), + path + ".accountSecurityCutoff.accountAuthorityGeneration"); + requireEquals( + EVENT_STREAM_PREFIX + "account/" + accountId, + cutoff.outboxStreamKey(), + path + ".accountSecurityCutoff.outboxStreamKey"); + requirePositiveDecimal( + cutoff.outboxSequence(), path + ".accountSecurityCutoff.outboxSequence"); + requireEquals( + tuple.accountAuthorityGeneration(), + cutoff.accountAuthorityGeneration(), + path + ".accountSecurityCutoff.accountAuthorityGeneration"); + }); + } + + private static void requireSupportedTupleExtensions(AuthorityTuple tuple, String path) { + if (!tuple.privateRealmGrantVersions().isEmpty()) { + throw invalid(path + ".privateRealmGrantVersions", "is not supported by this candidate"); + } + if (tuple.tenantBillingCutoff().isPresent()) { + throw invalid(path + ".tenantBillingCutoff", "is not supported by this candidate"); + } + } + + private static void requireExactTenantValue( + Map values, String tenantId, String path) { + if (values.size() != 1 || !values.containsKey(tenantId)) { + throw invalid(path, "must contain exactly the current tenantId key"); + } + requirePositiveDecimal(values.get(tenantId), path + "." + tenantId); + } + + private static void requireCanonicalUuid(String value, String path) { + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(path, "must be a canonical lowercase non-nil UUID"); + } + } + + private static void requireNonBlank(String value, String path) { + if (value.isBlank()) { + throw invalid(path, "must be nonblank"); + } + } + + private static void requirePositiveDecimal(String value, String path) { + if (!POSITIVE_DECIMAL.matcher(value).matches()) { + throw invalid(path, "must be a positive canonical decimal string"); + } + } + + private static void requireNonNegativeDecimal(String value, String path) { + if (!NON_NEGATIVE_DECIMAL.matcher(value).matches()) { + throw invalid(path, "must be a non-negative canonical decimal string"); + } + } + + private static void requireAtMost(String lowerOrEqual, String upper, String path) { + requirePositiveDecimal(lowerOrEqual, path); + requirePositiveDecimal(upper, path + " current"); + if (compareDecimal(lowerOrEqual, upper) > 0) { + throw invalid(path, "must not be ahead of current authority"); + } + } + + private static int compareDecimal(String left, String right) { + return new BigInteger(left).compareTo(new BigInteger(right)); + } + + private static int compareUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int comparison = + Integer.compare( + Byte.toUnsignedInt(leftBytes[index]), Byte.toUnsignedInt(rightBytes[index])); + if (comparison != 0) { + return comparison; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static void requireEquals(Object expected, Object actual, String path) { + if (!Objects.equals(expected, actual)) { + throw invalid(path, "does not match its bound evidence"); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + private record AccountSource( + String eventId, + String eventDigest, + String canonicalJson, + String outboxStreamKey, + String outboxSequence, + String accountId, + String accountAuthorityGeneration, + String cutoffGeneration, + String cutoffStream, + String cutoffSequence) {} + + /** Immutable sequence checkpoint for one exact Account authority stream. */ + public record Checkpoint(String outboxStreamKey, String outboxSequence) { + public Checkpoint { + Objects.requireNonNull(outboxStreamKey, "outboxStreamKey must not be null"); + Objects.requireNonNull(outboxSequence, "outboxSequence must not be null"); + } + } + + /** Immutable source-event carrier bound to its exact stream and checkpoint. */ + public record SourceEvidence( + String outboxStreamKey, + String outboxSequence, + String eventId, + String eventDigest, + String canonicalEventJson) { + public SourceEvidence { + Objects.requireNonNull(outboxStreamKey, "outboxStreamKey must not be null"); + Objects.requireNonNull(outboxSequence, "outboxSequence must not be null"); + Objects.requireNonNull(eventId, "eventId must not be null"); + Objects.requireNonNull(eventDigest, "eventDigest must not be null"); + Objects.requireNonNull(canonicalEventJson, "canonicalEventJson must not be null"); + } + } + + /** Immutable current recipient carrier plus the exact source evidence it claims to summarize. */ + public record Snapshot( + String issuerId, + String accountId, + String tenantId, + boolean membershipExists, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + Map membershipVersion, + String membershipAuthorityGeneration, + List roles, + AuthorityTuple authorityTuple, + String issuanceFence, + List checkpoints, + List sourceEvidence) { + public Snapshot { + Objects.requireNonNull(issuerId, "issuerId must not be null"); + Objects.requireNonNull(accountId, "accountId must not be null"); + Objects.requireNonNull(tenantId, "tenantId must not be null"); + Objects.requireNonNull(membershipLifecycleState, "membershipLifecycleState must not be null"); + membershipVersion = + Map.copyOf( + Objects.requireNonNull(membershipVersion, "membershipVersion must not be null")); + Objects.requireNonNull( + membershipAuthorityGeneration, "membershipAuthorityGeneration must not be null"); + roles = List.copyOf(Objects.requireNonNull(roles, "roles must not be null")); + Objects.requireNonNull(authorityTuple, "authorityTuple must not be null"); + Objects.requireNonNull(issuanceFence, "issuanceFence must not be null"); + checkpoints = + List.copyOf(Objects.requireNonNull(checkpoints, "checkpoints must not be null")); + sourceEvidence = + List.copyOf(Objects.requireNonNull(sourceEvidence, "sourceEvidence must not be null")); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/TenantGenerationAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/TenantGenerationAuthorityEventV1Codec.java new file mode 100644 index 0000000000..05dc61645a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/TenantGenerationAuthorityEventV1Codec.java @@ -0,0 +1,323 @@ +package net.firedevops.firemud.common.account.authority; + +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.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Strict codec for committed Account tenant-generation authority events. */ +public final class TenantGenerationAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-tenant-generation-event/v1"; + public static final String EVENT_TYPE = "TENANT_GENERATION_ADVANCED"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + public static final String EVENT_ID_PREFIX = "account-tenant-generation-event-v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "tenantId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "tenantAuthorityGeneration", + "sourceVersion"); + private static final Set WIRE_FIELDS; + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); + wireFields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(wireFields); + } + + private TenantGenerationAuthorityEventV1Codec() {} + + /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */ + public static TenantGenerationAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "preimage must not be null"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event", "must be a JSON object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return toEvidence(wire, digest, canonicalJson(wire)); + } + + /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */ + public static TenantGenerationAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "wireJson must not be null"); + final JsonNode tree; + try { + // JCS parsing rejects duplicate JSON object properties before Jackson builds a tree. + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + /** Validates and verifies one wire event supplied as JSON-compatible map data. */ + public static TenantGenerationAuthorityEvent verify(Map wireEvent) { + Objects.requireNonNull(wireEvent, "wireEvent must not be null"); + JsonNode tree = JSON.valueToTree(wireEvent); + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + private static TenantGenerationAuthorityEvent verifyWireNode(ObjectNode wire) { + requireExactFields(wire, WIRE_FIELDS, "event"); + String suppliedDigest = requireText(wire, "eventDigest", "event"); + if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + String expectedDigest = digest(preimage); + if (!MessageDigest.isEqual( + suppliedDigest.getBytes(StandardCharsets.US_ASCII), + expectedDigest.getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest", "does not match the canonical event preimage"); + } + return toEvidence(wire, suppliedDigest, canonicalJson(wire)); + } + + private static void validatePreimage(ObjectNode event) { + requireExactFields(event, PREIMAGE_FIELDS, "event preimage"); + requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event"); + requireExactText(event, "eventType", EVENT_TYPE, "event"); + + String requestId = requireUuid(event, "requestId", "event"); + requireExactText(event, "eventId", EVENT_ID_PREFIX + requestId, "event"); + + String tenantId = requireUuid(event, "tenantId", "event"); + String sourceScope = "tenant/" + tenantId; + requireExactText(event, "sourceScope", sourceScope, "event"); + requireExactText(event, "outboxStreamKey", EVENT_STREAM_PREFIX + sourceScope, "event"); + + requirePositiveDecimal(event, "outboxSequence", "event"); + requirePositiveDecimal(event, "tenantAuthorityGeneration", "event"); + requirePositiveDecimal(event, "sourceVersion", "event"); + } + + private static TenantGenerationAuthorityEvent toEvidence( + ObjectNode wire, String digest, String canonicalJson) { + return new TenantGenerationAuthorityEvent( + wire.path("schemaVersion").textValue(), + wire.path("eventType").textValue(), + wire.path("eventId").textValue(), + wire.path("requestId").textValue(), + wire.path("tenantId").textValue(), + wire.path("sourceScope").textValue(), + wire.path("outboxStreamKey").textValue(), + wire.path("outboxSequence").textValue(), + wire.path("tenantAuthorityGeneration").textValue(), + wire.path("sourceVersion").textValue(), + digest, + canonicalJson); + } + + private static void requireExactFields(ObjectNode object, Set required, String path) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(required)) { + Set missing = new java.util.HashSet<>(required); + missing.removeAll(actual); + Set unexpected = new java.util.HashSet<>(actual); + unexpected.removeAll(required); + StringBuilder message = new StringBuilder("must contain exactly the declared fields"); + if (!missing.isEmpty()) { + message.append("; missing ").append(missing); + } + if (!unexpected.isEmpty()) { + message.append("; unexpected ").append(unexpected); + } + throw invalid(path, message.toString()); + } + } + + private static String requireExactText( + ObjectNode object, String field, String expected, String path) { + String value = requireText(object, field, path); + if (!expected.equals(value)) { + throw invalid(path + "." + field, "must equal " + expected); + } + return value; + } + + private static String requireText(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(path + "." + field, "must be a required string"); + } + return value.textValue(); + } + + private static String requireUuid(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(path + "." + field, "must be a canonical lowercase non-nil UUID"); + } + return value; + } + + private static String requirePositiveDecimal(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!POSITIVE_DECIMAL_PATTERN.matcher(value).matches()) { + throw invalid(path + "." + field, "must be a positive canonical decimal string"); + } + return value; + } + + private static String digest(ObjectNode preimage) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString()); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical); + return "sha256:" + java.util.HexFormat.of().formatHex(hash); + } catch (IOException exception) { + throw new IllegalArgumentException("event preimage cannot be canonicalized", exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String canonicalJson(ObjectNode wire) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(wire.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + /** Immutable verified or producer-sealed tenant-generation event evidence. */ + public static final class TenantGenerationAuthorityEvent { + private final String schemaVersion; + private final String eventType; + private final String eventId; + private final String requestId; + private final String tenantId; + private final String sourceScope; + private final String outboxStreamKey; + private final String outboxSequence; + private final String tenantAuthorityGeneration; + private final String sourceVersion; + private final String eventDigest; + private final String canonicalJson; + + private TenantGenerationAuthorityEvent( + String schemaVersion, + String eventType, + String eventId, + String requestId, + String tenantId, + String sourceScope, + String outboxStreamKey, + String outboxSequence, + String tenantAuthorityGeneration, + String sourceVersion, + String eventDigest, + String canonicalJson) { + this.schemaVersion = schemaVersion; + this.eventType = eventType; + this.eventId = eventId; + this.requestId = requestId; + this.tenantId = tenantId; + this.sourceScope = sourceScope; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.tenantAuthorityGeneration = tenantAuthorityGeneration; + this.sourceVersion = sourceVersion; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return schemaVersion; + } + + public String eventType() { + return eventType; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String tenantId() { + return tenantId; + } + + public String sourceScope() { + return sourceScope; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String tenantAuthorityGeneration() { + return tenantAuthorityGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a caller-owned copy of the canonical complete wire event bytes. */ + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } +} diff --git a/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json b/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json new file mode 100644 index 0000000000..fd7cbdb26b --- /dev/null +++ b/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json @@ -0,0 +1,150 @@ +{ + "schemaVersion": "account-auth-logout-all-event-vectors/v1", + "validEvents": [ + { + "name": "standard-account-logout-all-cutoff", + "expectedEventDigest": "sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"2\",\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"2\",\"outboxSequence\":\"1\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\"},\"eventDigest\":\"sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439\",\"eventId\":\"account-logout-all-event-v1:22222222-2222-4222-8222-222222222222\",\"eventType\":\"LOGOUT_ALL_COMMITTED\",\"outboxSequence\":\"1\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"schemaVersion\":\"account-auth-logout-all-event/v1\",\"sourceScope\":\"account/11111111-1111-4111-8111-111111111111\",\"sourceVersion\":\"2\"}", + "event": { + "schemaVersion": "account-auth-logout-all-event/v1", + "eventType": "LOGOUT_ALL_COMMITTED", + "eventId": "account-logout-all-event-v1:22222222-2222-4222-8222-222222222222", + "requestId": "22222222-2222-4222-8222-222222222222", + "accountId": "11111111-1111-4111-8111-111111111111", + "sourceScope": "account/11111111-1111-4111-8111-111111111111", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "1", + "accountAuthorityGeneration": "2", + "sourceVersion": "2", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "2", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "1" + }, + "eventDigest": "sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439" + } + }, + { + "name": "counters-above-javascript-safe-integer-and-signed-long", + "expectedEventDigest": "sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\"},\"eventDigest\":\"sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7\",\"eventId\":\"account-logout-all-event-v1:22222222-2222-4222-8222-222222222222\",\"eventType\":\"LOGOUT_ALL_COMMITTED\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"schemaVersion\":\"account-auth-logout-all-event/v1\",\"sourceScope\":\"account/11111111-1111-4111-8111-111111111111\",\"sourceVersion\":\"90071992547409931234567890123456789\"}", + "event": { + "schemaVersion": "account-auth-logout-all-event/v1", + "eventType": "LOGOUT_ALL_COMMITTED", + "eventId": "account-logout-all-event-v1:22222222-2222-4222-8222-222222222222", + "requestId": "22222222-2222-4222-8222-222222222222", + "accountId": "11111111-1111-4111-8111-111111111111", + "sourceScope": "account/11111111-1111-4111-8111-111111111111", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "18446744073709551616000000000000000001", + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "sourceVersion": "90071992547409931234567890123456789", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "18446744073709551616000000000000000001" + }, + "eventDigest": "sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7" + } + } + ], + "changedDeclaredFieldMutations": [ + { + "name": "request-and-derived-event-identities", + "changes": { + "requestId": "33333333-3333-4333-8333-333333333333", + "eventId": "account-logout-all-event-v1:33333333-3333-4333-8333-333333333333" + } + }, + { + "name": "account-identity-and-derived-scope", + "changes": { + "accountId": "44444444-4444-4444-8444-444444444444", + "sourceScope": "account/44444444-4444-4444-8444-444444444444", + "outboxStreamKey": "account:auth-authority:v1:account/44444444-4444-4444-8444-444444444444", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "2", + "outboxStreamKey": "account:auth-authority:v1:account/44444444-4444-4444-8444-444444444444", + "outboxSequence": "1" + } + } + }, + { + "name": "outbox-sequence-and-cutoff", + "changes": { + "outboxSequence": "3", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "2", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "3" + } + } + }, + { + "name": "account-authority-generation-and-cutoff", + "changes": { + "accountAuthorityGeneration": "4", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "4", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "1" + } + } + }, + {"name": "source-version", "changes": {"sourceVersion": "3"}} + ], + "canonicalReorderedPropertyOrder": [ + "sourceVersion", + "requestId", + "outboxSequence", + "outboxStreamKey", + "eventType", + "eventId", + "eventDigest", + "accountId", + "accountAuthorityGeneration", + "accountSecurityCutoff", + "schemaVersion", + "sourceScope" + ], + "invalidMutations": [ + {"name": "unsupported-schema", "op": "replace", "path": "/schemaVersion", "value": "account-auth-logout-all-event/v2"}, + {"name": "password-reset-schema-is-not-an-alias", "op": "replace", "path": "/schemaVersion", "value": "account-auth-password-reset-event/v1"}, + {"name": "unsupported-event-type", "op": "replace", "path": "/eventType", "value": "PASSWORD_RESET_COMMITTED"}, + {"name": "numeric-event-type", "op": "replace", "path": "/eventType", "value": 7}, + {"name": "missing-event-id", "op": "remove", "path": "/eventId"}, + {"name": "null-event-id", "op": "replace", "path": "/eventId", "value": null}, + {"name": "missing-request-id", "op": "remove", "path": "/requestId"}, + {"name": "nil-request-id", "op": "replace", "path": "/requestId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-request-id", "op": "replace", "path": "/requestId", "value": "22222222-2222-4222-8222-22222222222A"}, + {"name": "request-event-identity-mismatch", "op": "replace", "path": "/requestId", "value": "33333333-3333-4333-8333-333333333333"}, + {"name": "wrong-event-id-prefix", "op": "replace", "path": "/eventId", "value": "password-reset-event-v1:22222222-2222-4222-8222-222222222222"}, + {"name": "nil-account-id", "op": "replace", "path": "/accountId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-account-id", "op": "replace", "path": "/accountId", "value": "11111111-1111-4111-8111-11111111111A"}, + {"name": "numeric-account-id", "op": "replace", "path": "/accountId", "value": 111}, + {"name": "mismatched-source-scope", "op": "replace", "path": "/sourceScope", "value": "account/22222222-2222-4222-8222-222222222222"}, + {"name": "mismatched-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": "account:auth-authority:v1:account/22222222-2222-4222-8222-222222222222"}, + {"name": "numeric-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": 1}, + {"name": "zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "leading-zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "01"}, + {"name": "negative-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "-1"}, + {"name": "numeric-account-generation", "op": "replace", "path": "/accountAuthorityGeneration", "value": 2}, + {"name": "zero-source-version", "op": "replace", "path": "/sourceVersion", "value": "0"}, + {"name": "null-source-version", "op": "replace", "path": "/sourceVersion", "value": null}, + {"name": "null-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": null}, + {"name": "array-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": []}, + {"name": "missing-cutoff-sequence", "op": "remove", "path": "/accountSecurityCutoff/outboxSequence"}, + {"name": "extra-cutoff-field", "op": "add", "path": "/accountSecurityCutoff/issuanceFence", "value": "4"}, + {"name": "numeric-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": 2}, + {"name": "mismatched-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": "3"}, + {"name": "mismatched-cutoff-stream", "op": "replace", "path": "/accountSecurityCutoff/outboxStreamKey", "value": "account:auth-authority:v1:account/22222222-2222-4222-8222-222222222222"}, + {"name": "mismatched-cutoff-sequence", "op": "replace", "path": "/accountSecurityCutoff/outboxSequence", "value": "2"}, + {"name": "unknown-fence-field", "op": "add", "path": "/issuanceFence", "value": "9"}, + {"name": "forbidden-authority-tuple", "op": "add", "path": "/authorityTuple", "value": {}}, + {"name": "forbidden-presented-token-identity", "op": "add", "path": "/tokenHash", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "forbidden-recipient-tuple", "op": "add", "path": "/recipientAuthorityTuple", "value": {}}, + {"name": "missing-digest", "op": "remove", "path": "/eventDigest"}, + {"name": "malformed-digest", "op": "replace", "path": "/eventDigest", "value": "SHA256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "digest-mismatch", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +} diff --git a/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-tenant-generation-event-v1-vectors.json b/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-tenant-generation-event-v1-vectors.json new file mode 100644 index 0000000000..1e64ed8181 --- /dev/null +++ b/services/common-platform-core/src/main/resources/net/firedevops/firemud/common/account/authority/account-auth-tenant-generation-event-v1-vectors.json @@ -0,0 +1,169 @@ +{ + "schemaVersion": "account-auth-tenant-generation-event-vectors/v1", + "validEvents": [ + { + "name": "tenant-generation-advance", + "event": { + "schemaVersion": "account-auth-tenant-generation-event/v1", + "eventType": "TENANT_GENERATION_ADVANCED", + "eventId": "account-tenant-generation-event-v1:11111111-2222-4333-8444-555555555555", + "requestId": "11111111-2222-4333-8444-555555555555", + "tenantId": "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee", + "sourceScope": "tenant/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee", + "outboxStreamKey": "account:auth-authority:v1:tenant/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee", + "outboxSequence": "7", + "tenantAuthorityGeneration": "5", + "sourceVersion": "6", + "eventDigest": "sha256:b2045381c7e4106b9e07a4c2ab4b0ccb83dabe30bf37267e3a223117fa5ef8db" + }, + "expectedEventDigest": "sha256:b2045381c7e4106b9e07a4c2ab4b0ccb83dabe30bf37267e3a223117fa5ef8db", + "expectedCanonicalJson": "{\"eventDigest\":\"sha256:b2045381c7e4106b9e07a4c2ab4b0ccb83dabe30bf37267e3a223117fa5ef8db\",\"eventId\":\"account-tenant-generation-event-v1:11111111-2222-4333-8444-555555555555\",\"eventType\":\"TENANT_GENERATION_ADVANCED\",\"outboxSequence\":\"7\",\"outboxStreamKey\":\"account:auth-authority:v1:tenant/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\",\"requestId\":\"11111111-2222-4333-8444-555555555555\",\"schemaVersion\":\"account-auth-tenant-generation-event/v1\",\"sourceScope\":\"tenant/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\",\"sourceVersion\":\"6\",\"tenantAuthorityGeneration\":\"5\",\"tenantId\":\"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee\"}" + }, + { + "name": "arbitrary-precision-counters", + "event": { + "schemaVersion": "account-auth-tenant-generation-event/v1", + "eventType": "TENANT_GENERATION_ADVANCED", + "eventId": "account-tenant-generation-event-v1:22222222-3333-4444-8555-666666666666", + "requestId": "22222222-3333-4444-8555-666666666666", + "tenantId": "bbbbbbbb-cccc-4ddd-8eee-ffffffffffff", + "sourceScope": "tenant/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff", + "outboxStreamKey": "account:auth-authority:v1:tenant/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff", + "outboxSequence": "18446744073709551616000000000000000001", + "tenantAuthorityGeneration": "92233720368547758081234567890123456789", + "sourceVersion": "90071992547409931234567890123456789", + "eventDigest": "sha256:f4b19a099b5db15cb76888e65c35c9f10369e9191564c972bc289340ff4908a2" + }, + "expectedEventDigest": "sha256:f4b19a099b5db15cb76888e65c35c9f10369e9191564c972bc289340ff4908a2", + "expectedCanonicalJson": "{\"eventDigest\":\"sha256:f4b19a099b5db15cb76888e65c35c9f10369e9191564c972bc289340ff4908a2\",\"eventId\":\"account-tenant-generation-event-v1:22222222-3333-4444-8555-666666666666\",\"eventType\":\"TENANT_GENERATION_ADVANCED\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:tenant/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\",\"requestId\":\"22222222-3333-4444-8555-666666666666\",\"schemaVersion\":\"account-auth-tenant-generation-event/v1\",\"sourceScope\":\"tenant/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\",\"sourceVersion\":\"90071992547409931234567890123456789\",\"tenantAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"tenantId\":\"bbbbbbbb-cccc-4ddd-8eee-ffffffffffff\"}" + } + ], + "canonicalReorderedPropertyOrder": [ + "sourceVersion", + "sourceScope", + "schemaVersion", + "requestId", + "outboxStreamKey", + "outboxSequence", + "tenantId", + "tenantAuthorityGeneration", + "eventType", + "eventId", + "eventDigest" + ], + "changedDeclaredFieldMutations": [ + { + "name": "schema-version", + "sealValid": false, + "changes": {"schemaVersion": "account-auth-tenant-generation-event/v2"} + }, + { + "name": "event-type", + "sealValid": false, + "changes": {"eventType": "TENANT_GENERATION_RESET"} + }, + { + "name": "event-id-bound-to-request-id", + "sealValid": true, + "changes": { + "eventId": "account-tenant-generation-event-v1:22222222-3333-4444-8555-666666666666", + "requestId": "22222222-3333-4444-8555-666666666666" + } + }, + { + "name": "request-id-bound-to-event-id", + "sealValid": true, + "changes": { + "requestId": "22222222-3333-4444-8555-666666666666", + "eventId": "account-tenant-generation-event-v1:22222222-3333-4444-8555-666666666666" + } + }, + { + "name": "tenant-id-binds-source-scope-and-stream", + "sealValid": true, + "changes": { + "tenantId": "bbbbbbbb-cccc-4ddd-8eee-ffffffffffff", + "sourceScope": "tenant/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff", + "outboxStreamKey": "account:auth-authority:v1:tenant/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff" + } + }, + { + "name": "source-scope", + "sealValid": false, + "changes": {"sourceScope": "tenant/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff"} + }, + { + "name": "outbox-stream-key", + "sealValid": false, + "changes": {"outboxStreamKey": "account:auth-authority:v1:tenant/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff"} + }, + { + "name": "outbox-sequence", + "sealValid": true, + "changes": {"outboxSequence": "8"} + }, + { + "name": "tenant-authority-generation", + "sealValid": true, + "changes": {"tenantAuthorityGeneration": "6"} + }, + { + "name": "source-version", + "sealValid": true, + "changes": {"sourceVersion": "7"} + } + ], + "invalidMutations": [ + {"name": "missing-schema-version", "op": "remove", "path": "/schemaVersion"}, + {"name": "missing-event-type", "op": "remove", "path": "/eventType"}, + {"name": "missing-event-id", "op": "remove", "path": "/eventId"}, + {"name": "missing-request-id", "op": "remove", "path": "/requestId"}, + {"name": "missing-required-tenant-id", "op": "remove", "path": "/tenantId"}, + {"name": "missing-source-scope", "op": "remove", "path": "/sourceScope"}, + {"name": "missing-outbox-stream-key", "op": "remove", "path": "/outboxStreamKey"}, + {"name": "missing-outbox-sequence", "op": "remove", "path": "/outboxSequence"}, + {"name": "missing-tenant-authority-generation", "op": "remove", "path": "/tenantAuthorityGeneration"}, + {"name": "missing-source-version", "op": "remove", "path": "/sourceVersion"}, + {"name": "missing-event-digest", "op": "remove", "path": "/eventDigest"}, + {"name": "unknown-top-level-property", "op": "add", "path": "/unexpected", "value": true}, + {"name": "recipient-account-extra", "op": "add", "path": "/accountId", "value": "cccccccc-dddd-4eee-8fff-000000000000"}, + {"name": "recipient-authority-tuple-extra", "op": "add", "path": "/authorityTuple", "value": {}}, + {"name": "recipient-issuance-fence-extra", "op": "add", "path": "/issuanceFence", "value": "1"}, + {"name": "billing-cutoff-extra", "op": "add", "path": "/tenantBillingCutoff", "value": {}}, + {"name": "billing-sequence-extra", "op": "add", "path": "/tenantBillingSequence", "value": "1"}, + {"name": "null-schema-version", "op": "replace", "path": "/schemaVersion", "value": null}, + {"name": "null-event-type", "op": "replace", "path": "/eventType", "value": null}, + {"name": "null-event-id", "op": "replace", "path": "/eventId", "value": null}, + {"name": "null-request-id", "op": "replace", "path": "/requestId", "value": null}, + {"name": "null-tenant-id", "op": "replace", "path": "/tenantId", "value": null}, + {"name": "null-source-scope", "op": "replace", "path": "/sourceScope", "value": null}, + {"name": "null-outbox-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": null}, + {"name": "null-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": null}, + {"name": "null-generation", "op": "replace", "path": "/tenantAuthorityGeneration", "value": null}, + {"name": "null-source-version", "op": "replace", "path": "/sourceVersion", "value": null}, + {"name": "null-event-digest", "op": "replace", "path": "/eventDigest", "value": null}, + {"name": "numeric-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": 7}, + {"name": "numeric-generation", "op": "replace", "path": "/tenantAuthorityGeneration", "value": 5}, + {"name": "numeric-source-version", "op": "replace", "path": "/sourceVersion", "value": 6}, + {"name": "array-source-version", "op": "replace", "path": "/sourceVersion", "value": ["6"]}, + {"name": "wrong-schema-version", "op": "replace", "path": "/schemaVersion", "value": "account-auth-tenant-generation-event/v2"}, + {"name": "wrong-event-type", "op": "replace", "path": "/eventType", "value": "TENANT_BILLING_CUTOFF"}, + {"name": "empty-event-id", "op": "replace", "path": "/eventId", "value": ""}, + {"name": "event-id-not-derived-from-request", "op": "replace", "path": "/eventId", "value": "account-tenant-generation-event-v1:22222222-3333-4444-8555-666666666666"}, + {"name": "non-uuid-request-id", "op": "replace", "path": "/requestId", "value": "request-tenant-generation-001"}, + {"name": "uppercase-request-uuid", "op": "replace", "path": "/requestId", "value": "11111111-2222-4333-8444-55555555555A"}, + {"name": "nil-request-uuid", "op": "replace", "path": "/requestId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-tenant-uuid", "op": "replace", "path": "/tenantId", "value": "AAAAAAAA-BBBB-4CCC-8DDD-EEEEEEEEEEEE"}, + {"name": "nil-tenant-uuid", "op": "replace", "path": "/tenantId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "malformed-tenant-uuid", "op": "replace", "path": "/tenantId", "value": "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeee"}, + {"name": "mismatched-source-scope", "op": "replace", "path": "/sourceScope", "value": "tenant/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff"}, + {"name": "mismatched-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": "account:auth-authority:v1:tenant/bbbbbbbb-cccc-4ddd-8eee-ffffffffffff"}, + {"name": "zero-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "leading-zero-generation", "op": "replace", "path": "/tenantAuthorityGeneration", "value": "05"}, + {"name": "negative-source-version", "op": "replace", "path": "/sourceVersion", "value": "-1"}, + {"name": "decimal-sequence", "op": "replace", "path": "/outboxSequence", "value": "7.0"}, + {"name": "empty-generation", "op": "replace", "path": "/tenantAuthorityGeneration", "value": ""}, + {"name": "malformed-digest", "op": "replace", "path": "/eventDigest", "value": "SHA256:b2045381c7e4106b9e07a4c2ab4b0ccb83dabe30bf37267e3a223117fa5ef8db"}, + {"name": "changed-digest", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..ee5cb00e0f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java @@ -0,0 +1,197 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.core.type.TypeReference; +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.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class AccountLogoutAllAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/" + + "account-auth-logout-all-event-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (InputStream stream = + AccountLogoutAllAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void fixedVectorsVerifySealAndPreserveArbitraryPrecisionCounters() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-logout-all-event-vectors/v1"); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode wireEvent = vector.path("event"); + AccountLogoutAllAuthorityEvent verified = + AccountLogoutAllAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.eventDigest()).isEqualTo(wireEvent.path("eventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo( + vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + + ObjectNode preimage = (ObjectNode) wireEvent.deepCopy(); + preimage.remove("eventDigest"); + Map preimageMap = JSON.convertValue(preimage, new TypeReference<>() {}); + AccountLogoutAllAuthorityEvent sealed = + AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(sealed.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + AccountLogoutAllAuthorityEvent ordinary = + AccountLogoutAllAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(0).path("event").toString()); + assertThat(ordinary.accountId()).isEqualTo("11111111-1111-4111-8111-111111111111"); + assertThat(ordinary.requestId()).isEqualTo("22222222-2222-4222-8222-222222222222"); + assertThat(ordinary.eventId()) + .isEqualTo("account-logout-all-event-v1:22222222-2222-4222-8222-222222222222"); + assertThat(ordinary.accountSecurityCutoff().accountAuthorityGeneration()) + .isEqualTo(ordinary.accountAuthorityGeneration()); + assertThat(ordinary.accountSecurityCutoff().outboxStreamKey()) + .isEqualTo(ordinary.outboxStreamKey()); + assertThat(ordinary.accountSecurityCutoff().outboxSequence()) + .isEqualTo(ordinary.outboxSequence()); + + AccountLogoutAllAuthorityEvent large = + AccountLogoutAllAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(1).path("event").toString()); + assertThat(large.outboxSequence()).isEqualTo("18446744073709551616000000000000000001"); + assertThat(large.accountAuthorityGeneration()) + .isEqualTo("92233720368547758081234567890123456789"); + assertThat(large.sourceVersion()).isEqualTo("90071992547409931234567890123456789"); + } + + @Test + void everyMutableDeclaredSourceFieldChangesTheDigest() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + + for (JsonNode mutation : vectors.path("changedDeclaredFieldMutations")) { + ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); + JsonNode changes = mutation.path("changes"); + changes + .fieldNames() + .forEachRemaining(field -> changedWire.set(field, changes.get(field).deepCopy())); + ObjectNode changedPreimage = (ObjectNode) changedWire.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + + AccountLogoutAllAuthorityEvent sealed = + AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()) + .as(mutation.path("name").asText()) + .isNotEqualTo(originalDigest); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + } + + @Test + void canonicalPropertyReorderingPreservesTheFixedEvent() { + JsonNode vector = vectors.path("validEvents").get(0); + JsonNode event = vector.path("event"); + ObjectNode reordered = JSON.createObjectNode(); + for (JsonNode field : vectors.path("canonicalReorderedPropertyOrder")) { + String fieldName = field.asText(); + reordered.set(fieldName, event.path(fieldName).deepCopy()); + } + + AccountLogoutAllAuthorityEvent verified = + AccountLogoutAllAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + @Test + void malformedAndNoncanonicalVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + for (JsonNode mutation : vectors.path("invalidMutations")) { + ObjectNode changed = (ObjectNode) baseline.deepCopy(); + applyMutation(changed, mutation); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void duplicatePropertiesAndLegacySchemasAreRejected() { + assertThatThrownBy( + () -> + AccountLogoutAllAuthorityEventV1Codec.verify( + "{\"eventId\":\"first\",\"eventId\":\"second\"}")) + .isInstanceOf(IllegalArgumentException.class); + + ObjectNode passwordReset = + (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + passwordReset.put("schemaVersion", "account-auth-password-reset-event/v1"); + passwordReset.put("eventType", "PASSWORD_RESET_COMMITTED"); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(passwordReset.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("schemaVersion"); + + assertThatThrownBy( + () -> + AccountLogoutAllAuthorityEventV1Codec.verify( + "{\"schemaVersion\":\"account-auth-issuer-generation-event/v1\"," + + "\"eventType\":\"ISSUER_GENERATION_ADVANCED\"}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void parsedEvidenceAndReturnedBytesAreImmutable() { + JsonNode vector = vectors.path("validEvents").get(0); + AccountLogoutAllAuthorityEvent event = + AccountLogoutAllAuthorityEventV1Codec.verify(vector.path("event").toString()); + byte[] bytes = event.canonicalJsonUtf8(); + bytes[0] = (byte) 'x'; + + assertThat(event.canonicalJsonUtf8()) + .isEqualTo(vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(event.accountSecurityCutoff().accountAuthorityGeneration()) + .isEqualTo(event.accountAuthorityGeneration()); + } + + private static void applyMutation(ObjectNode root, JsonNode mutation) { + String[] path = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < path.length - 1; index++) { + parent = parent.path(path[index]); + } + if (!(parent instanceof ObjectNode object)) { + throw new IllegalArgumentException("Mutation parent must be an object: " + mutation); + } + String field = path[path.length - 1]; + switch (mutation.path("op").asText()) { + case "add", "replace" -> object.set(field, mutation.path("value").deepCopy()); + case "remove" -> object.remove(field); + default -> throw new IllegalArgumentException("Unsupported mutation operation: " + mutation); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java new file mode 100644 index 0000000000..003ea34277 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java @@ -0,0 +1,887 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +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.MembershipEvent; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import org.junit.jupiter.api.Test; + +class RuntimeMembershipAuthorityEvidenceValidatorTest { + private static final String ISSUER_ID = "issuer-main"; + private static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + private static final String TENANT_ID = "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f"; + private static final String STREAM_PREFIX = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + + @Test + void verifiesMembershipJoinThenUpstreamAdvancesWithoutRewritingItsHistoricalBytes() { + Fixture fixture = advancedFixture(false); + + Optional result = + RuntimeMembershipAuthorityEvidenceValidator.validate(fixture.snapshot()); + + assertThat(result).isPresent(); + assertThat(result.orElseThrow().canonicalJson()) + .isEqualTo(fixture.membershipEvent().canonicalJson()); + assertThat(result.orElseThrow().canonicalJson()) + .isEqualTo( + fixture.snapshot().sourceEvidence().stream() + .filter( + source -> + source + .outboxStreamKey() + .endsWith("membership/" + ACCOUNT_ID + "/" + TENANT_ID)) + .findFirst() + .orElseThrow() + .canonicalEventJson()); + assertThat(fixture.membershipEvent().authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(fixture.snapshot().authorityTuple().issuerAuthGeneration()) + .isEqualTo("9007199254740993"); + assertThat(fixture.membershipEvent().authorityTuple().accountAuthorityGeneration()) + .isEqualTo("1"); + assertThat(fixture.snapshot().authorityTuple().accountAuthorityGeneration()) + .isEqualTo("18446744073709551616000000000000000001"); + } + + @Test + void acceptsFixedCountersAndTheDeclaredLogoutAllAccountEvent() { + Fixture fixture = fixedFixture(true); + + Optional result = + RuntimeMembershipAuthorityEvidenceValidator.validate(fixture.snapshot()); + assertThat(result).isPresent(); + assertThat(result.orElseThrow().canonicalJson()) + .isEqualTo(fixture.membershipEvent().canonicalJson()); + } + + @Test + void acceptsAnExplicitMissingNonadmittingMembershipWithPositiveBaselineValues() { + Snapshot missing = missingSnapshot(); + + assertThat(RuntimeMembershipAuthorityEvidenceValidator.validate(missing)).isEmpty(); + } + + @Test + void rejectsMissingStateThatClaimsAdmissionOrMembership() { + Snapshot baseline = missingSnapshot(); + Snapshot falselyAdmitting = + new Snapshot( + baseline.issuerId(), + baseline.accountId(), + baseline.tenantId(), + true, + "MISSING", + true, + baseline.membershipVersion(), + baseline.membershipAuthorityGeneration(), + List.of("player"), + baseline.authorityTuple(), + baseline.issuanceFence(), + baseline.checkpoints(), + baseline.sourceEvidence()); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(falselyAdmitting)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("zero checkpoint"); + } + + @Test + void rejectsCarrierMembershipValuesThatDifferFromTheImmutableEvent() { + Snapshot baseline = advancedFixture(false).snapshot(); + Snapshot mismatched = + new Snapshot( + baseline.issuerId(), + baseline.accountId(), + baseline.tenantId(), + baseline.membershipExists(), + "INACTIVE", + false, + baseline.membershipVersion(), + baseline.membershipAuthorityGeneration(), + baseline.roles(), + baseline.authorityTuple(), + baseline.issuanceFence(), + baseline.checkpoints(), + baseline.sourceEvidence()); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(mismatched)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("membershipLifecycleState"); + } + + @Test + void rejectsWellFormedMembershipEventsWhoseUpstreamGenerationOrFenceLeadsCurrent() { + Snapshot baseline = advancedFixture(false).snapshot(); + AuthorityTuple current = baseline.authorityTuple(); + String memberGeneration = current.membershipAuthorityGeneration().get(TENANT_ID); + String accountStream = STREAM_PREFIX + "account/" + ACCOUNT_ID; + String accountSequence = current.accountSecurityCutoff().orElseThrow().outboxSequence(); + + List aheadEvents = + List.of( + resealedMembership( + baseline, + tuple( + increment(current.issuerAuthGeneration()), + current.accountAuthorityGeneration(), + current.tenantAuthorityGeneration().get(TENANT_ID), + memberGeneration, + current.accountSecurityCutoff()), + baseline.issuanceFence()), + resealedMembership( + baseline, + tuple( + current.issuerAuthGeneration(), + increment(current.accountAuthorityGeneration()), + current.tenantAuthorityGeneration().get(TENANT_ID), + memberGeneration, + Optional.of( + new AccountSecurityCutoff( + increment(current.accountAuthorityGeneration()), + accountStream, + accountSequence))), + baseline.issuanceFence()), + resealedMembership( + baseline, + tuple( + current.issuerAuthGeneration(), + current.accountAuthorityGeneration(), + increment(current.tenantAuthorityGeneration().get(TENANT_ID)), + memberGeneration, + current.accountSecurityCutoff()), + baseline.issuanceFence()), + resealedMembership(baseline, current, increment(baseline.issuanceFence()))); + + for (MembershipEvent aheadEvent : aheadEvents) { + // Each case is a valid, freshly sealed event. The validator must reject its authority + // relationship to the current carrier, not its schema or digest. + assertThat(MembershipAuthorityEventV1Codec.verify(aheadEvent.canonicalJson()).eventDigest()) + .isEqualTo(aheadEvent.eventDigest()); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + withMembershipEvent(baseline, aheadEvent))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not be ahead"); + } + } + + @Test + void rejectsPositiveCheckpointsWithoutTheirSourceAndWrongSourceCheckpointSequences() { + Snapshot baseline = advancedFixture(false).snapshot(); + List missingIssuer = new ArrayList<>(baseline.sourceEvidence()); + missingIssuer.remove(sourceFor(baseline, "issuer/" + ISSUER_ID)); + + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + withSources(baseline, missingIssuer))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one source for each positive checkpoint"); + + String membershipStream = STREAM_PREFIX + "membership/" + ACCOUNT_ID + "/" + TENANT_ID; + Checkpoint original = + baseline.checkpoints().stream() + .filter(checkpoint -> checkpoint.outboxStreamKey().equals(membershipStream)) + .findFirst() + .orElseThrow(); + Snapshot wrongSequence = + withCheckpointSequence(baseline, membershipStream, increment(original.outboxSequence())); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(wrongSequence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence must equal its exact current checkpoint"); + } + + @Test + void rejectsExtraTenantAuthorityInTheCurrentCarrier() { + Snapshot baseline = advancedFixture(false).snapshot(); + AuthorityTuple current = baseline.authorityTuple(); + AuthorityTuple withExtraTenant = + new AuthorityTuple( + current.issuerAuthGeneration(), + current.accountAuthorityGeneration(), + Map.of( + TENANT_ID, + current.tenantAuthorityGeneration().get(TENANT_ID), + "00000001-0000-0000-0000-000000000000", + "1"), + current.membershipAuthorityGeneration(), + current.privateRealmGrantVersions(), + current.accountSecurityCutoff(), + current.tenantBillingCutoff()); + + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + withTuple(baseline, withExtraTenant))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenantAuthorityGeneration") + .hasMessageContaining("exactly the current tenantId key"); + } + + @Test + void validatesPositiveUpstreamEvidenceBeforeReturningAnEmptyMissingMembership() { + Snapshot baseline = advancedFixture(false).snapshot(); + Snapshot missing = missingMembershipWithUpstream(baseline, false, List.of()); + + assertThat(RuntimeMembershipAuthorityEvidenceValidator.validate(missing)).isEmpty(); + + Snapshot falselyAdmitting = missingMembershipWithUpstream(baseline, true, List.of("player")); + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(falselyAdmitting)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("zero checkpoint"); + } + + @Test + void acceptsEqualAndNonRegressingHistoricalAccountCutoffsButRejectsASequenceAhead() { + Snapshot baseline = advancedFixture(false).snapshot(); + AuthorityTuple current = baseline.authorityTuple(); + String memberGeneration = current.membershipAuthorityGeneration().get(TENANT_ID); + String currentAccountGeneration = current.accountAuthorityGeneration(); + AccountSecurityCutoff currentCutoff = current.accountSecurityCutoff().orElseThrow(); + + MembershipEvent equalCutoffEvent = + resealedMembership(baseline, current, baseline.issuanceFence()); + assertThat( + RuntimeMembershipAuthorityEvidenceValidator.validate( + withMembershipEvent(baseline, equalCutoffEvent))) + .isPresent(); + + String historicalGeneration = decrement(currentAccountGeneration); + String historicalSequence = decrement(currentCutoff.outboxSequence()); + AuthorityTuple historicalTuple = + tuple( + current.issuerAuthGeneration(), + historicalGeneration, + current.tenantAuthorityGeneration().get(TENANT_ID), + memberGeneration, + Optional.of( + new AccountSecurityCutoff( + historicalGeneration, currentCutoff.outboxStreamKey(), historicalSequence))); + MembershipEvent historicalEvent = + resealedMembership(baseline, historicalTuple, decrement(baseline.issuanceFence())); + assertThat( + RuntimeMembershipAuthorityEvidenceValidator.validate( + withMembershipEvent(baseline, historicalEvent))) + .isPresent(); + + AuthorityTuple regressedGenerationButAdvancedSequence = + tuple( + current.issuerAuthGeneration(), + historicalGeneration, + current.tenantAuthorityGeneration().get(TENANT_ID), + memberGeneration, + Optional.of( + new AccountSecurityCutoff( + historicalGeneration, + currentCutoff.outboxStreamKey(), + increment(currentCutoff.outboxSequence())))); + MembershipEvent aheadCutoffEvent = + resealedMembership( + baseline, regressedGenerationButAdvancedSequence, decrement(baseline.issuanceFence())); + assertThat( + MembershipAuthorityEventV1Codec.verify(aheadCutoffEvent.canonicalJson()).eventDigest()) + .isEqualTo(aheadCutoffEvent.eventDigest()); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + withMembershipEvent(baseline, aheadCutoffEvent))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("historical account cutoff sequence") + .hasMessageContaining("must not be ahead"); + } + + @Test + void rejectsChangedSourceEventBytesAndCarrierDigest() { + Snapshot baseline = advancedFixture(false).snapshot(); + SourceEvidence issuerSource = sourceFor(baseline, "issuer/" + ISSUER_ID); + List changedSources = new ArrayList<>(baseline.sourceEvidence()); + int issuerIndex = changedSources.indexOf(issuerSource); + changedSources.set( + issuerIndex, + new SourceEvidence( + issuerSource.outboxStreamKey(), + issuerSource.outboxSequence(), + issuerSource.eventId(), + issuerSource.eventDigest(), + issuerSource.canonicalEventJson().replace("9007199254740993", "9007199254740994"))); + Snapshot changedEvent = withSources(baseline, changedSources); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(changedEvent)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + + changedSources.set( + issuerIndex, + new SourceEvidence( + issuerSource.outboxStreamKey(), + issuerSource.outboxSequence(), + issuerSource.eventId(), + "sha256:" + "0".repeat(64), + issuerSource.canonicalEventJson())); + Snapshot changedCarrier = withSources(baseline, changedSources); + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(changedCarrier)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + + @Test + void rejectsACurrentAccountCutoffThatDoesNotBindTheSuppliedSource() { + Snapshot baseline = advancedFixture(false).snapshot(); + AuthorityTuple tuple = baseline.authorityTuple(); + AccountSecurityCutoff original = tuple.accountSecurityCutoff().orElseThrow(); + AuthorityTuple wrongCutoff = + tuple( + tuple.issuerAuthGeneration(), + tuple.accountAuthorityGeneration(), + tuple.tenantAuthorityGeneration().get(TENANT_ID), + tuple.membershipAuthorityGeneration().get(TENANT_ID), + Optional.of( + new AccountSecurityCutoff( + original.accountAuthorityGeneration(), + original.outboxStreamKey(), + "18446744073709551616000000000000000002"))); + Snapshot mismatched = withTuple(baseline, wrongCutoff); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(mismatched)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("current account cutoff sequence"); + } + + @Test + void rejectsWrongScopeAndDuplicateSourceEvidence() { + Snapshot baseline = advancedFixture(false).snapshot(); + var wrongIssuerEvent = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "issuer-event-wrong-scope"), + Map.entry("requestId", "issuer-request-wrong-scope"), + Map.entry("issuerId", "another-issuer"), + Map.entry("sourceScope", "issuer/another-issuer"), + Map.entry("outboxStreamKey", STREAM_PREFIX + "issuer/another-issuer"), + Map.entry("outboxSequence", "9007199254740995"), + Map.entry("issuerAuthGeneration", "9007199254740993"), + Map.entry("sourceVersion", "2"))); + SourceEvidence expectedIssuer = sourceFor(baseline, "issuer/" + ISSUER_ID); + List wrongScopeSources = new ArrayList<>(baseline.sourceEvidence()); + wrongScopeSources.set( + wrongScopeSources.indexOf(expectedIssuer), + new SourceEvidence( + expectedIssuer.outboxStreamKey(), + expectedIssuer.outboxSequence(), + wrongIssuerEvent.eventId(), + wrongIssuerEvent.eventDigest(), + wrongIssuerEvent.canonicalJson())); + Snapshot wrongScope = withSources(baseline, wrongScopeSources); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(wrongScope)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source event stream key"); + + List duplicateSources = new ArrayList<>(baseline.sourceEvidence()); + duplicateSources.add(0, duplicateSources.get(0)); + Snapshot duplicate = withSources(baseline, duplicateSources); + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(duplicate)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sourceEvidence"); + } + + private static Fixture advancedFixture(boolean logoutAll) { + String issuerGeneration = "9007199254740993"; + String accountGeneration = "18446744073709551616000000000000000001"; + String tenantGeneration = "340282366920938463463374607431768211457"; + String membershipGeneration = "12"; + String issuerSequence = "9007199254740995"; + String accountSequence = "18446744073709551616000000000000000003"; + String tenantSequence = "340282366920938463463374607431768211459"; + String membershipSequence = "9007199254740997"; + String membershipVersion = "9007199254740999"; + + AuthorityTuple joinTuple = tuple("1", "1", "1", membershipGeneration, Optional.empty()); + MembershipEvent joined = + membershipEvent( + membershipSequence, + membershipVersion, + membershipGeneration, + "9007199254740996", + joinTuple, + "ACTIVE", + List.of("player"), + true); + + var issuer = issuerEvent(issuerSequence, issuerGeneration); + var tenant = tenantEvent(tenantSequence, tenantGeneration); + AccountSourceFixture account = accountEvent(accountSequence, accountGeneration, logoutAll); + AuthorityTuple currentTuple = + tuple( + issuerGeneration, + accountGeneration, + tenantGeneration, + membershipGeneration, + Optional.of( + new AccountSecurityCutoff( + accountGeneration, STREAM_PREFIX + "account/" + ACCOUNT_ID, accountSequence))); + + List sources = + sortedSources(List.of(source(issuer), account.evidence(), source(tenant), source(joined))); + Snapshot snapshot = + snapshot( + true, + "ACTIVE", + true, + Map.of(TENANT_ID, membershipVersion), + membershipGeneration, + List.of("player"), + currentTuple, + "9007199254741000", + Map.of( + STREAM_PREFIX + "issuer/" + ISSUER_ID, issuerSequence, + STREAM_PREFIX + "account/" + ACCOUNT_ID, accountSequence, + STREAM_PREFIX + "tenant/" + TENANT_ID, tenantSequence, + STREAM_PREFIX + "membership/" + ACCOUNT_ID + "/" + TENANT_ID, membershipSequence), + sources); + return new Fixture(snapshot, joined); + } + + private static Fixture fixedFixture(boolean logoutAll) { + AuthorityTuple eventTuple = tuple("1", "1", "1", "2", Optional.empty()); + MembershipEvent member = + membershipEvent("1", "1", "2", "1", eventTuple, "ACTIVE", List.of("player"), true); + var issuer = issuerEvent("1", "2"); + var tenant = tenantEvent("1", "2"); + AccountSourceFixture account = accountEvent("1", "2", logoutAll); + AuthorityTuple currentTuple = + tuple( + "2", + "2", + "2", + "2", + Optional.of( + new AccountSecurityCutoff("2", STREAM_PREFIX + "account/" + ACCOUNT_ID, "1"))); + Snapshot snapshot = + snapshot( + true, + "ACTIVE", + true, + Map.of(TENANT_ID, "1"), + "2", + List.of("player"), + currentTuple, + "2", + Map.of( + STREAM_PREFIX + "issuer/" + ISSUER_ID, "1", + STREAM_PREFIX + "account/" + ACCOUNT_ID, "1", + STREAM_PREFIX + "tenant/" + TENANT_ID, "1", + STREAM_PREFIX + "membership/" + ACCOUNT_ID + "/" + TENANT_ID, "1"), + sortedSources( + List.of(source(issuer), account.evidence(), source(tenant), source(member)))); + return new Fixture(snapshot, member); + } + + private static Snapshot missingSnapshot() { + return snapshot( + false, + "MISSING", + false, + Map.of(TENANT_ID, "1"), + "1", + List.of(), + tuple("1", "1", "1", "1", Optional.empty()), + "1", + Map.of( + STREAM_PREFIX + "issuer/" + ISSUER_ID, "0", + STREAM_PREFIX + "account/" + ACCOUNT_ID, "0", + STREAM_PREFIX + "tenant/" + TENANT_ID, "0", + STREAM_PREFIX + "membership/" + ACCOUNT_ID + "/" + TENANT_ID, "0"), + List.of()); + } + + private static Snapshot missingMembershipWithUpstream( + Snapshot baseline, boolean admission, List roles) { + String membershipStream = + STREAM_PREFIX + "membership/" + baseline.accountId() + "/" + baseline.tenantId(); + List checkpoints = + baseline.checkpoints().stream() + .map( + checkpoint -> + checkpoint.outboxStreamKey().equals(membershipStream) + ? new Checkpoint(membershipStream, "0") + : checkpoint) + .toList(); + List upstreamSources = + baseline.sourceEvidence().stream() + .filter(source -> !source.outboxStreamKey().equals(membershipStream)) + .toList(); + return new Snapshot( + baseline.issuerId(), + baseline.accountId(), + baseline.tenantId(), + false, + "MISSING", + admission, + Map.of(baseline.tenantId(), "1"), + baseline.membershipAuthorityGeneration(), + roles, + baseline.authorityTuple(), + baseline.issuanceFence(), + checkpoints, + upstreamSources); + } + + private static Snapshot withCheckpointSequence( + Snapshot snapshot, String streamKey, String sequence) { + List checkpoints = + snapshot.checkpoints().stream() + .map( + checkpoint -> + checkpoint.outboxStreamKey().equals(streamKey) + ? new Checkpoint(streamKey, sequence) + : checkpoint) + .toList(); + return new Snapshot( + snapshot.issuerId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.membershipExists(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.roles(), + snapshot.authorityTuple(), + snapshot.issuanceFence(), + checkpoints, + snapshot.sourceEvidence()); + } + + private static Snapshot withMembershipEvent(Snapshot snapshot, MembershipEvent event) { + List sources = new ArrayList<>(snapshot.sourceEvidence()); + SourceEvidence original = + sourceFor(snapshot, "membership/" + snapshot.accountId() + "/" + snapshot.tenantId()); + sources.set(sources.indexOf(original), source(event)); + return withSources(snapshot, sortedSources(sources)); + } + + private static MembershipEvent resealedMembership( + Snapshot snapshot, AuthorityTuple tuple, String issuanceFence) { + SourceEvidence original = + sourceFor(snapshot, "membership/" + snapshot.accountId() + "/" + snapshot.tenantId()); + return membershipEvent( + original.outboxSequence(), + snapshot.membershipVersion().get(snapshot.tenantId()), + snapshot.membershipAuthorityGeneration(), + issuanceFence, + tuple, + snapshot.membershipLifecycleState(), + snapshot.roles(), + snapshot.gameplayAdmissionAllowed()); + } + + private static String increment(String decimal) { + return new BigInteger(decimal).add(BigInteger.ONE).toString(); + } + + private static String decrement(String decimal) { + return new BigInteger(decimal).subtract(BigInteger.ONE).toString(); + } + + private static Snapshot snapshot( + boolean membershipExists, + String lifecycle, + boolean admission, + Map membershipVersion, + String membershipGeneration, + List roles, + AuthorityTuple tuple, + String issuanceFence, + Map checkpointSequences, + List sources) { + List checkpoints = + checkpointSequences.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(entry -> new Checkpoint(entry.getKey(), entry.getValue())) + .toList(); + return new Snapshot( + ISSUER_ID, + ACCOUNT_ID, + TENANT_ID, + membershipExists, + lifecycle, + admission, + membershipVersion, + membershipGeneration, + roles, + tuple, + issuanceFence, + checkpoints, + sources); + } + + private static AuthorityTuple tuple( + String issuerGeneration, + String accountGeneration, + String tenantGeneration, + String membershipGeneration, + Optional cutoff) { + return new AuthorityTuple( + issuerGeneration, + accountGeneration, + Map.of(TENANT_ID, tenantGeneration), + Map.of(TENANT_ID, membershipGeneration), + List.of(), + cutoff, + Optional.empty()); + } + + private static MembershipEvent membershipEvent( + String sequence, + String version, + String membershipGeneration, + String issuanceFence, + AuthorityTuple tuple, + String lifecycle, + List roles, + boolean admission) { + String scope = "membership/" + ACCOUNT_ID + "/" + TENANT_ID; + Map preimage = new HashMap<>(); + preimage.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + preimage.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + preimage.put("eventId", "membership-event-" + sequence); + preimage.put("requestId", "membership-request-" + sequence); + preimage.put("outboxStreamKey", STREAM_PREFIX + scope); + preimage.put("outboxSequence", sequence); + preimage.put("sourceScope", scope); + preimage.put("accountId", ACCOUNT_ID); + preimage.put("tenantId", TENANT_ID); + preimage.put("membershipExists", true); + preimage.put("membershipLifecycleState", lifecycle); + preimage.put("membershipVersion", Map.of(TENANT_ID, version)); + preimage.put("membershipAuthorityGeneration", membershipGeneration); + preimage.put("authorityTuple", tupleWire(tuple)); + preimage.put("issuanceFence", issuanceFence); + preimage.put("roles", roles); + preimage.put("gameplayAdmissionAllowed", admission); + preimage.put("callerBoundAuthorityInvalidated", true); + return MembershipAuthorityEventV1Codec.seal(preimage); + } + + private static Map tupleWire(AuthorityTuple tuple) { + Map wire = new HashMap<>(); + wire.put("issuerAuthGeneration", tuple.issuerAuthGeneration()); + wire.put("accountAuthorityGeneration", tuple.accountAuthorityGeneration()); + wire.put("tenantAuthorityGeneration", tuple.tenantAuthorityGeneration()); + wire.put("membershipAuthorityGeneration", tuple.membershipAuthorityGeneration()); + wire.put("privateRealmGrantVersions", tuple.privateRealmGrantVersions()); + tuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> + wire.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); + return wire; + } + + private static IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent issuerEvent( + String sequence, String generation) { + String scope = "issuer/" + ISSUER_ID; + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + "issuer-event-" + sequence, + "requestId", + "issuer-request-" + sequence, + "issuerId", + ISSUER_ID, + "sourceScope", + scope, + "outboxStreamKey", + STREAM_PREFIX + scope, + "outboxSequence", + sequence, + "issuerAuthGeneration", + generation, + "sourceVersion", + "2")); + } + + private static TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent tenantEvent( + String sequence, String generation) { + String requestId = "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a"; + String scope = "tenant/" + TENANT_ID; + return TenantGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + TenantGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + TenantGenerationAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId, + "requestId", + requestId, + "tenantId", + TENANT_ID, + "sourceScope", + scope, + "outboxStreamKey", + STREAM_PREFIX + scope, + "outboxSequence", + sequence, + "tenantAuthorityGeneration", + generation, + "sourceVersion", + "2")); + } + + private static AccountSourceFixture accountEvent( + String sequence, String generation, boolean logoutAll) { + String stream = STREAM_PREFIX + "account/" + ACCOUNT_ID; + String requestId = + logoutAll ? "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a" : "reset-request-" + sequence; + Map preimage = new HashMap<>(); + preimage.put( + "schemaVersion", + logoutAll + ? AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION + : PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION); + preimage.put( + "eventType", + logoutAll + ? AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE + : PasswordResetAuthorityEventV1Codec.EVENT_TYPE); + preimage.put( + "eventId", + logoutAll + ? AccountLogoutAllAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId + : "password-reset-event-" + sequence); + preimage.put("requestId", requestId); + preimage.put("accountId", ACCOUNT_ID); + preimage.put("sourceScope", "account/" + ACCOUNT_ID); + preimage.put("outboxStreamKey", stream); + preimage.put("outboxSequence", sequence); + preimage.put("accountAuthorityGeneration", generation); + preimage.put("sourceVersion", "2"); + preimage.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", generation, + "outboxStreamKey", stream, + "outboxSequence", sequence)); + String canonical; + String eventId; + String digest; + if (logoutAll) { + var event = AccountLogoutAllAuthorityEventV1Codec.seal(preimage); + canonical = event.canonicalJson(); + eventId = event.eventId(); + digest = event.eventDigest(); + } else { + var event = PasswordResetAuthorityEventV1Codec.seal(preimage); + canonical = event.canonicalJson(); + eventId = event.eventId(); + digest = event.eventDigest(); + } + return new AccountSourceFixture( + new SourceEvidence(stream, sequence, eventId, digest, canonical)); + } + + private static SourceEvidence source( + IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent event) { + return new SourceEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.canonicalJson()); + } + + private static SourceEvidence source( + TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent event) { + return new SourceEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.canonicalJson()); + } + + private static SourceEvidence source(MembershipEvent event) { + return new SourceEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.canonicalJson()); + } + + private static List sortedSources(List sources) { + return sources.stream().sorted(Comparator.comparing(SourceEvidence::outboxStreamKey)).toList(); + } + + private static SourceEvidence sourceFor(Snapshot snapshot, String scope) { + String expected = STREAM_PREFIX + scope; + return snapshot.sourceEvidence().stream() + .filter(source -> source.outboxStreamKey().equals(expected)) + .findFirst() + .orElseThrow(); + } + + private static Snapshot withSources(Snapshot snapshot, List sources) { + return new Snapshot( + snapshot.issuerId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.membershipExists(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.roles(), + snapshot.authorityTuple(), + snapshot.issuanceFence(), + snapshot.checkpoints(), + sources); + } + + private static Snapshot withTuple(Snapshot snapshot, AuthorityTuple tuple) { + return new Snapshot( + snapshot.issuerId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.membershipExists(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.roles(), + tuple, + snapshot.issuanceFence(), + snapshot.checkpoints(), + snapshot.sourceEvidence()); + } + + private record AccountSourceFixture(SourceEvidence evidence) {} + + private record Fixture(Snapshot snapshot, MembershipEvent membershipEvent) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/TenantGenerationAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/TenantGenerationAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..ed9c7be5c3 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/TenantGenerationAuthorityEventV1CodecTest.java @@ -0,0 +1,211 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.core.type.TypeReference; +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.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class TenantGenerationAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/account-auth-tenant-generation-event-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (InputStream stream = + TenantGenerationAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void fixedVectorsVerifySealAndArbitraryPrecisionCounters() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-tenant-generation-event-vectors/v1"); + + for (JsonNode vector : vectors.path("validEvents")) { + JsonNode wireEvent = vector.path("event"); + TenantGenerationAuthorityEvent verified = + TenantGenerationAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.eventDigest()).isEqualTo(wireEvent.path("eventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo( + vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + + Map wireMap = JSON.convertValue(wireEvent, new TypeReference<>() {}); + assertThat(TenantGenerationAuthorityEventV1Codec.verify(wireMap).canonicalJson()) + .isEqualTo(vector.path("expectedCanonicalJson").asText()); + + ObjectNode preimage = (ObjectNode) wireEvent.deepCopy(); + preimage.remove("eventDigest"); + Map preimageMap = JSON.convertValue(preimage, new TypeReference<>() {}); + TenantGenerationAuthorityEvent sealed = + TenantGenerationAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(sealed.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + TenantGenerationAuthorityEvent baseline = + TenantGenerationAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(0).path("event").toString()); + assertThat(baseline.schemaVersion()).isEqualTo("account-auth-tenant-generation-event/v1"); + assertThat(baseline.eventType()).isEqualTo("TENANT_GENERATION_ADVANCED"); + assertThat(baseline.eventId()) + .isEqualTo("account-tenant-generation-event-v1:11111111-2222-4333-8444-555555555555"); + assertThat(baseline.requestId()).isEqualTo("11111111-2222-4333-8444-555555555555"); + assertThat(baseline.tenantId()).isEqualTo("aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"); + assertThat(baseline.sourceScope()).isEqualTo("tenant/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"); + assertThat(baseline.outboxStreamKey()) + .isEqualTo("account:auth-authority:v1:tenant/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"); + assertThat(baseline.outboxSequence()).isEqualTo("7"); + assertThat(baseline.tenantAuthorityGeneration()).isEqualTo("5"); + assertThat(baseline.sourceVersion()).isEqualTo("6"); + + TenantGenerationAuthorityEvent large = + TenantGenerationAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(1).path("event").toString()); + assertThat(large.outboxSequence()).isEqualTo("18446744073709551616000000000000000001"); + assertThat(large.tenantAuthorityGeneration()) + .isEqualTo("92233720368547758081234567890123456789"); + assertThat(large.sourceVersion()).isEqualTo("90071992547409931234567890123456789"); + } + + @Test + void changingEveryDeclaredPreimageFieldCannotReuseTheOriginalDigest() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + + for (JsonNode mutation : vectors.path("changedDeclaredFieldMutations")) { + ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); + JsonNode changes = mutation.path("changes"); + changes + .fieldNames() + .forEachRemaining(field -> changedWire.set(field, changes.get(field).deepCopy())); + ObjectNode changedPreimage = (ObjectNode) changedWire.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + + if (mutation.path("sealValid").asBoolean()) { + TenantGenerationAuthorityEvent sealed = + TenantGenerationAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()) + .as(mutation.path("name").asText()) + .isNotEqualTo(originalDigest); + assertThatThrownBy( + () -> TenantGenerationAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } else { + assertThatThrownBy(() -> TenantGenerationAuthorityEventV1Codec.seal(preimageMap)) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> TenantGenerationAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + } + + @Test + void canonicalPropertyReorderingPreservesTheFixedCanonicalEvent() { + JsonNode vector = vectors.path("validEvents").get(0); + JsonNode event = vector.path("event"); + ObjectNode reordered = JSON.createObjectNode(); + for (JsonNode field : vectors.path("canonicalReorderedPropertyOrder")) { + String fieldName = field.asText(); + reordered.set(fieldName, event.path(fieldName).deepCopy()); + } + + TenantGenerationAuthorityEvent verified = + TenantGenerationAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + @Test + void malformedAndNoncanonicalVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + for (JsonNode mutation : vectors.path("invalidMutations")) { + ObjectNode changed = (ObjectNode) baseline.deepCopy(); + applyMutation(changed, mutation); + assertThatThrownBy(() -> TenantGenerationAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void duplicatePropertiesAreRejectedBeforeShapeValidation() { + assertThatThrownBy( + () -> + TenantGenerationAuthorityEventV1Codec.verify( + "{\"requestId\":\"11111111-2222-4333-8444-555555555555\"," + + "\"requestId\":\"22222222-3333-4444-8555-666666666666\"}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void malformedNonObjectAndTrailingJsonAreRejected() { + assertThatThrownBy(() -> TenantGenerationAuthorityEventV1Codec.verify("{")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TenantGenerationAuthorityEventV1Codec.verify("[]")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + TenantGenerationAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(0).path("event").toString() + " true")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void parsedEvidenceIsImmutableAndCanonicalBytesAreCallerOwned() { + JsonNode vector = vectors.path("validEvents").get(0); + TenantGenerationAuthorityEvent event = + TenantGenerationAuthorityEventV1Codec.verify(vector.path("event").toString()); + byte[] bytes = event.canonicalJsonUtf8(); + bytes[0] = (byte) 'x'; + + assertThat(event.canonicalJsonUtf8()) + .isEqualTo(vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(event.tenantAuthorityGeneration()).isEqualTo("5"); + } + + private static void applyMutation(ObjectNode root, JsonNode mutation) { + String[] path = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < path.length - 1; index++) { + parent = parent.path(path[index]); + } + if (!(parent instanceof ObjectNode object)) { + throw new IllegalArgumentException("Mutation parent must be an object: " + mutation); + } + String field = path[path.length - 1]; + switch (mutation.path("op").asText()) { + case "add", "replace" -> object.set(field, mutation.path("value").deepCopy()); + case "remove" -> object.remove(field); + default -> throw new IllegalArgumentException("Unsupported mutation operation: " + mutation); + } + } +} diff --git a/services/common-redis-contracts/build.gradle.kts b/services/common-redis-contracts/build.gradle.kts new file mode 100644 index 0000000000..f6727627a1 --- /dev/null +++ b/services/common-redis-contracts/build.gradle.kts @@ -0,0 +1,3 @@ +plugins { + `java-library` +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java new file mode 100644 index 0000000000..588fa2e818 --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistry.java @@ -0,0 +1,284 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** Validates owner declarations and prepares immutable invocation contracts. */ +public final class RedisContractRegistry { + + private static final int REDIS_CLUSTER_SLOT_COUNT = 16384; + private final Map descriptorsById; + + public RedisContractRegistry( + Collection prefixDeclarations, + Collection descriptors) { + Objects.requireNonNull(prefixDeclarations, "prefixDeclarations are required"); + Objects.requireNonNull(descriptors, "descriptors are required"); + if (prefixDeclarations.isEmpty()) { + throw new IllegalArgumentException("at least one owner prefix declaration is required"); + } + + Map byPrefix = new HashMap<>(); + List declarations = new ArrayList<>(prefixDeclarations); + Set uniqueDeclarations = new HashSet<>(); + for (PrefixDeclaration declaration : declarations) { + Objects.requireNonNull(declaration, "prefix declaration is required"); + if (!uniqueDeclarations.add(declaration)) { + throw new IllegalArgumentException( + "duplicate owner prefix declaration: " + declaration.prefix()); + } + PrefixDeclaration existing = byPrefix.putIfAbsent(declaration.prefix(), declaration); + if (existing != null) { + throw new IllegalArgumentException( + "conflicting owner prefix declarations: " + declaration.prefix()); + } + } + rejectOverlappingOwnership(declarations); + + Map byId = new HashMap<>(); + Set resourcePaths = new HashSet<>(); + for (RedisScriptDescriptor descriptor : descriptors) { + Objects.requireNonNull(descriptor, "script descriptor is required"); + if (byId.putIfAbsent(descriptor.scriptId(), descriptor) != null) { + throw new IllegalArgumentException("duplicate script identifier: " + descriptor.scriptId()); + } + if (!resourcePaths.add(descriptor.resourcePath())) { + throw new IllegalArgumentException( + "duplicate script resource path: " + descriptor.resourcePath()); + } + validateDeclaredOwnership(descriptor, byPrefix); + } + + this.descriptorsById = Map.copyOf(byId); + } + + /** + * Validates all supplied invocation metadata before returning a handle. The returned handle is + * declarative only; this registry does not load or execute Redis scripts. + */ + public RedisInvocationContract prepareInvocation(InvocationRequest request) { + Objects.requireNonNull(request, "invocation request is required"); + RedisScriptDescriptor descriptor = descriptorsById.get(request.scriptId()); + if (descriptor == null) { + throw new IllegalArgumentException("unregistered script identifier: " + request.scriptId()); + } + + requireEquals(descriptor.resourcePath(), request.resourcePath(), "script resource path"); + requireEquals(descriptor.sha256(), request.sha256(), "script SHA-256 digest"); + requireEquals(descriptor.owner(), request.owner(), "script owner"); + requireEquals(descriptor.principal(), request.principal(), "Redis principal"); + requireEquals(descriptor.role(), request.role(), "Redis role"); + + if (request.keys().size() != descriptor.keys().size()) { + throw new IllegalArgumentException( + "KEYS arity mismatch: expected " + + descriptor.keys().size() + + ", got " + + request.keys().size()); + } + if (request.arguments().size() != descriptor.arguments().size()) { + throw new IllegalArgumentException( + "ARGV arity mismatch: expected " + + descriptor.arguments().size() + + ", got " + + request.arguments().size()); + } + + Integer commonSlot = null; + String commonTag = null; + for (int index = 0; index < descriptor.keys().size(); index++) { + RedisScriptDescriptor.KeySpec keySpec = descriptor.keys().get(index); + String key = request.keys().get(index); + if (key.isEmpty() + || containsControlCharacter(key) + || !key.startsWith(keySpec.ownedPrefix())) { + throw new IllegalArgumentException( + "KEYS[" + index + "] does not match its declared owner prefix"); + } + + if (keySpec.hashTagDeclaration() == RedisScriptDescriptor.HashTagDeclaration.REQUIRED) { + String tag = extractHashTag(key); + if (tag == null) { + throw new IllegalArgumentException( + "KEYS[" + index + "] is missing a non-empty Redis hash tag"); + } + int slot = clusterSlot(key); + if (commonTag != null && !commonTag.equals(tag)) { + throw new IllegalArgumentException("multi-key invocation uses different Redis hash tags"); + } + if (commonSlot != null && commonSlot != slot) { + throw new IllegalArgumentException("multi-key invocation crosses Redis Cluster slots"); + } + commonTag = tag; + commonSlot = slot; + } + } + + return new RedisInvocationContract(descriptor, request.keys(), request.arguments(), commonSlot); + } + + /** Returns the Redis Cluster slot for a key using the first non-empty {@code {...}} tag. */ + public static int clusterSlot(String key) { + Objects.requireNonNull(key, "key is required"); + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + int openingBrace = -1; + int closingBrace = -1; + for (int index = 0; index < keyBytes.length; index++) { + if (keyBytes[index] == '{') { + openingBrace = index; + break; + } + } + if (openingBrace >= 0) { + for (int index = openingBrace + 1; index < keyBytes.length; index++) { + if (keyBytes[index] == '}') { + closingBrace = index; + break; + } + } + } + + byte[] hashInput = keyBytes; + int offset = 0; + int length = keyBytes.length; + if (openingBrace >= 0 && closingBrace > openingBrace + 1) { + offset = openingBrace + 1; + length = closingBrace - openingBrace - 1; + } + int crc = crc16(hashInput, offset, length); + return crc % REDIS_CLUSTER_SLOT_COUNT; + } + + private static void rejectOverlappingOwnership(List declarations) { + for (int leftIndex = 0; leftIndex < declarations.size(); leftIndex++) { + PrefixDeclaration left = declarations.get(leftIndex); + for (int rightIndex = leftIndex + 1; rightIndex < declarations.size(); rightIndex++) { + PrefixDeclaration right = declarations.get(rightIndex); + boolean overlaps = + left.prefix().startsWith(right.prefix()) || right.prefix().startsWith(left.prefix()); + boolean samePrincipalScope = + left.owner().equals(right.owner()) + && left.role() == right.role() + && left.principal().equals(right.principal()); + if (overlaps && !samePrincipalScope) { + throw new IllegalArgumentException( + "overlapping Redis prefixes have conflicting ownership: " + + left.prefix() + + " and " + + right.prefix()); + } + } + } + } + + private static void validateDeclaredOwnership( + RedisScriptDescriptor descriptor, Map prefixDeclarations) { + for (RedisScriptDescriptor.KeySpec key : descriptor.keys()) { + PrefixDeclaration declaration = prefixDeclarations.get(key.ownedPrefix()); + if (declaration == null) { + throw new IllegalArgumentException( + "script " + + descriptor.scriptId() + + " references an unowned prefix: " + + key.ownedPrefix()); + } + if (!declaration.owner().equals(descriptor.owner()) + || declaration.role() != descriptor.role() + || !declaration.principal().equals(descriptor.principal())) { + throw new IllegalArgumentException( + "script " + descriptor.scriptId() + " has a wrong owner, principal, or Redis role"); + } + } + } + + private static String extractHashTag(String key) { + int openingBrace = key.indexOf('{'); + if (openingBrace < 0) { + return null; + } + int closingBrace = key.indexOf('}', openingBrace + 1); + int nestedOpeningBrace = key.indexOf('{', openingBrace + 1); + if (closingBrace <= openingBrace + 1 + || (nestedOpeningBrace >= 0 && nestedOpeningBrace < closingBrace)) { + return null; + } + return key.substring(openingBrace + 1, closingBrace); + } + + private static int crc16(byte[] bytes, int offset, int length) { + int crc = 0; + for (int index = offset; index < offset + length; index++) { + crc ^= (bytes[index] & 0xff) << 8; + for (int bit = 0; bit < 8; bit++) { + crc = (crc & 0x8000) == 0 ? crc << 1 : (crc << 1) ^ 0x1021; + } + crc &= 0xffff; + } + return crc; + } + + private static boolean containsControlCharacter(String value) { + return value.chars().anyMatch(Character::isISOControl); + } + + private static void requireEquals(Object expected, Object actual, String fieldName) { + if (!Objects.equals(expected, actual)) { + throw new IllegalArgumentException( + "invocation " + fieldName + " does not match its registration"); + } + } + + public record PrefixDeclaration( + String owner, RedisScriptDescriptor.RedisRole role, String principal, String prefix) { + public PrefixDeclaration { + Objects.requireNonNull(role, "prefix Redis role is required"); + if (owner == null || !owner.matches("[a-z][a-z0-9-]*")) { + throw new IllegalArgumentException("prefix owner must be a lowercase service identifier"); + } + if (principal == null || !principal.matches("[a-z][a-z0-9_]*")) { + throw new IllegalArgumentException("prefix principal must be a lowercase Redis principal"); + } + if (prefix == null || !prefix.matches("[a-z][a-z0-9_-]*(?::[a-z][a-z0-9_-]*)*:")) { + throw new IllegalArgumentException("prefix must be colon-delimited and end with a colon"); + } + } + } + + /** The supplied identity and exact KEYS/ARGV values to validate before any Redis call. */ + public record InvocationRequest( + String scriptId, + String resourcePath, + String sha256, + String owner, + String principal, + RedisScriptDescriptor.RedisRole role, + List keys, + List arguments) { + public InvocationRequest { + keys = immutableValues(keys, "KEYS values are required"); + arguments = immutableValues(arguments, "ARGV values are required"); + } + + public List keys() { + return List.copyOf(keys); + } + + public List arguments() { + return List.copyOf(arguments); + } + + private static List immutableValues(List values, String message) { + if (values == null) { + throw new IllegalArgumentException(message); + } + return List.copyOf(values); + } + } +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisInvocationContract.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisInvocationContract.java new file mode 100644 index 0000000000..9e60213b29 --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisInvocationContract.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.util.List; +import java.util.OptionalInt; + +/** Immutable proof that an invocation matched one registered Redis script contract. */ +public final class RedisInvocationContract { + + private final RedisScriptDescriptor descriptor; + private final List keys; + private final List arguments; + private final Integer clusterSlot; + + RedisInvocationContract( + RedisScriptDescriptor descriptor, + List keys, + List arguments, + Integer clusterSlot) { + this.descriptor = descriptor; + this.keys = List.copyOf(keys); + this.arguments = List.copyOf(arguments); + this.clusterSlot = clusterSlot; + } + + public RedisScriptDescriptor descriptor() { + return descriptor; + } + + public List keys() { + return keys; + } + + public List arguments() { + return arguments; + } + + /** Empty when no KEYS entry declared a hash tag. */ + public OptionalInt clusterSlot() { + return clusterSlot == null ? OptionalInt.empty() : OptionalInt.of(clusterSlot); + } +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java new file mode 100644 index 0000000000..f7203482ba --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java @@ -0,0 +1,264 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; + +/** Immutable declaration of one versioned, owner-executed Redis script contract. */ +public record RedisScriptDescriptor( + String scriptId, + String resourcePath, + String sha256, + String owner, + String principal, + RedisRole role, + List keys, + List arguments, + ScriptCategory category, + List outcomes, + ResetSensitivity resetSensitivity, + LossClass lossClass, + String tailLossBehavior, + CompatibilityLevel compatibilityLevel, + List supportedCoexistence, + String legacyPayloadShape) { + + public static final String NO_PAYLOAD_VERSION = "none"; + public static final String LEGACY_PAYLOAD_VERSION = "legacy"; + + private static final Pattern SCRIPT_ID_PATTERN = + Pattern.compile("[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)*\\.v[1-9][0-9]*"); + private static final Pattern RESOURCE_PATH_PATTERN = + Pattern.compile("redis/(?:[a-z0-9][a-z0-9_-]*/)*[a-z0-9][a-z0-9_-]*\\.lua"); + private static final Pattern OWNER_PATTERN = Pattern.compile("[a-z][a-z0-9-]*"); + private static final Pattern PRINCIPAL_PATTERN = Pattern.compile("[a-z][a-z0-9_]*"); + private static final Pattern PREFIX_PATTERN = + Pattern.compile("[a-z][a-z0-9_-]*(?::[a-z][a-z0-9_-]*)*:"); + private static final Pattern DECLARATION_NAME_PATTERN = Pattern.compile("[a-z][A-Za-z0-9]*"); + private static final Pattern OUTCOME_CODE_PATTERN = Pattern.compile("[A-Z][A-Z0-9_]*"); + private static final Pattern VERSION_PATTERN = Pattern.compile("v[1-9][0-9]*"); + + public RedisScriptDescriptor { + requireMatch(scriptId, SCRIPT_ID_PATTERN, "scriptId must be a supported versioned identifier"); + requireMatch( + resourcePath, + RESOURCE_PATH_PATTERN, + "resourcePath must be a relative redis/ classpath Lua resource path"); + requireMatch(sha256, Pattern.compile("[0-9a-f]{64}"), "sha256 must be 64 lowercase hex digits"); + requireMatch(owner, OWNER_PATTERN, "owner must be a lowercase service identifier"); + requireMatch(principal, PRINCIPAL_PATTERN, "principal must be a lowercase Redis principal"); + Objects.requireNonNull(role, "role is required"); + Objects.requireNonNull(category, "category is required"); + Objects.requireNonNull(resetSensitivity, "resetSensitivity is required"); + Objects.requireNonNull(lossClass, "lossClass is required"); + Objects.requireNonNull(compatibilityLevel, "compatibilityLevel is required"); + + keys = immutableNonEmpty(keys, "KEYS declarations are required"); + arguments = + immutable(arguments, "ARGV declarations are required, including an explicit empty list"); + outcomes = immutableNonEmpty(outcomes, "outcomes are required"); + supportedCoexistence = + immutableNonEmpty( + supportedCoexistence, "supported caller/payload coexistence metadata is required"); + tailLossBehavior = requireDescription(tailLossBehavior, "tailLossBehavior"); + legacyPayloadShape = optionalDescription(legacyPayloadShape, "legacyPayloadShape"); + + Set keyNames = new HashSet<>(); + for (KeySpec key : keys) { + if (!keyNames.add(key.name())) { + throw new IllegalArgumentException("duplicate KEYS declaration name: " + key.name()); + } + } + + Set argumentNames = new HashSet<>(); + for (ArgumentSpec argument : arguments) { + if (!argumentNames.add(argument.name())) { + throw new IllegalArgumentException("duplicate ARGV declaration name: " + argument.name()); + } + } + + Set outcomeCodes = new HashSet<>(); + for (OutcomeSpec outcome : outcomes) { + if (!outcomeCodes.add(outcome.code())) { + throw new IllegalArgumentException("duplicate outcome code: " + outcome.code()); + } + } + + Set combinations = new HashSet<>(); + boolean supportsLegacyPayload = false; + for (SupportedCoexistence combination : supportedCoexistence) { + if (!combinations.add(combination)) { + throw new IllegalArgumentException("duplicate caller/payload coexistence declaration"); + } + supportsLegacyPayload |= combination.payloadVersion().equals(LEGACY_PAYLOAD_VERSION); + } + if (supportsLegacyPayload && legacyPayloadShape == null) { + throw new IllegalArgumentException( + "legacyPayloadShape is required when a versionless payload is supported"); + } + if (!supportsLegacyPayload && legacyPayloadShape != null) { + throw new IllegalArgumentException( + "legacyPayloadShape is only valid when a legacy payload is supported"); + } + + if (keys.size() > 1 + && keys.stream().anyMatch(key -> key.hashTagDeclaration() != HashTagDeclaration.REQUIRED)) { + throw new IllegalArgumentException( + "every KEYS declaration in a multi-key script must require a hash tag"); + } + } + + public List keys() { + return List.copyOf(keys); + } + + public List arguments() { + return List.copyOf(arguments); + } + + public List outcomes() { + return List.copyOf(outcomes); + } + + public List supportedCoexistence() { + return List.copyOf(supportedCoexistence); + } + + public enum RedisRole { + COORDINATION, + CACHE_RATE_LIMIT + } + + public enum HashTagDeclaration { + NOT_REQUIRED, + REQUIRED + } + + public enum ScriptCategory { + TICK_LOCK, + TIMER_QUEUE, + SESSION_CAS, + SESSION_TO_REGION_BRIDGE, + MAINTENANCE, + CACHE, + RATE_LIMIT + } + + public enum OutcomeCategory { + SUCCESS, + REPLAY, + STALE, + VALIDATION_FAILURE, + CONTENTION, + DEFERRAL + } + + public enum MutationEffect { + MUTATING, + NON_MUTATING + } + + public enum ResetSensitivity { + NONE, + SESSION, + REGION, + TENANT, + CLUSTER + } + + /** Work classes from ADR 0058. */ + public enum LossClass { + ACCEPTED_PLAYER_COMMAND, + STAGED_EFFECT_OR_RETRY, + CORRECTNESS_BEARING_TIMER, + LOSSY_TIMER_OR_ADVISORY_HINT, + SESSION_LEASE_CACHE_OR_WAKE_UP, + PREMIUM_FINANCIAL_CROSS_TENANT_OR_UNIQUE_EXTERNAL_EFFECT, + EMPTY_REDIS_COLD_START_OR_RESET + } + + public enum CompatibilityLevel { + COMPATIBLE, + REQUIRES_REGION_RESET, + REQUIRES_TENANT_RESET, + REQUIRES_CLUSTER_RESET + } + + public record KeySpec(String name, String ownedPrefix, HashTagDeclaration hashTagDeclaration) { + public KeySpec { + requireMatch(name, DECLARATION_NAME_PATTERN, "KEYS name must be a supported identifier"); + requireMatch(ownedPrefix, PREFIX_PATTERN, "ownedPrefix must be a colon-delimited key prefix"); + Objects.requireNonNull(hashTagDeclaration, "hashTagDeclaration is required"); + } + } + + public record ArgumentSpec(String name) { + public ArgumentSpec { + requireMatch(name, DECLARATION_NAME_PATTERN, "ARGV name must be a supported identifier"); + } + } + + public record OutcomeSpec(String code, OutcomeCategory category, MutationEffect effect) { + public OutcomeSpec { + requireMatch(code, OUTCOME_CODE_PATTERN, "outcome code must be uppercase and stable"); + Objects.requireNonNull(category, "outcome category is required"); + Objects.requireNonNull(effect, "outcome mutation effect is required"); + if (category != OutcomeCategory.SUCCESS && effect != MutationEffect.NON_MUTATING) { + throw new IllegalArgumentException( + "replay, stale, validation, contention, and deferral outcomes must be non-mutating"); + } + } + } + + /** A caller version and payload version that may coexist for this script version. */ + public record SupportedCoexistence(String callerVersion, String payloadVersion) { + public SupportedCoexistence { + requireMatch(callerVersion, VERSION_PATTERN, "callerVersion must use vN syntax"); + if (!NO_PAYLOAD_VERSION.equals(payloadVersion) + && !LEGACY_PAYLOAD_VERSION.equals(payloadVersion)) { + requireMatch( + payloadVersion, VERSION_PATTERN, "payloadVersion must use vN, none, or legacy"); + } + } + } + + private static void requireMatch(String value, Pattern pattern, String message) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException(message); + } + } + + private static String requireDescription(String value, String fieldName) { + if (value == null || value.isBlank() || !value.equals(value.trim())) { + throw new IllegalArgumentException(fieldName + " is required and must be trimmed"); + } + return value; + } + + private static String optionalDescription(String value, String fieldName) { + if (value == null || value.isBlank()) { + return null; + } + if (!value.equals(value.trim())) { + throw new IllegalArgumentException(fieldName + " must be trimmed"); + } + return value; + } + + private static List immutable(List values, String message) { + if (values == null) { + throw new IllegalArgumentException(message); + } + return List.copyOf(values); + } + + private static List immutableNonEmpty(List values, String message) { + List copy = immutable(values, message); + if (copy.isEmpty()) { + throw new IllegalArgumentException(message); + } + return copy; + } +} diff --git a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java new file mode 100644 index 0000000000..30fe3b8265 --- /dev/null +++ b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisContractRegistryTest.java @@ -0,0 +1,444 @@ +package net.firedevops.firemud.common.redis.contracts; + +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.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +class RedisContractRegistryTest { + + private static final String ISSUER_PREFIX = "session:game:auth:issuer-generation:v1:"; + private static final String ISSUER_KEY = ISSUER_PREFIX + "current"; + private static final RedisScriptDescriptor ISSUER_DESCRIPTOR = issuerDescriptor(); + + @Test + void preparesRegisteredSingleKeyInvocation() { + RedisInvocationContract invocation = issuerRegistry().prepareInvocation(issuerRequest()); + + assertEquals(ISSUER_DESCRIPTOR, invocation.descriptor()); + assertEquals(List.of(ISSUER_KEY), invocation.keys()); + assertEquals(List.of("12", "13"), invocation.arguments()); + assertTrue(invocation.clusterSlot().isEmpty()); + } + + @Test + void preparesTaggedMultiKeyInvocationAndReportsClusterSlot() { + RedisScriptDescriptor descriptor = tickDescriptor(); + RedisContractRegistry registry = + new RedisContractRegistry( + List.of(prefix("game-session", "gamesession_coord_app", "tick:")), List.of(descriptor)); + RedisContractRegistry.InvocationRequest request = + new RedisContractRegistry.InvocationRequest( + descriptor.scriptId(), + descriptor.resourcePath(), + descriptor.sha256(), + descriptor.owner(), + descriptor.principal(), + descriptor.role(), + List.of("tick:{region-one}:lease", "tick:{region-one}:meta"), + List.of("41")); + + RedisInvocationContract invocation = registry.prepareInvocation(request); + + assertEquals( + RedisContractRegistry.clusterSlot("tick:{region-one}:lease"), + invocation.clusterSlot().orElseThrow()); + assertEquals( + invocation.clusterSlot(), + java.util.OptionalInt.of(RedisContractRegistry.clusterSlot("tick:{region-one}:meta"))); + } + + @Test + void clusterSlotUsesRedisCrc16XmodemKnownVector() { + assertEquals(12739, RedisContractRegistry.clusterSlot("key{123456789}")); + } + + @Test + void rejectsWrongRedisRole() { + assertThrows( + IllegalArgumentException.class, + () -> + issuerRegistry() + .prepareInvocation( + request( + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.CACHE_RATE_LIMIT, + ISSUER_DESCRIPTOR.sha256(), + ISSUER_KEY, + List.of("12", "13")))); + } + + @Test + void rejectsWrongOwner() { + assertThrows( + IllegalArgumentException.class, + () -> + issuerRegistry() + .prepareInvocation( + request( + "account", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + ISSUER_DESCRIPTOR.sha256(), + ISSUER_KEY, + List.of("12", "13")))); + } + + @Test + void rejectsWrongPrincipal() { + assertThrows( + IllegalArgumentException.class, + () -> + issuerRegistry() + .prepareInvocation( + request( + "game-session", + "account_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + ISSUER_DESCRIPTOR.sha256(), + ISSUER_KEY, + List.of("12", "13")))); + } + + @Test + void rejectsWrongDigestAndResourcePath() { + assertThrows( + IllegalArgumentException.class, + () -> { + RedisContractRegistry.InvocationRequest valid = issuerRequest(); + issuerRegistry() + .prepareInvocation( + new RedisContractRegistry.InvocationRequest( + valid.scriptId(), + valid.resourcePath(), + "b".repeat(64), + valid.owner(), + valid.principal(), + valid.role(), + valid.keys(), + valid.arguments())); + }); + assertThrows( + IllegalArgumentException.class, + () -> { + RedisContractRegistry.InvocationRequest valid = issuerRequest(); + issuerRegistry() + .prepareInvocation( + new RedisContractRegistry.InvocationRequest( + valid.scriptId(), + "redis/auth/other.lua", + valid.sha256(), + valid.owner(), + valid.principal(), + valid.role(), + valid.keys(), + valid.arguments())); + }); + } + + @Test + void rejectsUnknownScriptIdentity() { + RedisContractRegistry.InvocationRequest valid = issuerRequest(); + assertThrows( + IllegalArgumentException.class, + () -> + issuerRegistry() + .prepareInvocation( + new RedisContractRegistry.InvocationRequest( + "game-session.issuer-generation.v2", + valid.resourcePath(), + valid.sha256(), + valid.owner(), + valid.principal(), + valid.role(), + valid.keys(), + valid.arguments()))); + } + + @Test + void rejectsUnownedKeyPrefix() { + assertThrows( + IllegalArgumentException.class, + () -> + issuerRegistry() + .prepareInvocation( + request( + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + ISSUER_DESCRIPTOR.sha256(), + "session:game:auth:another-family:key", + List.of("12", "13")))); + } + + @Test + void rejectsMissingAndMalformedRequiredHashTags() { + RedisContractRegistry registry = tickRegistry(); + assertThrows( + IllegalArgumentException.class, + () -> registry.prepareInvocation(tickRequest("tick:lease", "tick:meta"))); + assertThrows( + IllegalArgumentException.class, + () -> registry.prepareInvocation(tickRequest("tick:{}:lease", "tick:{}:meta"))); + assertThrows( + IllegalArgumentException.class, + () -> + registry.prepareInvocation( + tickRequest("tick:{region-one:lease", "tick:{region-one:meta"))); + assertThrows( + IllegalArgumentException.class, + () -> registry.prepareInvocation(tickRequest("tick:{{scope}:lease", "tick:{{scope}:meta"))); + } + + @Test + void rejectsMultiKeyCrossSlotInvocation() { + RedisContractRegistry registry = tickRegistry(); + assertThrows( + IllegalArgumentException.class, + () -> + registry.prepareInvocation( + tickRequest("tick:{region-one}:lease", "tick:{region-two}:meta"))); + } + + @Test + void rejectsKeysAndArgumentsArityMismatch() { + RedisContractRegistry registry = issuerRegistry(); + RedisContractRegistry.InvocationRequest valid = issuerRequest(); + assertThrows( + IllegalArgumentException.class, + () -> + registry.prepareInvocation( + new RedisContractRegistry.InvocationRequest( + valid.scriptId(), + valid.resourcePath(), + valid.sha256(), + valid.owner(), + valid.principal(), + valid.role(), + List.of(), + valid.arguments()))); + assertThrows( + IllegalArgumentException.class, + () -> + registry.prepareInvocation( + new RedisContractRegistry.InvocationRequest( + valid.scriptId(), + valid.resourcePath(), + valid.sha256(), + valid.owner(), + valid.principal(), + valid.role(), + valid.keys(), + List.of("12")))); + } + + @Test + void rejectsDuplicateAndConflictingPrefixOwnership() { + RedisContractRegistry.PrefixDeclaration declaration = + prefix("game-session", "gamesession_coord_app", ISSUER_PREFIX); + assertThrows( + IllegalArgumentException.class, + () -> + new RedisContractRegistry( + List.of(declaration, declaration), List.of(ISSUER_DESCRIPTOR))); + assertThrows( + IllegalArgumentException.class, + () -> + new RedisContractRegistry( + List.of(declaration, prefix("account", "account_coord_app", "session:game:auth:")), + List.of(ISSUER_DESCRIPTOR))); + } + + @Test + void rejectsDescriptorWhoseOwnerPrincipalOrRoleDoesNotOwnItsPrefix() { + RedisScriptDescriptor wrongOwner = + descriptor( + "game-session.issuer-generation.v1", + "redis/auth/issuer_generation.lua", + "a".repeat(64), + "account", + "account_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + ISSUER_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of("expectedGeneration", "nextGeneration"), + "tail-loss behavior is explicit"); + + assertThrows( + IllegalArgumentException.class, + () -> + new RedisContractRegistry( + List.of(prefix("game-session", "gamesession_coord_app", ISSUER_PREFIX)), + List.of(wrongOwner))); + } + + @Test + void defensivelyCopiesInvocationInputs() { + RedisContractRegistry registry = issuerRegistry(); + List keys = new ArrayList<>(List.of(ISSUER_KEY)); + List arguments = new ArrayList<>(List.of("12", "13")); + RedisContractRegistry.InvocationRequest request = + new RedisContractRegistry.InvocationRequest( + ISSUER_DESCRIPTOR.scriptId(), + ISSUER_DESCRIPTOR.resourcePath(), + ISSUER_DESCRIPTOR.sha256(), + ISSUER_DESCRIPTOR.owner(), + ISSUER_DESCRIPTOR.principal(), + ISSUER_DESCRIPTOR.role(), + keys, + arguments); + keys.clear(); + arguments.clear(); + + assertEquals(List.of(ISSUER_KEY), request.keys()); + assertEquals(List.of("12", "13"), request.arguments()); + assertThrows(UnsupportedOperationException.class, () -> request.keys().add("other")); + assertThrows(UnsupportedOperationException.class, () -> request.arguments().add("14")); + + RedisInvocationContract invocation = registry.prepareInvocation(request); + + assertEquals(List.of(ISSUER_KEY), invocation.keys()); + assertEquals(List.of("12", "13"), invocation.arguments()); + assertThrows(UnsupportedOperationException.class, () -> invocation.keys().add("other")); + assertFalse(invocation.clusterSlot().isPresent()); + } + + private static RedisContractRegistry issuerRegistry() { + return new RedisContractRegistry( + List.of(prefix("game-session", "gamesession_coord_app", ISSUER_PREFIX)), + List.of(ISSUER_DESCRIPTOR)); + } + + private static RedisContractRegistry tickRegistry() { + return new RedisContractRegistry( + List.of(prefix("game-session", "gamesession_coord_app", "tick:")), + List.of(tickDescriptor())); + } + + private static RedisContractRegistry.InvocationRequest issuerRequest() { + return request( + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + ISSUER_DESCRIPTOR.sha256(), + ISSUER_KEY, + List.of("12", "13")); + } + + private static RedisContractRegistry.InvocationRequest request( + String owner, + String principal, + RedisScriptDescriptor.RedisRole role, + String digest, + String key, + List arguments) { + return new RedisContractRegistry.InvocationRequest( + ISSUER_DESCRIPTOR.scriptId(), + ISSUER_DESCRIPTOR.resourcePath(), + digest, + owner, + principal, + role, + List.of(key), + arguments); + } + + private static RedisContractRegistry.InvocationRequest tickRequest( + String firstKey, String secondKey) { + RedisScriptDescriptor descriptor = tickDescriptor(); + return new RedisContractRegistry.InvocationRequest( + descriptor.scriptId(), + descriptor.resourcePath(), + descriptor.sha256(), + descriptor.owner(), + descriptor.principal(), + descriptor.role(), + List.of(firstKey, secondKey), + List.of("41")); + } + + private static RedisContractRegistry.PrefixDeclaration prefix( + String owner, String principal, String prefix) { + return new RedisContractRegistry.PrefixDeclaration( + owner, RedisScriptDescriptor.RedisRole.COORDINATION, principal, prefix); + } + + private static RedisScriptDescriptor issuerDescriptor() { + return descriptor( + "game-session.issuer-generation.v1", + "redis/auth/issuer_generation_cas.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuerGeneration", + ISSUER_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of("expectedGeneration", "nextGeneration"), + "loss closes the issuer scope until authenticated Account reconciliation"); + } + + private static RedisScriptDescriptor tickDescriptor() { + return descriptor( + "game-session.tick-stage.v1", + "redis/tick_stage.lua", + "c".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "lease", "tick:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED), + new RedisScriptDescriptor.KeySpec( + "metadata", "tick:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED)), + List.of("expectedEpoch"), + "lost staged work remains subject to its durable ledger and owner reconciliation"); + } + + private static RedisScriptDescriptor descriptor( + String scriptId, + String resourcePath, + String digest, + String owner, + String principal, + RedisScriptDescriptor.RedisRole role, + List keys, + List argumentNames, + String tailLossBehavior) { + return new RedisScriptDescriptor( + scriptId, + resourcePath, + digest, + owner, + principal, + role, + keys, + argumentNames.stream().map(RedisScriptDescriptor.ArgumentSpec::new).toList(), + RedisScriptDescriptor.ScriptCategory.SESSION_CAS, + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "UPDATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "STALE_GENERATION", + RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, + tailLossBehavior, + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none")), + null); + } +} diff --git a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java new file mode 100644 index 0000000000..f06f974337 --- /dev/null +++ b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java @@ -0,0 +1,229 @@ +package net.firedevops.firemud.common.redis.contracts; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class RedisScriptDescriptorTest { + + @Test + void requiresScriptIdentityResourceDigestAndAllMetadata() { + assertThrows( + IllegalArgumentException.class, + () -> descriptor("game-session.issuer.v1", "../issuer.lua", "a".repeat(64))); + assertThrows( + IllegalArgumentException.class, + () -> descriptor("issuer", "redis/issuer.lua", "a".repeat(64))); + assertThrows( + IllegalArgumentException.class, + () -> descriptor("game-session.issuer.v1", "redis/issuer.lua", "bad-digest")); + assertThrows( + IllegalArgumentException.class, + () -> descriptor("game-session.issuer.v1", "redis/issuer.lua", "a".repeat(64), " ")); + } + + @Test + void rejectsDuplicateKeyAndArgumentDeclarations() { + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor( + "game-session.issuer.v1", + "redis/issuer.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED), + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(new RedisScriptDescriptor.ArgumentSpec("expected")), + category(), + outcomes(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + "loss behavior is explicit", + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + coexistence(), + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor( + "game-session.issuer.v1", + "redis/issuer.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of( + new RedisScriptDescriptor.ArgumentSpec("expected"), + new RedisScriptDescriptor.ArgumentSpec("expected")), + category(), + outcomes(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + "loss behavior is explicit", + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + coexistence(), + null)); + } + + @Test + void requiresOutcomesAndCallerPayloadCoexistence() { + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor( + "game-session.issuer.v1", + "redis/issuer.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(), + category(), + List.of(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + "loss behavior is explicit", + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + coexistence(), + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor( + "game-session.issuer.v1", + "redis/issuer.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(), + category(), + outcomes(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + "loss behavior is explicit", + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + List.of(), + null)); + } + + @Test + void requiresExplicitLegacyPayloadShapeAndNonMutatingFailureOutcomes() { + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor( + "game-session.issuer.v1", + "redis/issuer.lua", + "a".repeat(64), + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", + "session:auth:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(), + category(), + outcomes(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + "loss behavior is explicit", + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "legacy")), + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new RedisScriptDescriptor.OutcomeSpec( + "INVALID_ARGS", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.MUTATING)); + } + + @Test + void descriptorListAccessorsRemainImmutable() { + RedisScriptDescriptor descriptor = + descriptor("game-session.issuer.v1", "redis/issuer.lua", "a".repeat(64)); + + assertThrows(UnsupportedOperationException.class, () -> descriptor.keys().clear()); + assertThrows(UnsupportedOperationException.class, () -> descriptor.arguments().clear()); + assertThrows(UnsupportedOperationException.class, () -> descriptor.outcomes().clear()); + assertThrows( + UnsupportedOperationException.class, () -> descriptor.supportedCoexistence().clear()); + } + + private static RedisScriptDescriptor descriptor(String id, String path, String digest) { + return descriptor(id, path, digest, "loss behavior is explicit"); + } + + private static RedisScriptDescriptor descriptor( + String id, String path, String digest, String tailLoss) { + return new RedisScriptDescriptor( + id, + path, + digest, + "game-session", + "gamesession_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "issuer", "session:auth:", RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(), + category(), + outcomes(), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + lossClass(), + tailLoss, + RedisScriptDescriptor.CompatibilityLevel.COMPATIBLE, + coexistence(), + null); + } + + private static RedisScriptDescriptor.ScriptCategory category() { + return RedisScriptDescriptor.ScriptCategory.SESSION_CAS; + } + + private static List outcomes() { + return List.of( + new RedisScriptDescriptor.OutcomeSpec( + "UPDATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING)); + } + + private static RedisScriptDescriptor.LossClass lossClass() { + return RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP; + } + + private static List coexistence() { + return List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none")); + } +} diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 81a8bd7842..73b780434a 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -50,6 +50,7 @@ dependencies { implementation(libs.spring.boot.starter.websocket) implementation(project(":common-saga")) implementation(project(":common-security")) + implementation(project(":common-redis-contracts")) implementation(libs.jjwt.api) runtimeOnly(libs.jjwt.impl) runtimeOnly(libs.jjwt.jackson) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountMembershipAuthorityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountMembershipAuthorityClient.java new file mode 100644 index 0000000000..dbb74e3551 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountMembershipAuthorityClient.java @@ -0,0 +1,213 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ManagedChannel; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; + +/** Unwired Game Session client for Account-authenticated runtime membership readback. */ +public final class AccountMembershipAuthorityClient + extends AbstractReloadingBlockingGrpcClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final long MAX_FRESHNESS_SECONDS = 15L; + private static final String EXPECTED_ACCOUNT_SERVICE = "account-service"; + + private final String workloadNamespace; + + /** + * Creates a source-only client. Construction does not open a channel; an explicit owner must call + * {@link #init()} before a read. Workload mTLS authenticates this route, while the typed player + * context selects the exact recipient snapshot and is not itself a credential. + */ + public AccountMembershipAuthorityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + String workloadNamespace) { + super( + endpoints, + requireGameSessionMtls(tlsProps), + channelFactory, + stubCustomizer, + AccountMembershipAuthorityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be one DNS label"); + } + if (stubCustomizer == null) { + throw new IllegalArgumentException("Game Session internal gRPC stub customizer is required"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes this client only when an explicit owner activates the membership read. */ + public void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountServiceGrpc.AccountServiceBlockingStub buildStub(ManagedChannel channel) { + return applyStubCustomizer( + AccountServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/" + EXPECTED_ACCOUNT_SERVICE)) + .withCompression("gzip")); + } + + /** Reads the exact Account recipient snapshot and fails closed on any incomplete evidence. */ + public GetTenantMembershipForRuntimeResponse getTenantMembershipForRuntime( + PlayerExecutionContext playerContext) { + validatePlayerContext(playerContext); + AccountServiceGrpc.AccountServiceBlockingStub currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException("Account membership authority client is not initialized"); + } + + GetTenantMembershipForRuntimeRequest request = + GetTenantMembershipForRuntimeRequest.newBuilder().setPlayerContext(playerContext).build(); + try { + GetTenantMembershipForRuntimeResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getTenantMembershipForRuntime(request); + return verifyResponse(response, playerContext); + } catch (StatusRuntimeException exception) { + throw new IllegalStateException("Account runtime membership read failed closed", exception); + } + } + + private GetTenantMembershipForRuntimeResponse verifyResponse( + GetTenantMembershipForRuntimeResponse response, PlayerExecutionContext request) { + if (response == null) { + throw invalidResponse("is absent"); + } + if (response.hasError()) { + throw invalidResponse("contains an Account error"); + } + if (!"AVAILABLE".equals(response.getAuthorityAvailability()) + || !request.getAccountId().equals(response.getAccountId()) + || !request.getTenantId().equals(response.getTenantId()) + || !request.getAccountId().equals(response.getRequestAccountId()) + || !request.getTenantId().equals(response.getRequestTenantId()) + || !request.getRequestId().equals(response.getRequestId())) { + throw invalidResponse("availability or exact recipient/request echoes changed"); + } + + final Instant evaluatedAt; + try { + evaluatedAt = Instant.parse(response.getEvaluatedAt()); + } catch (RuntimeException exception) { + throw invalidResponse("evaluation time is malformed", exception); + } + Instant now = Instant.now(); + if (evaluatedAt.isAfter(now) + || evaluatedAt.isBefore(now.minus(MAX_FRESHNESS_SECONDS, ChronoUnit.SECONDS))) { + throw invalidResponse("evaluation time is stale or in the future"); + } + + try { + RuntimeMembershipResponseValidator.validateContent(response); + } catch (IllegalArgumentException exception) { + throw invalidResponse("content evidence is incomplete or contradictory", exception); + } + return response; + } + + private static void validatePlayerContext(PlayerExecutionContext context) { + if (context == null || !context.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Complete typed PlayerExecutionContext is required"); + } + if (!isCanonicalNonNilUuid(context.getAccountId()) + || !isCanonicalNonNilUuid(context.getTenantId()) + || !isCanonicalNonNilUuid(context.getPlayableStateNamespaceId()) + || !isCanonicalNonNilUuid(context.getRealmId()) + || !isCanonicalNonNilUuid(context.getGameInstanceId()) + || !isPositiveCanonicalDecimal(context.getSessionId()) + || (!context.getCharacterId().isEmpty() + && !isPositiveCanonicalDecimal(context.getCharacterId())) + || (!"SHARED".equals(context.getPlayableStateScope()) + && !"ISOLATED".equals(context.getPlayableStateScope())) + || context.getRequestId().isBlank()) { + throw new IllegalArgumentException( + "PlayerExecutionContext selectors are incomplete or invalid"); + } + } + + private static boolean isCanonicalNonNilUuid(String value) { + if (value == null || value.isBlank()) { + return false; + } + try { + return UUID.fromString(value).toString().equals(value) + && !new UUID(0L, 0L).toString().equals(value); + } catch (IllegalArgumentException exception) { + return false; + } + } + + private static boolean isPositiveCanonicalDecimal(String value) { + return value != null && value.matches("[1-9][0-9]*"); + } + + private static CommonGrpcClientProperties requireGameSessionMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Game Session gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Runtime membership read requires Game Session workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Runtime membership read requires Game Session certificate, key, and CA files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Runtime membership read requires file-backed Game Session workload mTLS"); + } + return tlsProps; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } + + private static IllegalStateException invalidResponse(String message) { + return new IllegalStateException("Account runtime membership response " + message); + } + + private static IllegalStateException invalidResponse(String message, Throwable cause) { + return new IllegalStateException("Account runtime membership response " + message, cause); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/RuntimeMembershipResponseValidator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/RuntimeMembershipResponseValidator.java new file mode 100644 index 0000000000..a125f0f18f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/RuntimeMembershipResponseValidator.java @@ -0,0 +1,193 @@ +package net.firedevops.firemud.gamesession.client; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.RuntimeMembershipBaseline; +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.MembershipEvent; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; + +/** Adapts Account's runtime membership protobuf to the shared closed content validator. */ +public final class RuntimeMembershipResponseValidator { + private static final String ACCOUNT_AUTHORITY_ISSUER = "firemud-account-service"; + private static final String ACCOUNT_AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; + + private RuntimeMembershipResponseValidator() {} + + /** + * Converts and validates one complete Account content carrier. + * + *

This checks only response content and its internal historical/current evidence binding. It + * does not authenticate Account, validate the request echoes or freshness, prove absence in + * Account, or authorize gameplay admission. The returned event is immutable historical evidence; + * an empty result is the shared validator's non-admitting sequence-zero membership baseline. + * + * @throws IllegalArgumentException if the content carrier is incomplete, unsupported, or + * inconsistent + */ + public static Optional validateContent( + GetTenantMembershipForRuntimeResponse response) { + if (response == null) { + throw invalid("response is absent"); + } + requireNoUnknownFields(response); + if (response.hasError()) { + throw invalid("response contains an Account error"); + } + if (!response.hasMembershipBaseline() || !response.hasAuthorityTuple()) { + throw invalid("membership baseline or authority tuple is absent"); + } + if (!isCanonicalNonNilUuid(response.getAccountId()) + || !isCanonicalUuid(response.getTenantId())) { + throw invalid("account or tenant identity is not canonical"); + } + if (!response + .getMembershipBaseline() + .equals( + RuntimeMembershipBaseline.newBuilder() + .setMembershipLifecycleState(response.getMembershipLifecycleState()) + .putAllMembershipVersion(response.getMembershipVersionMap()) + .setMembershipAuthorityGeneration(response.getMembershipAuthorityGeneration()) + .build())) { + throw invalid("membership baseline differs from the current membership carrier"); + } + + var tuple = response.getAuthorityTuple(); + if (tuple.getPrivateRealmGrantVersionsCount() != 0 || tuple.hasTenantBillingCutoff()) { + throw invalid("unsupported grant or tenant billing authority is present"); + } + + String membershipStream = + ACCOUNT_AUTHORITY_STREAM_PREFIX + + "membership/" + + response.getAccountId() + + "/" + + response.getTenantId(); + if (response.getOutboxSourceEvidenceList().stream() + .filter(source -> membershipStream.equals(source.getOutboxStreamKey())) + .anyMatch(source -> !isCanonicalUuid(source.getEventId()))) { + throw invalid("membership source event identity is not a canonical UUID"); + } + + Optional accountSecurityCutoff = + tuple.hasAccountSecurityCutoff() + ? Optional.of( + new AccountSecurityCutoff( + tuple.getAccountSecurityCutoff().getAccountAuthorityGeneration(), + tuple.getAccountSecurityCutoff().getOutboxStreamKey(), + tuple.getAccountSecurityCutoff().getOutboxSequence())) + : Optional.empty(); + AuthorityTuple currentTuple = + new AuthorityTuple( + tuple.getIssuerAuthGeneration(), + tuple.getAccountAuthorityGeneration(), + tuple.getTenantAuthorityGenerationMap(), + tuple.getMembershipAuthorityGenerationMap(), + List.of(), + accountSecurityCutoff, + Optional.empty()); + List checkpoints = + response.getOutboxCheckpointsList().stream() + .map( + checkpoint -> + new Checkpoint(checkpoint.getOutboxStreamKey(), checkpoint.getOutboxSequence())) + .toList(); + List sourceEvidence = + response.getOutboxSourceEvidenceList().stream() + .map( + source -> + new SourceEvidence( + source.getOutboxStreamKey(), + source.getOutboxSequence(), + source.getEventId(), + source.getEventDigest(), + source.getCanonicalEventJson())) + .toList(); + return RuntimeMembershipAuthorityEvidenceValidator.validate( + new Snapshot( + ACCOUNT_AUTHORITY_ISSUER, + response.getAccountId(), + response.getTenantId(), + response.getMembershipExists(), + response.getMembershipLifecycleState(), + response.getGameplayAdmissionAllowed(), + response.getMembershipVersionMap(), + response.getMembershipAuthorityGeneration(), + response.getRolesList(), + currentTuple, + response.getIssuanceFence(), + checkpoints, + sourceEvidence)); + } + + /** + * Returns false for malformed content so existing command denial paths remain local and stable. + */ + public static boolean hasCompleteAuthorityCarrier( + GetTenantMembershipForRuntimeResponse response) { + try { + validateContent(response); + return true; + } catch (IllegalArgumentException exception) { + return false; + } + } + + private static void requireNoUnknownFields(GetTenantMembershipForRuntimeResponse response) { + if (!response.getUnknownFields().asMap().isEmpty() + || response.hasError() && !response.getError().getUnknownFields().asMap().isEmpty() + || response.hasMembershipBaseline() + && !response.getMembershipBaseline().getUnknownFields().asMap().isEmpty()) { + throw invalid("response or a nested message contains unsupported fields"); + } + if (!response.hasAuthorityTuple()) { + return; + } + var tuple = response.getAuthorityTuple(); + if (!tuple.getUnknownFields().asMap().isEmpty() + || tuple.hasAccountSecurityCutoff() + && !tuple.getAccountSecurityCutoff().getUnknownFields().asMap().isEmpty()) { + throw invalid("authority tuple contains unsupported fields"); + } + for (var grant : tuple.getPrivateRealmGrantVersionsList()) { + if (!grant.getUnknownFields().asMap().isEmpty()) { + throw invalid("authority tuple grant contains unsupported fields"); + } + } + for (var checkpoint : response.getOutboxCheckpointsList()) { + if (!checkpoint.getUnknownFields().asMap().isEmpty()) { + throw invalid("outbox checkpoint contains unsupported fields"); + } + } + for (var source : response.getOutboxSourceEvidenceList()) { + if (!source.getUnknownFields().asMap().isEmpty()) { + throw invalid("outbox source evidence contains unsupported fields"); + } + } + } + + private static boolean isCanonicalNonNilUuid(String value) { + return isCanonicalUuid(value) && !new UUID(0L, 0L).toString().equals(value); + } + + private static boolean isCanonicalUuid(String value) { + if (value == null || value.isBlank()) { + return false; + } + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException exception) { + return false; + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException("Runtime membership response " + message); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 947f49d618..18767eb784 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -4,7 +4,6 @@ import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import java.time.Clock; -import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -15,14 +14,13 @@ import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; -import net.firedevops.firemud.account.v1.RuntimeAuthorityTuple; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.client.ModerationPolicyClient; +import net.firedevops.firemud.gamesession.client.RuntimeMembershipResponseValidator; import net.firedevops.firemud.gamesession.config.GameLogicProperties; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameplayCommand; @@ -64,8 +62,6 @@ public class PlayCommandHandler { private static final String RESUME_DENIED_METRIC = "gamesession.session.resume_denied"; private static final String FRESH_ENTRY_FALLBACK_METRIC = "gamesession.session.fresh_entry_fallback"; - private static final String ACCOUNT_AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; - private static final String ACCOUNT_AUTHORITY_ISSUER = "firemud-account-service"; private final SessionAuthenticationService sessionAuthenticationService; private final SessionContextService sessionContextService; @@ -943,6 +939,20 @@ private Optional validateMembershipResponse( authorityUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } + if (AccountIds.isCanonicalNonNilUuid(response.getAccountId()) + && !response.getAccountId().equals(context.accountId())) { + // Another account's evidence cannot authorize clearing this caller's existing binding. + return Optional.of( + failure( + GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE, + GameplayStageCommandConstants.WORLD_ACCESS_DENIED_MESSAGE, + "error.play.world-access-denied", + Map.of(), + tenantTag, + Long.toString(selectedRealm.gameInstanceId()), + Long.toString(requestedCharacterId), + null)); + } if (!isSafeMembershipAuthorityResponse( response, context, selectedRealm, canonicalTenantId, requestId)) { return Optional.of( @@ -1032,7 +1042,7 @@ private Optional validateMembershipResponse( private boolean isValidMembershipLifecycleEvidence( GetTenantMembershipForRuntimeResponse response) { - if (!hasCompleteMembershipAuthorityCarrier(response)) { + if (!RuntimeMembershipResponseValidator.hasCompleteAuthorityCarrier(response)) { return false; } return switch (response.getMembershipLifecycleState()) { @@ -1064,227 +1074,10 @@ private static boolean hasPositiveMembershipVersion( && isPositiveCanonicalDecimal(version.getValue()); } - private static boolean hasCompleteMembershipAuthorityCarrier( - GetTenantMembershipForRuntimeResponse response) { - if (!response.hasMembershipBaseline() || !response.hasAuthorityTuple()) { - return false; - } - if (!response.getAuthorityTuple().getUnknownFields().asMap().isEmpty()) { - return false; - } - if (!AccountIds.isCanonicalNonNilUuid(response.getAccountId()) - || !isCanonicalUuid(response.getTenantId())) { - return false; - } - if (!response - .getMembershipBaseline() - .equals( - net.firedevops.firemud.account.v1.RuntimeMembershipBaseline.newBuilder() - .setMembershipLifecycleState(response.getMembershipLifecycleState()) - .putAllMembershipVersion(response.getMembershipVersionMap()) - .setMembershipAuthorityGeneration(response.getMembershipAuthorityGeneration()) - .build())) { - return false; - } - if (!isPositiveCanonicalDecimal(response.getIssuanceFence())) { - return false; - } - - var tuple = response.getAuthorityTuple(); - String tenantId = response.getTenantId(); - if (!"1".equals(tuple.getIssuerAuthGeneration()) - || !"1".equals(tuple.getAccountAuthorityGeneration()) - || !tuple.getTenantAuthorityGenerationMap().keySet().equals(java.util.Set.of(tenantId)) - || !tuple.getMembershipAuthorityGenerationMap().keySet().equals(java.util.Set.of(tenantId)) - || !"1".equals(tuple.getTenantAuthorityGenerationMap().get(tenantId)) - || !isPositiveCanonicalDecimal(tuple.getMembershipAuthorityGenerationMap().get(tenantId)) - || !tuple - .getMembershipAuthorityGenerationMap() - .get(tenantId) - .equals(response.getMembershipAuthorityGeneration()) - || tuple.getPrivateRealmGrantVersionsCount() != 0 - || tuple.hasAccountSecurityCutoff() - || tuple.hasTenantBillingCutoff()) { - return false; - } - - String membershipStream = - ACCOUNT_AUTHORITY_STREAM_PREFIX + "membership/" + response.getAccountId() + "/" + tenantId; - String accountStream = ACCOUNT_AUTHORITY_STREAM_PREFIX + "account/" + response.getAccountId(); - String issuerStream = ACCOUNT_AUTHORITY_STREAM_PREFIX + "issuer/" + ACCOUNT_AUTHORITY_ISSUER; - String tenantStream = ACCOUNT_AUTHORITY_STREAM_PREFIX + "tenant/" + tenantId; - List expectedStreamKeys = - new ArrayList<>(List.of(accountStream, issuerStream, membershipStream, tenantStream)); - expectedStreamKeys.sort(String::compareTo); - if (response.getOutboxCheckpointsCount() != expectedStreamKeys.size()) { - return false; - } - List actualStreamKeys = new ArrayList<>(); - Map checkpointSequences = new java.util.HashMap<>(); - for (var checkpoint : response.getOutboxCheckpointsList()) { - if (!checkpoint.getUnknownFields().asMap().isEmpty() - || !isCanonicalNonNegativeDecimal(checkpoint.getOutboxSequence()) - || checkpointSequences.putIfAbsent( - checkpoint.getOutboxStreamKey(), checkpoint.getOutboxSequence()) - != null) { - return false; - } - actualStreamKeys.add(checkpoint.getOutboxStreamKey()); - } - if (!actualStreamKeys.equals(expectedStreamKeys)) { - return false; - } - boolean committedMembership = !"MISSING".equals(response.getMembershipLifecycleState()); - for (String streamKey : expectedStreamKeys) { - String sequence = checkpointSequences.get(streamKey); - if (streamKey.equals(membershipStream)) { - if (committedMembership != isPositiveCanonicalDecimal(sequence)) { - return false; - } - } else if (!"0".equals(sequence)) { - return false; - } - } - if (!committedMembership) { - return "MISSING".equals(response.getMembershipLifecycleState()) - && !response.getMembershipExists() - && !response.getGameplayAdmissionAllowed() - && response.getOutboxSourceEvidenceCount() == 0 - && "1".equals(response.getMembershipVersionMap().get(tenantId)) - && "1".equals(response.getMembershipAuthorityGeneration()) - && "1".equals(tuple.getIssuerAuthGeneration()) - && "1".equals(tuple.getAccountAuthorityGeneration()) - && "1".equals(tuple.getTenantAuthorityGenerationMap().get(tenantId)) - && response.getMembershipVersionCount() == 1; - } - - if (response.getOutboxSourceEvidenceCount() != 1 - || !response.getMembershipExists() - || ("INACTIVE".equals(response.getMembershipLifecycleState()) - && response.getGameplayAdmissionAllowed()) - || response.getMembershipVersionCount() != 1 - || !hasPositiveMembershipVersion(response)) { - return false; - } - var source = response.getOutboxSourceEvidence(0); - if (!source.getUnknownFields().asMap().isEmpty() - || !source.getOutboxStreamKey().equals(membershipStream) - || !source.getOutboxSequence().equals(checkpointSequences.get(membershipStream)) - || !isCanonicalUuid(source.getEventId()) - || !source.getEventDigest().matches("sha256:[0-9a-f]{64}") - || !StringUtils.hasText(source.getCanonicalEventJson())) { - return false; - } - final MembershipAuthorityEventV1Codec.MembershipEvent event; - try { - event = MembershipAuthorityEventV1Codec.verify(source.getCanonicalEventJson()); - } catch (IllegalArgumentException ex) { - return false; - } - return matchesMembershipEvent(response, source, event, checkpointSequences, membershipStream); - } - - private static boolean matchesMembershipEvent( - GetTenantMembershipForRuntimeResponse response, - net.firedevops.firemud.account.v1.RuntimeOutboxSourceEvidence source, - MembershipAuthorityEventV1Codec.MembershipEvent event, - Map checkpointSequences, - String membershipStream) { - return event.canonicalJson().equals(source.getCanonicalEventJson()) - && event.eventId().equals(source.getEventId()) - && event.eventDigest().equals(source.getEventDigest()) - && event.outboxStreamKey().equals(source.getOutboxStreamKey()) - && event.outboxSequence().equals(source.getOutboxSequence()) - && event.outboxStreamKey().equals(membershipStream) - && event.outboxSequence().equals(checkpointSequences.get(membershipStream)) - && event.accountId().equals(response.getAccountId()) - && event.tenantId().equals(response.getTenantId()) - && event.membershipLifecycleState().equals(response.getMembershipLifecycleState()) - && event.membershipVersion().equals(response.getMembershipVersionMap()) - && event.membershipAuthorityGeneration().equals(response.getMembershipAuthorityGeneration()) - && event.issuanceFence().equals(response.getIssuanceFence()) - && event.roles().equals(response.getRolesList()) - && event.gameplayAdmissionAllowed() == response.getGameplayAdmissionAllowed() - && matchesAuthorityTuple(response.getAuthorityTuple(), event.authorityTuple()); - } - - private static boolean matchesAuthorityTuple( - RuntimeAuthorityTuple response, MembershipAuthorityEventV1Codec.AuthorityTuple event) { - if (!response.getIssuerAuthGeneration().equals(event.issuerAuthGeneration()) - || !response.getAccountAuthorityGeneration().equals(event.accountAuthorityGeneration()) - || !response.getTenantAuthorityGenerationMap().equals(event.tenantAuthorityGeneration()) - || !response - .getMembershipAuthorityGenerationMap() - .equals(event.membershipAuthorityGeneration()) - || response.getPrivateRealmGrantVersionsCount() != event.privateRealmGrantVersions().size() - || response.hasAccountSecurityCutoff() != event.accountSecurityCutoff().isPresent() - || response.hasTenantBillingCutoff() != event.tenantBillingCutoff().isPresent()) { - return false; - } - for (int index = 0; index < response.getPrivateRealmGrantVersionsCount(); index++) { - var responseGrant = response.getPrivateRealmGrantVersions(index); - var eventGrant = event.privateRealmGrantVersions().get(index); - if (!responseGrant.getTenantId().equals(eventGrant.tenantId()) - || !responseGrant.getWorldSlug().equals(eventGrant.worldSlug()) - || !responseGrant.getRealmSlug().equals(eventGrant.realmSlug()) - || !responseGrant.getPlaytestLifecycleId().equals(eventGrant.playtestLifecycleId()) - || !responseGrant.getGrantVersion().equals(eventGrant.grantVersion())) { - return false; - } - } - if (response.hasAccountSecurityCutoff()) { - var responseCutoff = response.getAccountSecurityCutoff(); - var eventCutoff = event.accountSecurityCutoff().orElseThrow(); - if (!responseCutoff - .getAccountAuthorityGeneration() - .equals(eventCutoff.accountAuthorityGeneration()) - || !responseCutoff.getOutboxStreamKey().equals(eventCutoff.outboxStreamKey()) - || !responseCutoff.getOutboxSequence().equals(eventCutoff.outboxSequence())) { - return false; - } - } - if (response.hasTenantBillingCutoff()) { - var eventCutoffs = event.tenantBillingCutoff().orElseThrow(); - var responseCutoffs = response.getTenantBillingCutoff().getEntriesList(); - if (responseCutoffs.size() != eventCutoffs.size()) { - return false; - } - Set responseCutoffTenants = new HashSet<>(); - for (var responseEntry : responseCutoffs) { - var eventCutoff = eventCutoffs.get(responseEntry.getTenantId()); - if (!responseCutoffTenants.add(responseEntry.getTenantId()) - || eventCutoff == null - || !responseEntry - .getCutoff() - .getTenantAuthorityGeneration() - .equals(eventCutoff.tenantAuthorityGeneration()) - || !responseEntry - .getCutoff() - .getTenantBillingSequence() - .equals(eventCutoff.tenantBillingSequence()) - || !responseEntry.getCutoff().getOutboxStreamKey().equals(eventCutoff.outboxStreamKey()) - || !responseEntry - .getCutoff() - .getOutboxSequence() - .equals(eventCutoff.outboxSequence())) { - return false; - } - } - if (!responseCutoffTenants.equals(eventCutoffs.keySet())) { - return false; - } - } - return true; - } - private static boolean isPositiveCanonicalDecimal(String value) { return value != null && value.matches("[1-9][0-9]*"); } - private static boolean isCanonicalNonNegativeDecimal(String value) { - return value != null && value.matches("(?:0|[1-9][0-9]*)"); - } - private static boolean isCanonicalUuid(String value) { if (!StringUtils.hasText(value)) { return false; @@ -1580,6 +1373,7 @@ private boolean isSafeMembershipAuthorityResponse( || !StringUtils.hasText(response.getTenantId()) || !StringUtils.hasText(response.getEvaluatedAt()) || !AccountIds.isCanonicalNonNilUuid(response.getAccountId()) + || !response.getAccountId().equals(context.accountId()) || !isCanonicalUuid(response.getTenantId()) || !response.getTenantId().equals(canonicalTenantId) || !response.getRequestAccountId().equals(context.accountId()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContract.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContract.java new file mode 100644 index 0000000000..59bbf8210b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContract.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.PrefixDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisInvocationContract; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ArgumentSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.CompatibilityLevel; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.KeySpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.LossClass; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.MutationEffect; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.RedisRole; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ResetSensitivity; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ScriptCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.SupportedCoexistence; + +/** Registered single-key coordination contract for Game Session's issuer projection. */ +public final class IssuerAuthorityProjectionRedisContract { + public static final String SCRIPT_ID = "game-session.issuer-authority-projection.v1"; + public static final String RESOURCE_PATH = "redis/issuer_authority_projection_cas.lua"; + public static final String OWNER = "game-session-service"; + public static final String PRINCIPAL = "gamesession_coord_app"; + public static final RedisRole ROLE = RedisRole.COORDINATION; + public static final String PROJECTION_SCHEMA_VERSION = + IssuerAuthorityProjectionTransitions.SCHEMA_VERSION; + public static final String KEY_PREFIX = IssuerAuthorityProjectionTransitions.KEY_PREFIX; + + private static final String RESOURCE_SHA256 = + "1c1df7fdf6edc42a9e3ad5dfd5a0db7c33295b41a9e5c28df2a65e98d9069c16"; + private static final RedisScriptDescriptor DESCRIPTOR = createDescriptor(); + private static final RedisContractRegistry REGISTRY = + new RedisContractRegistry( + List.of(new PrefixDeclaration(OWNER, ROLE, PRINCIPAL, KEY_PREFIX)), List.of(DESCRIPTOR)); + + private IssuerAuthorityProjectionRedisContract() {} + + public static RedisScriptDescriptor descriptor() { + return DESCRIPTOR; + } + + /** Declarative registry only; executable access remains private to the typed owner store. */ + public static RedisContractRegistry registry() { + return REGISTRY; + } + + public static String keyForIssuer(String issuerId) { + Objects.requireNonNull(issuerId, "exact issuer ID is required"); + if (issuerId.isBlank() || issuerId.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException( + "exact issuer ID must be nonblank and contain no controls"); + } + return KEY_PREFIX + issuerId; + } + + static RedisInvocationContract prepareInvocation( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + return REGISTRY.prepareInvocation( + new InvocationRequest( + SCRIPT_ID, + RESOURCE_PATH, + RESOURCE_SHA256, + OWNER, + PRINCIPAL, + ROLE, + List.of(key), + List.of(expectedMode, expectedBytes, candidateBytes))); + } + + private static RedisScriptDescriptor createDescriptor() { + return new RedisScriptDescriptor( + SCRIPT_ID, + RESOURCE_PATH, + RESOURCE_SHA256, + OWNER, + PRINCIPAL, + ROLE, + List.of(new KeySpec("issuerProjection", KEY_PREFIX, HashTagDeclaration.NOT_REQUIRED)), + List.of( + new ArgumentSpec("expectedMode"), + new ArgumentSpec("expectedBytes"), + new ArgumentSpec("candidateBytes")), + ScriptCategory.SESSION_CAS, + List.of( + new OutcomeSpec("APPLIED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING), + new OutcomeSpec("REPLAY", OutcomeCategory.REPLAY, MutationEffect.NON_MUTATING), + new OutcomeSpec("STALE", OutcomeCategory.STALE, MutationEffect.NON_MUTATING), + new OutcomeSpec( + "INVALID", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING), + new OutcomeSpec( + "TTL_PRESENT", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING)), + ResetSensitivity.CLUSTER, + LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, + "On loss, quarantine this issuer scope until an authenticated exact Account checkpoint is reconciled; never admit from this projection.", + CompatibilityLevel.COMPATIBLE, + List.of(new SupportedCoexistence("v1", "v1")), + null); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitions.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitions.java new file mode 100644 index 0000000000..d55623afe1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitions.java @@ -0,0 +1,610 @@ +package net.firedevops.firemud.gamesession.service; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceSnapshot; + +/** Pure decision layer for the derived Game Session issuer-authority projection. */ +public final class IssuerAuthorityProjectionTransitions { + public static final String KEY_PREFIX = "session:game:auth:issuer-generation:v1:"; + public static final String SCHEMA_VERSION = "game-session-auth-issuer-projection/v1"; + + private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; + private static final BigInteger ZERO = BigInteger.ZERO; + private static final BigInteger ONE = BigInteger.ONE; + + private static final Set BASE_FIELDS = + Set.of( + "schemaVersion", + "issuerId", + "issuerAuthGeneration", + "lastAppliedSourceOutboxSequence", + "sourceOutboxStreamKey", + "appliedAt", + "appliedSourceEvidence"); + private static final Set POSITIVE_FIELDS = Set.of("sourceEventId", "sourceEventDigest"); + + private IssuerAuthorityProjectionTransitions() {} + + /** + * Creates an initial projection only from Account's complete authenticated current readback. + * Sequence zero is source absence evidence; it is not recipient admission evidence. + */ + public static Decision bootstrap(SourceReadback currentReadback, String appliedAt) { + try { + VerifiedReadback readback = verifyReadback(currentReadback); + if (readback.selectedEvent().isPresent()) { + return new Quarantine( + Optional.empty(), QuarantineReason.BOOTSTRAP_REQUIRES_CURRENT_READBACK); + } + requireAppliedAt(appliedAt); + return new Mutation( + Optional.empty(), projectionFor(readback.snapshot(), appliedAt), MutationKind.BOOTSTRAP); + } catch (EvidenceRejected rejected) { + return new Quarantine(Optional.empty(), rejected.reason()); + } catch (IllegalArgumentException malformed) { + return new Quarantine(Optional.empty(), QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + } + + /** + * Decides whether one Account-authenticated selected source event advances, duplicates, or + * contradicts the observed projection. The expected fields and next projection are immutable + * compare-and-set evidence; this method performs no storage operation. + */ + public static Decision decide( + Map observedProjection, SourceReadback sourceReadback, String appliedAt) { + Optional> observed = immutableObserved(observedProjection); + final ExistingProjection existing; + try { + if (observedProjection == null) { + return new Quarantine(Optional.empty(), QuarantineReason.MISSING_EXISTING_PROJECTION); + } + existing = parseExistingProjection(observedProjection); + } catch (IllegalArgumentException malformed) { + return new Quarantine(observed, QuarantineReason.MALFORMED_EXISTING_PROJECTION); + } + + try { + VerifiedReadback readback = verifyReadback(sourceReadback); + if (readback.selectedEvent().isEmpty()) { + return new Quarantine(observed, QuarantineReason.SELECTED_EVENT_REQUIRED); + } + + Checkpoint current = readback.snapshot(); + IssuerGenerationAuthorityEvent selected = readback.selectedEvent().orElseThrow(); + if (!existing.issuerId().equals(current.issuerId()) + || !existing.streamKey().equals(current.streamKey())) { + return new Quarantine(observed, QuarantineReason.ISSUER_OR_STREAM_CHANGED); + } + if (current.sequence().compareTo(existing.sequence()) < 0 + || current.generation().compareTo(existing.generation()) < 0 + || current.sourceVersion().compareTo(existing.sourceVersion()) < 0) { + return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_REGRESSED); + } + if (current.sequence().equals(existing.sequence())) { + if (existing.latestEvent() == null) { + if (current.latestEvent() != null + || !current.generation().equals(ONE) + || !current.sourceVersion().equals(ONE)) { + return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_CONFLICT); + } + } else if (current.latestEvent() == null + || !existing + .latestEvent() + .canonicalJson() + .equals(current.latestEvent().canonicalJson())) { + return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_CONFLICT); + } + } else if (current.sourceVersion().compareTo(existing.sourceVersion()) <= 0) { + return new Quarantine(observed, QuarantineReason.CURRENT_CHECKPOINT_REGRESSED); + } + + BigInteger selectedSequence = positiveDecimal(selected.outboxSequence(), "selected sequence"); + int order = selectedSequence.compareTo(existing.sequence()); + if (order < 0) { + if (positiveDecimal(selected.issuerAuthGeneration(), "selected generation") + .compareTo(existing.generation()) + > 0) { + return new Quarantine(observed, QuarantineReason.HISTORICAL_EVENT_PROGRESS_CONFLICT); + } + if (positiveDecimal(selected.sourceVersion(), "selected source version") + .compareTo(existing.sourceVersion()) + > 0) { + return new Quarantine(observed, QuarantineReason.HISTORICAL_EVENT_PROGRESS_CONFLICT); + } + // The selected event is an exact immutable Account lookup. Historical generations and + // source versions may be lower than the installed later projection. + return new NoOp(NoOpReason.VERIFIED_HISTORICAL_DUPLICATE); + } + + if (order == 0) { + if (existing.latestEvent() == null + || !existing.latestEvent().canonicalJson().equals(selected.canonicalJson())) { + return new Quarantine(observed, QuarantineReason.DUPLICATE_EVENT_CONFLICT); + } + return new NoOp(NoOpReason.EXACT_DUPLICATE); + } + + BigInteger expectedNextSequence = existing.sequence().add(ONE); + if (!selectedSequence.equals(expectedNextSequence)) { + return new Quarantine(observed, QuarantineReason.EVENT_SEQUENCE_GAP); + } + + BigInteger eventGeneration = + positiveDecimal(selected.issuerAuthGeneration(), "selected generation"); + BigInteger eventSourceVersion = + positiveDecimal(selected.sourceVersion(), "selected source version"); + if (eventGeneration.compareTo(existing.generation()) < 0) { + return new Quarantine(observed, QuarantineReason.EVENT_GENERATION_REGRESSED); + } + if (eventSourceVersion.compareTo(existing.sourceVersion()) <= 0) { + return new Quarantine(observed, QuarantineReason.EVENT_SOURCE_VERSION_REGRESSED); + } + requireAppliedAt(appliedAt); + + BigInteger nextGeneration = eventGeneration.max(existing.generation()); + return new Mutation( + observed, + projectionFor( + selected, nextGeneration.toString(), selectedSequence.toString(), appliedAt), + MutationKind.ADVANCE); + } catch (EvidenceRejected rejected) { + return new Quarantine(observed, rejected.reason()); + } catch (IllegalArgumentException malformed) { + return new Quarantine(observed, QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + } + + private static VerifiedReadback verifyReadback(SourceReadback readback) { + if (readback == null + || readback.requestId() == null + || readback.targetNamespace() == null + || readback.targetNamespace().isBlank() + || readback.sourceSnapshot() == null) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + UUID requestId; + try { + requestId = UUID.fromString(readback.requestId()); + } catch (IllegalArgumentException malformed) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + if (new UUID(0L, 0L).equals(requestId) || !requestId.toString().equals(readback.requestId())) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + + Checkpoint snapshot = verifySnapshot(readback.sourceSnapshot()); + Optional selected = readback.requestedEvent(); + if (selected.isPresent()) { + IssuerGenerationAuthorityEvent event = verifyEvent(selected.orElseThrow()); + if (!sameSource(event, snapshot.issuerId(), snapshot.streamKey()) + || positiveDecimal(event.outboxSequence(), "selected sequence") + .compareTo(snapshot.sequence()) + > 0 + || positiveDecimal(event.issuerAuthGeneration(), "selected generation") + .compareTo(snapshot.generation()) + > 0 + || positiveDecimal(event.sourceVersion(), "selected source version") + .compareTo(snapshot.sourceVersion()) + > 0) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + if (snapshot.sequence().equals(positiveDecimal(event.outboxSequence(), "selected sequence")) + && (snapshot.latestEvent() == null + || !snapshot.latestEvent().canonicalJson().equals(event.canonicalJson()))) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + } + return new VerifiedReadback(snapshot, selected); + } + + private static Checkpoint verifySnapshot(SourceSnapshot source) { + if (source == null || source.issuerId() == null || source.issuerId().isBlank()) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + String expectedScope = "issuer/" + source.issuerId(); + String expectedStream = + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + expectedScope; + if (!expectedScope.equals(source.sourceScope()) + || !expectedStream.equals(source.outboxStreamKey())) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + + BigInteger generation = positiveDecimal(source.issuerAuthGeneration(), "issuer generation"); + BigInteger sourceVersion = positiveDecimal(source.sourceVersion(), "source version"); + BigInteger sequence = nonnegativeDecimal(source.outboxSequence(), "outbox sequence"); + IssuerGenerationAuthorityEvent latest = + source.latestEvent().map(IssuerAuthorityProjectionTransitions::verifyEvent).orElse(null); + if (sequence.equals(ZERO)) { + if (!generation.equals(ONE) || !sourceVersion.equals(ONE) || latest != null) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + } else if (latest == null + || !sameSource(latest, source.issuerId(), source.outboxStreamKey()) + || !sequence.equals(positiveDecimal(latest.outboxSequence(), "latest event sequence")) + || !generation.equals( + positiveDecimal(latest.issuerAuthGeneration(), "latest event generation")) + || !sourceVersion.equals( + positiveDecimal(latest.sourceVersion(), "latest event source version"))) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + return new Checkpoint( + source.issuerId(), source.outboxStreamKey(), generation, sourceVersion, sequence, latest); + } + + private static IssuerGenerationAuthorityEvent verifyEvent( + IssuerGenerationAuthorityEvent supplied) { + if (supplied == null) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + IssuerGenerationAuthorityEvent verified; + try { + verified = IssuerGenerationAuthorityEventV1Codec.verify(supplied.canonicalJson()); + } catch (IllegalArgumentException malformed) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + if (!verified.canonicalJson().equals(supplied.canonicalJson()) + || !verified.eventId().equals(supplied.eventId()) + || !verified.eventDigest().equals(supplied.eventDigest()) + || !verified.issuerId().equals(supplied.issuerId()) + || !verified.sourceScope().equals(supplied.sourceScope()) + || !verified.outboxStreamKey().equals(supplied.outboxStreamKey()) + || !verified.outboxSequence().equals(supplied.outboxSequence()) + || !verified.issuerAuthGeneration().equals(supplied.issuerAuthGeneration()) + || !verified.sourceVersion().equals(supplied.sourceVersion())) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + UUID eventRequestId; + try { + eventRequestId = UUID.fromString(verified.requestId()); + } catch (IllegalArgumentException malformed) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + if (new UUID(0L, 0L).equals(eventRequestId) + || !eventRequestId.toString().equals(verified.requestId()) + || !(EVENT_ID_PREFIX + verified.requestId()).equals(verified.eventId())) { + throw reject(QuarantineReason.MALFORMED_ACCOUNT_READBACK); + } + return verified; + } + + private static boolean sameSource( + IssuerGenerationAuthorityEvent event, String issuerId, String streamKey) { + return issuerId.equals(event.issuerId()) + && ("issuer/" + issuerId).equals(event.sourceScope()) + && streamKey.equals(event.outboxStreamKey()); + } + + private static Map projectionFor(Checkpoint checkpoint, String appliedAt) { + if (checkpoint.sequence().equals(ZERO)) { + return projectionMap( + checkpoint.issuerId(), + checkpoint.generation().toString(), + "0", + checkpoint.streamKey(), + null, + appliedAt, + Map.of()); + } + return projectionFor( + checkpoint.latestEvent(), + checkpoint.generation().toString(), + checkpoint.sequence().toString(), + appliedAt); + } + + private static Map projectionFor( + IssuerGenerationAuthorityEvent event, + String issuerGeneration, + String sequence, + String appliedAt) { + return projectionMap( + event.issuerId(), + issuerGeneration, + sequence, + event.outboxStreamKey(), + event, + appliedAt, + Map.of(sequence, event.canonicalJson())); + } + + private static Map projectionMap( + String issuerId, + String issuerGeneration, + String sequence, + String streamKey, + IssuerGenerationAuthorityEvent latestEvent, + String appliedAt, + Map appliedSourceEvidence) { + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", SCHEMA_VERSION); + fields.put("issuerId", issuerId); + fields.put("issuerAuthGeneration", issuerGeneration); + fields.put("lastAppliedSourceOutboxSequence", sequence); + fields.put("sourceOutboxStreamKey", streamKey); + if (latestEvent != null) { + fields.put("sourceEventId", latestEvent.eventId()); + fields.put("sourceEventDigest", latestEvent.eventDigest()); + } + fields.put("appliedAt", appliedAt); + fields.put("appliedSourceEvidence", appliedSourceEvidence); + return immutableMap(fields); + } + + private static ExistingProjection parseExistingProjection(Map supplied) { + if (supplied == null) { + throw new IllegalArgumentException("projection is absent"); + } + String schema = requiredString(supplied, "schemaVersion"); + String issuer = requiredString(supplied, "issuerId"); + String generationText = requiredString(supplied, "issuerAuthGeneration"); + String sequenceText = requiredString(supplied, "lastAppliedSourceOutboxSequence"); + String stream = requiredString(supplied, "sourceOutboxStreamKey"); + String appliedAt = requiredString(supplied, "appliedAt"); + if (!SCHEMA_VERSION.equals(schema) || issuer.isBlank() || appliedAt.isBlank()) { + throw new IllegalArgumentException("projection identity or schema is malformed"); + } + + BigInteger generation = positiveDecimal(generationText, "projection generation"); + BigInteger sequence = nonnegativeDecimal(sequenceText, "projection sequence"); + String expectedStream = + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + issuer; + if (!expectedStream.equals(stream)) { + throw new IllegalArgumentException("projection stream identity is malformed"); + } + + Set expectedFields = new java.util.HashSet<>(BASE_FIELDS); + IssuerGenerationAuthorityEvent latest = null; + BigInteger sourceVersion = ONE; + Object evidenceValue = supplied.get("appliedSourceEvidence"); + if (!(evidenceValue instanceof Map evidence)) { + throw new IllegalArgumentException("projection source evidence is malformed"); + } + if (sequence.equals(ZERO)) { + if (!generation.equals(ONE) || !evidence.isEmpty()) { + throw new IllegalArgumentException("zero checkpoint projection is contradictory"); + } + } else { + expectedFields.addAll(POSITIVE_FIELDS); + if (evidence.size() != 1) { + throw new IllegalArgumentException("projection must retain its current source checkpoint"); + } + Object canonicalValue = evidence.get(sequenceText); + if (!(canonicalValue instanceof String canonicalEvent)) { + throw new IllegalArgumentException("projection current source evidence is absent"); + } + latest = verifiedProjectionEvent(canonicalEvent); + if (!sameSource(latest, issuer, stream) + || !sequence.equals(positiveDecimal(latest.outboxSequence(), "projection event sequence")) + || !generation.equals( + positiveDecimal(latest.issuerAuthGeneration(), "projection event generation")) + || !requiredString(supplied, "sourceEventId").equals(latest.eventId()) + || !requiredString(supplied, "sourceEventDigest").equals(latest.eventDigest())) { + throw new IllegalArgumentException("projection event does not match its checkpoint"); + } + sourceVersion = positiveDecimal(latest.sourceVersion(), "projection event source version"); + } + if (!supplied.keySet().equals(expectedFields)) { + throw new IllegalArgumentException("projection fields do not match the declared schema"); + } + validateEvidenceMapKeys(evidence, sequence, sequenceText); + return new ExistingProjection(issuer, generation, sourceVersion, sequence, stream, latest); + } + + private static IssuerGenerationAuthorityEvent verifiedProjectionEvent(String canonicalEvent) { + try { + IssuerGenerationAuthorityEvent event = + IssuerGenerationAuthorityEventV1Codec.verify(canonicalEvent); + if (!event.canonicalJson().equals(canonicalEvent)) { + throw new IllegalArgumentException("projection event is not canonical"); + } + return verifyEvent(event); + } catch (EvidenceRejected rejected) { + throw new IllegalArgumentException("projection event evidence is malformed", rejected); + } + } + + private static void validateEvidenceMapKeys( + Map evidence, BigInteger sequence, String sequenceText) { + for (Map.Entry entry : evidence.entrySet()) { + if (!(entry.getKey() instanceof String key) || !(entry.getValue() instanceof String)) { + throw new IllegalArgumentException("projection applied-source evidence is malformed"); + } + positiveDecimal(key, "projection evidence sequence"); + if (!sequence.equals(ZERO) && !sequenceText.equals(key)) { + throw new IllegalArgumentException("projection evidence is not the current checkpoint"); + } + } + } + + private static String requiredString(Map fields, String name) { + Object value = fields.get(name); + if (!(value instanceof String text)) { + throw new IllegalArgumentException("projection field " + name + " must be a string"); + } + return text; + } + + private static BigInteger positiveDecimal(String value, String label) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal"); + } + return new BigInteger(value); + } + + private static BigInteger nonnegativeDecimal(String value, String label) { + if (value == null || !value.matches("(?:0|[1-9][0-9]*)")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal"); + } + return new BigInteger(value); + } + + private static void requireAppliedAt(String appliedAt) { + if (appliedAt == null || appliedAt.isBlank()) { + throw reject(QuarantineReason.APPLIED_AT_REQUIRED); + } + } + + private static Optional> immutableObserved(Map observed) { + if (observed == null) { + return Optional.empty(); + } + try { + return Optional.of(immutableMap(observed)); + } catch (IllegalArgumentException malformed) { + return Optional.empty(); + } + } + + private static Map immutableMap(Map source) { + if (source == null) { + throw new IllegalArgumentException("projection maps must not be null"); + } + Map copy = new LinkedHashMap<>(); + for (Map.Entry entry : source.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw new IllegalArgumentException("projection map keys must be strings"); + } + copy.put(key, immutableValue(entry.getValue())); + } + return Collections.unmodifiableMap(copy); + } + + private static Object immutableValue(Object value) { + if (value instanceof Map map) { + return immutableMap(map); + } + if (value instanceof List list) { + List copy = new ArrayList<>(list.size()); + for (Object item : list) { + copy.add(immutableValue(item)); + } + return Collections.unmodifiableList(copy); + } + if (value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean) { + return value; + } + throw new IllegalArgumentException("projection values must be JSON-compatible"); + } + + private static EvidenceRejected reject(QuarantineReason reason) { + return new EvidenceRejected(reason); + } + + private record Checkpoint( + String issuerId, + String streamKey, + BigInteger generation, + BigInteger sourceVersion, + BigInteger sequence, + IssuerGenerationAuthorityEvent latestEvent) {} + + private record VerifiedReadback( + Checkpoint snapshot, Optional selectedEvent) {} + + private record ExistingProjection( + String issuerId, + BigInteger generation, + BigInteger sourceVersion, + BigInteger sequence, + String streamKey, + IssuerGenerationAuthorityEvent latestEvent) {} + + private static final class EvidenceRejected extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final QuarantineReason reason; + + private EvidenceRejected(QuarantineReason reason) { + this.reason = reason; + } + + private QuarantineReason reason() { + return reason; + } + } + + public sealed interface Decision permits Mutation, NoOp, Quarantine {} + + public enum MutationKind { + BOOTSTRAP, + ADVANCE + } + + public enum NoOpReason { + EXACT_DUPLICATE, + VERIFIED_HISTORICAL_DUPLICATE + } + + public enum QuarantineReason { + APPLIED_AT_REQUIRED, + BOOTSTRAP_REQUIRES_CURRENT_READBACK, + CURRENT_CHECKPOINT_CONFLICT, + CURRENT_CHECKPOINT_REGRESSED, + DUPLICATE_EVENT_CONFLICT, + EVENT_GENERATION_REGRESSED, + EVENT_SEQUENCE_GAP, + EVENT_SOURCE_VERSION_REGRESSED, + HISTORICAL_EVENT_PROGRESS_CONFLICT, + ISSUER_OR_STREAM_CHANGED, + MALFORMED_ACCOUNT_READBACK, + MALFORMED_EXISTING_PROJECTION, + MISSING_EXISTING_PROJECTION, + SELECTED_EVENT_REQUIRED + } + + /** An immutable atomic compare-and-set proposal. Empty expected state means bootstrap. */ + public record Mutation( + Optional> expectedProjection, + Map nextProjection, + MutationKind kind) + implements Decision { + public Mutation { + expectedProjection = Objects.requireNonNull(expectedProjection, "expected state is required"); + expectedProjection = + expectedProjection.map(IssuerAuthorityProjectionTransitions::immutableMap); + nextProjection = + immutableMap(Objects.requireNonNull(nextProjection, "next state is required")); + Objects.requireNonNull(kind, "mutation kind is required"); + } + + public Map nextProjection() { + return immutableMap(nextProjection); + } + } + + public record NoOp(NoOpReason reason) implements Decision { + public NoOp { + Objects.requireNonNull(reason, "no-op reason is required"); + } + } + + /** + * Quarantine contains the exact observed state when it could be represented as immutable JSON. + */ + public record Quarantine( + Optional> expectedProjection, QuarantineReason reason) + implements Decision { + public Quarantine { + expectedProjection = Objects.requireNonNull(expectedProjection, "expected state is required"); + expectedProjection = + expectedProjection.map(IssuerAuthorityProjectionTransitions::immutableMap); + Objects.requireNonNull(reason, "quarantine reason is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStore.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStore.java new file mode 100644 index 0000000000..5ea3f9d901 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStore.java @@ -0,0 +1,472 @@ +package net.firedevops.firemud.gamesession.service; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import java.io.IOException; +import java.nio.ByteBuffer; +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.time.Duration; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.redis.contracts.RedisInvocationContract; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.Decision; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.Mutation; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.NoOp; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.Quarantine; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.connection.RedisPassword; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; + +/** Explicitly owned, unwired Coordination Redis store for the derived issuer projection. */ +public final class RedisIssuerAuthorityProjectionStore implements AutoCloseable { + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); + private static final TypeReference> OBJECT_MAP = new TypeReference<>() {}; + private static final byte[] CAS_SCRIPT_BYTES = scriptBytes(); + private static final String CAS_SCRIPT_SHA1 = scriptSha1(CAS_SCRIPT_BYTES); + private static final byte[] CAS_SCRIPT_SHA256 = scriptSha256(CAS_SCRIPT_BYTES); + private static final Duration COMMAND_TIMEOUT = Duration.ofSeconds(3); + + private final String expectedWorkloadNamespace; + private final CoordinationEndpoint coordinationEndpoint; + private final CacheRateLimitEndpoint cacheRateLimitEndpoint; + + private LettuceConnectionFactory connectionFactory; + private StringRedisTemplate redisTemplate; + private boolean closed; + + /** + * Captures explicit role endpoints and credentials. This constructor creates no Spring bean and + * opens no connection; callers must invoke {@link #init()} explicitly. + */ + public RedisIssuerAuthorityProjectionStore( + String expectedWorkloadNamespace, + CoordinationEndpoint coordinationEndpoint, + CacheRateLimitEndpoint cacheRateLimitEndpoint) { + if (!GrpcPeerIdentity.isValidNamespace(expectedWorkloadNamespace)) { + throw new IllegalArgumentException("A valid expected workload namespace is required"); + } + this.expectedWorkloadNamespace = expectedWorkloadNamespace; + this.coordinationEndpoint = + Objects.requireNonNull(coordinationEndpoint, "Coordination endpoint is required"); + this.cacheRateLimitEndpoint = + Objects.requireNonNull(cacheRateLimitEndpoint, "Cache/Rate-Limit endpoint is required"); + validateDistinctEndpoints(coordinationEndpoint, cacheRateLimitEndpoint); + } + + /** Initializes this store's private Coordination-only Lettuce client and String template. */ + public synchronized void init() { + if (closed) { + throw new IllegalStateException("issuer projection store is closed"); + } + if (connectionFactory != null) { + return; + } + verifyScriptDigest(); + + RedisStandaloneConfiguration redisConfiguration = + new RedisStandaloneConfiguration(coordinationEndpoint.host(), coordinationEndpoint.port()); + redisConfiguration.setUsername(coordinationEndpoint.principal()); + redisConfiguration.setPassword(RedisPassword.of(coordinationEndpoint.password())); + LettuceClientConfiguration clientConfiguration = + LettuceClientConfiguration.builder().commandTimeout(COMMAND_TIMEOUT).build(); + + LettuceConnectionFactory newConnectionFactory = + new LettuceConnectionFactory(redisConfiguration, clientConfiguration); + newConnectionFactory.afterPropertiesSet(); + StringRedisTemplate newTemplate = new StringRedisTemplate(newConnectionFactory); + newTemplate.afterPropertiesSet(); + connectionFactory = newConnectionFactory; + redisTemplate = newTemplate; + } + + /** + * Applies one privately verified Account readback. This path performs one exact GET and at most + * one registered owner-script call; it never retries after a stale result. + */ + public synchronized ApplyResult apply(SourceReadback readback, String appliedAt) { + requireInitialized(); + if (readback == null) { + return quarantined("MALFORMED_ACCOUNT_READBACK", Optional.empty()); + } + if (!expectedWorkloadNamespace.equals(readback.targetNamespace())) { + return quarantined("ACCOUNT_NAMESPACE_MISMATCH", Optional.empty()); + } + if (readback.sourceSnapshot() == null || readback.sourceSnapshot().issuerId() == null) { + return quarantined("MALFORMED_ACCOUNT_READBACK", Optional.empty()); + } + + final String key; + try { + key = + IssuerAuthorityProjectionRedisContract.keyForIssuer(readback.sourceSnapshot().issuerId()); + } catch (IllegalArgumentException malformed) { + return quarantined("MALFORMED_ACCOUNT_READBACK", Optional.empty()); + } + + StoredValue observed = readStoredValue(key); + if (observed.bytes() != null && observed.ttlMillis() != -1L) { + return quarantined("TTL_PRESENT", Optional.empty()); + } + + final String observedJson; + final Decision decision; + if (observed.bytes() == null) { + observedJson = null; + decision = IssuerAuthorityProjectionTransitions.bootstrap(readback, appliedAt); + } else { + try { + observedJson = decodeUtf8(observed.bytes()); + Map observedProjection = parseProjection(observedJson); + decision = + IssuerAuthorityProjectionTransitions.decide(observedProjection, readback, appliedAt); + } catch (IOException | IllegalArgumentException malformed) { + return quarantined("MALFORMED_STORED_JSON", Optional.empty()); + } + } + + if (decision instanceof Quarantine quarantine) { + return quarantined(quarantine.reason().name(), Optional.of(decision)); + } + if (decision instanceof NoOp) { + if (observedJson == null) { + return quarantined("NO_OP_WITHOUT_EXISTING_PROJECTION", Optional.of(decision)); + } + String result = executeRegistered(key, "VERIFY", observedJson, ""); + if ("REPLAY".equals(result)) { + return new ApplyResult( + Outcome.NO_OP, + Optional.of(new ProjectionSnapshot(key, observedJson)), + Optional.empty(), + Optional.of(decision)); + } + return mutationOutcome(result, key, observedJson, decision); + } + if (!(decision instanceof Mutation mutation)) { + return quarantined("UNSUPPORTED_TRANSITION_DECISION", Optional.of(decision)); + } + + String expectedMode = observedJson == null ? "ABSENT" : "PRESENT"; + if (mutation.expectedProjection().isPresent() != (observedJson != null)) { + return quarantined("TRANSITION_EXPECTATION_MISMATCH", Optional.of(decision)); + } + String candidateJson; + try { + candidateJson = serializeProjection(mutation.nextProjection()); + } catch (IOException | IllegalArgumentException malformed) { + return quarantined("MALFORMED_CANDIDATE", Optional.of(decision)); + } + String result = + executeRegistered( + key, expectedMode, observedJson == null ? "" : observedJson, candidateJson); + return mutationOutcome(result, key, candidateJson, decision); + } + + @Override + public synchronized void close() { + closed = true; + if (connectionFactory != null) { + connectionFactory.destroy(); + connectionFactory = null; + redisTemplate = null; + } + } + + private ApplyResult mutationOutcome( + String result, String key, String candidateJson, Decision decision) { + if ("APPLIED".equals(result)) { + return new ApplyResult( + Outcome.APPLIED, + Optional.of(new ProjectionSnapshot(key, candidateJson)), + Optional.empty(), + Optional.of(decision)); + } + if ("REPLAY".equals(result)) { + return new ApplyResult( + Outcome.REPLAYED, + Optional.of(new ProjectionSnapshot(key, candidateJson)), + Optional.empty(), + Optional.of(decision)); + } + if ("STALE".equals(result)) { + return new ApplyResult( + Outcome.STALE, Optional.empty(), Optional.empty(), Optional.of(decision)); + } + if ("TTL_PRESENT".equals(result)) { + return quarantined("TTL_PRESENT", Optional.of(decision)); + } + if ("INVALID".equals(result)) { + return quarantined("REGISTERED_SCRIPT_REJECTED_INVOCATION", Optional.of(decision)); + } + return quarantined( + "UNKNOWN_REGISTERED_SCRIPT_RESULT:" + Objects.toString(result, "null"), + Optional.of(decision)); + } + + private String executeRegistered( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + RedisInvocationContract invocation = + IssuerAuthorityProjectionRedisContract.prepareInvocation( + key, expectedMode, expectedBytes, candidateBytes); + RedisScriptDescriptor descriptor = invocation.descriptor(); + if (descriptor != IssuerAuthorityProjectionRedisContract.descriptor() + || !descriptor.scriptId().equals(IssuerAuthorityProjectionRedisContract.SCRIPT_ID) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !IssuerAuthorityProjectionRedisContract.PRINCIPAL.equals(descriptor.principal())) { + throw new IllegalStateException( + "issuer projection invocation is not its registered owner contract"); + } + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + byte[] expectedModeBytes = expectedMode.getBytes(StandardCharsets.US_ASCII); + byte[] expectedBytesUtf8 = expectedBytes.getBytes(StandardCharsets.UTF_8); + byte[] candidateBytesUtf8 = candidateBytes.getBytes(StandardCharsets.UTF_8); + return redisTemplate.execute( + (RedisCallback) + connection -> { + String loadedSha = connection.scriptingCommands().scriptLoad(CAS_SCRIPT_BYTES); + if (!CAS_SCRIPT_SHA1.equals(loadedSha)) { + throw new IllegalStateException( + "Redis loaded a different issuer authority projection script"); + } + Object result = + connection + .scriptingCommands() + .evalSha( + loadedSha, + ReturnType.VALUE, + 1, + keyBytes, + expectedModeBytes, + expectedBytesUtf8, + candidateBytesUtf8); + return decodeScriptResult(result); + }); + } + + private StoredValue readStoredValue(String key) { + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + return redisTemplate.execute( + (RedisCallback) + connection -> { + byte[] value = connection.stringCommands().get(keyBytes); + long ttlMillis = value == null ? -2L : connection.keyCommands().pTtl(keyBytes); + return new StoredValue(value, ttlMillis); + }); + } + + private static Map parseProjection(String json) throws IOException { + JsonNode root = JSON.readTree(json); + if (root == null || !root.isObject()) { + throw new IllegalArgumentException("stored issuer projection must be a JSON object"); + } + return JSON.convertValue(root, OBJECT_MAP); + } + + private static String serializeProjection(Map projection) throws IOException { + return JSON.writeValueAsString(projection); + } + + private static String decodeUtf8(byte[] value) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } + + private static String decodeScriptResult(Object result) { + if (result instanceof byte[] bytes) { + try { + return StandardCharsets.US_ASCII + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalStateException( + "Registered issuer projection script returned non-ASCII", malformed); + } + } + if (result instanceof String text) { + return text; + } + if (result == null) { + return null; + } + throw new IllegalStateException( + "Registered issuer projection script returned an unsupported result type"); + } + + private void requireInitialized() { + if (closed || redisTemplate == null) { + throw new IllegalStateException("issuer projection store requires explicit init()"); + } + } + + private static void validateDistinctEndpoints( + CoordinationEndpoint coordination, CacheRateLimitEndpoint cache) { + if (normalizeHost(coordination.host()).equals(normalizeHost(cache.host())) + && coordination.port() == cache.port()) { + throw new IllegalArgumentException( + "Coordination and Cache/Rate-Limit Redis endpoints must be distinct"); + } + } + + private static String normalizeHost(String host) { + String normalized = host.toLowerCase(Locale.ROOT); + if (normalized.startsWith("[") && normalized.endsWith("]")) { + normalized = normalized.substring(1, normalized.length() - 1); + } + while (normalized.endsWith(".")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + return normalized; + } + + private static byte[] scriptBytes() { + try (var input = + new ClassPathResource(IssuerAuthorityProjectionRedisContract.RESOURCE_PATH) + .getInputStream()) { + return input.readAllBytes(); + } catch (IOException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + private static String scriptSha1(byte[] scriptBytes) { + try { + return java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-1").digest(scriptBytes)); + } catch (NoSuchAlgorithmException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + private static byte[] scriptSha256(byte[] scriptBytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(scriptBytes); + } catch (NoSuchAlgorithmException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + private static void verifyScriptDigest() { + String actual = java.util.HexFormat.of().formatHex(CAS_SCRIPT_SHA256); + if (!IssuerAuthorityProjectionRedisContract.descriptor().sha256().equals(actual)) { + throw new IllegalStateException( + "issuer projection Lua resource digest differs from its registration"); + } + } + + private static ApplyResult quarantined(String detail, Optional decision) { + return new ApplyResult(Outcome.QUARANTINED, Optional.empty(), Optional.of(detail), decision); + } + + private record StoredValue(byte[] bytes, long ttlMillis) {} + + public enum Outcome { + APPLIED, + NO_OP, + QUARANTINED, + REPLAYED, + STALE + } + + /** + * Immutable JSON snapshot returned for observation; it grants no admission or rebind authority. + */ + public record ProjectionSnapshot(String key, String json) { + public ProjectionSnapshot { + Objects.requireNonNull(key, "projection key is required"); + Objects.requireNonNull(json, "projection JSON is required"); + } + } + + public record ApplyResult( + Outcome outcome, + Optional snapshot, + Optional detail, + Optional transitionDecision) { + public ApplyResult { + Objects.requireNonNull(outcome, "outcome is required"); + snapshot = Objects.requireNonNull(snapshot, "snapshot optional is required"); + detail = Objects.requireNonNull(detail, "detail optional is required"); + transitionDecision = + Objects.requireNonNull(transitionDecision, "transition decision optional is required"); + } + } + + /** Explicit Coordination endpoint and ACL identity; the principal is not caller-selectable. */ + public record CoordinationEndpoint(String host, int port, String principal, String password) { + public CoordinationEndpoint { + validateHost(host, "Coordination host"); + validatePort(port, "Coordination port"); + if (!IssuerAuthorityProjectionRedisContract.PRINCIPAL.equals(principal)) { + throw new IllegalArgumentException("Coordination principal must be gamesession_coord_app"); + } + if (password == null || password.isBlank()) { + throw new IllegalArgumentException("Coordination ACL credential is required"); + } + } + + @Override + public String toString() { + return "CoordinationEndpoint[host=" + + host + + ", port=" + + port + + ", principal=" + + principal + + ", password=]"; + } + } + + /** Required separate Cache/Rate-Limit endpoint used only for collision validation. */ + public record CacheRateLimitEndpoint(String host, int port) { + public CacheRateLimitEndpoint { + validateHost(host, "Cache/Rate-Limit host"); + validatePort(port, "Cache/Rate-Limit port"); + } + } + + private static void validateHost(String host, String label) { + if (host == null + || host.isBlank() + || !host.equals(host.trim()) + || host.contains("://") + || host.chars().anyMatch(Character::isWhitespace) + || host.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(label + " must be an explicit host or IP address"); + } + } + + private static void validatePort(int port, String label) { + if (port < 1 || port > 65535) { + throw new IllegalArgumentException(label + " must be between 1 and 65535"); + } + } +} diff --git a/services/game-session-service/src/main/resources/redis/issuer_authority_projection_cas.lua b/services/game-session-service/src/main/resources/redis/issuer_authority_projection_cas.lua new file mode 100644 index 0000000000..a7b32ccc60 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/issuer_authority_projection_cas.lua @@ -0,0 +1,54 @@ +if #KEYS ~= 1 or #ARGV ~= 3 then + return 'INVALID' +end + +local mode = ARGV[1] +local expectedBytes = ARGV[2] +local candidateBytes = ARGV[3] + +if mode ~= 'ABSENT' and mode ~= 'PRESENT' and mode ~= 'VERIFY' then + return 'INVALID' +end + +if mode == 'VERIFY' then + if expectedBytes == '' or candidateBytes ~= '' then + return 'INVALID' + end +elseif mode == 'ABSENT' then + if expectedBytes ~= '' or candidateBytes == '' then + return 'INVALID' + end +elseif expectedBytes == '' or candidateBytes == '' then + return 'INVALID' +end + +local currentBytes = redis.call('GET', KEYS[1]) +if currentBytes ~= false and redis.call('PTTL', KEYS[1]) ~= -1 then + return 'TTL_PRESENT' +end + +if mode == 'VERIFY' then + if currentBytes == expectedBytes then + return 'REPLAY' + end + return 'STALE' +end + +if currentBytes == candidateBytes then + return 'REPLAY' +end + +if mode == 'ABSENT' then + if currentBytes ~= false then + return 'STALE' + end + redis.call('SET', KEYS[1], candidateBytes) + return 'APPLIED' +end + +if currentBytes ~= expectedBytes then + return 'STALE' +end + +redis.call('SET', KEYS[1], candidateBytes) +return 'APPLIED' diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcMtlsCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcMtlsCrossServiceTest.java new file mode 100644 index 0000000000..26639fe7bf --- /dev/null +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcMtlsCrossServiceTest.java @@ -0,0 +1,688 @@ +package crossservice.net.firedevops.firemud.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto.MembershipBaseline; +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.accountservice.service.impl.AccountMembershipAuthorityGrpcService; +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 net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamesession.client.AccountMembershipAuthorityClient; +import net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; + +/** Physical mutual-TLS proof for the deliberately unwired runtime membership readback. */ +class AccountMembershipAuthorityGrpcMtlsCrossServiceTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72001"; + private static final String TENANT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72002"; + private static final String OTHER_ACCOUNT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72003"; + private static final String OTHER_TENANT_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72004"; + private static final String REALM_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72005"; + private static final String PLAYABLE_NAMESPACE_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72006"; + private static final String GAME_INSTANCE_UUID = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72007"; + private static final String REQUEST_ID = "runtime-membership/read:operation-42"; + private static final String ACCOUNT_PEER_URI = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service"; + private static final String MEMBERSHIP_STREAM = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + ACCOUNT_UUID + + "/" + + TENANT_UUID; + + @TempDir private Path tempDir; + + private final Map copiedCertificates = new HashMap<>(); + + @Test + void exactGameSessionPeerReceivesNonadmittingPositiveMissingBaselineOverSocketMtls() + throws Exception { + AccountMembershipAuthorityEventProducer producer = + mock(AccountMembershipAuthorityEventProducer.class); + when(producer.readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID))) + .thenReturn(missingSnapshot(ACCOUNT_UUID, TENANT_UUID)); + Server server = startCandidateServer("account", producer); + + try (AccountMembershipAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + GetTenantMembershipForRuntimeResponse response = + client.getTenantMembershipForRuntime(validPlayerContext()); + + assertThat(response.getAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(response.getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getTenantId()).isEqualTo(TENANT_UUID); + assertThat(response.getRequestAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getRequestTenantId()).isEqualTo(TENANT_UUID); + assertThat(response.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(response.getMembershipExists()).isFalse(); + assertThat(response.getMembershipLifecycleState()).isEqualTo("MISSING"); + assertThat(response.getGameplayAdmissionAllowed()).isFalse(); + assertThat(response.getRolesList()).isEmpty(); + assertThat(response.getMembershipVersionMap()) + .containsOnlyKeys(TENANT_UUID) + .containsEntry(TENANT_UUID, "1"); + assertThat(response.getMembershipAuthorityGeneration()).isEqualTo("1"); + assertThat(response.getMembershipBaseline().getMembershipVersionMap()) + .containsOnlyKeys(TENANT_UUID) + .containsEntry(TENANT_UUID, "1"); + assertThat(response.getOutboxCheckpointsList()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.getOutboxStreamKey()).isEqualTo(MEMBERSHIP_STREAM); + assertThat(checkpoint.getOutboxSequence()).isEqualTo("0"); + }); + assertThat(response.getOutboxSourceEvidenceList()).isEmpty(); + + verify(producer) + .readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID)); + } finally { + stop(server); + } + } + + @Test + void exactGameSessionPeerReceivesBoundActiveMembershipEventOverSocketMtls() throws Exception { + AccountMembershipAuthorityEventProducer producer = + mock(AccountMembershipAuthorityEventProducer.class); + when(producer.readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID))) + .thenReturn(activeSnapshot()); + Server server = startCandidateServer("account", producer); + + try (AccountMembershipAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + GetTenantMembershipForRuntimeResponse response = + client.getTenantMembershipForRuntime(validPlayerContext()); + + assertThat(response.getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getTenantId()).isEqualTo(TENANT_UUID); + assertThat(response.getRequestAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getRequestTenantId()).isEqualTo(TENANT_UUID); + assertThat(response.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(response.getMembershipExists()).isTrue(); + assertThat(response.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(response.getGameplayAdmissionAllowed()).isTrue(); + assertThat(response.getMembershipVersionMap()) + .containsOnlyKeys(TENANT_UUID) + .containsEntry(TENANT_UUID, "2"); + assertThat(response.getRolesList()).containsExactly("player"); + assertThat(response.getOutboxCheckpointsList()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.getOutboxStreamKey()).isEqualTo(MEMBERSHIP_STREAM); + assertThat(checkpoint.getOutboxSequence()).isEqualTo("1"); + }); + assertThat(response.getOutboxSourceEvidenceList()).hasSize(1); + var source = response.getOutboxSourceEvidence(0); + MembershipEvent verifiedEvent = + MembershipAuthorityEventV1Codec.verify(source.getCanonicalEventJson()); + assertThat(source.getOutboxStreamKey()).isEqualTo(MEMBERSHIP_STREAM); + assertThat(source.getOutboxSequence()).isEqualTo("1"); + assertThat(verifiedEvent.accountId()).isEqualTo(ACCOUNT_UUID); + assertThat(verifiedEvent.tenantId()).isEqualTo(TENANT_UUID); + assertThat(verifiedEvent.eventId()).isEqualTo(source.getEventId()); + assertThat(verifiedEvent.eventDigest()).isEqualTo(source.getEventDigest()); + + verify(producer) + .readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID)); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(strings = {"wrong-service", "wrong-namespace"}) + void trustedButUnauthorizedGameSessionPeerIsDeniedBeforeProducerAccess(String clientIdentity) + throws Exception { + AccountMembershipAuthorityEventProducer producer = + mock(AccountMembershipAuthorityEventProducer.class); + Server server = startCandidateServer("account", producer); + + try (AccountMembershipAuthorityClient client = newClient(server.getPort(), clientIdentity)) { + client.init(); + + Throwable failure = + catchThrowable(() -> client.getTenantMembershipForRuntime(validPlayerContext())); + assertStatusFailure(failure, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(producer); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(strings = {"game-session", "wrong-account-namespace"}) + void trustedAccountWithWrongServiceOrNamespaceIsRejectedBeforeContentAcceptance( + String serverIdentity) throws Exception { + AccountMembershipAuthorityEventProducer producer = + mock(AccountMembershipAuthorityEventProducer.class); + when(producer.readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID))) + .thenReturn(missingSnapshot(ACCOUNT_UUID, TENANT_UUID)); + Server server = startCandidateServer(serverIdentity, producer); + + try (AccountMembershipAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + Throwable failure = + catchThrowable(() -> client.getTenantMembershipForRuntime(validPlayerContext())); + assertStatusFailure(failure, Status.Code.UNAUTHENTICATED); + verify(producer) + .readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID)); + } finally { + stop(server); + } + } + + @Test + void missingClientCertificateIsRejectedByTheRequiredTlsHandshake() throws Exception { + AccountMembershipAuthorityEventProducer producer = + mock(AccountMembershipAuthorityEventProducer.class); + Server server = startCandidateServer("account", producer); + SSLContext trustOnlyClientContext = trustOnlyClientContext(); + + try { + Throwable handshakeFailure = + catchThrowable( + () -> { + try (Socket transport = new Socket()) { + transport.connect(new InetSocketAddress("127.0.0.1", server.getPort()), 5_000); + try (SSLSocket socket = + (SSLSocket) + trustOnlyClientContext + .getSocketFactory() + .createSocket(transport, "127.0.0.1", server.getPort(), true)) { + socket.setSoTimeout(5_000); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setApplicationProtocols(new String[] {"h2"}); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + socket.setSSLParameters(parameters); + socket.startHandshake(); + // TLS 1.3 may report the server's certificate rejection on the first read. + socket + .getOutputStream() + .write( + "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); + socket.getOutputStream().flush(); + socket.getInputStream().read(); + } + } + }); + + assertThat(handshakeFailure) + .as("the REQUIRED client-certificate handshake must fail") + .isNotNull(); + assertThat(TlsTestSupport.isTlsHandshakeRejection(handshakeFailure)) + .as("failure must identify certificate rejection: %s", describe(handshakeFailure)) + .isTrue(); + verifyNoInteractions(producer); + } finally { + stop(server); + } + } + + @Test + void exactGameSessionPeerCannotSendMalformedTypedContextToTheCandidateHandler() throws Exception { + AccountMembershipAuthorityEventProducer producer = + mock(AccountMembershipAuthorityEventProducer.class); + Server server = startCandidateServer("account", producer); + RawClient rawClient = newRawClient(server.getPort(), "game-session"); + + try { + PlayerExecutionContext malformedContext = + validPlayerContext().toBuilder().setSessionId("050").build(); + GetTenantMembershipForRuntimeRequest request = + GetTenantMembershipForRuntimeRequest.newBuilder() + .setPlayerContext(malformedContext) + .build(); + + assertThatThrownBy( + () -> + rawClient + .stub() + .withDeadlineAfter(5, TimeUnit.SECONDS) + .getTenantMembershipForRuntime(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT)); + verifyNoInteractions(producer); + } finally { + stop(rawClient.channel()); + stop(server); + } + } + + @Test + void exactPeerCannotReceiveCrossBoundProducerSnapshot() throws Exception { + AccountMembershipAuthorityEventProducer producer = + mock(AccountMembershipAuthorityEventProducer.class); + when(producer.readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID))) + .thenReturn(missingSnapshot(OTHER_ACCOUNT_UUID, OTHER_TENANT_UUID)); + Server server = startCandidateServer("account", producer); + + try (AccountMembershipAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + Throwable failure = + catchThrowable(() -> client.getTenantMembershipForRuntime(validPlayerContext())); + assertStatusFailure(failure, Status.Code.FAILED_PRECONDITION); + verify(producer) + .readRuntimeMembershipSnapshot( + UUID.fromString(ACCOUNT_UUID), UUID.fromString(TENANT_UUID)); + } finally { + stop(server); + } + } + + @Test + void exactAccountPeerCannotDeliverCrossBoundRecipientEchoes() throws Exception { + GetTenantMembershipForRuntimeResponse crossBoundResponse = + currentActiveResponse(validPlayerContext()).toBuilder() + .setRequestAccountId(OTHER_ACCOUNT_UUID) + .build(); + Server server = startResponseServer("account", ignored -> crossBoundResponse); + + try (AccountMembershipAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + assertThatThrownBy(() -> client.getTenantMembershipForRuntime(validPlayerContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("availability or exact recipient/request echoes changed"); + } finally { + stop(server); + } + } + + @Test + void exactAccountPeerCannotDeliverMalformedCurrentMembershipCarrier() throws Exception { + GetTenantMembershipForRuntimeResponse malformedResponse = + currentActiveResponse(validPlayerContext()).toBuilder().clearOutboxSourceEvidence().build(); + Server server = startResponseServer("account", ignored -> malformedResponse); + + try (AccountMembershipAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + assertThatThrownBy(() -> client.getTenantMembershipForRuntime(validPlayerContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("content evidence is incomplete or contradictory") + .satisfies( + failure -> + assertThat(failure.getCause()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sourceEvidence")); + } finally { + stop(server); + } + } + + private AccountMembershipAuthorityClient newClient(int port, String clientIdentity) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + return new AccountMembershipAuthorityClient( + endpoints, + tlsProperties(clientIdentity), + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE); + } + + private RawClient newRawClient(int port, String clientIdentity) throws Exception { + CommonGrpcClientProperties tls = tlsProperties(clientIdentity); + ManagedChannel channel = + new GrpcChannelFactory().buildChannel("localhost:" + port, 6565, tls, false); + AccountServiceGrpc.AccountServiceBlockingStub stub = + AccountServiceGrpc.newBlockingStub(channel) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(ACCOUNT_PEER_URI)); + return new RawClient(channel, stub); + } + + private CommonGrpcClientProperties tlsProperties(String clientIdentity) throws IOException { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate(clientIdentity + ".crt").toString()); + tls.setPrivateKey(certificate(clientIdentity + ".key").toString()); + tls.setCaCert(certificate("ca.crt").toString()); + return tls; + } + + private Server startCandidateServer( + String serverIdentity, AccountMembershipAuthorityEventProducer producer) throws Exception { + return startServer( + serverIdentity, + new AccountMembershipAuthorityGrpcService( + producer, new TestTransactionManager(), NAMESPACE)); + } + + private Server startResponseServer(String serverIdentity, ResponseFactory responseFactory) + throws Exception { + AccountServiceGrpc.AccountServiceImplBase responseService = + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest request, + StreamObserver responseObserver) { + responseObserver.onNext(responseFactory.response(request.getPlayerContext())); + responseObserver.onCompleted(); + } + }; + return startServer(serverIdentity, responseService); + } + + private Server startServer( + String serverIdentity, AccountServiceGrpc.AccountServiceImplBase service) throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + certificate(serverIdentity + ".crt").toFile(), + certificate(serverIdentity + ".key").toFile()) + .trustManager(certificate("ca.crt").toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private Path certificate(String name) throws IOException { + Path existing = copiedCertificates.get(name); + if (existing != null) { + return existing; + } + + String resourcePath = "/certs/issuer-authority/" + name; + try (InputStream resource = + AccountMembershipAuthorityGrpcMtlsCrossServiceTest.class.getResourceAsStream( + resourcePath)) { + if (resource == null) { + throw new IllegalStateException("Missing workload mTLS test fixture: " + resourcePath); + } + Path copied = tempDir.resolve(name); + Files.copy(resource, copied); + copiedCertificates.put(name, copied); + return copied; + } + } + + private SSLContext trustOnlyClientContext() throws Exception { + X509Certificate caCertificate; + try (InputStream input = Files.newInputStream(certificate("ca.crt"))) { + caCertificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null); + trustStore.setCertificateEntry("test-ca", caCertificate); + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + + SSLContext context = SSLContext.getInstance("TLS"); + context.init(new KeyManager[0], trustManagers.getTrustManagers(), null); + return context; + } + + private static RuntimeMembershipSnapshotDto missingSnapshot( + String accountUuid, String tenantUuid) { + return new RuntimeMembershipSnapshotDto( + accountUuid, + tenantUuid, + accountUuid, + tenantUuid, + false, + false, + new MembershipBaseline("MISSING", Map.of(tenantUuid, "1"), "1"), + List.of(), + new AuthorityTuple( + "1", + "1", + Map.of(tenantUuid, "1"), + Map.of(tenantUuid, "1"), + List.of(), + Optional.empty(), + Optional.empty()), + "7", + Instant.now(), + checkpoints(accountUuid, tenantUuid, "0"), + List.of(), + null); + } + + private static RuntimeMembershipSnapshotDto activeSnapshot() { + MembershipEvent event = activeMembershipEvent(); + return new RuntimeMembershipSnapshotDto( + ACCOUNT_UUID, + TENANT_UUID, + ACCOUNT_UUID, + TENANT_UUID, + true, + true, + new MembershipBaseline("ACTIVE", Map.of(TENANT_UUID, "2"), "1"), + List.of("player"), + new AuthorityTuple( + "1", + "1", + Map.of(TENANT_UUID, "1"), + Map.of(TENANT_UUID, "1"), + List.of(), + Optional.empty(), + Optional.empty()), + "7", + Instant.now(), + checkpoints(ACCOUNT_UUID, TENANT_UUID, "1"), + List.of( + new OutboxSourceEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.canonicalJson())), + event); + } + + private static List checkpoints( + String accountUuid, String tenantUuid, String membershipSequence) { + return List.of( + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + accountUuid, "0"), + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "issuer/" + + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + "0"), + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid, + membershipSequence), + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantUuid, "0")); + } + + private static MembershipEvent activeMembershipEvent() { + Map preimage = new LinkedHashMap<>(); + preimage.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + preimage.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + preimage.put("eventId", "04ef66b4-c0ad-3d5b-b3b2-0e8510e72008"); + preimage.put("requestId", "membership-join/committed-operation-1"); + preimage.put("outboxStreamKey", MEMBERSHIP_STREAM); + preimage.put("outboxSequence", "1"); + preimage.put("sourceScope", "membership/" + ACCOUNT_UUID + "/" + TENANT_UUID); + preimage.put("accountId", ACCOUNT_UUID); + preimage.put("tenantId", TENANT_UUID); + preimage.put("membershipExists", true); + preimage.put("membershipLifecycleState", "ACTIVE"); + preimage.put("membershipVersion", Map.of(TENANT_UUID, "2")); + preimage.put("membershipAuthorityGeneration", "1"); + preimage.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(TENANT_UUID, "1"), + "membershipAuthorityGeneration", + Map.of(TENANT_UUID, "1"), + "privateRealmGrantVersions", + List.of())); + preimage.put("issuanceFence", "7"); + preimage.put("roles", List.of("player")); + preimage.put("gameplayAdmissionAllowed", true); + preimage.put("callerBoundAuthorityInvalidated", false); + return MembershipAuthorityEventV1Codec.seal(preimage); + } + + private static GetTenantMembershipForRuntimeResponse currentActiveResponse( + PlayerExecutionContext request) { + return RuntimeMembershipTestFixtures.active(ACCOUNT_UUID, 1L, TENANT_UUID, "2").toBuilder() + .setRequestAccountId(request.getAccountId()) + .setRequestTenantId(request.getTenantId()) + .setRequestId(request.getRequestId()) + .build(); + } + + private static PlayerExecutionContext validPlayerContext() { + return PlayerExecutionContext.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId(TENANT_UUID) + .setRealmId(REALM_UUID) + .setPlayableStateNamespaceId(PLAYABLE_NAMESPACE_UUID) + .setPlayableStateScope("SHARED") + .setGameInstanceId(GAME_INSTANCE_UUID) + .setSessionId("50") + .setCharacterId("9") + .setRequestId(REQUEST_ID) + .build(); + } + + private static void assertStatusFailure(Throwable failure, Status.Code code) { + assertThat(failure).isInstanceOf(IllegalStateException.class); + assertThat(failure.getCause()).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code); + } + + private static String describe(Throwable failure) { + StringBuilder description = new StringBuilder(); + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (description.length() > 0) { + description.append(" <- "); + } + description.append(cause.getClass().getSimpleName()); + if (cause.getMessage() != null) { + description.append(": ").append(cause.getMessage()); + } + } + return description.toString(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + server.awaitTermination(2, TimeUnit.SECONDS); + } + + private static void stop(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + channel.awaitTermination(2, TimeUnit.SECONDS); + } + + @FunctionalInterface + private interface ResponseFactory { + GetTenantMembershipForRuntimeResponse response(PlayerExecutionContext request); + } + + private record RawClient( + ManagedChannel channel, AccountServiceGrpc.AccountServiceBlockingStub stub) {} + + private static final class TestTransactionManager extends AbstractPlatformTransactionManager { + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected boolean isExistingTransaction(Object transaction) { + return false; + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.java new file mode 100644 index 0000000000..39a17500fc --- /dev/null +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.java @@ -0,0 +1,1463 @@ +package crossservice.net.firedevops.firemud.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.when; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.accountservice.AccountServiceApplication; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; +import net.firedevops.firemud.accountservice.dto.MembershipTransitionReceipt; +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.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountMembershipLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.AccountTenantAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.impl.AccountMembershipAuthorityGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import net.firedevops.firemud.gamesession.client.AccountMembershipAuthorityClient; +import net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.v1.GameplayRealm; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import net.firedevops.firemud.test.GatewayTestProperties; +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; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Account producer and PostgreSQL readback composed with the physical Game Session mTLS + * client. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = AccountServiceApplication.class, + properties = { + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, + GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.grpc.workload-namespace=test" + }) +class AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_SLUG = "membership-mtls-proof-world"; + private static final String REALM_SLUG = "production"; + private static final String PLAYABLE_STATE_NAMESPACE_ID = "3fb3292a-8737-4d4f-bd24-90419d325747"; + private static final UUID REALM_ID = UUID.fromString("7bda1169-a8a3-4b43-96a4-53f8579ac164"); + private static final UUID GAME_INSTANCE_CONTEXT_ID = + UUID.fromString("2c5f6201-68ba-4d4f-afb0-928a925830ec"); + private static final long RETAINED_JOIN_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:"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + @Autowired private AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; + @Autowired private AccountAuthorityGenerationRepository authorityGenerationRepository; + @Autowired private AccountAuthorityOutboxRepository authorityOutboxRepository; + @Autowired private AccountRepository accountRepository; + @Autowired private AccountMembershipLifecycleService membershipLifecycleService; + @Autowired private AccountLogoutAllOperationRepository logoutAllOperationRepository; + @Autowired private AccountPasswordResetOperationRepository passwordResetOperationRepository; + @Autowired private ApprovedLegacyTenantAssociationRepository tenantAssociationRepository; + @Autowired private LegacyTenantSourceEvidence legacyTenantSourceEvidence; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @TempDir private Path tempDir; + + private final Map copiedCertificates = new HashMap<>(); + + @Test + void realMembershipSnapshotAndSequenceZeroBaselineCrossPostgresAndAuthenticatedSocket() + throws Exception { + // Account JOIN creates the committed fixture source; this test does not issue auth credentials + // or invoke Game Session gameplay admission through the membership read. + JoinFixture joined = fixture(); + JoinPublicProductionResult joinResult = join(joined); + assertThat(joinResult.success()).isTrue(); + + RuntimeMembershipSnapshotDto beforeCutoff = readRuntimeMembershipSnapshot(joined); + var immutableMembershipEvent = beforeCutoff.sourceEvent(); + byte[] immutableMembershipBytes = immutableMembershipEvent.canonicalJsonUtf8(); + assertThat(beforeCutoff.membershipExists()).isTrue(); + assertThat(beforeCutoff.gameplayAdmissionAllowed()).isTrue(); + assertThat(beforeCutoff.issuanceFence()).isEqualTo("1"); + assertThat(immutableMembershipEvent.issuanceFence()).isEqualTo("1"); + assertThat(immutableMembershipEvent.authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(immutableMembershipEvent.authorityTuple().accountAuthorityGeneration()) + .isEqualTo("1"); + assertThat(immutableMembershipEvent.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "1")); + + Server server = startServer(); + try (AccountMembershipAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + PlayerExecutionContext initialContext = + playerContext(joined, joined.tenantUuid(), "membership-read-before-cutoff"); + GetTenantMembershipForRuntimeResponse initialRead = + client.getTenantMembershipForRuntime(initialContext); + assertResponseMatchesSnapshot(initialRead, initialContext, beforeCutoff); + assertMembershipEvidence( + initialRead, joined, immutableMembershipEvent, immutableMembershipBytes); + assertThat(initialRead.getOutboxSourceEvidenceCount()).isEqualTo(1); + assertThat(initialRead.getAuthorityTuple().getIssuerAuthGeneration()).isEqualTo("1"); + assertThat(initialRead.getAuthorityTuple().getAccountAuthorityGeneration()).isEqualTo("1"); + assertThat(initialRead.getAuthorityTuple().getTenantAuthorityGenerationMap()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "1")); + assertThat(initialRead.getAuthorityTuple().getMembershipAuthorityGenerationMap()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "1")); + + UUID issuerRequestId = UUID.randomUUID(); + UUID tenantRequestId = UUID.randomUUID(); + UUID logoutRequestId = UUID.randomUUID(); + String presentedTokenHash = "b".repeat(64); + String tokenProfile = "control-ui"; + String requestDigest = + AccountLogoutRequestDigest.accountLogoutAll( + joined.accountUuid(), tokenProfile, presentedTokenHash); + AccountIssuerAuthorityEventProducer issuerProducer = issuerProducer(); + AccountTenantAuthorityEventProducer tenantProducer = tenantProducer(); + AccountLogoutAllAuthorityEventProducer logoutProducer = logoutProducer(); + var issuerEvent = + issuerProducer.advance(AccountServiceImpl.ACCOUNT_JWT_ISSUER, issuerRequestId, 1L, 1L); + var tenantEvent = tenantProducer.advance(joined.tenantUuid(), tenantRequestId, 1L, 1L); + ScopeState preLogoutAccountState = readAccountAuthority(joined.accountUuid()); + Account account = readAccount(joined.accountId()); + assertThat( + logoutProducer.commit( + logoutRequestId, + 1, + requestDigest, + tokenProfile, + presentedTokenHash, + account, + preLogoutAccountState)) + .isEqualTo(AccountLogoutAllAuthorityEventProducer.LogoutAllResult.LOGOUT_ALL_COMMITTED); + + RuntimeMembershipSnapshotDto afterCutoff = readRuntimeMembershipSnapshot(joined); + assertThat(afterCutoff.membershipBaseline()).isEqualTo(beforeCutoff.membershipBaseline()); + assertThat(afterCutoff.roles()).isEqualTo(beforeCutoff.roles()); + assertThat(afterCutoff.authorityTuple().issuerAuthGeneration()).isEqualTo("2"); + assertThat(afterCutoff.authorityTuple().accountAuthorityGeneration()).isEqualTo("2"); + assertThat(afterCutoff.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "2")); + assertThat(afterCutoff.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "1")); + assertThat(afterCutoff.issuanceFence()).isEqualTo("2"); + assertThat(afterCutoff.authorityTuple().accountSecurityCutoff()) + .hasValueSatisfying( + cutoff -> { + assertThat(cutoff.accountAuthorityGeneration()).isEqualTo("2"); + assertThat(cutoff.outboxStreamKey()) + .isEqualTo(accountStreamKey(joined.accountUuid())); + assertThat(cutoff.outboxSequence()).isEqualTo("1"); + }); + assertThat(afterCutoff.outboxCheckpoints()) + .containsExactly( + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + accountStreamKey(joined.accountUuid()), "1"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + issuerStreamKey(), "1"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + membershipStreamKey(joined), "1"), + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + tenantStreamKey(joined.tenantUuid()), "1")); + assertThat(afterCutoff.outboxSourceEvidence()) + .extracting(AccountMembershipAuthorityEventProducer.OutboxSourceEvidence::outboxStreamKey) + .containsExactly( + accountStreamKey(joined.accountUuid()), + issuerStreamKey(), + membershipStreamKey(joined), + tenantStreamKey(joined.tenantUuid())); + + PlayerExecutionContext currentContext = + playerContext(joined, joined.tenantUuid(), "membership-read-after-cutoff"); + GetTenantMembershipForRuntimeResponse currentRead = + client.getTenantMembershipForRuntime(currentContext); + assertResponseMatchesSnapshot(currentRead, currentContext, afterCutoff); + assertMembershipEvidence( + currentRead, joined, immutableMembershipEvent, immutableMembershipBytes); + assertThat(currentRead.getAuthorityTuple().getIssuerAuthGeneration()).isEqualTo("2"); + assertThat(currentRead.getAuthorityTuple().getAccountAuthorityGeneration()).isEqualTo("2"); + assertThat(currentRead.getAuthorityTuple().getTenantAuthorityGenerationMap()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "2")); + assertThat(currentRead.getAuthorityTuple().getMembershipAuthorityGenerationMap()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "1")); + assertThat(currentRead.getIssuanceFence()).isEqualTo("2"); + assertThat(currentRead.getAuthorityTuple().hasAccountSecurityCutoff()).isTrue(); + assertThat( + currentRead + .getAuthorityTuple() + .getAccountSecurityCutoff() + .getAccountAuthorityGeneration()) + .isEqualTo("2"); + assertThat(currentRead.getAuthorityTuple().getAccountSecurityCutoff().getOutboxStreamKey()) + .isEqualTo(accountStreamKey(joined.accountUuid())); + assertThat(currentRead.getAuthorityTuple().getAccountSecurityCutoff().getOutboxSequence()) + .isEqualTo("1"); + assertThat(currentRead.getOutboxCheckpointsList()) + .extracting( + checkpoint -> checkpoint.getOutboxStreamKey() + "=" + checkpoint.getOutboxSequence()) + .containsExactly( + accountStreamKey(joined.accountUuid()) + "=1", + issuerStreamKey() + "=1", + membershipStreamKey(joined) + "=1", + tenantStreamKey(joined.tenantUuid()) + "=1"); + assertThat(currentRead.getOutboxSourceEvidenceCount()).isEqualTo(4); + assertSourceEvidence( + currentRead, issuerStreamKey(), issuerEvent.eventId(), issuerEvent.eventDigest()); + assertSourceEvidence( + currentRead, + tenantStreamKey(joined.tenantUuid()), + tenantEvent.eventId(), + tenantEvent.eventDigest()); + assertThat(currentRead.getOutboxSourceEvidenceList()) + .allSatisfy( + evidence -> { + assertThat(evidence.getEventId()).isNotBlank(); + assertThat(evidence.getEventDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(evidence.getCanonicalEventJson()).isNotBlank(); + }); + + assertThat( + issuerProducer + .advance(AccountServiceImpl.ACCOUNT_JWT_ISSUER, issuerRequestId, 1L, 1L) + .eventDigest()) + .isEqualTo(issuerEvent.eventDigest()); + assertThat(tenantProducer.advance(joined.tenantUuid(), tenantRequestId, 1L, 1L).eventDigest()) + .isEqualTo(tenantEvent.eventDigest()); + assertThat( + logoutProducer.commit( + logoutRequestId, + 1, + requestDigest, + tokenProfile, + presentedTokenHash, + account, + preLogoutAccountState)) + .isEqualTo(AccountLogoutAllAuthorityEventProducer.LogoutAllResult.LOGOUT_ALL_COMMITTED); + + RuntimeMembershipSnapshotDto retryReadback = readRuntimeMembershipSnapshot(joined); + assertThat(retryReadback.authorityTuple()).isEqualTo(afterCutoff.authorityTuple()); + assertThat(retryReadback.issuanceFence()).isEqualTo(afterCutoff.issuanceFence()); + assertThat(retryReadback.outboxCheckpoints()).isEqualTo(afterCutoff.outboxCheckpoints()); + assertThat(retryReadback.outboxSourceEvidence()) + .isEqualTo(afterCutoff.outboxSourceEvidence()); + assertThat(retryReadback.sourceEvent().canonicalJsonUtf8()) + .containsExactly(immutableMembershipBytes); + assertThat(membershipEventBytes(joined)).containsExactly(immutableMembershipBytes); + PlayerExecutionContext retryContext = + playerContext(joined, joined.tenantUuid(), "membership-read-retry"); + GetTenantMembershipForRuntimeResponse retryResponse = + client.getTenantMembershipForRuntime(retryContext); + assertResponseMatchesSnapshot(retryResponse, retryContext, retryReadback); + assertMembershipEvidence( + retryResponse, joined, immutableMembershipEvent, immutableMembershipBytes); + assertThat(stableCarrier(retryResponse)).isEqualTo(stableCarrier(currentRead)); + + JoinFixture neverJoined = fixture(); + UUID neverJoinedTenantRequestId = UUID.randomUUID(); + var neverJoinedTenantEvent = + tenantProducer.advance(neverJoined.tenantUuid(), neverJoinedTenantRequestId, 1L, 1L); + DenialReadback beforeUnauthorizedRead = denialReadback(neverJoined); + assertThat(beforeUnauthorizedRead.membershipPairRows()).isZero(); + assertThat(beforeUnauthorizedRead.membershipGenerationRows()).isZero(); + assertThat(beforeUnauthorizedRead.membershipRows()).isZero(); + assertThat(beforeUnauthorizedRead.membershipEvents()).isZero(); + + for (String wrongPeer : List.of("wrong-service", "wrong-namespace")) { + try (AccountMembershipAuthorityClient wrongPeerClient = + newClient(server.getPort(), wrongPeer)) { + wrongPeerClient.init(); + PlayerExecutionContext deniedContext = + playerContext(neverJoined, neverJoined.tenantUuid(), "membership-read-wrong-peer"); + assertRemoteFailure( + () -> wrongPeerClient.getTenantMembershipForRuntime(deniedContext), + Status.Code.PERMISSION_DENIED); + } + assertThat(denialReadback(neverJoined)).isEqualTo(beforeUnauthorizedRead); + } + + PlayerExecutionContext absentContext = + playerContext(neverJoined, neverJoined.tenantUuid(), "membership-read-never-joined"); + GetTenantMembershipForRuntimeResponse absentRead = + client.getTenantMembershipForRuntime(absentContext); + RuntimeMembershipSnapshotDto absentSnapshot = readRuntimeMembershipSnapshot(neverJoined); + assertResponseMatchesSnapshot(absentRead, absentContext, absentSnapshot); + assertThat(absentRead.getMembershipExists()).isFalse(); + assertThat(absentRead.getGameplayAdmissionAllowed()).isFalse(); + assertThat(absentRead.getMembershipLifecycleState()).isEqualTo("MISSING"); + assertThat(absentRead.getMembershipVersionMap()) + .isEqualTo(Map.of(neverJoined.tenantUuid().toString(), "1")); + assertThat(absentRead.getMembershipAuthorityGeneration()).isEqualTo("1"); + assertThat(absentRead.getMembershipBaseline().getMembershipLifecycleState()) + .isEqualTo("MISSING"); + assertThat(absentRead.getRolesList()).isEmpty(); + assertThat(absentRead.getIssuanceFence()).isEqualTo("1"); + assertThat(absentRead.getAuthorityTuple().getIssuerAuthGeneration()).isEqualTo("2"); + assertThat(absentRead.getAuthorityTuple().getAccountAuthorityGeneration()).isEqualTo("1"); + assertThat(absentRead.getAuthorityTuple().getTenantAuthorityGenerationMap()) + .isEqualTo(Map.of(neverJoined.tenantUuid().toString(), "2")); + assertThat(absentRead.getAuthorityTuple().getMembershipAuthorityGenerationMap()) + .isEqualTo(Map.of(neverJoined.tenantUuid().toString(), "1")); + assertThat(absentRead.getOutboxCheckpointsList()) + .extracting( + checkpoint -> checkpoint.getOutboxStreamKey() + "=" + checkpoint.getOutboxSequence()) + .containsExactly( + accountStreamKey(neverJoined.accountUuid()) + "=0", + issuerStreamKey() + "=1", + membershipStreamKey(neverJoined) + "=0", + tenantStreamKey(neverJoined.tenantUuid()) + "=1"); + assertThat(absentRead.getOutboxSourceEvidenceList()) + .extracting(evidence -> evidence.getOutboxStreamKey()) + .containsExactly(issuerStreamKey(), tenantStreamKey(neverJoined.tenantUuid())); + assertThat(absentRead.getOutboxSourceEvidenceList().get(1).getEventId()) + .isEqualTo(neverJoinedTenantEvent.eventId()); + assertThat(absentRead.getOutboxSourceEvidenceList().get(1).getEventDigest()) + .isEqualTo(neverJoinedTenantEvent.eventDigest()); + assertThat(absentRead.getOutboxSourceEvidenceList()) + .noneMatch( + evidence -> membershipStreamKey(neverJoined).equals(evidence.getOutboxStreamKey())); + assertDurableSequenceZeroPairBaseline(neverJoined); + assertThat(countMembershipRows(neverJoined)).isZero(); + assertThat(countStreamEvents(membershipStreamKey(neverJoined))).isZero(); + GetTenantMembershipForRuntimeResponse absentReadback = + client.getTenantMembershipForRuntime( + playerContext( + neverJoined, neverJoined.tenantUuid(), "membership-read-absence-retry")); + assertThat(stableCarrier(absentReadback)).isEqualTo(stableCarrier(absentRead)); + assertThat(denialReadback(neverJoined).membershipPairRows()).isEqualTo(1L); + + UUID unmappedTenantUuid = UUID.randomUUID(); + DenialReadback beforeUnmappedRead = denialReadback(neverJoined); + PlayerExecutionContext unmappedContext = + playerContext(neverJoined, unmappedTenantUuid, "membership-read-unmapped-tenant"); + assertRemoteFailure( + () -> client.getTenantMembershipForRuntime(unmappedContext), + Status.Code.FAILED_PRECONDITION); + assertThat(denialReadback(neverJoined)).isEqualTo(beforeUnmappedRead); + assertThat(countMembershipPairRows(neverJoined.accountUuid(), unmappedTenantUuid)).isZero(); + assertThat(countMembershipGenerationRows(neverJoined.accountUuid(), unmappedTenantUuid)) + .isZero(); + assertThat( + countStreamEvents(membershipStreamKey(neverJoined.accountUuid(), unmappedTenantUuid))) + .isZero(); + } finally { + stop(server); + } + } + + @Test + void retainedInactiveLeftAndReactivationSnapshotsCrossPostgresAndAuthenticatedSocket() + throws Exception { + // JOIN/LEFT here create Account-owned source state only. This transport read is not gameplay + // admission, does not mint credentials, and does not establish a Game Session binding. + JoinFixture joined = fixture(); + JoinPublicProductionResult joinResult = join(joined); + assertThat(joinResult.success()).isTrue(); + assertThat(joinResult.outcomeCode()).isEqualTo("JOINED"); + + RuntimeMembershipSnapshotDto beforeLeft = readRuntimeMembershipSnapshot(joined); + assertThat(beforeLeft.membershipBaseline().membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(beforeLeft.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "2")); + assertThat(beforeLeft.membershipBaseline().membershipAuthorityGeneration()).isEqualTo("1"); + byte[] originalJoinEventBytes = membershipEventBytes(joined, 1L); + assertThat(beforeLeft.sourceEvent().canonicalJsonUtf8()) + .containsExactly(originalJoinEventBytes); + + Server server = startServer(); + try (AccountMembershipAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + PlayerExecutionContext beforeLeftContext = + playerContext(joined, joined.tenantUuid(), "membership-left-before-transition"); + GetTenantMembershipForRuntimeResponse beforeLeftResponse = + client.getTenantMembershipForRuntime(beforeLeftContext); + assertResponseMatchesSnapshot(beforeLeftResponse, beforeLeftContext, beforeLeft); + assertCurrentMembershipEvent(beforeLeftResponse, joined, beforeLeft, "1", "ACTIVE"); + assertThat(beforeLeftResponse.getGameplayAdmissionAllowed()).isTrue(); + + String leftRequestId = "membership-mtls-left-" + UUID.randomUUID(); + MembershipTransitionReceipt left = + membershipLifecycleService.leave( + joined.accountId(), joined.legacyTenantId(), leftRequestId); + assertThat(left.transitionType()).isEqualTo("MEMBERSHIP_LEFT"); + assertThat(left.requestId()).isEqualTo(leftRequestId); + assertThat(left.receiptSequence()).isEqualTo(2L); + assertThat(left.membershipId()).isEqualTo(joinResult.membershipId()); + + MembershipPersistenceSnapshot afterLeftCommit = membershipPersistenceSnapshot(joined); + RuntimeMembershipSnapshotDto inactive = readRuntimeMembershipSnapshot(joined); + PlayerExecutionContext inactiveContext = + playerContext(joined, joined.tenantUuid(), "membership-left-current-read"); + GetTenantMembershipForRuntimeResponse inactiveResponse = + client.getTenantMembershipForRuntime(inactiveContext); + assertResponseMatchesSnapshot(inactiveResponse, inactiveContext, inactive); + assertThat(inactive.membershipExists()).isTrue(); + assertThat(inactive.gameplayAdmissionAllowed()).isFalse(); + assertThat(inactive.membershipBaseline().membershipLifecycleState()).isEqualTo("INACTIVE"); + assertThat(inactive.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "3")); + assertThat(inactive.membershipBaseline().membershipAuthorityGeneration()).isEqualTo("2"); + assertThat(inactive.roles()).containsExactly("player"); + assertThat(inactive.issuanceFence()) + .isEqualTo(Long.toString(Long.parseLong(beforeLeft.issuanceFence()) + 1L)); + assertThat(inactive.authorityTuple().issuerAuthGeneration()) + .isEqualTo(beforeLeft.authorityTuple().issuerAuthGeneration()); + assertThat(inactive.authorityTuple().accountAuthorityGeneration()) + .isEqualTo(beforeLeft.authorityTuple().accountAuthorityGeneration()); + assertThat(inactive.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(beforeLeft.authorityTuple().tenantAuthorityGeneration()); + assertThat(inactive.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "2")); + assertCurrentMembershipEvent(inactiveResponse, joined, inactive, "2", "INACTIVE"); + assertNonMembershipAuthorityEvidenceUnchanged(beforeLeft, inactive, joined); + assertThat(inactive.sourceEvent().requestId()).isEqualTo(leftRequestId); + assertThat(inactive.sourceEvent().callerBoundAuthorityInvalidated()).isTrue(); + assertMembershipCheckpoint(beforeLeft, inactive, joined, "2"); + assertThat(inactiveResponse.getGameplayAdmissionAllowed()).isFalse(); + assertThat(afterLeftCommit.membershipRow()) + .containsEntry("lifecycle_state", "INACTIVE") + .containsEntry("gameplay_admission_allowed", false) + .containsEntry("membership_version", 3L) + .containsEntry("membership_authority_generation", 2L) + .containsEntry("authority_provenance", "EXPLICIT_JOIN"); + assertThat(afterLeftCommit.pairAuthorityRow()) + .containsEntry("membership_exists", true) + .containsEntry("membership_version", 3L) + .containsEntry("membership_authority_generation", 2L) + .containsEntry("last_event_sequence", 2L) + .containsEntry("last_event_id", inactive.sourceEvent().eventId()) + .containsEntry("last_event_digest", inactive.sourceEvent().eventDigest()) + .containsEntry("last_transition_invalidated", true); + assertThat(afterLeftCommit.membershipAuthorityState().generation()).isEqualTo(2L); + assertThat(afterLeftCommit.issuanceFence()).isEqualTo(2L); + assertThat(afterLeftCommit.authorityEvents()).hasSize(2); + assertThat( + afterLeftCommit + .authorityEvents() + .get(0) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)) + .containsExactly(originalJoinEventBytes); + byte[] leftEventBytes = membershipEventBytes(joined, 2L); + assertThat(inactive.sourceEvent().canonicalJsonUtf8()).containsExactly(leftEventBytes); + assertThat(afterLeftCommit.authorityEvents().get(1).requestId()).isEqualTo(leftRequestId); + assertThat( + afterLeftCommit + .authorityEvents() + .get(1) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)) + .containsExactly(leftEventBytes); + assertThat(afterLeftCommit.transitionReceiptCount()).isEqualTo(2L); + assertThat(afterLeftCommit.leftAuditCount()).isEqualTo(1L); + + // Exact LEFT retry is a receipt read, not a new lifecycle mutation. + assertThat( + membershipLifecycleService.leave( + joined.accountId(), joined.legacyTenantId(), leftRequestId)) + .isEqualTo(left); + assertThat(membershipPersistenceSnapshot(joined)).isEqualTo(afterLeftCommit); + RuntimeMembershipSnapshotDto leftRetryReadback = readRuntimeMembershipSnapshot(joined); + assertSameCurrentMembershipSnapshot(inactive, leftRetryReadback); + PlayerExecutionContext leftRetryContext = + playerContext(joined, joined.tenantUuid(), "membership-left-exact-retry-read"); + GetTenantMembershipForRuntimeResponse leftRetryResponse = + client.getTenantMembershipForRuntime(leftRetryContext); + assertResponseMatchesSnapshot(leftRetryResponse, leftRetryContext, leftRetryReadback); + assertThat(stableCarrier(leftRetryResponse)).isEqualTo(stableCarrier(inactiveResponse)); + + JoinFixture reactivation = reactivationFixture(joined); + JoinPublicProductionResult reactivated = join(reactivation); + assertThat(reactivated.success()).isTrue(); + assertThat(reactivated.outcomeCode()).isEqualTo("JOINED"); + assertThat(reactivated.membershipId()).isEqualTo(joinResult.membershipId()); + assertThat(reactivated.membershipVersion()).isEqualTo(4L); + assertThat(reactivated.membershipAuthorityGeneration()).isEqualTo(3L); + + MembershipPersistenceSnapshot afterReactivation = membershipPersistenceSnapshot(joined); + RuntimeMembershipSnapshotDto active = readRuntimeMembershipSnapshot(joined); + PlayerExecutionContext activeContext = + playerContext(reactivation, reactivation.tenantUuid(), reactivation.requestId()); + GetTenantMembershipForRuntimeResponse activeResponse = + client.getTenantMembershipForRuntime(activeContext); + assertResponseMatchesSnapshot(activeResponse, activeContext, active); + assertThat(active.membershipExists()).isTrue(); + assertThat(active.gameplayAdmissionAllowed()).isTrue(); + assertThat(active.membershipBaseline().membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(active.membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "4")); + assertThat(active.membershipBaseline().membershipAuthorityGeneration()).isEqualTo("3"); + assertThat(active.issuanceFence()) + .isEqualTo(Long.toString(Long.parseLong(beforeLeft.issuanceFence()) + 2L)); + assertThat(active.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(joined.tenantUuid().toString(), "3")); + assertCurrentMembershipEvent(activeResponse, joined, active, "3", "ACTIVE"); + assertNonMembershipAuthorityEvidenceUnchanged(beforeLeft, active, joined); + assertThat(active.sourceEvent().requestId()).isEqualTo(reactivation.requestId()); + assertThat(active.sourceEvent().callerBoundAuthorityInvalidated()).isTrue(); + assertMembershipCheckpoint(beforeLeft, active, joined, "3"); + assertThat(afterReactivation.membershipRow()) + .containsEntry("lifecycle_state", "ACTIVE") + .containsEntry("gameplay_admission_allowed", true) + .containsEntry("membership_version", 4L) + .containsEntry("membership_authority_generation", 3L) + .containsEntry("authority_provenance", "EXPLICIT_JOIN"); + assertThat(afterReactivation.pairAuthorityRow()) + .containsEntry("membership_exists", true) + .containsEntry("membership_version", 4L) + .containsEntry("membership_authority_generation", 3L) + .containsEntry("last_event_sequence", 3L) + .containsEntry("last_event_id", active.sourceEvent().eventId()) + .containsEntry("last_event_digest", active.sourceEvent().eventDigest()) + .containsEntry("last_transition_invalidated", true); + assertThat(afterReactivation.membershipAuthorityState().generation()).isEqualTo(3L); + assertThat(afterReactivation.issuanceFence()).isEqualTo(3L); + assertThat(afterReactivation.authorityEvents()).hasSize(3); + assertThat( + afterReactivation + .authorityEvents() + .get(0) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)) + .containsExactly(originalJoinEventBytes); + assertThat( + afterReactivation + .authorityEvents() + .get(1) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)) + .containsExactly(leftEventBytes); + assertThat(afterReactivation.authorityEvents().get(2).requestId()) + .isEqualTo(reactivation.requestId()); + assertThat( + afterReactivation + .authorityEvents() + .get(2) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)) + .containsExactly(active.sourceEvent().canonicalJsonUtf8()); + assertThat(afterReactivation.transitionReceiptCount()).isEqualTo(3L); + assertThat(afterReactivation.leftAuditCount()).isEqualTo(1L); + + // A late replay returns the historical LEFT receipt while current ACTIVE evidence remains + // byte-for-byte stable; the historical receipt cannot roll the current pair back to INACTIVE. + assertThat( + membershipLifecycleService.leave( + joined.accountId(), joined.legacyTenantId(), leftRequestId)) + .isEqualTo(left); + assertThat(membershipPersistenceSnapshot(joined)).isEqualTo(afterReactivation); + RuntimeMembershipSnapshotDto afterHistoricalRetry = readRuntimeMembershipSnapshot(joined); + assertSameCurrentMembershipSnapshot(active, afterHistoricalRetry); + PlayerExecutionContext lateRetryContext = + playerContext(joined, joined.tenantUuid(), "membership-left-late-retry-read"); + GetTenantMembershipForRuntimeResponse lateRetryResponse = + client.getTenantMembershipForRuntime(lateRetryContext); + assertResponseMatchesSnapshot(lateRetryResponse, lateRetryContext, afterHistoricalRetry); + assertThat(stableCarrier(lateRetryResponse)).isEqualTo(stableCarrier(activeResponse)); + assertThat(membershipEventBytes(joined, 1L)).containsExactly(originalJoinEventBytes); + assertThat(membershipEventBytes(joined, 2L)).containsExactly(leftEventBytes); + } finally { + stop(server); + } + } + + private JoinFixture fixture() { + String suffix = UUID.randomUUID().toString(); + String shortSuffix = suffix.replace("-", "").substring(0, 12); + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "amg-" + shortSuffix, + "membership-mtls-" + suffix + "@example.com", + "test-hash") + .fetchOne(0, Long.class)); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + seedAccountAuthorityState(accountUuid); + + // Numeric retained tenant and Game Instance selectors are private to this Account JOIN fixture. + // The membership client sends the separately stored canonical tenant UUID and its own UUID + // Game Instance selector; neither is inferred from a numeric key. The synthetic approved + // association does not claim a real legacy association. + long legacyTenantId = positiveRandomLong(); + seedRetainedV26TenantEvidence(legacyTenantId, suffix); + dsl.execute( + "INSERT INTO subscription (account_id, tenant_id, plan_id, status, entitlement_version) " + + "VALUES (?, ?, 'membership-mtls-proof', 'active', 1)", + accountId, + legacyTenantId); + UUID tenantUuid = UUID.randomUUID(); + String evidenceDigest = legacyTenantSourceEvidence.digest(legacyTenantId); + tenantAssociationRepository.importApproved( + legacyTenantId, + approvedTenantAssociation(legacyTenantId, tenantUuid, evidenceDigest, suffix)); + var association = + tenantAssociationRepository.findByLegacyTenantId(legacyTenantId).orElseThrow(); + assertThat(association.canonicalTenantId()).isEqualTo(tenantUuid); + + GameplayRealm realm = + GameplayRealm.newBuilder() + .setTenantId(Long.toString(legacyTenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setGameInstanceId(Long.toString(RETAINED_JOIN_GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + GameplayAdmissionPointer pointer = + GameplayAdmissionPointer.newBuilder() + .setTenantId(Long.toString(legacyTenantId)) + .setRealmId(REALM_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setRealmSlug(REALM_SLUG) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setGameInstanceId(Long.toString(RETAINED_JOIN_GAME_INSTANCE_ID)) + .setCatalogRevision(CATALOG_REVISION) + .setPointerVersion(POINTER_VERSION) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .build(); + when(gameSessionClient.listGameplayRealms(WORLD_SLUG)).thenReturn(List.of(realm)); + when(gameSessionClient.getAdmissionPointer(legacyTenantId, WORLD_SLUG, REALM_SLUG)) + .thenReturn(pointer); + + String requestId = "membership-mtls-join-" + suffix; + DirectTextCallerContext caller = + new DirectTextCallerContext( + accountId, + legacyTenantId, + REALM_ID, + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + RETAINED_JOIN_GAME_INSTANCE_ID, + "membership-mtls-session-" + suffix, + requestId); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + legacyTenantId, + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + RETAINED_JOIN_GAME_INSTANCE_ID, + CATALOG_REVISION, + POINTER_VERSION); + DirectTextJoinScope scope = accountService.issueDirectTextConnectScope(caller, target); + return new JoinFixture( + accountId, accountUuid, legacyTenantId, tenantUuid, requestId, caller, scope); + } + + private JoinPublicProductionResult join(JoinFixture fixture) { + return accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.scope().connectScopeId(), fixture.requestId())); + } + + private RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot(JoinFixture fixture) { + return new TransactionTemplate(transactionManager) + .execute( + status -> + membershipAuthorityEventProducer.readRuntimeMembershipSnapshot( + fixture.accountUuid(), fixture.tenantUuid())); + } + + private JoinFixture reactivationFixture(JoinFixture existing) { + String suffix = UUID.randomUUID().toString(); + String requestId = "membership-mtls-reactivation-" + suffix; + DirectTextCallerContext caller = + new DirectTextCallerContext( + existing.accountId(), + existing.legacyTenantId(), + REALM_ID, + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + RETAINED_JOIN_GAME_INSTANCE_ID, + "membership-mtls-reactivation-session-" + suffix, + requestId); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + existing.legacyTenantId(), + REALM_ID, + WORLD_SLUG, + REALM_SLUG, + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + RETAINED_JOIN_GAME_INSTANCE_ID, + CATALOG_REVISION, + POINTER_VERSION); + DirectTextJoinScope scope = accountService.issueDirectTextConnectScope(caller, target); + return new JoinFixture( + existing.accountId(), + existing.accountUuid(), + existing.legacyTenantId(), + existing.tenantUuid(), + requestId, + caller, + scope); + } + + private ScopeState readAuthorityState(AuthorityScope scope) { + return new TransactionTemplate(transactionManager) + .execute(status -> authorityGenerationRepository.read(scope)); + } + + private ScopeState readAccountAuthority(UUID accountUuid) { + return readAuthorityState(AuthorityScope.account(accountUuid)); + } + + private Account readAccount(long accountId) { + return new TransactionTemplate(transactionManager) + .execute(status -> accountRepository.findById(accountId).orElseThrow()); + } + + 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 AccountLogoutAllAuthorityEventProducer logoutProducer() { + return new AccountLogoutAllAuthorityEventProducer( + accountRepository, + authorityGenerationRepository, + authorityOutboxRepository, + logoutAllOperationRepository, + new AccountAuthoritySourceEventReadback( + authorityOutboxRepository, + passwordResetOperationRepository, + logoutAllOperationRepository), + dsl, + transactionManager); + } + + private PlayerExecutionContext playerContext( + JoinFixture fixture, UUID tenantUuid, String requestId) { + // The transport's UUID Game Instance selector is explicit and independent of the private + // numeric Game Instance used by the retained JOIN fixture. + return PlayerExecutionContext.newBuilder() + .setAccountId(fixture.accountUuid().toString()) + .setTenantId(tenantUuid.toString()) + .setRealmId(REALM_ID.toString()) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setGameInstanceId(GAME_INSTANCE_CONTEXT_ID.toString()) + .setSessionId("9001") + .setPlayableStateScope("SHARED") + .setRequestId(requestId) + .build(); + } + + private void assertResponseMatchesSnapshot( + GetTenantMembershipForRuntimeResponse response, + PlayerExecutionContext context, + RuntimeMembershipSnapshotDto expected) { + assertThat(response.getUnknownFields().asMap()).isEmpty(); + assertThat(response.hasError()).isFalse(); + assertThat(response.getAuthorityAvailability()).isEqualTo("AVAILABLE"); + assertThat(response.getAccountId()).isEqualTo(expected.accountUuid()); + assertThat(response.getTenantId()).isEqualTo(expected.tenantUuid()); + assertThat(response.getRequestAccountId()).isEqualTo(context.getAccountId()); + assertThat(response.getRequestTenantId()).isEqualTo(context.getTenantId()); + assertThat(response.getRequestId()).isEqualTo(context.getRequestId()); + assertThat(response.getMembershipExists()).isEqualTo(expected.membershipExists()); + assertThat(response.getGameplayAdmissionAllowed()) + .isEqualTo(expected.gameplayAdmissionAllowed()); + assertThat(response.getMembershipLifecycleState()) + .isEqualTo(expected.membershipBaseline().membershipLifecycleState()); + assertThat(response.getMembershipVersionMap()) + .isEqualTo(expected.membershipBaseline().membershipVersion()); + assertThat(response.getMembershipAuthorityGeneration()) + .isEqualTo(expected.membershipBaseline().membershipAuthorityGeneration()); + assertThat(response.getMembershipBaseline().getMembershipLifecycleState()) + .isEqualTo(expected.membershipBaseline().membershipLifecycleState()); + assertThat(response.getMembershipBaseline().getMembershipVersionMap()) + .isEqualTo(expected.membershipBaseline().membershipVersion()); + assertThat(response.getMembershipBaseline().getMembershipAuthorityGeneration()) + .isEqualTo(expected.membershipBaseline().membershipAuthorityGeneration()); + assertThat(response.getRolesList()).containsExactlyElementsOf(expected.roles()); + assertThat(response.getIssuanceFence()).isEqualTo(expected.issuanceFence()); + + var tuple = response.getAuthorityTuple(); + assertThat(tuple.getIssuerAuthGeneration()) + .isEqualTo(expected.authorityTuple().issuerAuthGeneration()); + assertThat(tuple.getAccountAuthorityGeneration()) + .isEqualTo(expected.authorityTuple().accountAuthorityGeneration()); + assertThat(tuple.getTenantAuthorityGenerationMap()) + .isEqualTo(expected.authorityTuple().tenantAuthorityGeneration()); + assertThat(tuple.getMembershipAuthorityGenerationMap()) + .isEqualTo(expected.authorityTuple().membershipAuthorityGeneration()); + assertThat(tuple.getPrivateRealmGrantVersionsCount()).isZero(); + assertThat(tuple.hasTenantBillingCutoff()).isFalse(); + assertThat(tuple.hasAccountSecurityCutoff()) + .isEqualTo(expected.authorityTuple().accountSecurityCutoff().isPresent()); + expected + .authorityTuple() + .accountSecurityCutoff() + .ifPresent( + cutoff -> { + assertThat(tuple.getAccountSecurityCutoff().getAccountAuthorityGeneration()) + .isEqualTo(cutoff.accountAuthorityGeneration()); + assertThat(tuple.getAccountSecurityCutoff().getOutboxStreamKey()) + .isEqualTo(cutoff.outboxStreamKey()); + assertThat(tuple.getAccountSecurityCutoff().getOutboxSequence()) + .isEqualTo(cutoff.outboxSequence()); + }); + + assertThat(response.getOutboxCheckpointsCount()).isEqualTo(expected.outboxCheckpoints().size()); + for (int index = 0; index < expected.outboxCheckpoints().size(); index++) { + var actual = response.getOutboxCheckpoints(index); + var source = expected.outboxCheckpoints().get(index); + assertThat(actual.getOutboxStreamKey()).isEqualTo(source.outboxStreamKey()); + assertThat(actual.getOutboxSequence()).isEqualTo(source.outboxSequence()); + assertThat(actual.getUnknownFields().asMap()).isEmpty(); + } + assertThat(response.getOutboxSourceEvidenceCount()) + .isEqualTo(expected.outboxSourceEvidence().size()); + for (int index = 0; index < expected.outboxSourceEvidence().size(); index++) { + var actual = response.getOutboxSourceEvidence(index); + var source = expected.outboxSourceEvidence().get(index); + assertThat(actual.getOutboxStreamKey()).isEqualTo(source.outboxStreamKey()); + assertThat(actual.getOutboxSequence()).isEqualTo(source.outboxSequence()); + assertThat(actual.getEventId()).isEqualTo(source.eventId()); + assertThat(actual.getEventDigest()).isEqualTo(source.eventDigest()); + assertThat(actual.getCanonicalEventJson()).isEqualTo(source.canonicalEventJson()); + assertThat(actual.getUnknownFields().asMap()).isEmpty(); + } + } + + private void assertMembershipEvidence( + GetTenantMembershipForRuntimeResponse response, + JoinFixture fixture, + MembershipAuthorityEventV1Codec.MembershipEvent immutableEvent, + byte[] immutableBytes) { + var membershipEvidence = + response.getOutboxSourceEvidenceList().stream() + .filter(evidence -> membershipStreamKey(fixture).equals(evidence.getOutboxStreamKey())) + .findFirst() + .orElseThrow(); + assertThat(membershipEvidence.getOutboxSequence()).isEqualTo("1"); + assertThat(membershipEvidence.getEventId()).isEqualTo(immutableEvent.eventId()); + assertThat(membershipEvidence.getEventDigest()).isEqualTo(immutableEvent.eventDigest()); + assertThat(membershipEvidence.getCanonicalEventJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(immutableBytes); + assertThat(immutableEvent.canonicalJsonUtf8()).containsExactly(immutableBytes); + assertThat(immutableEvent.issuanceFence()).isEqualTo("1"); + assertThat(immutableEvent.authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(immutableEvent.authorityTuple().accountAuthorityGeneration()).isEqualTo("1"); + assertThat(immutableEvent.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(immutableEvent.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + } + + private void assertCurrentMembershipEvent( + GetTenantMembershipForRuntimeResponse response, + JoinFixture fixture, + RuntimeMembershipSnapshotDto snapshot, + String expectedSequence, + String expectedLifecycle) { + var event = snapshot.sourceEvent(); + assertThat(event).isNotNull(); + assertThat(event.accountId()).isEqualTo(fixture.accountUuid().toString()); + assertThat(event.tenantId()).isEqualTo(fixture.tenantUuid().toString()); + assertThat(event.outboxStreamKey()).isEqualTo(membershipStreamKey(fixture)); + assertThat(event.outboxSequence()).isEqualTo(expectedSequence); + assertThat(event.membershipLifecycleState()).isEqualTo(expectedLifecycle); + assertThat(event.gameplayAdmissionAllowed()).isEqualTo("ACTIVE".equals(expectedLifecycle)); + assertThat(event.membershipVersion()) + .isEqualTo(snapshot.membershipBaseline().membershipVersion()); + assertThat(event.membershipAuthorityGeneration()) + .isEqualTo(snapshot.membershipBaseline().membershipAuthorityGeneration()); + assertThat(event.authorityTuple()).isEqualTo(snapshot.authorityTuple()); + assertThat(event.issuanceFence()).isEqualTo(snapshot.issuanceFence()); + var membershipEvidence = + response.getOutboxSourceEvidenceList().stream() + .filter(source -> membershipStreamKey(fixture).equals(source.getOutboxStreamKey())) + .toList(); + assertThat(membershipEvidence).hasSize(1); + var exactMembershipEvidence = membershipEvidence.get(0); + assertThat(exactMembershipEvidence.getOutboxStreamKey()) + .isEqualTo(membershipStreamKey(fixture)); + assertThat(exactMembershipEvidence.getOutboxSequence()).isEqualTo(expectedSequence); + assertThat(exactMembershipEvidence.getEventId()).isEqualTo(event.eventId()); + assertThat(exactMembershipEvidence.getEventDigest()).isEqualTo(event.eventDigest()); + assertThat(exactMembershipEvidence.getCanonicalEventJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(event.canonicalJsonUtf8()); + } + + private void assertMembershipCheckpoint( + RuntimeMembershipSnapshotDto baseline, + RuntimeMembershipSnapshotDto current, + JoinFixture fixture, + String expectedMembershipSequence) { + String streamKey = membershipStreamKey(fixture); + List baselineNonMembership = + baseline.outboxCheckpoints().stream() + .filter(checkpoint -> !streamKey.equals(checkpoint.outboxStreamKey())) + .toList(); + List currentNonMembership = + current.outboxCheckpoints().stream() + .filter(checkpoint -> !streamKey.equals(checkpoint.outboxStreamKey())) + .toList(); + List baselineMembership = + baseline.outboxCheckpoints().stream() + .filter(checkpoint -> streamKey.equals(checkpoint.outboxStreamKey())) + .toList(); + assertThat(baseline.outboxCheckpoints()).hasSize(4); + assertThat(current.outboxCheckpoints()).hasSize(4); + assertThat(currentNonMembership).containsExactlyElementsOf(baselineNonMembership); + assertThat(baselineMembership) + .containsExactly( + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry(streamKey, "1")); + List membershipCheckpoint = + current.outboxCheckpoints().stream() + .filter(checkpoint -> streamKey.equals(checkpoint.outboxStreamKey())) + .toList(); + assertThat(membershipCheckpoint) + .containsExactly( + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + streamKey, expectedMembershipSequence)); + } + + private void assertNonMembershipAuthorityEvidenceUnchanged( + RuntimeMembershipSnapshotDto baseline, + RuntimeMembershipSnapshotDto current, + JoinFixture fixture) { + String membershipStream = membershipStreamKey(fixture); + assertThat(current.authorityTuple().issuerAuthGeneration()) + .isEqualTo(baseline.authorityTuple().issuerAuthGeneration()); + assertThat(current.authorityTuple().accountAuthorityGeneration()) + .isEqualTo(baseline.authorityTuple().accountAuthorityGeneration()); + assertThat(current.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(baseline.authorityTuple().tenantAuthorityGeneration()); + assertThat(current.authorityTuple().privateRealmGrantVersions()) + .isEqualTo(baseline.authorityTuple().privateRealmGrantVersions()); + assertThat(current.authorityTuple().accountSecurityCutoff()) + .isEqualTo(baseline.authorityTuple().accountSecurityCutoff()); + assertThat(current.authorityTuple().tenantBillingCutoff()) + .isEqualTo(baseline.authorityTuple().tenantBillingCutoff()); + assertThat( + current.outboxSourceEvidence().stream() + .filter(evidence -> !membershipStream.equals(evidence.outboxStreamKey())) + .toList()) + .containsExactlyElementsOf( + baseline.outboxSourceEvidence().stream() + .filter(evidence -> !membershipStream.equals(evidence.outboxStreamKey())) + .toList()); + } + + private void assertSameCurrentMembershipSnapshot( + RuntimeMembershipSnapshotDto expected, RuntimeMembershipSnapshotDto actual) { + assertThat(actual.membershipExists()).isEqualTo(expected.membershipExists()); + assertThat(actual.gameplayAdmissionAllowed()).isEqualTo(expected.gameplayAdmissionAllowed()); + assertThat(actual.membershipBaseline()).isEqualTo(expected.membershipBaseline()); + assertThat(actual.roles()).isEqualTo(expected.roles()); + assertThat(actual.authorityTuple()).isEqualTo(expected.authorityTuple()); + assertThat(actual.issuanceFence()).isEqualTo(expected.issuanceFence()); + assertThat(actual.outboxCheckpoints()).isEqualTo(expected.outboxCheckpoints()); + assertThat(actual.outboxSourceEvidence()).isEqualTo(expected.outboxSourceEvidence()); + assertThat(actual.sourceEvent().canonicalJsonUtf8()) + .containsExactly(expected.sourceEvent().canonicalJsonUtf8()); + } + + private MembershipPersistenceSnapshot membershipPersistenceSnapshot(JoinFixture fixture) { + var membershipRow = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT id, lifecycle_state, gameplay_admission_allowed, membership_version, " + + "membership_authority_generation, authority_provenance " + + "FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.legacyTenantId()) + .fetchOne()); + var pairRow = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT membership_exists, membership_version, " + + "membership_authority_generation, last_event_sequence, last_event_id, " + + "last_event_digest, last_transition_invalidated " + + "FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()) + .fetchOne()); + List authorityEvents = + dsl.resultQuery( + "SELECT outbox_sequence, request_id, event_id, event_digest, payload " + + "FROM account_authority_outbox_events WHERE outbox_stream_key = ? " + + "ORDER BY outbox_sequence", + membershipStreamKey(fixture)) + .fetch() + .map( + row -> + new MembershipAuthorityEventSnapshot( + row.get("outbox_sequence", Long.class), + row.get("request_id", String.class), + row.get("event_id", String.class), + row.get("event_digest", String.class), + new String(row.get("payload", byte[].class), StandardCharsets.UTF_8))); + return new MembershipPersistenceSnapshot( + membershipRow.intoMap(), + pairRow.intoMap(), + readAuthorityState(AuthorityScope.membership(fixture.accountUuid(), fixture.tenantUuid())), + accountIssuanceFence(fixture.accountUuid()), + authorityEvents, + countMembershipTransitionReceipts(fixture), + countLeftAuditEvents(fixture)); + } + + private long accountIssuanceFence(UUID accountUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class)); + } + + private long countMembershipTransitionReceipts(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.legacyTenantId()) + .fetchOne(0, Long.class)); + } + + private long countLeftAuditEvents(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE scope = 'tenant' " + + "AND tenant_id = ? AND event_type = 'ACCOUNT_MEMBERSHIP_LEFT'", + fixture.legacyTenantId()) + .fetchOne(0, Long.class)); + } + + private void assertSourceEvidence( + GetTenantMembershipForRuntimeResponse response, + String streamKey, + String eventId, + String eventDigest) { + var evidence = + response.getOutboxSourceEvidenceList().stream() + .filter(source -> streamKey.equals(source.getOutboxStreamKey())) + .findFirst() + .orElseThrow(); + assertThat(evidence.getOutboxSequence()).isEqualTo("1"); + assertThat(evidence.getEventId()).isEqualTo(eventId); + assertThat(evidence.getEventDigest()).isEqualTo(eventDigest); + assertThat(evidence.getCanonicalEventJson()).isNotBlank(); + } + + private static GetTenantMembershipForRuntimeResponse stableCarrier( + GetTenantMembershipForRuntimeResponse response) { + return response.toBuilder().clearEvaluatedAt().clearRequestId().build(); + } + + private void assertRemoteFailure(Runnable request, Status.Code expectedCode) { + assertThatThrownBy(request::run) + .isInstanceOf(IllegalStateException.class) + .hasCauseInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure.getCause()).getCode()) + .isEqualTo(expectedCode)); + } + + private DenialReadback denialReadback(JoinFixture fixture) { + UUID accountUuid = fixture.accountUuid(); + UUID tenantUuid = fixture.tenantUuid(); + return new DenialReadback( + readAuthorityState(AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER)), + readAuthorityState(AuthorityScope.account(accountUuid)), + readAuthorityState(AuthorityScope.tenant(tenantUuid)), + countMembershipPairRows(accountUuid, tenantUuid), + countMembershipGenerationRows(accountUuid, tenantUuid), + countMembershipRows(fixture), + countStreamEvents(membershipStreamKey(fixture)), + countStreamEvents(accountStreamKey(accountUuid)), + countStreamEvents(issuerStreamKey()), + countStreamEvents(tenantStreamKey(tenantUuid))); + } + + private void assertDurableSequenceZeroPairBaseline(JoinFixture fixture) { + var pair = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT membership_exists, membership_version, " + + "membership_authority_generation, last_event_sequence, last_event_id, " + + "last_event_digest, last_transition_invalidated " + + "FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()) + .fetchOne()); + assertThat(pair.get(0, Boolean.class)).isFalse(); + assertThat(pair.get(1, Long.class)).isEqualTo(1L); + assertThat(pair.get(2, Long.class)).isEqualTo(1L); + assertThat(pair.get(3, Long.class)).isZero(); + assertThat(pair.get(4, String.class)).isNull(); + assertThat(pair.get(5, String.class)).isNull(); + assertThat(pair.get(6, Boolean.class)).isFalse(); + } + + private long countMembershipPairRows(UUID accountUuid, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid) + .fetchOne(0, Long.class)); + } + + private long countMembershipGenerationRows(UUID accountUuid, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_generations " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid) + .fetchOne(0, Long.class)); + } + + private long countMembershipRows(JoinFixture fixture) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.legacyTenantId()) + .fetchOne(0, Long.class)); + } + + private long countStreamEvents(String streamKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + streamKey) + .fetchOne(0, Long.class)); + } + + private byte[] membershipEventBytes(JoinFixture fixture) { + return membershipEventBytes(fixture, 1L); + } + + private byte[] membershipEventBytes(JoinFixture fixture, long sequence) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT payload FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = ?", + membershipStreamKey(fixture), + sequence) + .fetchOne()) + .get("payload", byte[].class); + } + + private void seedRetainedV26TenantEvidence(long legacyTenantId, String suffix) { + String shortSuffix = suffix.replace("-", "").substring(0, 12); + long donorAccountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, ?, ?) RETURNING id", + "amspd-" + shortSuffix, + "membership-mtls-donor-" + suffix + "@example.com", + "test-hash", + legacyTenantId) + .fetchOne(0, Long.class)); + UUID donorAccountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", donorAccountId) + .fetchOne(0, UUID.class)); + seedAccountAuthorityState(donorAccountUuid); + long retainedMembershipId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED') " + + "RETURNING id", + donorAccountId, + legacyTenantId) + .fetchOne(0, Long.class)); + dsl.execute( + "INSERT INTO account_legacy_tenant_sources " + + "(account_id, legacy_tenant_id, matching_membership_id, " + + "matching_membership_admission_allowed, profile_tenant_count, " + + "matching_profile_count, disposition) VALUES (?, ?, ?, FALSE, 0, 0, 'UNVERIFIED')", + donorAccountId, + legacyTenantId, + retainedMembershipId); + dsl.execute( + "INSERT INTO account_legacy_membership_sources " + + "(membership_id, account_id, tenant_id, original_gameplay_admission_allowed, " + + "matches_account_legacy_tenant, disposition) " + + "VALUES (?, ?, ?, FALSE, TRUE, 'UNVERIFIED')", + retainedMembershipId, + donorAccountId, + legacyTenantId); + } + + private void seedAccountAuthorityState(UUID accountUuid) { + 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); + } + + private ResolveLegacyAccountTenantAssociationResponse approvedTenantAssociation( + long legacyTenantId, UUID tenantUuid, String evidenceDigest, String suffix) { + String sourceLegacyGameTenantId = "legacy-game-" + suffix.replace("-", "").substring(0, 24); + return ResolveLegacyAccountTenantAssociationResponse.newBuilder() + .setLegacyAccountTenantId(legacyTenantId) + .setCanonicalTenantId(tenantUuid.toString()) + .setSourceLegacyGameTenantId(sourceLegacyGameTenantId) + .setSourceGameRowId(positiveRandomLong()) + .setAccountEvidenceDigest(evidenceDigest) + .setOperationId(UUID.randomUUID().toString()) + .setManifestDigest("sha256:" + "b".repeat(64)) + .setManifestSignature(Base64.getEncoder().encodeToString(new byte[64])) + .setTargetNamespace(NAMESPACE) + .setSignerKeyId("game-design-owner-test") + .setApprovedBy("owner@example.test") + .setApprovalReference("unit-1b-membership-mtls-proof") + .setSignedAt("2026-09-26T00:00:00Z") + .setOperationEntryCount(1) + .setManifestSchemaVersion(1) + .build(); + } + + private long positiveRandomLong() { + long candidate = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return candidate == 0L ? 1L : candidate; + } + + private String accountStreamKey(UUID accountUuid) { + return AUTHORITY_STREAM_PREFIX + "account/" + accountUuid; + } + + private String issuerStreamKey() { + return AUTHORITY_STREAM_PREFIX + "issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER; + } + + private String tenantStreamKey(UUID tenantUuid) { + return AUTHORITY_STREAM_PREFIX + "tenant/" + tenantUuid; + } + + private String membershipStreamKey(JoinFixture fixture) { + return membershipStreamKey(fixture.accountUuid(), fixture.tenantUuid()); + } + + private String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid; + } + + private Server startServer() throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + certificate("account.crt").toFile(), certificate("account.key").toFile()) + .trustManager(certificate("ca.crt").toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new AccountMembershipAuthorityGrpcService( + membershipAuthorityEventProducer, transactionManager, NAMESPACE), + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private AccountMembershipAuthorityClient newClient(int port, String clientIdentity) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate(clientIdentity + ".crt").toString()); + tls.setPrivateKey(certificate(clientIdentity + ".key").toString()); + tls.setCaCert(certificate("ca.crt").toString()); + return new AccountMembershipAuthorityClient( + endpoints, tls, new GrpcChannelFactory(), BlockingGrpcStubCustomizer.noop(), NAMESPACE); + } + + private Path certificate(String name) throws IOException { + Path existing = copiedCertificates.get(name); + if (existing != null) { + return existing; + } + + String resourcePath = "/certs/issuer-authority/" + name; + try (InputStream resource = + AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.class.getResourceAsStream( + resourcePath)) { + if (resource == null) { + throw new IllegalStateException( + "Missing membership-authority TLS fixture: " + resourcePath); + } + Path copied = tempDir.resolve(name); + Files.copy(resource, copied); + copiedCertificates.put(name, copied); + return copied; + } + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + server.awaitTermination(2, TimeUnit.SECONDS); + } + + private record JoinFixture( + long accountId, + UUID accountUuid, + long legacyTenantId, + UUID tenantUuid, + String requestId, + DirectTextCallerContext caller, + DirectTextJoinScope scope) {} + + private record DenialReadback( + ScopeState issuerState, + ScopeState accountState, + ScopeState tenantState, + long membershipPairRows, + long membershipGenerationRows, + long membershipRows, + long membershipEvents, + long accountEvents, + long issuerEvents, + long tenantEvents) {} + + private record MembershipAuthorityEventSnapshot( + long sequence, String requestId, String eventId, String eventDigest, String canonicalJson) {} + + private record MembershipPersistenceSnapshot( + Map membershipRow, + Map pairAuthorityRow, + ScopeState membershipAuthorityState, + long issuanceFence, + List authorityEvents, + long transitionReceiptCount, + long leftAuditCount) { + private MembershipPersistenceSnapshot { + membershipRow = Map.copyOf(membershipRow); + pairAuthorityRow = Map.copyOf(pairAuthorityRow); + authorityEvents = List.copyOf(authorityEvents); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/IssuerAuthorityProjectionRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/IssuerAuthorityProjectionRedisIntegrationTest.java new file mode 100644 index 0000000000..b7708ea0b9 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/IssuerAuthorityProjectionRedisIntegrationTest.java @@ -0,0 +1,403 @@ +package integration.net.firedevops.firemud.gamesession; + +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.when; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionRedisContract; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ApplyResult; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.Outcome; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ProjectionSnapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.connection.RedisPassword; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.script.RedisScript; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Redis integration; Account readbacks are minted by the client over its mocked response seam. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class IssuerAuthorityProjectionRedisIntegrationTest { + private static final String NAMESPACE = "test"; + private static final String QUERY_ID = "11111111-1111-4111-8111-111111111111"; + private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; + private static final String COORD_PASSWORD = "issuer-projection-integration-secret"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final RedisScript CAS_SCRIPT = + RedisScript.of( + new ClassPathResource(IssuerAuthorityProjectionRedisContract.RESOURCE_PATH), + String.class); + + @Container + static final GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--save", + "", + "--appendonly", + "no", + "--user", + "gamesession_coord_app", + "on", + ">" + COORD_PASSWORD, + "~session:game:auth:issuer-generation:v1:*", + "+get", + "+set", + "+pttl", + "+evalsha", + "+script|load"); + + private String issuerId; + private RedisIssuerAuthorityProjectionStore store; + private LettuceConnectionFactory adminConnectionFactory; + private StringRedisTemplate adminTemplate; + private LettuceConnectionFactory ownerConnectionFactory; + private StringRedisTemplate ownerTemplate; + + @BeforeEach + void startOwnerStoreAndTestOnlyAdminReadback() { + issuerId = "https://accounts.example.test/issuer/" + UUID.randomUUID(); + store = + new RedisIssuerAuthorityProjectionStore( + NAMESPACE, + new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( + redis.getHost(), + redis.getMappedPort(6379), + "gamesession_coord_app", + COORD_PASSWORD), + new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint( + "redis-cache.test.invalid", 6380)); + store.init(); + + adminConnectionFactory = + new LettuceConnectionFactory( + new RedisStandaloneConfiguration(redis.getHost(), redis.getMappedPort(6379))); + adminConnectionFactory.afterPropertiesSet(); + adminTemplate = new StringRedisTemplate(adminConnectionFactory); + adminTemplate.afterPropertiesSet(); + + RedisStandaloneConfiguration ownerConfiguration = + new RedisStandaloneConfiguration(redis.getHost(), redis.getMappedPort(6379)); + ownerConfiguration.setUsername("gamesession_coord_app"); + ownerConfiguration.setPassword(RedisPassword.of(COORD_PASSWORD)); + ownerConnectionFactory = new LettuceConnectionFactory(ownerConfiguration); + ownerConnectionFactory.afterPropertiesSet(); + ownerTemplate = new StringRedisTemplate(ownerConnectionFactory); + ownerTemplate.afterPropertiesSet(); + } + + @AfterEach + void closeConnections() { + if (store != null) { + store.close(); + } + if (adminConnectionFactory != null) { + adminConnectionFactory.destroy(); + } + if (ownerConnectionFactory != null) { + ownerConnectionFactory.destroy(); + } + } + + @Test + void ownerPrincipalCannotInvokeEvalDirectly() { + assertThatThrownBy( + () -> + ownerTemplate.execute( + (RedisCallback) + connection -> + connection + .scriptingCommands() + .eval( + "return 1".getBytes(StandardCharsets.UTF_8), + ReturnType.INTEGER, + 0))) + .satisfies(failure -> assertThat(exceptionMessageChain(failure)).contains("NOPERM")); + } + + @Test + void authenticatedCurrentBootstrapAndContiguousEventUseDeterministicPersistentSnapshots() + throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "3", 1); + SourceReadback current = readback("2", "3", "1", first, null); + + ApplyResult bootstrap = store.apply(current, "2026-10-02T11:00:00Z"); + assertThat(bootstrap.outcome()).isEqualTo(Outcome.APPLIED); + ProjectionSnapshot firstSnapshot = bootstrap.snapshot().orElseThrow(); + assertThat(firstSnapshot.key()).isEqualTo(key()); + assertThat(parse(firstSnapshot.json()).path("lastAppliedSourceOutboxSequence").asText()) + .isEqualTo("1"); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(firstSnapshot.json()); + assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + + IssuerGenerationAuthorityEvent second = event("2", "3", "4", 2); + SourceReadback selected = readback("3", "4", "2", second, second); + ApplyResult advanced = store.apply(selected, "2026-10-02T11:01:00Z"); + assertThat(advanced.outcome()).isEqualTo(Outcome.APPLIED); + String deterministicCandidate = advanced.snapshot().orElseThrow().json(); + assertThat(parse(deterministicCandidate).path("lastAppliedSourceOutboxSequence").asText()) + .isEqualTo("2"); + + ApplyResult exactDuplicate = store.apply(selected, "ignored-for-no-op"); + assertThat(exactDuplicate.outcome()).isEqualTo(Outcome.NO_OP); + assertThat(exactDuplicate.snapshot().orElseThrow().json()).isEqualTo(deterministicCandidate); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(deterministicCandidate); + assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + + @Test + void authenticatedSequenceZeroAbsenceBootstrapsWithoutEventIdentityOrAdmissionEvidence() + throws Exception { + ApplyResult bootstrap = + store.apply(readback("1", "1", "0", null, null), "2026-10-02T10:59:00Z"); + + assertThat(bootstrap.outcome()).isEqualTo(Outcome.APPLIED); + JsonNode projection = parse(bootstrap.snapshot().orElseThrow().json()); + assertThat(projection.path("lastAppliedSourceOutboxSequence").asText()).isEqualTo("0"); + assertThat(projection.has("sourceEventId")).isFalse(); + assertThat(projection.has("sourceEventDigest")).isFalse(); + assertThat(projection.path("appliedSourceEvidence").isEmpty()).isTrue(); + assertThat(adminTemplate.opsForValue().get(key())) + .isEqualTo(bootstrap.snapshot().orElseThrow().json()); + assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + + @Test + void gapAndAuthenticatedOlderDuplicateHaveDistinctNoMutationOutcomes() throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "3", 3); + IssuerGenerationAuthorityEvent second = event("2", "3", "4", 4); + assertThat(store.apply(readback("2", "3", "1", first, null), "stable-1").outcome()) + .isEqualTo(Outcome.APPLIED); + assertThat(store.apply(readback("3", "4", "2", second, second), "stable-2").outcome()) + .isEqualTo(Outcome.APPLIED); + String before = adminTemplate.opsForValue().get(key()); + + IssuerGenerationAuthorityEvent fourth = event("4", "6", "7", 6); + ApplyResult gap = store.apply(readback("6", "7", "4", fourth, fourth), "ignored-for-gap"); + assertThat(gap.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(gap.detail()).contains("EVENT_SEQUENCE_GAP"); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(before); + + ApplyResult olderDuplicate = + store.apply(readback("3", "4", "2", second, first), "ignored-for-older-duplicate"); + assertThat(olderDuplicate.outcome()).isEqualTo(Outcome.NO_OP); + assertThat(olderDuplicate.transitionDecision().orElseThrow()) + .isInstanceOf(IssuerAuthorityProjectionTransitions.NoOp.class); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(before); + assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + + @Test + void staleExpectedBytesAreNonMutatingThroughTheRegisteredOwnerScript() { + String key = key(); + adminTemplate.opsForValue().set(key, "newer exact bytes"); + String result = executeRegistered(key, "PRESENT", "older exact bytes", "stale candidate bytes"); + + assertThat(result).isEqualTo("STALE"); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo("newer exact bytes"); + assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + + @Test + void unknownOrDuplicateJsonFieldsQuarantineWithoutChangingBytesOrTtl() throws Exception { + String key = key(); + String unknownFieldJson = "{\"schemaVersion\":\"unknown\",\"extra\":true}"; + adminTemplate.opsForValue().set(key, unknownFieldJson); + IssuerGenerationAuthorityEvent event = event("2", "3", "4", 7); + + ApplyResult unknown = store.apply(readback("3", "4", "2", event, event), "stable-time"); + + assertThat(unknown.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(adminTemplate.opsForValue().get(key)).isEqualTo(unknownFieldJson); + assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-1L); + + String duplicatePropertyJson = + "{\"schemaVersion\":\"game-session-auth-issuer-projection/v1\"," + + "\"schemaVersion\":\"game-session-auth-issuer-projection/v1\"}"; + adminTemplate.opsForValue().set(key, duplicatePropertyJson); + ApplyResult duplicateProperty = + store.apply(readback("3", "4", "2", event, event), "stable-time"); + assertThat(duplicateProperty.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(adminTemplate.opsForValue().get(key)).isEqualTo(duplicatePropertyJson); + assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + + @Test + void expiringProjectionIsQuarantinedWithoutChangingItsBytesOrExpiration() throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "3", 8); + assertThat(store.apply(readback("2", "3", "1", first, null), "stable-time").outcome()) + .isEqualTo(Outcome.APPLIED); + String before = adminTemplate.opsForValue().get(key()); + adminTemplate.expire(key(), 30, TimeUnit.SECONDS); + Long beforeTtl = adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS); + + IssuerGenerationAuthorityEvent second = event("2", "3", "4", 9); + ApplyResult result = store.apply(readback("3", "4", "2", second, second), "stable-time"); + + assertThat(result.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(result.detail()).contains("TTL_PRESENT"); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(before); + assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)) + .isPositive() + .isLessThanOrEqualTo(beforeTtl); + } + + private SourceReadback readback( + String generation, + String sourceVersion, + String sequence, + IssuerGenerationAuthorityEvent latest, + IssuerGenerationAuthorityEvent selected) + throws Exception { + String scope = "issuer/" + issuerId; + String streamKey = IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope; + IssuerAuthoritySourceSnapshot.Builder snapshot = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(issuerId) + .setSourceScope(scope) + .setOutboxStreamKey(streamKey) + .setIssuerAuthGeneration(generation) + .setSourceVersion(sourceVersion) + .setOutboxSequence(sequence); + if (latest != null) { + snapshot.setLatestEventCanonicalJson(latest.canonicalJson()); + } + ReadIssuerAuthorityForRuntimeResponse.Builder response = + ReadIssuerAuthorityForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-source-readback/v1") + .setTargetNamespace(NAMESPACE) + .setRequestId(QUERY_ID) + .setSourceSnapshot(snapshot.build()); + if (selected != null) { + response.setRequestedEventCanonicalJson(selected.canonicalJson()); + } + + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = + mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) + .thenReturn(response.build()); + AccountIssuerAuthorityClient client = newClient(stub); + if (selected == null) { + return client.readCurrent(QUERY_ID); + } + return client.readCommittedEvent(QUERY_ID, selected.outboxSequence()); + } + + private String executeRegistered( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + var descriptor = IssuerAuthorityProjectionRedisContract.descriptor(); + var request = + new InvocationRequest( + descriptor.scriptId(), + descriptor.resourcePath(), + descriptor.sha256(), + descriptor.owner(), + descriptor.principal(), + descriptor.role(), + List.of(key), + List.of(expectedMode, expectedBytes, candidateBytes)); + var invocation = IssuerAuthorityProjectionRedisContract.registry().prepareInvocation(request); + assertThat(invocation.descriptor()).isSameAs(descriptor); + return adminTemplate.execute( + CAS_SCRIPT, List.of(key), expectedMode, expectedBytes, candidateBytes); + } + + private String key() { + return IssuerAuthorityProjectionRedisContract.keyForIssuer(issuerId); + } + + private static JsonNode parse(String json) throws Exception { + return JSON.readTree(json); + } + + private IssuerGenerationAuthorityEvent event( + String sequence, String generation, String sourceVersion, int identity) { + String requestId = String.format(Locale.ROOT, "00000000-0000-4000-8000-%012d", identity); + String scope = "issuer/" + issuerId; + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", EVENT_ID_PREFIX + requestId, + "requestId", requestId, + "issuerId", issuerId, + "sourceScope", scope, + "outboxStreamKey", IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope, + "outboxSequence", sequence, + "issuerAuthGeneration", generation, + "sourceVersion", sourceVersion)); + } + + private AccountIssuerAuthorityClient newClient( + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub) throws Exception { + AccountIssuerAuthorityClient client = + new AccountIssuerAuthorityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + issuerId); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static CommonGrpcClientProperties mtlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/account-ca.crt"); + return tls; + } + + private static String exceptionMessageChain(Throwable failure) { + StringBuilder messages = new StringBuilder(); + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current.getMessage() != null) { + messages.append(current.getMessage()).append('\n'); + } + } + return messages.toString(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountMembershipAuthorityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountMembershipAuthorityClientTest.java new file mode 100644 index 0000000000..c6f00fe7bc --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountMembershipAuthorityClientTest.java @@ -0,0 +1,425 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Attributes; +import io.grpc.ClientCall; +import io.grpc.Grpc; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; + +class AccountMembershipAuthorityClientTest { + private static final String NAMESPACE = "game-session-test"; + private static final String ACCOUNT_ID = "00000000-0000-4000-8000-000000000101"; + private static final String TENANT_ID = "00000000-0000-0000-0000-000000000005"; + private static final String REALM_ID = "00000000-0000-4000-8000-000000000201"; + private static final String PLAYABLE_NAMESPACE_ID = "00000000-0000-4000-8000-000000000301"; + private static final String GAME_INSTANCE_ID = "00000000-0000-4000-8000-000000000401"; + private static final String REQUEST_ID = "session-7:attempt α"; + + @Test + void sendsCompleteTypedContextWithBoundedDeadlineAndReturnsVerifiedResponse() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = mockStub(); + GetTenantMembershipForRuntimeResponse response = membershipResponse(); + when(stub.getTenantMembershipForRuntime(any())).thenReturn(response); + AccountMembershipAuthorityClient client = newClient(stub); + + GetTenantMembershipForRuntimeResponse verified = + client.getTenantMembershipForRuntime(playerContext()); + + assertThat(verified).isEqualTo(response); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(GetTenantMembershipForRuntimeRequest.class); + verify(stub).getTenantMembershipForRuntime(requestCaptor.capture()); + assertThat(requestCaptor.getValue().hasPlayerContext()).isTrue(); + assertThat(requestCaptor.getValue().getPlayerContext()).isEqualTo(playerContext()); + } + + @Test + void returnsValidInactiveAndMissingSnapshotsWithoutTreatingMissingAsAdmission() throws Exception { + GetTenantMembershipForRuntimeResponse inactive = + bindToRequest(RuntimeMembershipTestFixtures.inactive(ACCOUNT_ID, 5L, "3")); + GetTenantMembershipForRuntimeResponse missing = + bindToRequest(RuntimeMembershipTestFixtures.missing(ACCOUNT_ID, 5L)); + AccountServiceGrpc.AccountServiceBlockingStub stub = mockStub(); + when(stub.getTenantMembershipForRuntime(any())).thenReturn(inactive, missing); + AccountMembershipAuthorityClient client = newClient(stub); + + GetTenantMembershipForRuntimeResponse verifiedInactive = + client.getTenantMembershipForRuntime(playerContext()); + GetTenantMembershipForRuntimeResponse verifiedMissing = + client.getTenantMembershipForRuntime(playerContext()); + + assertThat(verifiedInactive.getMembershipLifecycleState()).isEqualTo("INACTIVE"); + assertThat(verifiedMissing.getMembershipLifecycleState()).isEqualTo("MISSING"); + assertThat(verifiedMissing.getMembershipExists()).isFalse(); + assertThat(verifiedMissing.getGameplayAdmissionAllowed()).isFalse(); + } + + @Test + void acceptsCanonicalUuidTargetSelectorsAndOptionalCharacterButRejectsInvalidContextBeforeStub() + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountMembershipAuthorityClient client = newClientWithoutStub(channelFactory); + + assertThatThrownBy(() -> client.getTenantMembershipForRuntime(null)) + .isInstanceOf(IllegalArgumentException.class); + assertInvalidContext(client, playerContext().toBuilder().setGameInstanceId("7").build()); + assertInvalidContext(client, playerContext().toBuilder().setSessionId("07").build()); + assertInvalidContext(client, playerContext().toBuilder().setCharacterId("-1").build()); + assertInvalidContext( + client, playerContext().toBuilder().setPlayableStateScope("UNSPECIFIED").build()); + assertInvalidContext(client, playerContext().toBuilder().setRealmId("5").build()); + assertInvalidContext( + client, + playerContext().toBuilder().setAccountId("00000000-0000-0000-0000-000000000000").build()); + assertInvalidContext( + client, + playerContext().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build()); + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsEveryRecipientRequestAvailabilityFreshnessAndContentDeviation() throws Exception { + GetTenantMembershipForRuntimeResponse valid = membershipResponse(); + assertResponseRejected(valid.toBuilder().setAccountId(REALM_ID).build()); + assertResponseRejected(valid.toBuilder().setTenantId(REALM_ID).build()); + assertResponseRejected(valid.toBuilder().setRequestAccountId(REALM_ID).build()); + assertResponseRejected(valid.toBuilder().setRequestTenantId(REALM_ID).build()); + assertResponseRejected(valid.toBuilder().setRequestId("another-operation").build()); + assertResponseRejected(valid.toBuilder().setAuthorityAvailability("UNAVAILABLE").build()); + assertResponseRejected( + valid.toBuilder() + .setError(ErrorDetail.newBuilder().setCode("AUTH_UNAVAILABLE").build()) + .build()); + assertResponseRejected( + valid.toBuilder().setEvaluatedAt(Instant.now().minusSeconds(20).toString()).build()); + assertResponseRejected( + valid.toBuilder().setEvaluatedAt(Instant.now().plusSeconds(2).toString()).build()); + assertResponseRejected(valid.toBuilder().clearOutboxSourceEvidence().build()); + assertResponseRejected( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build()); + assertResponseRejected( + valid.toBuilder() + .setOutboxCheckpoints( + 0, + valid.getOutboxCheckpoints(0).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build())) + .build()); + } + + @Test + void rejectsAccountErrorsAndUnavailableTransportWithoutReturningContent() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub errorStub = mockStub(); + when(errorStub.getTenantMembershipForRuntime(any())) + .thenReturn(membershipResponse().toBuilder().setAuthorityAvailability("UNKNOWN").build()); + AccountMembershipAuthorityClient errorClient = newClient(errorStub); + assertThatThrownBy(() -> errorClient.getTenantMembershipForRuntime(playerContext())) + .isInstanceOf(IllegalStateException.class); + + AccountServiceGrpc.AccountServiceBlockingStub unavailableStub = mockStub(); + when(unavailableStub.getTenantMembershipForRuntime(any())) + .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); + AccountMembershipAuthorityClient unavailableClient = newClient(unavailableStub); + assertThatThrownBy(() -> unavailableClient.getTenantMembershipForRuntime(playerContext())) + .isInstanceOf(IllegalStateException.class) + .hasCauseInstanceOf(StatusRuntimeException.class); + } + + @Test + void constructorRequiresFileBackedWorkloadMtlsAndExplicitInitialization() throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountMembershipAuthorityClient( + new ServiceEndpointsProperties(), + plaintext, + channelFactory, + BlockingGrpcStubCustomizer.noop(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + + CommonGrpcClientProperties classpath = mtlsProperties(); + classpath.setPrivateKey("classpath:client.key"); + assertThatThrownBy( + () -> + new AccountMembershipAuthorityClient( + new ServiceEndpointsProperties(), + classpath, + channelFactory, + BlockingGrpcStubCustomizer.noop(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + CommonGrpcClientProperties incomplete = mtlsProperties(); + incomplete.setCaCert(""); + assertThatThrownBy( + () -> + new AccountMembershipAuthorityClient( + new ServiceEndpointsProperties(), + incomplete, + channelFactory, + BlockingGrpcStubCustomizer.noop(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountMembershipAuthorityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + channelFactory, + BlockingGrpcStubCustomizer.noop(), + "bad/namespace")) + .isInstanceOf(IllegalArgumentException.class); + + AccountMembershipAuthorityClient client = newClientWithoutStub(channelFactory); + verifyNoInteractions(channelFactory); + assertThatThrownBy(() -> client.getTenantMembershipForRuntime(playerContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + } + + @Test + void explicitInitUsesConfiguredAccountTargetAndFileBackedMtls(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + CommonGrpcClientProperties tls = fileBackedMtlsProperties(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + AccountMembershipAuthorityClient client = + new AccountMembershipAuthorityClient( + endpoints, tls, channelFactory, BlockingGrpcStubCustomizer.noop(), NAMESPACE); + try { + verifyNoInteractions(channelFactory); + client.init(); + verify(channelFactory) + .buildChannel( + eq("account.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + @Test + void installedPeerInterceptorRejectsMissingAndWrongAccountServerIdentity() throws Exception { + AccountMembershipAuthorityClient client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + for (SSLSession session : + new SSLSession[] { + null, + peerSession("game-design-service"), + peerSession("other-namespace", "account-service") + }) { + ManagedChannel channel = mock(ManagedChannel.class); + Attributes attributes = + session == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build(); + when(channel.newCall(any(), any())).thenAnswer(invocation -> immediateCloseCall(attributes)); + var stub = client.buildStub(channel); + + assertThatThrownBy( + () -> + stub.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setPlayerContext(playerContext()) + .build())) + .isInstanceOf(StatusRuntimeException.class) + .extracting(exception -> ((StatusRuntimeException) exception).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + } + } + + private static void assertInvalidContext( + AccountMembershipAuthorityClient client, PlayerExecutionContext context) { + assertThatThrownBy(() -> client.getTenantMembershipForRuntime(context)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertResponseRejected(GetTenantMembershipForRuntimeResponse response) + throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = mockStub(); + when(stub.getTenantMembershipForRuntime(any())).thenReturn(response); + AccountMembershipAuthorityClient client = newClient(stub); + assertThatThrownBy(() -> client.getTenantMembershipForRuntime(playerContext())) + .isInstanceOf(IllegalStateException.class); + } + + private static GetTenantMembershipForRuntimeResponse membershipResponse() { + return bindToRequest(RuntimeMembershipTestFixtures.active(ACCOUNT_ID, 5L, TENANT_ID, "1")); + } + + private static GetTenantMembershipForRuntimeResponse bindToRequest( + GetTenantMembershipForRuntimeResponse response) { + return response.toBuilder() + .setRequestAccountId(ACCOUNT_ID) + .setRequestTenantId(TENANT_ID) + .setRequestId(REQUEST_ID) + .setAuthorityAvailability("AVAILABLE") + .setEvaluatedAt(Instant.now().toString()) + .build(); + } + + private static PlayerExecutionContext playerContext() { + return PlayerExecutionContext.newBuilder() + .setAccountId(ACCOUNT_ID) + .setTenantId(TENANT_ID) + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_NAMESPACE_ID) + .setPlayableStateScope("SHARED") + .setGameInstanceId(GAME_INSTANCE_ID) + .setCharacterId("") + .setSessionId("7") + .setRequestId(REQUEST_ID) + .build(); + } + + private static AccountMembershipAuthorityClient newClient( + AccountServiceGrpc.AccountServiceBlockingStub stub) throws Exception { + AccountMembershipAuthorityClient client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static AccountMembershipAuthorityClient newClientWithoutStub( + GrpcChannelFactory channelFactory) { + return new AccountMembershipAuthorityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + channelFactory, + BlockingGrpcStubCustomizer.noop(), + NAMESPACE); + } + + private static AccountServiceGrpc.AccountServiceBlockingStub mockStub() { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static CommonGrpcClientProperties mtlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/account-ca.crt"); + return tls; + } + + private static CommonGrpcClientProperties fileBackedMtlsProperties(Path directory) + throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.createFile(directory.resolve("game-session-client.crt")).toString()); + tls.setPrivateKey(Files.createFile(directory.resolve("game-session-client.key")).toString()); + tls.setCaCert(Files.createFile(directory.resolve("account-ca.crt")).toString()); + return tls; + } + + private static ClientCall immediateCloseCall(Attributes attributes) { + return new ClientCall<>() { + private Listener listener; + + @Override + public void start(Listener callListener, Metadata headers) { + listener = callListener; + } + + @Override + public void request(int numMessages) {} + + @Override + public void cancel(String message, Throwable cause) {} + + @Override + public void halfClose() { + listener.onClose(Status.OK, new Metadata()); + } + + @Override + public void sendMessage(Object message) {} + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setMessageCompression(boolean enabled) {} + + @Override + public Attributes getAttributes() { + return attributes; + } + }; + } + + private static SSLSession peerSession(String service) throws Exception { + return peerSession(NAMESPACE, service); + } + + private static SSLSession peerSession(String namespace, String service) throws Exception { + X509Certificate certificate = mock(X509Certificate.class); + when(certificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/" + namespace + "/sa/" + service))); + SSLSession session = mock(SSLSession.class); + when(session.getPeerCertificates()).thenReturn(new Certificate[] {certificate}); + return session; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/RuntimeMembershipResponseValidatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/RuntimeMembershipResponseValidatorTest.java new file mode 100644 index 0000000000..bebae861fd --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/RuntimeMembershipResponseValidatorTest.java @@ -0,0 +1,221 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.RuntimeAuthorityTuple; +import net.firedevops.firemud.account.v1.RuntimeMembershipBaseline; +import net.firedevops.firemud.account.v1.RuntimeOutboxCheckpoint; +import net.firedevops.firemud.account.v1.RuntimeOutboxSourceEvidence; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +class RuntimeMembershipResponseValidatorTest { + private static final String ACCOUNT_ID = "00000000-0000-4000-8000-000000000101"; + private static final long RETAINED_TENANT_KEY = 5L; + private static final String TENANT_ID = "00000000-0000-0000-0000-000000000005"; + private static final String LARGE_COUNTER = "922337203685477580812345678901234567890"; + + @Test + void acceptsCurrentActiveInactiveAndNonadmittingMissingContent() { + GetTenantMembershipForRuntimeResponse active = + RuntimeMembershipTestFixtures.active(ACCOUNT_ID, RETAINED_TENANT_KEY, TENANT_ID, "1"); + GetTenantMembershipForRuntimeResponse inactive = + RuntimeMembershipTestFixtures.inactive(ACCOUNT_ID, RETAINED_TENANT_KEY, "3"); + GetTenantMembershipForRuntimeResponse missing = + RuntimeMembershipTestFixtures.missing(ACCOUNT_ID, RETAINED_TENANT_KEY); + + assertThat(RuntimeMembershipResponseValidator.validateContent(active)).isPresent(); + assertThat(RuntimeMembershipResponseValidator.validateContent(inactive)).isPresent(); + assertThat(RuntimeMembershipResponseValidator.validateContent(missing)).isEmpty(); + assertThat(missing.getMembershipExists()).isFalse(); + assertThat(missing.getGameplayAdmissionAllowed()).isFalse(); + assertThat(missing.getMembershipLifecycleState()).isEqualTo("MISSING"); + } + + @Test + void acceptsAdvancedMembershipEventAndArbitraryPrecisionCounters() { + GetTenantMembershipForRuntimeResponse advanced = + RuntimeMembershipTestFixtures.left(ACCOUNT_ID, RETAINED_TENANT_KEY, List.of("player")); + MembershipEvent historical = + RuntimeMembershipResponseValidator.validateContent(advanced).orElseThrow(); + assertThat(historical.outboxSequence()).isEqualTo("2"); + assertThat(historical.membershipLifecycleState()).isEqualTo("INACTIVE"); + + GetTenantMembershipForRuntimeResponse large = withLargeMembershipCounters(advanced); + MembershipEvent largeEvent = + RuntimeMembershipResponseValidator.validateContent(large).orElseThrow(); + + assertThat(largeEvent.outboxSequence()).isEqualTo(LARGE_COUNTER); + assertThat(largeEvent.membershipAuthorityGeneration()).isEqualTo(LARGE_COUNTER); + assertThat(large.getMembershipVersionMap()).containsEntry(TENANT_ID, LARGE_COUNTER); + } + + @Test + void rejectsMissingSourceAndBaselineMismatch() { + GetTenantMembershipForRuntimeResponse active = + RuntimeMembershipTestFixtures.active(ACCOUNT_ID, RETAINED_TENANT_KEY, TENANT_ID, "1"); + + assertRejected(active.toBuilder().clearOutboxSourceEvidence().build()); + assertRejected( + active.toBuilder() + .setMembershipBaseline( + active.getMembershipBaseline().toBuilder().setMembershipLifecycleState("INACTIVE")) + .build()); + } + + @Test + void rejectsUnknownFieldsAtEveryEvidenceMessageLevel() { + GetTenantMembershipForRuntimeResponse active = + RuntimeMembershipTestFixtures.active(ACCOUNT_ID, RETAINED_TENANT_KEY, TENANT_ID, "1"); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertRejected(active.toBuilder().setUnknownFields(unknown).build()); + assertRejected( + active.toBuilder() + .setMembershipBaseline( + active.getMembershipBaseline().toBuilder().setUnknownFields(unknown)) + .build()); + assertRejected( + active.toBuilder() + .setAuthorityTuple(active.getAuthorityTuple().toBuilder().setUnknownFields(unknown)) + .build()); + assertRejected( + active.toBuilder() + .setOutboxCheckpoints( + 0, active.getOutboxCheckpoints(0).toBuilder().setUnknownFields(unknown)) + .build()); + assertRejected( + active.toBuilder() + .setOutboxSourceEvidence( + 0, active.getOutboxSourceEvidence(0).toBuilder().setUnknownFields(unknown)) + .build()); + assertRejected(active.toBuilder().setError(ErrorDetail.getDefaultInstance()).build()); + } + + @Test + void rejectsUnsupportedAuthorityExtensionsAndMalformedMembershipEventIdentity() { + GetTenantMembershipForRuntimeResponse active = + RuntimeMembershipTestFixtures.active(ACCOUNT_ID, RETAINED_TENANT_KEY, TENANT_ID, "1"); + + assertRejected( + active.toBuilder() + .setAuthorityTuple( + active.getAuthorityTuple().toBuilder() + .addPrivateRealmGrantVersions( + net.firedevops.firemud.account.v1.RuntimePrivateRealmGrantVersion + .getDefaultInstance())) + .build()); + assertRejected( + active.toBuilder() + .setAuthorityTuple( + RuntimeAuthorityTuple.newBuilder() + .mergeFrom(active.getAuthorityTuple()) + .setTenantBillingCutoff( + net.firedevops.firemud.account.v1.RuntimeTenantBillingCutoffMap + .getDefaultInstance())) + .build()); + assertRejected( + active.toBuilder() + .setOutboxSourceEvidence( + 0, active.getOutboxSourceEvidence(0).toBuilder().setEventId("not-a-uuid")) + .build()); + } + + private static void assertRejected(GetTenantMembershipForRuntimeResponse response) { + assertThatThrownBy(() -> RuntimeMembershipResponseValidator.validateContent(response)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(RuntimeMembershipResponseValidator.hasCompleteAuthorityCarrier(response)).isFalse(); + } + + private static GetTenantMembershipForRuntimeResponse withLargeMembershipCounters( + GetTenantMembershipForRuntimeResponse response) { + String streamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + response.getAccountId() + + "/" + + response.getTenantId(); + MembershipEvent oldEvent = + MembershipAuthorityEventV1Codec.verify( + response.getOutboxSourceEvidence(0).getCanonicalEventJson()); + MembershipEvent largeEvent = + MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", oldEvent.eventId()), + Map.entry("requestId", oldEvent.requestId()), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", LARGE_COUNTER), + Map.entry( + "sourceScope", + "membership/" + response.getAccountId() + "/" + response.getTenantId()), + Map.entry("accountId", response.getAccountId()), + Map.entry("tenantId", response.getTenantId()), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "INACTIVE"), + Map.entry("membershipVersion", Map.of(response.getTenantId(), LARGE_COUNTER)), + Map.entry("membershipAuthorityGeneration", LARGE_COUNTER), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(response.getTenantId(), "1"), + "membershipAuthorityGeneration", + Map.of(response.getTenantId(), LARGE_COUNTER), + "privateRealmGrantVersions", + List.of())), + Map.entry("issuanceFence", LARGE_COUNTER), + Map.entry("roles", response.getRolesList()), + Map.entry("gameplayAdmissionAllowed", false), + Map.entry("callerBoundAuthorityInvalidated", true))); + + RuntimeAuthorityTuple currentTuple = + response.getAuthorityTuple().toBuilder() + .putMembershipAuthorityGeneration(response.getTenantId(), LARGE_COUNTER) + .build(); + RuntimeMembershipBaseline baseline = + response.getMembershipBaseline().toBuilder() + .putMembershipVersion(response.getTenantId(), LARGE_COUNTER) + .setMembershipAuthorityGeneration(LARGE_COUNTER) + .build(); + GetTenantMembershipForRuntimeResponse.Builder builder = + response.toBuilder() + .putMembershipVersion(response.getTenantId(), LARGE_COUNTER) + .setMembershipAuthorityGeneration(LARGE_COUNTER) + .setIssuanceFence(LARGE_COUNTER) + .setAuthorityTuple(currentTuple) + .setMembershipBaseline(baseline) + .clearOutboxSourceEvidence() + .addOutboxSourceEvidence( + RuntimeOutboxSourceEvidence.newBuilder() + .setOutboxStreamKey(streamKey) + .setOutboxSequence(LARGE_COUNTER) + .setEventId(largeEvent.eventId()) + .setEventDigest(largeEvent.eventDigest()) + .setCanonicalEventJson(largeEvent.canonicalJson())); + for (int index = 0; index < response.getOutboxCheckpointsCount(); index++) { + RuntimeOutboxCheckpoint checkpoint = response.getOutboxCheckpoints(index); + if (streamKey.equals(checkpoint.getOutboxStreamKey())) { + builder.setOutboxCheckpoints( + index, checkpoint.toBuilder().setOutboxSequence(LARGE_COUNTER)); + } + } + return builder.build(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 22e224c064..b18a4542bf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -26,7 +26,13 @@ import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.account.v1.RuntimeOutboxCheckpoint; +import net.firedevops.firemud.account.v1.RuntimeOutboxSourceEvidence; +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; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; @@ -73,6 +79,8 @@ class PlayCommandHandlerTest { private static final String SECOND_CANONICAL_TENANT_UUID = "67defbf2-3b74-4d0f-96cf-8f251b32e4d0"; private static final String FIXTURE_LEGACY_TENANT_UUID = "00000000-0000-0000-0000-000000000022"; private static final String OTHER_ACCOUNT_ID = "00000000-0000-0000-0000-000000000999"; + private static final String ACCOUNT_AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; + private static final String ACCOUNT_AUTHORITY_ISSUER = "firemud-account-service"; private static final ObjectMapper JSON = new ObjectMapper(); private static final UUID ADMISSION_REALM_ID = UUID.fromString("00000000-0000-0000-0000-000000000001"); @@ -3872,6 +3880,166 @@ void playPublicJoinRequiresFreshEntitlementEvidence(String evidence) { Mockito.verifyNoInteractions(sessionContextService, gameplayPresenceLifecycleService); } + @Test + void playLeftMembershipWithHigherCurrentFenceStillRequiresJoin() { + SessionContext context = unboundContext(); + var earlierMembership = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.left( + PLAYER_ACCOUNT_ID, 22L, List.of("designer", "player"))); + String earlierCanonicalEvent = + earlierMembership.getOutboxSourceEvidence(0).getCanonicalEventJson(); + var earlierEvent = MembershipAuthorityEventV1Codec.verify(earlierCanonicalEvent); + var currentMembership = earlierMembership.toBuilder().setIssuanceFence("3").build(); + assertThat(currentMembership.getIssuanceFence()).isEqualTo("3"); + assertThat(currentMembership.getOutboxSourceEvidence(0).getCanonicalEventJson()) + .isEqualTo(earlierCanonicalEvent); + assertThat(earlierEvent.issuanceFence()).isEqualTo("2"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId(currentMembership, invocation.getArgument(0))); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.join-required"); + Mockito.verifyNoInteractions( + entityManagementClient, + sessionContextService, + gameplayPresenceLifecycleService, + moderationPolicyClient, + scriptEventPublisher); + } + + @ParameterizedTest + @ValueSource(strings = {"logout-all", "password-reset"}) + void playAcceptsCurrentRecipientCarrierAfterAuthorityAdvances(String accountCutoffType) { + SessionContext context = unboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + var currentCarrier = currentMembershipCarrierAfterAuthorityAdvances(accountCutoffType); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId(currentCarrier, invocation.getArgument(0))); + + // This mocked Account boundary proves local content acceptance, not an authenticated runtime + // RPC. + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + Mockito.verify(entityManagementClient) + .listCharactersByAccount( + "22", PLAYER_ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Mockito.verify(sessionContextService).save(Mockito.any(SessionContext.class)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void playRejectsValidMembershipRecipientCarrierForDifferentAuthenticatedAccount( + boolean alreadyBound) { + SessionContext context = + alreadyBound + ? new SessionContext( + 1L, + 22L, + PLAYER_ACCOUNT_ID, + "demo@example.com", + 123L, + "demo", + 1L, + "R-1", + "jwt-token") + : unboundContext(); + String differentAccountId = "30000000-0000-4000-8000-000000000003"; + var otherAccountCarrier = + currentMembershipCarrierAfterAuthorityAdvances("logout-all", differentAccountId).toBuilder() + .setRequestAccountId(PLAYER_ACCOUNT_ID) + .build(); + String membershipStream = + ACCOUNT_AUTHORITY_STREAM_PREFIX + + "membership/" + + differentAccountId + + "/" + + CANONICAL_TENANT_UUID; + var membershipEvent = + MembershipAuthorityEventV1Codec.verify( + authoritySource(otherAccountCarrier, membershipStream).getCanonicalEventJson()); + var accountEvent = + AccountLogoutAllAuthorityEventV1Codec.verify( + authoritySource( + otherAccountCarrier, + ACCOUNT_AUTHORITY_STREAM_PREFIX + "account/" + differentAccountId) + .getCanonicalEventJson()); + assertThat(otherAccountCarrier.getAccountId()).isEqualTo(differentAccountId); + assertThat(otherAccountCarrier.getRequestAccountId()).isEqualTo(context.accountId()); + assertThat(otherAccountCarrier.getRequestTenantId()).isEqualTo(CANONICAL_TENANT_UUID); + assertThat(otherAccountCarrier.getOutboxSourceEvidenceCount()).isEqualTo(4); + assertThat(membershipEvent.accountId()).isEqualTo(differentAccountId); + assertThat(membershipEvent.sourceScope()) + .isEqualTo("membership/" + differentAccountId + "/" + CANONICAL_TENANT_UUID); + assertThat(accountEvent.accountId()).isEqualTo(differentAccountId); + + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId(otherAccountCarrier, invocation.getArgument(0))); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + Mockito.verifyNoInteractions( + entityManagementClient, + sessionContextService, + gameplayPresenceLifecycleService, + moderationPolicyClient, + scriptEventPublisher); + } + + @ParameterizedTest + @ValueSource(strings = {"missing", "changed", "scope", "ahead", "unknown-field"}) + void playRejectsMalformedCurrentRecipientEvidenceBeforeGameplayMutation(String defect) { + SessionContext context = unboundContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + var currentCarrier = + currentMembershipCarrierEvidenceWithDefect( + currentMembershipCarrierAfterAuthorityAdvances("logout-all"), defect); + when(accountClient.getTenantMembershipForRuntime( + Mockito.any(net.firedevops.firemud.shared.v1.PlayerExecutionContext.class))) + .thenAnswer( + invocation -> + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures + .echoRequestId(currentCarrier, invocation.getArgument(0))); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verifyNoInteractions( + entityManagementClient, + sessionContextService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @Test void playBoundLeftMembershipRequiresJoinAndClearsBindingForPublicProduction() { SessionContext context = @@ -4358,8 +4526,12 @@ void playRejectsInvalidPositiveMembershipAuthority(String invalidEvidence) { PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + .isEqualTo( + "wrong-account".equals(invalidEvidence) + ? GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE + : GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); Mockito.verify(gameplayPresenceLifecycleService, never()) .clearGameplayBinding(Mockito.any(), Mockito.anyString()); Mockito.verify(sessionContextService, never()).save(Mockito.any()); @@ -5245,6 +5417,295 @@ private static String joinedOutputText(List outputs) { .orElse(null); } + private static GetTenantMembershipForRuntimeResponse + currentMembershipCarrierAfterAuthorityAdvances(String accountCutoffType) { + return currentMembershipCarrierAfterAuthorityAdvances(accountCutoffType, PLAYER_ACCOUNT_ID); + } + + private static GetTenantMembershipForRuntimeResponse + currentMembershipCarrierAfterAuthorityAdvances(String accountCutoffType, String accountId) { + var earlierMembership = + freshMembership( + net.firedevops.firemud.gamesession.support.RuntimeMembershipTestFixtures.active( + accountId, 22L, "1")); + String accountStream = ACCOUNT_AUTHORITY_STREAM_PREFIX + "account/" + accountId; + String issuerStream = ACCOUNT_AUTHORITY_STREAM_PREFIX + "issuer/" + ACCOUNT_AUTHORITY_ISSUER; + String membershipStream = + ACCOUNT_AUTHORITY_STREAM_PREFIX + "membership/" + accountId + "/" + CANONICAL_TENANT_UUID; + String tenantStream = ACCOUNT_AUTHORITY_STREAM_PREFIX + "tenant/" + CANONICAL_TENANT_UUID; + + var issuerEvent = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "unit-test-issuer-advance"), + Map.entry("requestId", "unit-test-issuer-advance"), + Map.entry("issuerId", ACCOUNT_AUTHORITY_ISSUER), + Map.entry("sourceScope", "issuer/" + ACCOUNT_AUTHORITY_ISSUER), + Map.entry("outboxStreamKey", issuerStream), + Map.entry("outboxSequence", "1"), + Map.entry("issuerAuthGeneration", "2"), + Map.entry("sourceVersion", "2"))); + var accountEvidence = currentAccountCutoffEvidence(accountCutoffType, accountStream, accountId); + var tenantEvent = + TenantGenerationAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", TenantGenerationAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + "account-tenant-generation-event-v1:ac6c2c28-72a1-45a2-a8db-a8e92f932a50"), + Map.entry("requestId", "ac6c2c28-72a1-45a2-a8db-a8e92f932a50"), + Map.entry("tenantId", CANONICAL_TENANT_UUID), + Map.entry("sourceScope", "tenant/" + CANONICAL_TENANT_UUID), + Map.entry("outboxStreamKey", tenantStream), + Map.entry("outboxSequence", "1"), + Map.entry("tenantAuthorityGeneration", "2"), + Map.entry("sourceVersion", "2"))); + var membershipEvidence = + authoritySource( + earlierMembership, + ACCOUNT_AUTHORITY_STREAM_PREFIX + + "membership/" + + accountId + + "/" + + CANONICAL_TENANT_UUID); + + var currentTuple = + earlierMembership.getAuthorityTuple().toBuilder() + .setIssuerAuthGeneration("2") + .setAccountAuthorityGeneration("2") + .putTenantAuthorityGeneration(CANONICAL_TENANT_UUID, "2") + .setAccountSecurityCutoff( + net.firedevops.firemud.account.v1.RuntimeAccountSecurityCutoff.newBuilder() + .setAccountAuthorityGeneration("2") + .setOutboxStreamKey(accountStream) + .setOutboxSequence("1")) + .build(); + return earlierMembership.toBuilder() + .setIssuanceFence("2") + .setAuthorityTuple(currentTuple) + .clearOutboxCheckpoints() + .addAllOutboxCheckpoints( + List.of( + authorityCheckpoint(accountStream, "1"), + authorityCheckpoint(issuerStream, "1"), + authorityCheckpoint(membershipStream, membershipEvidence.getOutboxSequence()), + authorityCheckpoint(tenantStream, "1"))) + .clearOutboxSourceEvidence() + .addAllOutboxSourceEvidence( + List.of( + accountEvidence, + authoritySource(issuerEvent), + membershipEvidence, + authoritySource(tenantEvent))) + .build(); + } + + private static RuntimeOutboxSourceEvidence currentAccountCutoffEvidence( + String accountCutoffType, String accountStream, String accountId) { + String requestId = "b5a70a16-15df-4bfa-9568-7f28ce0fd7f6"; + String sourceScope = "account/" + accountId; + Map preimage = + Map.ofEntries( + Map.entry( + "schemaVersion", + "logout-all".equals(accountCutoffType) + ? AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION + : PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry( + "eventType", + "logout-all".equals(accountCutoffType) + ? AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE + : PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + "logout-all".equals(accountCutoffType) + ? "account-logout-all-event-v1:" + requestId + : "account-password-reset-event-v1:" + requestId), + Map.entry("requestId", requestId), + Map.entry("accountId", accountId), + Map.entry("sourceScope", sourceScope), + Map.entry("outboxStreamKey", accountStream), + Map.entry("outboxSequence", "1"), + Map.entry("accountAuthorityGeneration", "2"), + Map.entry("sourceVersion", "2"), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "2", + "outboxStreamKey", accountStream, + "outboxSequence", "1"))); + return "logout-all".equals(accountCutoffType) + ? authoritySource(AccountLogoutAllAuthorityEventV1Codec.seal(preimage)) + : authoritySource(PasswordResetAuthorityEventV1Codec.seal(preimage)); + } + + private static GetTenantMembershipForRuntimeResponse currentMembershipCarrierEvidenceWithDefect( + GetTenantMembershipForRuntimeResponse response, String defect) { + String accountStream = ACCOUNT_AUTHORITY_STREAM_PREFIX + "account/" + PLAYER_ACCOUNT_ID; + String membershipStream = + ACCOUNT_AUTHORITY_STREAM_PREFIX + + "membership/" + + PLAYER_ACCOUNT_ID + + "/" + + CANONICAL_TENANT_UUID; + var source = authoritySource(response, accountStream); + return switch (defect) { + case "missing" -> replaceAuthoritySource(response, accountStream, null); + case "changed" -> + replaceAuthoritySource( + response, + accountStream, + source.toBuilder() + .setCanonicalEventJson( + changeCanonicalEventWithoutResealing(source.getCanonicalEventJson())) + .build()); + case "scope" -> + replaceAuthoritySource( + response, + accountStream, + source.toBuilder() + .setOutboxStreamKey( + ACCOUNT_AUTHORITY_STREAM_PREFIX + + "account/00000000-0000-4000-8000-000000000099") + .build()); + case "ahead" -> { + var membershipSource = authoritySource(response, membershipStream); + yield replaceMembershipCanonicalEvent( + response, + membershipSource, + resealMembershipEventWithIssuerGeneration( + membershipSource.getCanonicalEventJson(), "3")); + } + case "unknown-field" -> + replaceAuthoritySource( + response, + accountStream, + source.toBuilder().setUnknownFields(testUnknownField()).build()); + default -> throw new IllegalArgumentException("Unknown current membership evidence defect"); + }; + } + + private static RuntimeOutboxSourceEvidence authoritySource( + PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent event) { + return RuntimeOutboxSourceEvidence.newBuilder() + .setOutboxStreamKey(event.outboxStreamKey()) + .setOutboxSequence(event.outboxSequence()) + .setEventId(event.eventId()) + .setEventDigest(event.eventDigest()) + .setCanonicalEventJson(event.canonicalJson()) + .build(); + } + + private static RuntimeOutboxSourceEvidence authoritySource( + AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent event) { + return RuntimeOutboxSourceEvidence.newBuilder() + .setOutboxStreamKey(event.outboxStreamKey()) + .setOutboxSequence(event.outboxSequence()) + .setEventId(event.eventId()) + .setEventDigest(event.eventDigest()) + .setCanonicalEventJson(event.canonicalJson()) + .build(); + } + + private static RuntimeOutboxSourceEvidence authoritySource( + IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent event) { + return RuntimeOutboxSourceEvidence.newBuilder() + .setOutboxStreamKey(event.outboxStreamKey()) + .setOutboxSequence(event.outboxSequence()) + .setEventId(event.eventId()) + .setEventDigest(event.eventDigest()) + .setCanonicalEventJson(event.canonicalJson()) + .build(); + } + + private static RuntimeOutboxSourceEvidence authoritySource( + TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent event) { + return RuntimeOutboxSourceEvidence.newBuilder() + .setOutboxStreamKey(event.outboxStreamKey()) + .setOutboxSequence(event.outboxSequence()) + .setEventId(event.eventId()) + .setEventDigest(event.eventDigest()) + .setCanonicalEventJson(event.canonicalJson()) + .build(); + } + + private static RuntimeOutboxCheckpoint authorityCheckpoint(String streamKey, String sequence) { + return RuntimeOutboxCheckpoint.newBuilder() + .setOutboxStreamKey(streamKey) + .setOutboxSequence(sequence) + .build(); + } + + private static GetTenantMembershipForRuntimeResponse replaceMembershipCanonicalEvent( + GetTenantMembershipForRuntimeResponse response, + RuntimeOutboxSourceEvidence source, + String canonicalJson) { + var event = MembershipAuthorityEventV1Codec.verify(canonicalJson); + return replaceAuthoritySource( + response, + source.getOutboxStreamKey(), + source.toBuilder() + .setOutboxStreamKey(event.outboxStreamKey()) + .setOutboxSequence(event.outboxSequence()) + .setEventId(event.eventId()) + .setEventDigest(event.eventDigest()) + .setCanonicalEventJson(event.canonicalJson()) + .build()); + } + + private static String resealMembershipEventWithIssuerGeneration( + String canonicalJson, String issuerGeneration) { + try { + ObjectNode event = (ObjectNode) JSON.readTree(canonicalJson); + ((ObjectNode) event.get("authorityTuple")).put("issuerAuthGeneration", issuerGeneration); + event.remove("eventDigest"); + return MembershipAuthorityEventV1Codec.seal( + JSON.convertValue(event, new TypeReference>() {})) + .canonicalJson(); + } catch (IOException ex) { + throw new AssertionError("test membership event should be valid JSON", ex); + } + } + + private static GetTenantMembershipForRuntimeResponse replaceAuthoritySource( + GetTenantMembershipForRuntimeResponse response, + String originalStreamKey, + RuntimeOutboxSourceEvidence replacement) { + var builder = response.toBuilder().clearOutboxSourceEvidence(); + boolean found = false; + for (var source : response.getOutboxSourceEvidenceList()) { + if (source.getOutboxStreamKey().equals(originalStreamKey)) { + found = true; + if (replacement != null) { + builder.addOutboxSourceEvidence(replacement); + } + } else { + builder.addOutboxSourceEvidence(source); + } + } + if (!found) { + throw new IllegalArgumentException("Authority source fixture is missing its stream"); + } + return builder.build(); + } + + private static RuntimeOutboxSourceEvidence authoritySource( + GetTenantMembershipForRuntimeResponse response, String streamKey) { + return response.getOutboxSourceEvidenceList().stream() + .filter(source -> source.getOutboxStreamKey().equals(streamKey)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Authority source fixture is missing")); + } + + private static UnknownFieldSet testUnknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + private static GetTenantMembershipForRuntimeResponse replaceCanonicalEvent( GetTenantMembershipForRuntimeResponse response, String canonicalJson, @@ -5479,7 +5940,7 @@ private static GetTenantMembershipForRuntimeResponse leftMembershipWithDefect(St response.getAuthorityTuple().toBuilder() .putMembershipAuthorityGeneration(tenantUuid, "3")); } - case "issuance-fence" -> builder.setIssuanceFence("3"); + case "issuance-fence" -> builder.setIssuanceFence("1"); case "zero-sequence" -> { String membershipStream = response.getOutboxSourceEvidence(0).getOutboxStreamKey(); boolean updated = false; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContractTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContractTest.java new file mode 100644 index 0000000000..2718de39e4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionRedisContractTest.java @@ -0,0 +1,107 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.LossClass; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.RedisRole; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ResetSensitivity; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionRedisContract; +import org.junit.jupiter.api.Test; + +class IssuerAuthorityProjectionRedisContractTest { + private static final String ISSUER_ID = "https://accounts.example.test/issuer"; + + @Test + void descriptorPinsOwnerPrincipalRoleResourceKeyAndArguments() { + var descriptor = IssuerAuthorityProjectionRedisContract.descriptor(); + + assertThat(descriptor.scriptId()).isEqualTo("game-session.issuer-authority-projection.v1"); + assertThat(descriptor.resourcePath()).isEqualTo("redis/issuer_authority_projection_cas.lua"); + assertThat(descriptor.owner()).isEqualTo("game-session-service"); + assertThat(descriptor.principal()).isEqualTo("gamesession_coord_app"); + assertThat(descriptor.role()).isEqualTo(RedisRole.COORDINATION); + assertThat(descriptor.resetSensitivity()).isEqualTo(ResetSensitivity.CLUSTER); + assertThat(descriptor.lossClass()).isEqualTo(LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP); + assertThat(descriptor.tailLossBehavior()) + .contains("quarantine this issuer scope") + .contains("never admit"); + assertThat(IssuerAuthorityProjectionRedisContract.PROJECTION_SCHEMA_VERSION) + .isEqualTo("game-session-auth-issuer-projection/v1"); + assertThat(descriptor.keys()) + .singleElement() + .satisfies( + key -> { + assertThat(key.ownedPrefix()).isEqualTo("session:game:auth:issuer-generation:v1:"); + assertThat(key.hashTagDeclaration()).isEqualTo(HashTagDeclaration.NOT_REQUIRED); + }); + assertThat(descriptor.arguments()) + .extracting(argument -> argument.name()) + .containsExactly("expectedMode", "expectedBytes", "candidateBytes"); + assertThat(descriptor.outcomes()) + .extracting(outcome -> outcome.code()) + .containsExactly("APPLIED", "REPLAY", "STALE", "INVALID", "TTL_PRESENT"); + assertThat(IssuerAuthorityProjectionRedisContract.keyForIssuer(ISSUER_ID)) + .isEqualTo("session:game:auth:issuer-generation:v1:" + ISSUER_ID); + } + + @Test + void registryAcceptsOnlyTheRegisteredOwnerInvocation() { + var descriptor = IssuerAuthorityProjectionRedisContract.descriptor(); + String key = IssuerAuthorityProjectionRedisContract.keyForIssuer(ISSUER_ID); + InvocationRequest valid = + new InvocationRequest( + descriptor.scriptId(), + descriptor.resourcePath(), + descriptor.sha256(), + descriptor.owner(), + descriptor.principal(), + descriptor.role(), + List.of(key), + List.of("ABSENT", "", "{}")); + + assertThat(IssuerAuthorityProjectionRedisContract.registry().prepareInvocation(valid).keys()) + .containsExactly(key); + assertThatThrownBy( + () -> + IssuerAuthorityProjectionRedisContract.registry() + .prepareInvocation( + new InvocationRequest( + valid.scriptId(), + valid.resourcePath(), + valid.sha256(), + valid.owner(), + valid.principal(), + RedisRole.CACHE_RATE_LIMIT, + valid.keys(), + valid.arguments()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Redis role"); + assertThatThrownBy( + () -> + IssuerAuthorityProjectionRedisContract.registry() + .prepareInvocation( + new InvocationRequest( + valid.scriptId(), + "redis/unregistered.lua", + valid.sha256(), + valid.owner(), + valid.principal(), + valid.role(), + valid.keys(), + valid.arguments()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("script resource path"); + } + + @Test + void ownerKeyBuilderRejectsMissingOrControlCharacterIssuer() { + assertThatThrownBy(() -> IssuerAuthorityProjectionRedisContract.keyForIssuer(" ")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> IssuerAuthorityProjectionRedisContract.keyForIssuer("issuer\nother")) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitionsTest.java new file mode 100644 index 0000000000..fef3948c4a --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerAuthorityProjectionTransitionsTest.java @@ -0,0 +1,399 @@ +package unit.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.when; + +import java.lang.reflect.Field; +import java.math.BigInteger; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions; +import org.junit.jupiter.api.Test; + +/** Decision/unit proof using AccountIssuerAuthorityClient's existing mocked response seam. */ +class IssuerAuthorityProjectionTransitionsTest { + private static final String ISSUER_ID = "https://accounts.example.test/issuer"; + private static final String NAMESPACE = "test"; + private static final String QUERY_ID = "11111111-1111-4111-8111-111111111111"; + private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; + + @Test + void bootstrapAtProvedSequenceZeroOmitsEventIdentityAndKeepsCallerAppliedAt() throws Exception { + SourceReadback readback = readback(ISSUER_ID, "1", "1", "0", null, null); + + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.bootstrap(readback, "2026-10-02T11:00:00Z"); + + assertThat(mutation.kind()) + .isEqualTo(IssuerAuthorityProjectionTransitions.MutationKind.BOOTSTRAP); + assertThat(mutation.expectedProjection()).isEmpty(); + assertThat(mutation.nextProjection()) + .containsEntry("schemaVersion", IssuerAuthorityProjectionTransitions.SCHEMA_VERSION) + .containsEntry("issuerId", ISSUER_ID) + .containsEntry("issuerAuthGeneration", "1") + .containsEntry("lastAppliedSourceOutboxSequence", "0") + .containsEntry("appliedAt", "2026-10-02T11:00:00Z") + .containsEntry("appliedSourceEvidence", Map.of()); + assertThat(mutation.nextProjection()).doesNotContainKeys("sourceEventId", "sourceEventDigest"); + } + + @Test + void bootstrapPositiveCurrentCheckpointRetainsCompleteLatestEventEvidence() throws Exception { + IssuerGenerationAuthorityEvent event = event("7", "92", "105", 1, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "92", "105", "7", event, null); + + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time"); + + assertThat(mutation.nextProjection()) + .containsEntry("issuerAuthGeneration", "92") + .containsEntry("lastAppliedSourceOutboxSequence", "7") + .containsEntry("sourceEventId", event.eventId()) + .containsEntry("sourceEventDigest", event.eventDigest()) + .containsEntry("appliedSourceEvidence", Map.of("7", event.canonicalJson())); + assertThat(mutation.nextProjection()).doesNotContainKey("admitted"); + } + + @Test + void mutationCandidateAccessorReturnsDefensiveImmutableCopies() throws Exception { + IssuerGenerationAuthorityEvent event = event("1", "2", "3", 24, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "2", "3", "1", event, null); + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time"); + + Map first = mutation.nextProjection(); + Map second = mutation.nextProjection(); + + assertThat(first).isEqualTo(second).isNotSameAs(second); + assertThatThrownBy(() -> first.put("unexpected", true)) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void bootstrapRejectsHistoricalSelectionWithoutProducingProjection() throws Exception { + IssuerGenerationAuthorityEvent latest = event("3", "4", "6", 2, ISSUER_ID); + IssuerGenerationAuthorityEvent selected = event("2", "3", "5", 1, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "4", "6", "3", latest, selected); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time"); + + assertThat(decision.reason()) + .isEqualTo( + IssuerAuthorityProjectionTransitions.QuarantineReason + .BOOTSTRAP_REQUIRES_CURRENT_READBACK); + assertThat(decision.expectedProjection()).isEmpty(); + } + + @Test + void selectedContiguousEventAdvancesWatermarkAndCheckpointEvenWhenGenerationIsEqual() + throws Exception { + IssuerGenerationAuthorityEvent prior = event("4", "80", "102", 4, ISSUER_ID); + Map existing = bootstrapProjection("80", "102", "4", prior); + IssuerGenerationAuthorityEvent next = event("5", "80", "103", 5, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "80", "103", "5", next, next); + + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(mutation.kind()) + .isEqualTo(IssuerAuthorityProjectionTransitions.MutationKind.ADVANCE); + assertThat(mutation.expectedProjection()).contains(existing); + assertThat(mutation.nextProjection()) + .containsEntry("issuerAuthGeneration", "80") + .containsEntry("lastAppliedSourceOutboxSequence", "5") + .containsEntry("sourceEventId", next.eventId()) + .containsEntry("sourceEventDigest", next.eventDigest()) + .containsEntry("appliedSourceEvidence", Map.of("5", next.canonicalJson())); + } + + @Test + void selectedContiguousEventUsesHigherGenerationWhenAccountAdvancedIt() throws Exception { + IssuerGenerationAuthorityEvent prior = event("4", "80", "102", 20, ISSUER_ID); + Map existing = bootstrapProjection("80", "102", "4", prior); + IssuerGenerationAuthorityEvent next = event("5", "81", "103", 21, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "81", "103", "5", next, next); + + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(mutation.nextProjection()) + .containsEntry("issuerAuthGeneration", "81") + .containsEntry("lastAppliedSourceOutboxSequence", "5"); + } + + @Test + void sequenceGapQuarantinesWithoutReturningAMutationCandidate() throws Exception { + IssuerGenerationAuthorityEvent prior = event("1", "2", "3", 6, ISSUER_ID); + Map existing = bootstrapProjection("2", "3", "1", prior); + IssuerGenerationAuthorityEvent gap = event("3", "4", "5", 7, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "4", "5", "3", gap, gap); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.EVENT_SEQUENCE_GAP); + assertThat(decision.expectedProjection()).contains(existing); + } + + @Test + void malformedExistingProjectionQuarantinesBeforeConsideringAccountEvent() throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "2", 22, ISSUER_ID); + Map validProjection = bootstrapProjection("2", "2", "1", first); + Map malformedProjection = new LinkedHashMap<>(validProjection); + malformedProjection.put("issuerAuthGeneration", "02"); + IssuerGenerationAuthorityEvent next = event("2", "2", "3", 23, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "2", "3", "2", next, next); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.decide( + malformedProjection, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo( + IssuerAuthorityProjectionTransitions.QuarantineReason.MALFORMED_EXISTING_PROJECTION); + assertThat(decision.expectedProjection()).contains(malformedProjection); + } + + @Test + void exactDuplicateIsNoOpAndDoesNotReplaceAppliedAt() throws Exception { + IssuerGenerationAuthorityEvent applied = event("2", "3", "4", 8, ISSUER_ID); + Map existing = bootstrapProjection("3", "4", "2", applied); + SourceReadback readback = readback(ISSUER_ID, "3", "4", "2", applied, applied); + + IssuerAuthorityProjectionTransitions.NoOp decision = + (IssuerAuthorityProjectionTransitions.NoOp) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "ignored-for-no-op"); + + assertThat(decision.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.NoOpReason.EXACT_DUPLICATE); + assertThat(existing).containsEntry("appliedAt", "stable-time"); + } + + @Test + void duplicateWithDifferentCompleteCanonicalEventQuarantines() throws Exception { + IssuerGenerationAuthorityEvent applied = event("1", "2", "2", 9, ISSUER_ID); + Map existing = bootstrapProjection("2", "2", "1", applied); + IssuerGenerationAuthorityEvent conflicting = event("1", "2", "2", 10, ISSUER_ID); + IssuerGenerationAuthorityEvent current = event("2", "3", "3", 11, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "3", "3", "2", current, conflicting); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.DUPLICATE_EVENT_CONFLICT); + assertThat(existing).containsEntry("lastAppliedSourceOutboxSequence", "1"); + } + + @Test + void authenticatedHistoricalDuplicateMayHaveLowerGenerationAndSourceVersion() throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "3", 12, ISSUER_ID); + IssuerGenerationAuthorityEvent later = event("2", "4", "6", 13, ISSUER_ID); + Map existing = bootstrapProjection("4", "6", "2", later); + SourceReadback readback = readback(ISSUER_ID, "4", "6", "2", later, first); + + IssuerAuthorityProjectionTransitions.NoOp decision = + (IssuerAuthorityProjectionTransitions.NoOp) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.NoOpReason.VERIFIED_HISTORICAL_DUPLICATE); + } + + @Test + void currentAccountCheckpointRegressionQuarantinesEvenForAContiguousSelectedEvent() + throws Exception { + IssuerGenerationAuthorityEvent installed = event("2", "8", "9", 14, ISSUER_ID); + Map existing = bootstrapProjection("8", "9", "2", installed); + IssuerGenerationAuthorityEvent regressedCurrent = event("3", "7", "8", 15, ISSUER_ID); + SourceReadback readback = + readback(ISSUER_ID, "7", "8", "3", regressedCurrent, regressedCurrent); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo( + IssuerAuthorityProjectionTransitions.QuarantineReason.CURRENT_CHECKPOINT_REGRESSED); + } + + @Test + void differentIssuerStreamProjectionQuarantines() throws Exception { + String otherIssuer = "https://other.example.test/issuer"; + IssuerGenerationAuthorityEvent otherEvent = event("1", "2", "3", 16, otherIssuer); + Map existing = bootstrapProjection(otherIssuer, "2", "3", "1", otherEvent); + IssuerGenerationAuthorityEvent current = event("1", "2", "3", 17, ISSUER_ID); + SourceReadback readback = readback(ISSUER_ID, "2", "3", "1", current, current); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.ISSUER_OR_STREAM_CHANGED); + } + + @Test + void countersBeyondLongRemainExactAndNoSequenceGenerationEquationIsAssumed() throws Exception { + BigInteger sequence = new BigInteger("922337203685477580812345678901234567891"); + BigInteger priorSequence = sequence.subtract(BigInteger.ONE); + String generation = "800000000000000000000000000000000000001"; + BigInteger priorVersion = new BigInteger("800000000000000000000000000000000000010"); + String version = priorVersion.add(BigInteger.ONE).toString(); + IssuerGenerationAuthorityEvent prior = + event(priorSequence.toString(), generation, priorVersion.toString(), 18, ISSUER_ID); + Map existing = + bootstrapProjection(generation, priorVersion.toString(), priorSequence.toString(), prior); + IssuerGenerationAuthorityEvent next = + event(sequence.toString(), generation, version, 19, ISSUER_ID); + SourceReadback readback = + readback(ISSUER_ID, generation, version, sequence.toString(), next, next); + + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); + + assertThat(mutation.nextProjection()) + .containsEntry("lastAppliedSourceOutboxSequence", sequence.toString()) + .containsEntry("issuerAuthGeneration", generation) + .containsEntry("sourceEventId", next.eventId()); + } + + private static Map bootstrapProjection( + String generation, + String sourceVersion, + String sequence, + IssuerGenerationAuthorityEvent latest) + throws Exception { + return bootstrapProjection(ISSUER_ID, generation, sourceVersion, sequence, latest); + } + + private static Map bootstrapProjection( + String issuerId, + String generation, + String sourceVersion, + String sequence, + IssuerGenerationAuthorityEvent latest) + throws Exception { + SourceReadback readback = readback(issuerId, generation, sourceVersion, sequence, latest, null); + return ((IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time")) + .nextProjection(); + } + + private static SourceReadback readback( + String issuerId, + String generation, + String sourceVersion, + String sequence, + IssuerGenerationAuthorityEvent latest, + IssuerGenerationAuthorityEvent selected) + throws Exception { + String sourceScope = "issuer/" + issuerId; + String streamKey = IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + sourceScope; + IssuerAuthoritySourceSnapshot.Builder snapshot = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(issuerId) + .setSourceScope(sourceScope) + .setOutboxStreamKey(streamKey) + .setIssuerAuthGeneration(generation) + .setSourceVersion(sourceVersion) + .setOutboxSequence(sequence); + if (latest != null) { + snapshot.setLatestEventCanonicalJson(latest.canonicalJson()); + } + ReadIssuerAuthorityForRuntimeResponse.Builder response = + ReadIssuerAuthorityForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-source-readback/v1") + .setTargetNamespace(NAMESPACE) + .setRequestId(QUERY_ID) + .setSourceSnapshot(snapshot.build()); + if (selected != null) { + response.setRequestedEventCanonicalJson(selected.canonicalJson()); + } + + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = + mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) + .thenReturn(response.build()); + AccountIssuerAuthorityClient client = newClient(stub, issuerId); + if (selected == null) { + return client.readCurrent(QUERY_ID); + } + return client.readCommittedEvent(QUERY_ID, selected.outboxSequence()); + } + + private static IssuerGenerationAuthorityEvent event( + String sequence, String generation, String sourceVersion, int identity, String issuerId) { + String requestId = String.format(Locale.ROOT, "00000000-0000-4000-8000-%012d", identity); + String scope = "issuer/" + issuerId; + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", EVENT_ID_PREFIX + requestId, + "requestId", requestId, + "issuerId", issuerId, + "sourceScope", scope, + "outboxStreamKey", IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope, + "outboxSequence", sequence, + "issuerAuthGeneration", generation, + "sourceVersion", sourceVersion)); + } + + private static AccountIssuerAuthorityClient newClient( + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub, String issuerId) + throws Exception { + AccountIssuerAuthorityClient client = + new AccountIssuerAuthorityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + issuerId); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static CommonGrpcClientProperties mtlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/account-ca.crt"); + return tls; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStoreTest.java new file mode 100644 index 0000000000..507d1769d1 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/RedisIssuerAuthorityProjectionStoreTest.java @@ -0,0 +1,309 @@ +package unit.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.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; +import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionRedisContract; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ProjectionSnapshot; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.core.io.ClassPathResource; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisKeyCommands; +import org.springframework.data.redis.connection.RedisScriptingCommands; +import org.springframework.data.redis.connection.RedisStringCommands; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; + +class RedisIssuerAuthorityProjectionStoreTest { + private static final String COORD_PASSWORD = "coordination-secret"; + private static final String ISSUER_ID = "https://accounts.example.test/issuer"; + private static final String REQUEST_ID = "11111111-1111-4111-8111-111111111111"; + + @Test + void requiresExactCoordinationPrincipalAndCredentials() { + assertThatThrownBy( + () -> + new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( + "coordination.internal", 6379, "gamesession_cache_app", COORD_PASSWORD)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("gamesession_coord_app"); + assertThatThrownBy( + () -> + new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( + "coordination.internal", 6379, "gamesession_coord_app", " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("credential"); + } + + @Test + void rejectsNormalizedCoordinationAndCacheEndpointCollision() { + var coordination = + new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( + "redis-coord.internal.", 6379, "gamesession_coord_app", COORD_PASSWORD); + var cache = + new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint( + "REDIS-COORD.INTERNAL", 6379); + + assertThatThrownBy(() -> new RedisIssuerAuthorityProjectionStore("test", coordination, cache)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("endpoints must be distinct"); + } + + @Test + void constructorRequiresBothTypedRoleEndpointsWithoutOpeningRedis() { + var store = + new RedisIssuerAuthorityProjectionStore( + "test", + coordination("coordination.internal", 6379), + new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint("cache.internal", 6379)); + + assertThatThrownBy(() -> store.apply(null, "stable-time")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("explicit init()"); + store.close(); + } + + @Test + void appliesWithTheExactRegisteredScriptLoadedThenExecutedByEvalSha() throws Exception { + byte[] resourceBytes = scriptBytes(); + String expectedSha1 = sha1(resourceBytes); + assertThat(sha256(resourceBytes)) + .isEqualTo(IssuerAuthorityProjectionRedisContract.descriptor().sha256()); + + RedisConnection connection = mock(RedisConnection.class); + RedisStringCommands stringCommands = mock(RedisStringCommands.class); + RedisKeyCommands keyCommands = mock(RedisKeyCommands.class); + RedisScriptingCommands scriptingCommands = mock(RedisScriptingCommands.class); + when(connection.stringCommands()).thenReturn(stringCommands); + when(connection.keyCommands()).thenReturn(keyCommands); + when(connection.scriptingCommands()).thenReturn(scriptingCommands); + when(stringCommands.get(any(byte[].class))).thenReturn(null); + AtomicReference loadedScript = new AtomicReference<>(); + AtomicReference evalShaArguments = new AtomicReference<>(); + when(scriptingCommands.scriptLoad(any(byte[].class))) + .thenAnswer( + invocation -> { + byte[] script = invocation.getArgument(0); + loadedScript.set(script.clone()); + return sha1(script); + }); + when(scriptingCommands.evalSha( + eq(expectedSha1), eq(ReturnType.VALUE), eq(1), any(byte[][].class))) + .thenAnswer( + invocation -> { + evalShaArguments.set((byte[][]) invocation.getRawArguments()[3]); + return "APPLIED".getBytes(StandardCharsets.US_ASCII); + }); + + RedisIssuerAuthorityProjectionStore store = storeWithConnection(connection); + try { + var result = store.apply(sourceReadback("test"), "stable-time"); + + assertThat(result.outcome()).isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.APPLIED); + ProjectionSnapshot projection = result.snapshot().orElseThrow(); + InOrder order = inOrder(scriptingCommands); + order.verify(scriptingCommands).scriptLoad(any(byte[].class)); + order + .verify(scriptingCommands) + .evalSha(eq(expectedSha1), eq(ReturnType.VALUE), eq(1), any(byte[][].class)); + assertThat(loadedScript.get()).containsExactly(resourceBytes); + byte[][] invocationArguments = evalShaArguments.get(); + assertThat(new String(invocationArguments[0], StandardCharsets.UTF_8)) + .isEqualTo(projection.key()); + assertThat(new String(invocationArguments[1], StandardCharsets.US_ASCII)).isEqualTo("ABSENT"); + assertThat(new String(invocationArguments[2], StandardCharsets.UTF_8)).isEmpty(); + assertThat(new String(invocationArguments[3], StandardCharsets.UTF_8)) + .isEqualTo(projection.json()); + verifyNoMoreInteractions(scriptingCommands); + } finally { + store.close(); + } + } + + @Test + void noscriptFromEvalShaPropagatesWithoutEvalFallback() throws Exception { + byte[] resourceBytes = scriptBytes(); + String expectedSha1 = sha1(resourceBytes); + RedisConnection connection = mock(RedisConnection.class); + RedisStringCommands stringCommands = mock(RedisStringCommands.class); + RedisKeyCommands keyCommands = mock(RedisKeyCommands.class); + RedisScriptingCommands scriptingCommands = mock(RedisScriptingCommands.class); + when(connection.stringCommands()).thenReturn(stringCommands); + when(connection.keyCommands()).thenReturn(keyCommands); + when(connection.scriptingCommands()).thenReturn(scriptingCommands); + when(stringCommands.get(any(byte[].class))).thenReturn(null); + when(scriptingCommands.scriptLoad(any(byte[].class))).thenReturn(expectedSha1); + DataAccessResourceFailureException noScript = + new DataAccessResourceFailureException("NOSCRIPT No matching script. Please use EVAL."); + when(scriptingCommands.evalSha( + eq(expectedSha1), eq(ReturnType.VALUE), eq(1), any(byte[][].class))) + .thenThrow(noScript); + + RedisIssuerAuthorityProjectionStore store = storeWithConnection(connection); + try { + assertThatThrownBy(() -> store.apply(sourceReadback("test"), "stable-time")) + .isSameAs(noScript); + + InOrder order = inOrder(scriptingCommands); + order.verify(scriptingCommands).scriptLoad(any(byte[].class)); + order + .verify(scriptingCommands) + .evalSha(eq(expectedSha1), eq(ReturnType.VALUE), eq(1), any(byte[][].class)); + verifyNoMoreInteractions(scriptingCommands); + } finally { + store.close(); + } + } + + @Test + void wrongSourceNamespaceIsRejectedBeforeAnyRedisCommand() throws Exception { + RedisIssuerAuthorityProjectionStore store = + new RedisIssuerAuthorityProjectionStore( + "other", + coordination("127.0.0.1", 1), + new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint("127.0.0.1", 2)); + store.init(); + + try { + var result = store.apply(sourceReadback("test"), "stable-time"); + + assertThat(result.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains("ACCOUNT_NAMESPACE_MISMATCH"); + } finally { + store.close(); + } + } + + @Test + void coordinationCredentialIsRedactedAndNoAmbientRedisTemplateConstructorExists() + throws Exception { + var endpoint = coordination("coordination.internal", 6379); + + assertThat(endpoint.toString()).contains("password=").doesNotContain(COORD_PASSWORD); + boolean acceptsAmbientTemplate = + Arrays.stream(RedisIssuerAuthorityProjectionStore.class.getConstructors()) + .anyMatch( + constructor -> + Arrays.stream(constructor.getParameterTypes()) + .anyMatch(RedisTemplate.class::isAssignableFrom)); + assertThat(acceptsAmbientTemplate).isFalse(); + } + + private static RedisIssuerAuthorityProjectionStore.CoordinationEndpoint coordination( + String host, int port) { + return new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( + host, port, "gamesession_coord_app", COORD_PASSWORD); + } + + private static RedisIssuerAuthorityProjectionStore storeWithConnection(RedisConnection connection) + throws Exception { + RedisIssuerAuthorityProjectionStore store = + new RedisIssuerAuthorityProjectionStore( + "test", + coordination("127.0.0.1", 1), + new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint("127.0.0.1", 2)); + store.init(); + StringRedisTemplate template = mock(StringRedisTemplate.class); + doAnswer( + invocation -> { + RedisCallback callback = invocation.getArgument(0); + return callback.doInRedis(connection); + }) + .when(template) + .execute(any(RedisCallback.class)); + Field templateField = + RedisIssuerAuthorityProjectionStore.class.getDeclaredField("redisTemplate"); + templateField.setAccessible(true); + templateField.set(store, template); + return store; + } + + private static String sha1(byte[] script) throws NoSuchAlgorithmException { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(script)); + } + + private static String sha256(byte[] script) throws NoSuchAlgorithmException { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(script)); + } + + private static byte[] scriptBytes() throws Exception { + try (var input = + new ClassPathResource(IssuerAuthorityProjectionRedisContract.RESOURCE_PATH) + .getInputStream()) { + return input.readAllBytes(); + } + } + + private static SourceReadback sourceReadback(String targetNamespace) throws Exception { + String scope = "issuer/" + ISSUER_ID; + IssuerAuthoritySourceSnapshot snapshot = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(ISSUER_ID) + .setSourceScope(scope) + .setOutboxStreamKey(IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope) + .setIssuerAuthGeneration("1") + .setSourceVersion("1") + .setOutboxSequence("0") + .build(); + ReadIssuerAuthorityForRuntimeResponse response = + ReadIssuerAuthorityForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-source-readback/v1") + .setTargetNamespace(targetNamespace) + .setRequestId(REQUEST_ID) + .setSourceSnapshot(snapshot) + .build(); + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = + mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) + .thenReturn(response); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/account-ca.crt"); + AccountIssuerAuthorityClient client = + new AccountIssuerAuthorityClient( + new ServiceEndpointsProperties(), + tls, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + "test", + ISSUER_ID); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client.readCurrent(REQUEST_ID); + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts index 4894fe1e4e..65b4497aa6 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -7,6 +7,9 @@ rootProject.name = "firemud" include("common-data-runtime") project(":common-data-runtime").projectDir = File("services/common-data-runtime") +include("common-redis-contracts") +project(":common-redis-contracts").projectDir = File("services/common-redis-contracts") + include("common-platform-core") project(":common-platform-core").projectDir = File("services/common-platform-core")