diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 35203c606a..bbd0dde132 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: @@ -1025,7 +1024,7 @@ jobs: if-no-files-found: warn retention-days: 7 - - name: Run Account issuer readback socket mTLS component proof + - name: Run Account issuer readback and acknowledgment socket mTLS component proof if: ${{ matrix.module == 'game-session-service' }} run: | ./gradlew :game-session-service:crossServiceTest \ @@ -1035,6 +1034,14 @@ jobs: --strict \ --require-suite crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest \ --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#exactWorkloadIdentitiesCarryCurrentAndHistoricalReadbacksOverSocketMtls()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#exactWorkloadIdentitiesCarryZeroAndPositiveCaptureReceiptsOverSocketMtls()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#exactGameSessionPeerCarriesTheClosedInstallationAcknowledgmentOverSocketMtls()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#acknowledgment caller "wrong-service"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#acknowledgment caller "wrong-namespace"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#capture caller "wrong-service"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#capture caller "wrong-namespace"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#capture server "game-session"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#capture server "wrong-account-namespace"' \ --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#missingClientCertificateFailsTheRequiredTlsHandshakeBeforeProducerAccess()' \ --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#[1] clientIdentity = "wrong-service"' \ --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcMtlsCrossServiceTest#[2] clientIdentity = "wrong-namespace"' \ @@ -1051,7 +1058,7 @@ jobs: if-no-files-found: warn retention-days: 7 - - name: Run Account PostgreSQL issuer readback socket mTLS composition proof + - name: Run Account PostgreSQL issuer readback and acknowledgment socket mTLS composition proof if: ${{ !cancelled() && matrix.module == 'game-session-service' }} run: | ./gradlew :game-session-service:crossServiceTest \ @@ -1061,6 +1068,25 @@ jobs: --strict \ --require-suite crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest \ --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#postgresIssuerSourceReturnsBootstrapCurrentAndHistoricalEvidenceOverSocketMtls()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#postgresCapturePreservesZeroAndOriginalPositiveReceiptAfterLaterSourceAdvance()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#concurrentExactPostgresCapturesFromSeparateSocketClientsReturnOneDurableReceipt()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#postgresCaptureRejectsMalformedAndMissingSourceRequestsWithoutSqlMutation()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#postgresZeroAndPositiveInstallationsReceiveFullDurableAcknowledgmentsOverSocketMtls()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#exactAcknowledgmentRetryReturnsOriginalAfterDiscardedResponseAndLaterSourceProgress()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#concurrentExactAcknowledgmentsReturnOneV44ResultOverSeparateSocketClients()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#firstAcknowledgmentOfCaptureThatIsStaleAfterSourceAdvanceIsDeniedWithoutAckRow()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#rawSamePeerAcknowledgmentRejectsChangedProjectionBytesAndCaptureBinding()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#acknowledgment server "game-session"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#acknowledgment server "wrong-account-namespace"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#capturedLatestCheckpointInstallsAcrossMissedEventsThenOrdinaryDeliveryIsContiguous()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#zeroCheckpointInstallsWithoutEventEvidenceThenAcceptsSequenceOne()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#exactInstallRetryPreservesOriginalReceiptProjectionBytesAndAppliedAt()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#concurrentExactInstallersDoNotDuplicateAccountSourceOrCaptureRows()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#capturedSourceThatAdvancesBeforeStoreWriteReturnsNoVerifiedReceipt()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#sourceAdvanceBetweenRedisWriteAndFinalAccountReadbackWithholdsReceipt()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#redisAuthenticationRefusalLeavesCapturedAccountReceiptAndSourceUntouched()' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#capture postgres caller "wrong-service"' \ + --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#capture postgres caller "wrong-namespace"' \ --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#[1] clientIdentity = "wrong-service"' \ --require-case 'crossservice.net.firedevops.firemud.gamesession.AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest#[2] clientIdentity = "wrong-namespace"' \ game-session-service @@ -1141,6 +1167,7 @@ jobs: --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#obsoletePersistedAliasesQuarantineWithoutChangingBytesOrTtl()' \ --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#expiringProjectionIsQuarantinedWithoutChangingItsBytesOrExpiration()' \ --require-case 'integration.net.firedevops.firemud.gamesession.IssuerAuthorityProjectionRedisIntegrationTest#ownerPrincipalCannotInvokeEvalDirectly()' \ game-session-service @@ -1159,13 +1186,48 @@ jobs: run: | ./gradlew :game-session-service:integrationTest \ --tests net.firedevops.firemud.gamesession.repository.GameInstanceOwnerUuidMigrationIntegrationTest \ + --tests net.firedevops.firemud.gamesession.repository.GameInstanceUuidIdentityIntegrationTest \ -PfullCheck --no-build-cache --no-configuration-cache bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite net.firedevops.firemud.gamesession.repository.GameInstanceOwnerUuidMigrationIntegrationTest \ --require-case 'net.firedevops.firemud.gamesession.repository.GameInstanceOwnerUuidMigrationIntegrationTest#migrationPreservesNumericHistoryAndStoresCanonicalOwnerUuid()' \ + --require-suite net.firedevops.firemud.gamesession.repository.GameInstanceUuidIdentityIntegrationTest \ + --require-case 'net.firedevops.firemud.gamesession.repository.GameInstanceUuidIdentityIntegrationTest#freshRepositoryIdentityIsPersistedAndRetainedRowsRemainUnmapped()' \ game-session-service + - name: Upload Game Session instance UUID PostgreSQL proof results + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-session-instance-uuid-postgresql-proof-${{ github.sha }} + path: | + services/game-session-service/build/test-results/integrationTest/TEST-*GameInstanceOwnerUuidMigrationIntegrationTest.xml + services/game-session-service/build/test-results/integrationTest/TEST-*GameInstanceUuidIdentityIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Run Account canonical membership identity PostgreSQL component proof + if: ${{ matrix.module == 'account-service' }} + run: | + ./gradlew :account-service:integrationTest \ + --tests integration.net.firedevops.firemud.accountservice.repository.AccountTenantMembershipCanonicalIdentityIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountTenantMembershipCanonicalIdentityIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountTenantMembershipCanonicalIdentityIntegrationTest#migrationPreservesRetainedMembershipAndCanonicalRowsUseExactUuidAndSourceEvidence()' \ + account-service + + - name: Upload Account canonical membership identity PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-canonical-membership-identity-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountTenantMembershipCanonicalIdentityIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Run Account persisted UUID authentication PostgreSQL component proof if: ${{ matrix.module == 'account-service' }} run: | @@ -1198,6 +1260,32 @@ jobs: --require-case 'net.firedevops.firemud.accountservice.AccountApplicationIntegrationTest#publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly()' \ account-service + - name: Run Account issuer installation acknowledgment PostgreSQL component proof + if: ${{ matrix.module == 'account-service' }} + run: | + ./gradlew :account-service:integrationTest \ + --tests 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest.acknowledgesProvedZeroBaselineWithExactBytesAndNoSourceMutation' \ + --tests 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest.acknowledgesCompletePositiveCheckpointAndRetainsSourceHistory' \ + --tests 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest.concurrentExactAcknowledgmentsReturnOneDurableOriginalResult' \ + --tests 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest.exactRetryAfterLaterSourceAdvanceReturnsOriginalAcknowledgment' \ + --tests 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest.committedAcknowledgmentWithMissingPostCommitReadbackRecoversOnExactRetry' \ + --tests 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest.staleFirstAcknowledgmentAndChangedBindingsOrProjectionEvidenceDenyWithoutInsertion' \ + --tests 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest.ambientTransactionsAndDirectSqlGuardsRejectAcknowledgmentMutation' \ + --tests 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest.storedAcknowledgmentRejectsDirectUpdateAndDelete' \ + -PfullCheck --no-build-cache --no-configuration-cache + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest#acknowledgesProvedZeroBaselineWithExactBytesAndNoSourceMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest#acknowledgesCompletePositiveCheckpointAndRetainsSourceHistory()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest#concurrentExactAcknowledgmentsReturnOneDurableOriginalResult()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest#exactRetryAfterLaterSourceAdvanceReturnsOriginalAcknowledgment()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest#committedAcknowledgmentWithMissingPostCommitReadbackRecoversOnExactRetry()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest#staleFirstAcknowledgmentAndChangedBindingsOrProjectionEvidenceDenyWithoutInsertion()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest#ambientTransactionsAndDirectSqlGuardsRejectAcknowledgmentMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionAcknowledgmentPostgresIntegrationTest#storedAcknowledgmentRejectsDirectUpdateAndDelete()' \ + account-service + - name: Run Game Session command Account UUID storage PostgreSQL component proof if: ${{ matrix.module == 'game-session-service' }} run: | @@ -1297,6 +1385,7 @@ jobs: --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#committedPasswordResetReceiptSurvivesCoordinationAuthFailureExactRetryAndProjection()' \ --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()' \ @@ -1312,6 +1401,54 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Verify Account tenant 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.TenantGenerationProjectionPostgresRedisIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantGenerationProjectionPostgresRedisIntegrationTest#installsOnlyTheProvenPristineTenantBaselineAndReadsBackExactBytes()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantGenerationProjectionPostgresRedisIntegrationTest#projectsCompleteSourceEventReplaysExactlyAndRepairsOnlyTheMissingRedisKey()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantGenerationProjectionPostgresRedisIntegrationTest#unknownAndAssociatedButUnenrolledTenantsCannotSynthesizeABaseline()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantGenerationProjectionPostgresRedisIntegrationTest#sourceAdvanceAfterCandidateReadReturnsNonconvergedWithoutChangingSqlHistory()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantGenerationProjectionPostgresRedisIntegrationTest#staleCandidateCannotReplaceAProjectionFromANewerTenantCommit()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantGenerationProjectionPostgresRedisIntegrationTest#malformedExpiringAheadAndSameCheckpointRedisValuesAreQuarantinedWithoutWrites()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.TenantGenerationProjectionPostgresRedisIntegrationTest#accountCoordinationPrincipalCanUseOnlyTenantProjectionKeysAndCannotInvokeEval()' \ + account-service + + - name: Upload Account tenant generation projection PostgreSQL and Redis proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-tenant-generation-projection-postgresql-redis-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*TenantGenerationProjectionPostgresRedisIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Verify Account membership generation projection PostgreSQL and Redis proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.accountservice.MembershipGenerationProjectionPostgresRedisIntegrationTest \ + --require-case 'net.firedevops.firemud.accountservice.MembershipGenerationProjectionPostgresRedisIntegrationTest#existingOnlyZeroBaselineProjectsWithoutAdmissionOrSqlMutation()' \ + --require-case 'net.firedevops.firemud.accountservice.MembershipGenerationProjectionPostgresRedisIntegrationTest#unknownAndAssociatedUnenrolledPairsCannotSynthesizeProjectionState()' \ + --require-case 'net.firedevops.firemud.accountservice.MembershipGenerationProjectionPostgresRedisIntegrationTest#retainedJoinLeftAndReactivationProjectExactIndependentSourceAxes()' \ + --require-case 'net.firedevops.firemud.accountservice.MembershipGenerationProjectionPostgresRedisIntegrationTest#sourceAdvanceBetweenCandidateAndFreshReadbackReturnsNonconverged()' \ + --require-case 'net.firedevops.firemud.accountservice.MembershipGenerationProjectionPostgresRedisIntegrationTest#staleCandidateCannotReplaceNewerSourceProjection()' \ + --require-case 'net.firedevops.firemud.accountservice.MembershipGenerationProjectionPostgresRedisIntegrationTest#aheadMalformedSameCheckpointAndExpiringRedisStatesAreDeniedWithoutSourceWrites()' \ + --require-case 'net.firedevops.firemud.accountservice.MembershipGenerationProjectionPostgresRedisIntegrationTest#coordinationPrincipalCannotReadOtherOwnersOrInvokeEval()' \ + account-service + + - name: Upload Account membership generation projection PostgreSQL and Redis proof + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-membership-generation-projection-postgresql-redis-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*MembershipGenerationProjectionPostgresRedisIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Verify Account issuer authority PostgreSQL proof cases if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | @@ -1335,6 +1472,41 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#generationAndSourceVersionOverflowFailBeforeAnyMutation()' \ account-service + - name: Verify Account issuer reconciliation capture 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.IssuerProjectionReconciliationPostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionReconciliationPostgresIntegrationTest#capturesProvedZeroBaselineWithoutSourceOrOutboxWrites()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionReconciliationPostgresIntegrationTest#capturesCompletePositiveCheckpointWithIndependentSourceCounters()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionReconciliationPostgresIntegrationTest#committedCaptureWithLostPostCommitReadbackRecoversTheSameReceipt()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionReconciliationPostgresIntegrationTest#exactRetryReturnsOriginalPositiveReceiptAfterLaterSourceAdvance()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionReconciliationPostgresIntegrationTest#concurrentExactCapturesReturnOneDurableOperation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionReconciliationPostgresIntegrationTest#captureAndSourceAdvanceSerializeOnOneIssuerFenceWithoutHybridSnapshot()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionReconciliationPostgresIntegrationTest#invalidBindingsAndMissingAuthorityDenyWithoutEnrollment()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionReconciliationPostgresIntegrationTest#durableReceiptsRejectUpdateAndDelete()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerProjectionReconciliationPostgresIntegrationTest#databaseRejectsIncompleteAndContradictoryPositiveReceiptEvidenceWithoutMutation()' \ + account-service + + - name: Upload Account issuer reconciliation capture PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-issuer-reconciliation-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*IssuerProjectionReconciliationPostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Upload Account issuer installation acknowledgment PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-issuer-installation-acknowledgment-postgresql-proof-${{ github.sha }} + path: services/account-service/build/test-results/integrationTest/TEST-*IssuerProjectionAcknowledgmentPostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: Upload Account issuer authority PostgreSQL proof results if: ${{ always() && matrix.module == 'account-service' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 @@ -1436,6 +1608,7 @@ jobs: --strict \ --require-suite net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest \ --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#postJoinSnapshotCarriesCurrentCompositeSourcesWithoutRewritingMembershipEvent()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest#membershipSourceReaderReadsRetainedInactiveRetryAndReactivationWithoutMutation()' \ account-service - name: Upload Account current recipient source composition PostgreSQL proof @@ -1539,8 +1712,38 @@ jobs: --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#canonicalRuntimeReadUsesFreshUuidAssociationWithoutInventingRetainedAlias()' \ --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#canonicalRuntimeReadRejectsUnmappedTenantUuidWithoutEnrollment()' \ --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#strictExistingMembershipReadDeniesFreshAssociationWithoutEnrollmentOrMutation()' \ + --require-case 'net.firedevops.firemud.accountservice.AccountFreshUuidMembershipSnapshotIntegrationTest#membershipSourceReaderRejectsAmbientAccountTransaction()' \ account-service + - name: Upload Account existing-only membership source PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-existing-membership-source-postgresql-proof-${{ github.sha }} + path: | + services/account-service/build/test-results/integrationTest/TEST-*AccountFreshUuidMembershipSnapshotIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Verify Game Session LOGIN fixture isolation proof + if: ${{ !cancelled() && matrix.module == 'game-session-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite net.firedevops.firemud.gamesession.GameSessionLoginIntegrationTest \ + --require-case 'net.firedevops.firemud.gamesession.GameSessionLoginIntegrationTest#loginCallsAccountServiceAndReturnsOk()' \ + game-session-service + + - name: Upload Game Session LOGIN fixture isolation proof + if: ${{ always() && matrix.module == 'game-session-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: game-session-login-fixture-proof-${{ github.sha }} + path: services/game-session-service/build/test-results/integrationTest/TEST-*GameSessionLoginIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + - name: 🔎 Verify Game Session PostgreSQL proof case if: ${{ matrix.module == 'game-session-service' }} run: | @@ -1621,7 +1824,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md b/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md index 4100164bca..a09df1500d 100644 --- a/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md +++ b/design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md @@ -52,7 +52,7 @@ Later clarification: [ADR 0132](./adr-0132-namespace-scoped-single-character-con Game Session consumes authoritative Account membership, entitlement, and revocation state. It stores only the token identity and freshness metadata needed to validate a binding, such as token hash, issued-at time, and `membershipVersion`; it must not make a persisted raw backend JWT the durable session authority. -For issuer-generation consumption only, Game Session may maintain one derived consumer-local projection under its own namespace: `session:game:auth:issuer-generation:v1:`. Its schema is `game-session-auth-issuer-projection/v1` with `{schemaVersion, issuerId, issuerAuthGeneration, lastAppliedSourceOutboxSequence, sourceOutboxStreamKey, sourceEventId, sourceEventDigest, appliedAt}` plus bounded per-sequence applied-source evidence, or an explicit immutable Account source-checkpoint lookup. The issuer source event and any recipient evidence it affects remain separate under [Authentication's source-event contract](../system-architecture-authentication.md#authority-source-events-and-recipient-evidence). For this derived issuer projection, bootstrap, advancement, and duplicate verification use Account-authenticated evidence for the exact issuer scope and source checkpoint: exact issuer and stream identity, committed issuer generation and source version, sequence, and complete applicable source-event identity, payload, and digest. No individual recipient's `authorityTuple`, actual `issuanceFence`, or complete `outboxCheckpoints` set is a prerequisite for maintaining this projection. Account's issuer `outboxStreamKey` is immutable for the life of that issuer authority and must not be regenerated by deployment, failover, Redis reset, or projection repair. If authoritative recovery ever changes the stream key or resets its sequence/epoch, Account must first install and expose an authoritative checkpoint for the new exact stream identity/epoch; consumers quarantine the scope and accept no changed- or reset-stream event until that checkpoint is validated. The checkpoint, not an inferred event baseline, is the only value that may establish the new local watermark or permit sequence advancement. The canonical issuer projection watermark is `lastAppliedSourceOutboxSequence`. For each exact `sourceOutboxStreamKey`, an incoming event is applicable only when its source sequence is exactly `lastAppliedSourceOutboxSequence + 1`; a higher sequence is a gap that must be quarantined and reconciled from Account before either the watermark or generation advances. An event at or below the watermark is an idempotent no-op only when retained source evidence or an exact Account checkpoint lookup proves the same complete event identity, payload, and digest, source sequence, exact stream key, and issuer source progress; generation-only equality is insufficient. Missing, partial, stale, regressed, conflicting, or ambiguous evidence, including an older event outside the bounded local evidence window that cannot be resolved by the exact Account lookup, quarantines the scope and is reconciled rather than treated as a no-op. A next-sequence event must pass the same exact source/checkpoint comparison before the watermark or generation advances, and the projection watermark and corresponding source/checkpoint evidence are updated atomically. A lower `issuerAuthGeneration` is contradictory Account evidence, while an equal generation is idempotent and a higher generation uses set-if-greater semantics. The projection is a revocation-consumer cache, not an authority source: it grants no admission or rebind authority. Any individual recipient authorization, admission, or rebind still requires the complete Account-authenticated recipient binding, including the applicable `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set, from one snapshot. Game Session must never write or mutate any canonical `session:auth:generation:*` key. Account's durable issuer generation and its canonical projection remain the only authority; Game Session owns only this derived consumer-local projection. +For issuer-generation consumption only, Game Session may maintain one derived consumer-local projection under its own namespace: `session:game:auth:issuer-generation:v1:`. The persisted field schema and exact mapping from Account source snapshot fields are owned by [Redis Coordination Invariants](../system-architecture-redis.md#log-of-record-vs-coordination-buffer). The issuer source event and any recipient evidence it affects remain separate under [Authentication's source-event contract](../system-architecture-authentication.md#authority-source-events-and-recipient-evidence). For this derived issuer projection, bootstrap, advancement, and duplicate verification use Account-authenticated evidence for the exact issuer scope and source checkpoint: exact issuer and stream identity, committed issuer generation and source version, sequence, and complete applicable source-event identity, payload, and digest. No individual recipient's `authorityTuple`, actual `issuanceFence`, or complete `outboxCheckpoints` set is a prerequisite for maintaining this projection. Account's issuer `outboxStreamKey` is immutable for the life of that issuer authority and must not be regenerated by deployment, failover, Redis reset, or projection repair. If authoritative recovery ever changes the stream key or resets its sequence/epoch, Account must first install and expose an authoritative checkpoint for the new exact stream identity/epoch; consumers quarantine the scope and accept no changed- or reset-stream event until that checkpoint is validated. The checkpoint, not an inferred event baseline, is the only value that may establish the new local watermark or permit sequence advancement. The canonical issuer projection watermark is `lastAppliedSourceOutboxSequence`. For each exact persisted `outboxStreamKey`, an incoming event is applicable only when its source sequence is exactly `lastAppliedSourceOutboxSequence + 1`; a higher sequence is a gap that must be quarantined and reconciled from Account before either the watermark or generation advances. An event at or below the watermark is an idempotent no-op only when retained source evidence or an exact Account checkpoint lookup proves the same complete event identity, payload, and digest, source sequence, exact stream key, and issuer source progress; generation-only equality is insufficient. Missing, partial, stale, regressed, conflicting, or ambiguous evidence, including an older event outside the bounded local evidence window that cannot be resolved by the exact Account lookup, quarantines the scope and is reconciled rather than treated as a no-op. A next-sequence event must pass the same exact source/checkpoint comparison before the watermark or generation advances, and the projection watermark and corresponding source/checkpoint evidence are updated atomically. A lower source `issuerAuthGeneration` is contradictory Account evidence, while an equal generation is idempotent and a higher generation uses set-if-greater semantics. The projection is a revocation-consumer cache, not an authority source: it grants no admission or rebind authority. Any individual recipient authorization, admission, or rebind still requires the complete Account-authenticated recipient binding, including the applicable `authorityTuple`, actual `issuanceFence`, and complete `outboxCheckpoints` set, from one snapshot. Game Session must never write or mutate any canonical `session:auth:generation:*` key. Account's durable issuer generation and its canonical projection remain the only authority; Game Session owns only this derived consumer-local projection. ### Canonical Checkpoint And Source-Evidence Binding diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 3446560c60..aec892c014 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. 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. +- **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), [tenant generation snapshot projection](./runtime-and-data.md#tenant-generation-snapshot-projection), and [membership generation snapshot projection](./runtime-and-data.md#membership-generation-snapshot-projection) define their exact storage, reprojection and readback consequences. These boundaries do 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 a37610c09f..4e8d9f1e90 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -76,6 +76,14 @@ The account lifecycle API, export surfaces, and deletion-precondition contracts The bounded Account-owned worker is readback-only. It terminalizes `JOINED` only from exact positive committed operation, scope, membership, role, transition receipt, authority event, and version-1 `COMMITTED` audit receipt/projection evidence, including the verified-projection marker and nonblank receiver identities read from the locked scoped outbox row. `ALREADY_ACTIVE` requires exact positive retained receipt history and is event-free. Missing, contradictory, or uncertain evidence remains `PENDING` with diagnostics/backoff; expiry, attempt limits, or absent evidence never terminalize or trigger resubmission. Legacy rows without the marker remain unresolved; readback does not promote them or invent projection provenance. Live `CreateLogEvent` is `UNAVAILABLE` and Account audit delivery is unscheduled, so outbox rows remain `PENDING`; historical receipt reads do not upgrade them. +### Canonical UUID JOIN Evidence + +The canonical UUID path uses scope, intent and policy-request digest version `2`; retained version-1 scope, operation, provisional receipt and audit evidence remains exact historical readback, not another public identity or permission to create numeric wire identities. Dispatch recovery from the durable representation/version and reject unknown or contradictory evidence; never rewrite retained digests, request IDs, receipt keys, sequence history, event bytes or counters. Account's numeric primary key remains a private storage selector. New evidence binds the persisted canonical Account UUID and the canonical tenant, realm, playable namespace and game-instance UUIDs proved by their owners; fresh tenant authority must not invent a numeric alias. + +For version `2`, each preimage segment is strict UTF-8 prefixed by its canonical decimal byte length and `:`, with no normalization or separator between framed segments. SHA-256 returns `sha256:` followed by lowercase hexadecimal. The fixed leading segments are the domain (`account-join-scope/v2`, `account-join-intent/v2` or `account-join-request/v2`), `2`, and operation kind (`PUBLIC_PRODUCTION` for scope; `JOIN` for intent and request). Intent then includes `requestId` and the exact verified caller binding; request includes that caller binding. All three then include, in order, `connectScopeId`, `accountId`, `tenantId`, `realmId`, `tenantSlug`, `worldSlug`, `realmSlug`, `playableStateNamespaceId`, `playableStateScope`, `gameInstanceId`, `catalogRevision`, `pointerVersion`, `evaluatedAt` and `connectScopeExpiresAt`. UUIDs are canonical non-nil strings; counters are positive canonical decimal strings. The selector pair comes from Game Session's authenticated catalog: `tenantSlug` is not `worldSlug` or durable tenant identity. Discovery timestamps retain their exact UTC RFC3339 bytes, not the separate Gateway context's epoch-second representation. + +Only after authoritative available entitlement evaluation, the policy-request preimage additionally includes `AVAILABLE`, the exact lowercase boolean `allowPublicJoin`, and positive canonical-decimal `entitlementVersion`, in that order. Unavailable authority has no invented policy result/version or policy digest; retain a policy-independent pending intent and failure diagnostics. A typed scope value or digest is not an authentication capability: Account still verifies caller and persisted source, re-resolves the exact current Game Session target, and revalidates entitlement at commit. Complete UUID scope persistence, positive JOIN/event/audit/reconciliation, producer/consumer and negative proof remain required before activation; their status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md), not to the presence of these encoding rules. + ### Current vs Target Export Lifecycle The current `GET /accounts/{accountId}/export` route is a synchronous Account/profile-local read. Direct account-ID `ExportAccount` gRPC and the legacy account-targeted tenant-export REST/service and gRPC entries deny before data access. The local Account read has no cross-service required-owner fan-in and does not satisfy ADR 0050; none of these current surfaces may be described as a complete portable-data or tenant-admin export. @@ -172,6 +180,34 @@ 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. +#### Issuer Projection Reconciliation Capture + +The [Redis issuer installation contract](../../system-architecture-redis.md#log-of-record-vs-coordination-buffer) requires a distinct durable Account reconciliation identity; neither the source mutation request nor the read-only RPC correlation identity supplies it. Its owner-local capture precursor binds one exact configured issuer, the exact certificate-authenticated Game Session workload identity, its fixed derived projection key `session:game:auth:issuer-generation:v1:`, and a caller-retained canonical non-nil UUID request ID. Account owns the immutable receipt and allocates one non-nil UUID operation ID on the first successful capture. The request identity is the exact `{issuerId, requestId}` pair; reusing it with a changed caller or projection binding conflicts. Identity matching in an unregistered local primitive is not certificate authentication, and the existing read-only RPC is not reinterpreted as a capture endpoint. + +The local request digest is `issuer-projection-reconciliation-request/v1`, lowercase hexadecimal SHA-256 over byte-length-framed UTF-8 strings in this exact order: version, `ISSUER_PROJECTION_SNAPSHOT_CAPTURE`, issuer ID, exact Game Session workload identity, complete derived projection key, canonical request UUID. Each segment is ASCII canonical decimal byte length, `:`, then the exact bytes; there are no extra separators or normalization. Captured generation, source version, sequence and event are Account-resolved outputs, not caller inputs or a reason to replace a receipt during retry. The receiver supplies the workload identity only after its exact-method certificate check; no JWT service-name or serialized caller substitute is authorized. + +Capture holds the same issuer-source fence through reading the complete current source snapshot and committing its immutable receipt, without advancing authority or writing an outbox event or Redis. The receipt preserves its operation/request identity, request digest and complete captured generation, source version, stream, sequence and canonical positive event. Sequence zero requires the proved original 1/1 baseline and absence of committed history in that capture transaction; source event fields are absent. Before returning, Account performs exact durable post-commit receipt readback and validates its retained source evidence under a fresh issuer fence. Exact concurrent or lost-response retries return the same original operation and captured snapshot without another receipt, source mutation or event, even after later source progress; changed bindings conflict. A missing source, unavailable or contradictory receipt/readback, or unprovable historical event fails closed rather than synthesizing a replacement. + +A captured receipt proves a source snapshot operation, not successful projection installation, current authority after a later advance, or a distributed commit. Any installation must separately prove that its captured source still matches current Account authority, atomically install and read back the complete Game Session projection, and bind its acknowledgment to this exact operation and checkpoint. A stale captured receipt remains historical readback only; a new capture requires a new request ID. Authenticated producer/consumer transport, installation acknowledgment, ordinary delivery, recipient authorization and activation remain separate obligations; capture grants no admission or rebind authority. + +Game Session's local installation and currentness proof are owned by [Redis Coordination Invariants](../../system-architecture-redis.md#log-of-record-vs-coordination-buffer). Account's complete fenced current readback is used before and after the local write; the immutable captured operation is not replaced or treated as current merely because exact retry returned it. Local installed-projection evidence is distinct from a durably committed Account acknowledgment, and neither alone supplies recipient authorization. + +The distinct internal `account.v1.IssuerAuthorityService/CaptureIssuerProjectionForRuntime` handoff carries only exact `issuerId` and canonical non-nil `requestId` in its closed request. Account verifies the exact Game Session certificate peer before parsing or owner access and derives `callerWorkloadIdentity` from that peer, never from serialized caller input. Its closed response uses `account-auth-issuer-projection-capture/v1` and carries target namespace, operation ID, request ID, issuer ID, caller workload identity, complete derived projection key, request-digest version `1`, exact request digest and the complete captured source snapshot. The snapshot reuses the existing issuer-source shape and canonical decimal-string counters; its positive canonical event is mandatory, and zero omits it. Captured evidence may be historical during exact retry and is not relabeled as a new current read. Game Session verifies the exact Account server certificate identity, response/request/namespace/caller/projection bindings, canonical UUIDs and digest, and complete snapshot/event content before returning a typed receipt. Unknown fields or missing/mismatched evidence fail closed. A bounded transport error never creates a replacement operation. The read-only RPC is unchanged, and both handoff candidates remain unregistered until their complete producer/consumer and negative proof is accepted; this transport alone cannot install or authorize a projection. + +#### Issuer Installation Acknowledgment + +Account durably records Game Session's authenticated installation acknowledgment separately from the immutable capture. The exact Game Session certificate peer is required before owner access; a serialized caller or JWT service-name claim is not authentication. The request binds the issuer, original capture operation ID, stable capture request ID and capture request digest, complete derived projection key and exact installed projection JSON bytes. The request never substitutes a new capture, snapshot, request ID or local baseline. Game Session sends only its privately verified installation receipt after the [Redis owner's currentness and exact-readback protocol](../../system-architecture-redis.md#log-of-record-vs-coordination-buffer) succeeds. Account does not connect to or mutate Game Session's Redis. + +For a first acknowledgment, Account holds the issuer source fence, reads back the exact retained capture, and proves the complete current source still equals that capture. It validates the closed projection against the captured issuer, stream, independent counters, sequence and complete canonical event, preserving zero's event absence. Source progress, missing/mismatched capture, changed peer, projection binding or evidence denies before acknowledgment insertion. One Account transaction inserts an immutable acknowledgment; it neither advances authority nor changes source/outbox history. A separate fenced transaction reads back the exact committed result before success is returned. + +The acknowledgment request digest is `issuer-projection-installation-ack/v1`, lowercase hexadecimal SHA-256 over the capture contract's byte-length-framed UTF-8 segments in this fixed order: version, `ISSUER_PROJECTION_INSTALLATION_ACK`, issuer ID, authenticated Game Session workload identity, complete derived projection key, canonical capture operation UUID, canonical capture request UUID, canonical decimal capture request-digest version, exact capture request digest and exact installed projection JSON. The projection retains the complete checkpoint/event evidence and original `appliedAt`; its original UTF-8 bytes are stored without JSON normalization, alongside their SHA-256 digest. Account allocates one non-nil acknowledgment UUID for the original success and retains the capture association, digest version/preimage evidence and original result. No secret material or recipient Account fence is introduced into issuer-scoped evidence. + +Exact concurrent or lost-response retries require the same authenticated peer and complete original request evidence and return that original acknowledgment after durable capture, retained source-history and acknowledgment readback. Later source progress does not rewrite a committed acknowledgment or turn it into current authority; a changed projection byte, `appliedAt`, capture identity or binding conflicts. A first acknowledgment of an already-stale capture remains denied. Uncertain or missing post-commit readback never mints a replacement acknowledgment. The result proves a historical owner-acknowledged installation, not current readiness, event-delivery activation or recipient admission/rebind authorization. Runtime registration remains denied until complete producer, consumer, negative and recovery proof is accepted; detailed status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + +The distinct candidate `account.v1.IssuerAuthorityService/AcknowledgeIssuerProjectionForRuntime` handoff has exactly `issuer_id`, `capture_operation_id`, `capture_request_id`, `capture_request_digest_version`, `capture_request_digest`, `projection_key` and `installed_projection_json`. IDs are canonical non-nil UUIDs, the capture digest version is `1`, the digest is lowercase hexadecimal SHA-256, and the supplied key must equal the complete issuer-derived key. The projection is the exact original valid UTF-8 JSON from the privately verified installation receipt, not a reconstructed or normalized object. Account verifies the exact Game Session certificate peer before request validation or owner access, derives caller identity from that peer, and independently verifies every capture and projection binding through the owner service. + +The closed response uses `schema_version=account-auth-issuer-projection-installation-ack/v1`, exact `target_namespace`, `acknowledgment_id`, `issuer_id`, `caller_workload_identity`, `projection_key`, `capture_operation_id`, `capture_request_id`, `capture_request_digest_version`, `capture_request_digest`, `request_digest_version=1`, `request_digest`, `installed_projection_json` and `installed_projection_sha256`. Both digest values and the projection SHA-256 use lowercase hexadecimal; exact installed JSON bytes and their original `appliedAt` survive readback. Game Session verifies the exact Account server certificate, closed response fields, complete namespace/caller/issuer/key/capture bindings, canonical acknowledgment UUID, shared acknowledgment request digest, exact projection bytes/hash and full captured checkpoint/event evidence before exposing a privately minted historical acknowledgment. The client accepts only the installer's private receipt as input, never an arbitrary caller-written projection. Bounded transport failures yield no positive receipt and never replace the capture, request, installed bytes or result; an exact retry reuses them. The read/capture transports remain distinct, and the acknowledgment handler/client remain unregistered until their complete producer/consumer and negative/recovery proof is accepted. + ### 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. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 782b2b6577..5fc5f73579 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The local V45 candidate widens the existing membership and role storage, rather than creating a second authority family. Retained numeric rows remain unbridged history with unchanged state, counters and receipt/event bytes. Canonical writes require the exact persisted Account UUID and existing immutable fresh or approved-retained tenant source; fresh membership has a canonical tenant UUID and no numeric alias. Typed source/provenance facts alone are not authentication. This foundation does not yet implement canonical scope persistence, positive fresh JOIN, event/audit/reconciliation or an enabled runtime RPC. The [canonical JOIN encoding](./api-contracts.md#canonical-uuid-join-evidence) belongs to the API owner; component status and required producer/consumer proof remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + Profile mapping receives the exact provenance-checked Account UUID explicitly rather than treating an ID-only profile relation as identity evidence. Numeric foreign keys stay private and retained rows are unchanged; reads, updates and local export verify exact Account/profile ownership. Proof and the separate tenant-qualified/delegated and Social Groups gaps remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). JOIN reconciliation also requires explicit version-1 COMMITTED receipt/projection evidence and nonblank receiver identities on the exact locked JOIN outbox row. A pending JOIN whose retained COMMITTED outbox row lacks that marker remains pending with retry diagnostics; the historical row is not upgraded or inferred as current projection proof. Deploying the receiver child alone does not promote these historical rows: current exact receipt/projection readback and a guarded evidence-recording path must be proved before they can enable recovery. An unavailable, minimized, or unsupported receiver response cannot enable recovery. @@ -162,6 +164,24 @@ This is current-snapshot reprojection by the source owner, not delivery-consumer 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). +### Tenant Generation Snapshot Projection + +Account's tenant-wide projection uses `session:auth:generation:tenant:` with `schemaVersion: "account-auth-tenant-generation-projection/v1"` and exactly `tenantId`, `tenantAuthorityGeneration`, `sourceVersion`, `outboxStreamKey`, and `outboxSequence`; a positive checkpoint additionally requires `sourceEvent`, the complete canonical JSON of its latest closed tenant-generation event as a string. Counters use canonical decimal strings. The canonical non-nil tenant UUID, exact `account:auth-authority:v1:tenant/` stream and latest event must match Account's fenced tenant-source readback. Sequence zero requires the proved original generation/source-version 1/1 baseline and no committed event; it omits `sourceEvent`. For positive tenant-source sequences, both counters equal sequence plus one. Neither Redis absence nor caller-supplied identifiers establish enrollment or an absence baseline. + +The [Account snapshot reprojection rules above](#account-generation-snapshot-projection) apply to this tenant-owned current snapshot: its candidate comes internally from the Account tenant-source reader, registered byte-exact CAS has no TTL or raw `EVAL` fallback, and convergence requires exact Redis and fresh durable-source readback. The descriptor binds this separate tenant prefix; sharing internal mechanics or exact script bytes does not permit a caller to select another owner or key family. The projection carries no recipient Account tuple or issuance fence and does not alter tenant billing, enroll a source, deliver events, authorize a caller or acknowledge complete cutoff enforcement. Authority scope and reset policy remain owned by [ADR 0036](../../decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md) and the [reset-policy matrix](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); implementation and executed proof remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + +### Existing Membership Source Readback + +Membership reprojection reads only already committed Account source state. Its owner-local reader uses a short Account transaction and the existing Account-row fence to resolve the exact persisted Account UUID and either the approved retained tenant association or Game Design's immutable fresh-tenant association. It requires an existing pair authority row and membership generation; reading or rebuilding a projection must not initialize a generation, enroll a pair, create a membership, or infer a baseline from absence. The complete existing-only membership snapshot and the exact membership generation row's independent `sourceVersion` are read under that same fence. This internal source record does not add fields to the runtime RPC or replace the authenticated recipient carrier. + +An already proved retained ACTIVE or INACTIVE membership keeps its current row, roles, receipt, immutable event and checkpoint evidence. A never-joined pair can return its existing positive baseline only when the complete same-fence no-membership/no-history proof succeeds; its sequence is zero, its event evidence is absent and it grants no admission. Fresh UUID associations currently support only this already enrolled non-admitting baseline; fresh positive JOIN remains separately tracked. The transmitted membership version remains the exact one-tenant map. Membership generation, membership version, generation source version and stream sequence are independent axes and must not be reconstructed from one another. Source reads retain exact identity/provenance readback and refuse ambient transactions in the owner-local transaction wrapper; the separate runtime enrollment paths retain their existing behavior. The membership RPC and all credential paths remain denied until their declared producer, consumer and negative activation proof is complete. Implementation and executed proof remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + +### Membership Generation Snapshot Projection + +Account's membership-generation projection uses the exact `session:auth:generation:membership::` key for two canonical non-nil UUIDs. Its closed physical record has `schemaVersion: "account-auth-membership-generation-projection/v1"`, `accountId`, `tenantId`, `membershipAuthorityGeneration`, `sourceVersion`, the exact one-tenant `membershipVersion` map, `outboxStreamKey`, and `outboxSequence`; positive checkpoints additionally carry `sourceEvent`, the complete canonical membership-event JSON as a string. All counters are canonical decimal strings, with zero allowed only for sequence. The stream is exactly `account:auth-authority:v1:membership//`. Source generation, source version, membership version and event sequence remain independent: first JOIN may have generation/source-version 1/1, membership version 2 and event sequence 1. A sequence-zero record instead requires the proved existing original positive pair baseline, version 1 and generation/source-version 1/1, with no event evidence; Redis absence is not proof. + +Candidates come internally from the existing-only reader above, never from a caller-provided snapshot or runtime enrollment method. The [Account snapshot reprojection rules](#account-generation-snapshot-projection) govern the explicit Coordination client, registered single-key byte CAS, TTL rejection, exact Redis readback and fresh source readback. Same-checkpoint conflicts, regression, malformed state or changed source cannot be acknowledged as convergence. The owner-local descriptor permits only this exact pair prefix; shared private Redis mechanics grant no access to Account, tenant or derived Game Session keys. This record is generation/source projection evidence, not recipient authorization, event delivery, a complete membership response or admission. Source mutation and post-commit enforcement, reset orchestration, live role/cohort and activation proof remain separate tracked gates; no runtime RPC or credential path is enabled by constructing or repairing a projection. + ## 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. 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 cdd7101023..e67b45b95d 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,8 @@ 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 local V11 candidate adds nullable unique `game_instances.game_instance_uuid` without backfilling retained rows. Game Session's repository allocates a UUID on fresh insertion, reads back that exact persisted source and preserves it on update; unmapped retained identity denies strict canonical lookup. This is only the owner-local identity source: tenant storage, public DTO/proto/catalog/pointer migration, creation-request idempotency and authenticated selected-target composition remain separate gaps. It neither derives a UUID from a private numeric key nor enables admission. Validation and executed-versus-skipped proof belong to [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md). + - 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). diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index f9233d7753..d018adeb0f 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -99,6 +99,7 @@ Redis coordination keys form a long-running, measured-exposure **coordination bu - Every issuer-generation projection, including the canonical `session:auth:generation:issuer:` projection and the Game Session `session:game:auth:issuer-generation:v1:` consumer projection, atomically stores `lastAppliedSourceOutboxSequence` (the accepted source `outboxSequence`) and `lastAppliedIssuerGeneration` for its exact canonical `outboxStreamKey`, plus `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` as derived source-checkpoint evidence for every nonzero sequence. These `lastAppliedSource*` fields are projection evidence associated with the canonical `outboxStreamKey`/`outboxSequence` and the applicable `outboxCheckpoints`; they are not authority-tuple fields or JWT claims. For sequence `0`, the two source-event fields are omitted from the projection, not serialized as JSON `null`, an empty string, a zero digest, or another sentinel; the Account-owned zero-sequence checkpoint is the only evidence. For every positive sequence, both source-event fields are required non-null values in their canonical formats. Ordinary delivered events may apply only the next contiguous sequence. A higher delivered sequence is a gap and must quarantine the affected projection and reconcile from Account before advancing the watermark or generation. The sole exception is one Account-owned authoritative snapshot/reconciliation installation, which may atomically install the exact Account checkpoint and generation at its latest sequence without consuming skipped events; that installation must carry the exact snapshot/checkpoint evidence and operation identity, and the next delivered event must be exactly one greater than the installed sequence. For each stream, the projection also retains bounded duplicate evidence for the most recent accepted sequences, at minimum `{outboxStreamKey, outboxSequence, eventId, eventDigest}`; each evidence entry has a required non-null `eventDigest`, and no entry represents the zero-sequence baseline. An equal or lower sequence is a no-op only when that bounded evidence matches or an authoritative Account lookup for the exact `(outboxStreamKey, outboxSequence)` proves the same event identity and digest; a high-water mark alone is never duplicate proof. If the evidence has aged out, the lookup is unavailable, or same-sequence evidence conflicts, the projection is quarantined. A valid next event advances the complete persisted checkpoint even when set-if-greater generation semantics leave the generation unchanged. The gameplay binding's separate `{outboxStreamKey, outboxSequence}` freshness set does not replace this projection-local replay evidence. Projection recovery fails closed while the checkpoint is missing, stale, regressed, ambiguous, or quarantined, including any invalid omitted/null/sentinel representation. - An empty Game Session issuer projection is an uninstalled and quarantined state, not an implicit zero-authority state and not permission to consume live events. Game Session, not Account, must install `session:game:auth:issuer-generation:v1:` from one Account-owned authoritative snapshot/reconciliation transaction for the exact `issuer/` scope and read back that installed derived projection. That transaction returns the exact checkpoint: `outboxStreamKey = account:auth-authority:v1:issuer/`, `lastAppliedSourceOutboxSequence` equal to the Account checkpoint's exact latest `outboxSequence`, and source `issuerAuthGeneration` from the same snapshot. For a nonzero sequence it also returns the exact source `eventId` and `eventDigest`; for sequence `0`, permitted only when the stream has no committed event, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are absent, and the Account-owned zero-sequence checkpoint itself is the evidence. The result also carries the source transaction or immutable bundle version, the exact checkpoint evidence, and the reconciliation operation identity; Game Session must not invent bootstrap event IDs, digests, sequences, or authority values locally. Before consuming events, Game Session atomically persists that complete checkpoint with the exact `issuerAuthGeneration` mapped to canonical persisted `lastAppliedIssuerGeneration`, stores matching `{outboxStreamKey, outboxSequence, eventId, eventDigest}` duplicate evidence only for a nonzero checkpoint, and reads back the installed projection. For a zero-sequence baseline, duplicate evidence is empty and the first consumable event must be sequence `1`; for a nonzero baseline, the next consumable event must be exactly `lastAppliedSourceOutboxSequence + 1`. Until the atomic installation and exact readback succeed, or if any applicable snapshot, source-checkpoint, event-identity/digest, or authority value is missing, stale, regressed, contradictory, or ambiguous, the projection remains quarantined and issuer-gated admission, reconnect, and revocation consumption fail closed. - Canonical issuer snapshot mapping is exact across bootstrap, persistence, readback, replay, and recovery: Account's authoritative snapshot field `issuerAuthGeneration` maps one-to-one to the projection field `lastAppliedIssuerGeneration`. The latter is the only persisted projection field used for comparison and replay advancement; `issuerAuthGeneration` is the source snapshot/authority name and is not a second persisted alias or a local fallback. Every bootstrap install, event replay, exact readback, set-if-greater repair decision, and recovery acknowledgement must compare the mapped value together with the exact `outboxStreamKey`, `lastAppliedSourceOutboxSequence`, source event evidence, and operation/checkpoint evidence. +- Issuer reconciliation installation consumes the privately verified [Account capture receipt](./microservices/account-service/api-contracts.md#issuer-projection-reconciliation-capture), not a caller-supplied projection map. Game Session verifies complete current Account readback before the single registered Redis CAS and another complete Account readback after exact persistent projection readback. Both source reads must exactly match the captured issuer, stream, independent generation/source-version counters, sequence and complete canonical event; request correlation and namespace must match the operation's caller binding. With the source's existing monotonic fenced history, that unchanged before/after checkpoint brackets the local write without a distributed transaction. Source progress, changed binding, unavailable read, poisoned/ahead projection or failed exact readback yields no verified installation result and does not authorize a replacement operation. Only this explicit reconciliation path may jump a valid behind projection to the captured checkpoint; ordinary events stay contiguous. An exact matching projection retry preserves stored bytes and `appliedAt`. Successful local evidence carries the original operation/request/digest, complete captured checkpoint and exact stored projection bytes; it is not a durably committed Account acknowledgment, live readiness, event-delivery activation or recipient authorization. - Spring Cloud Gateway has one narrow Coordination Redis authority: one-use connect-token replay consumption under `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, browser-revocation deny markers under `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, the shared replay-readiness record under `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and a separate Gateway-generated disposable recovery-probe marker under `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`. The readiness value carries the shared `replayAdmissionFence`. Any marker-loss or reset event that can break replay continuity keeps shared readiness quarantined under an advanced `replayAdmissionFence` until the canonical [ADR 0029 readiness proof](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md) permits reopening; during that quarantine, an absent `jti` marker alone never proves first use. The probe marker is not a player `jti` or deny marker: its typed probe runs only in `QUARANTINED`, does not accept player credentials or write shared readiness, and returns evidence to the recovery coordinator. Normal player consume remains `OPEN`-only; only the coordinator may reopen after every release gate passes. The Gateway fails closed when that replay authority is unavailable, owns marker TTLs and reset contract, and must not expand this exception into ownership of gameplay sessions, Account auth state, or general coordination policy. These probe and release contracts are target-only and currently unimplemented. Game Session owns the live and recent account-presence projections described in [Game Session Runtime and Data](./microservices/game-session-service/runtime-and-data.md), but their current Redis shapes are implementation drift rather than accepted target authority. The live `gameplaypresence:session:`, `gameplaypresence:::sessions`, and `gameplaypresence::account::sessions` families, and the recent `accountrecentpresence::` family, currently use direct untagged writes with separate value/index mutations. Their exact owner scope, storage role, partial-write behavior, reset policy, rebuild/readback evidence, and private-by-failure semantics are not proven. These shapes must remain outside the accepted target key contract: the target owner projection requires an exact scope, atomic owner-controlled mutation, and a missing, stale, partial, or ambiguous projection must make presence private/unavailable rather than expose stale or cross-scope presence. The current families are cataloged in the reset matrix only to prevent an operator from treating an unregistered legacy shape as safe to delete, preserve, or use as authority. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 501d37b2be..b2b0834bfd 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -375,3 +375,8 @@ Entry format: - 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. + +- `2026-10-03`: Preserve the exact external run identifier in watcher assignments + - Context: two bounded CI sentinels inspected a shortened or mistyped run identifier instead of the supplied full identifier and reported HTTP 404. That was not evidence that the authorized run was inaccessible or nonexistent. + - Outcome: direct same-task corrections restored observation of the intended runs. The current run37030807027 is visible; its earlier lookup of37007080727 supplied no validation evidence. No repository or CI mutation was needed. + - Expected pattern: copy the complete identifier from the assigned run URL, verify the returned run identifier and head SHA before attribution, and include the actually inspected identifier in a lookup-failure report. Do not escalate a mistyped-ID lookup as a platform-access failure or silently substitute a different run. 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 1c85c9f099..48aa650ec8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,60 @@ This is a non-normative implementation tracker for player access and session. Ca The source-to-cutoff reconciliation preserves Account's LEFT receipt migration at V42 and mechanically places the child logout-all receipt migration at V42.1, before the already-preserved downstream V43–V55 lineage. The logout SQL bytes and immutable receipt/event guards are unchanged; both behaviors remain present rather than selecting one duplicate version. This prepares a collision-free unapplied candidate, not permission to renumber an applied migration or repair retained Flyway history. Deployment still requires exact owning-environment migration inventory and retained-data readback; a conflicting applied history must remain a fail-closed rollout gate. Historical component executions below do not prove this newly composed migration sequence or enable any runtime path. +Exact #2945 checkpoint `91a001128df72ce83e8c9784e50457e267b7b582` [CI37061673261](https://github.com/benhook1013/FireMUD/actions/runs/37061673261) executed all67 targeted cases with zero skips, failures or errors: canonical Account membership1, Game Session owner migration1/instance identity1, membership PostgreSQL/socket2, issuer PostgreSQL/socket22, issuer mTLS14/Redis8, acknowledgment8, capture9 and mock-backed LOGIN1. Root independently parsed and hashed the raw XML. Both corrected UUID fixtures are runner-proved. Game Session passed; Account's later aggregate check exposed a stale retained-row test projection: V45 adds four explicitly unbridged membership metadata fields while all preexisting values match. The scoped correction compares every original field unchanged and separately proves the new null/source provenance slots. Corrected aggregate execution remains required; other jobs retain their concrete failures. This is not complete positive fresh JOIN, live readiness or activation proof; the ring mount remains unpublished and runtime paths denied. Earlier exact-head failures below preserve their historical attribution. + +Exact corrected #2945 checkpoint `ef3e415927f3bc17776d7a522a45e4eb643326d4` [CI37059352216](https://github.com/benhook1013/FireMUD/actions/runs/37059352216) completed with aggregate failure. Both required membership PostgreSQL/mTLS cases passed, confirming the provenance-field decoding correction. All 22 issuer PostgreSQL/socket, 14 physical issuer mTLS and eight issuer Redis cases also executed cleanly. The new Account canonical membership method failed in setup because its random source key exceeded the unchanged 36-code-point owner bound; the Game Session UUID method reached the database immutability rejection but expected a trigger name instead of the actual owner denial message. The scoped fixture corrections preserve the production bounds, trigger and postcondition assertions. Acknowledgment, capture and mock LOGIN proof was unavailable in this run after earlier failures; no absent suite is credited as a pass. Local PostgreSQL execution, corrected-head runner execution, fresh-image/live proof and complete positive JOIN remain gates. Runtime activation stays denied and the Account-ring mount remains unpublished. + +Exact UUID-foundation checkpoint `dfa42fe19e39cdecfecd6205cb7fe8287eabfb8a` [CI37056915994](https://github.com/benhook1013/FireMUD/actions/runs/37056915994) failed in both Account and Game Session. The new Account database method executed but failed during setup because its username exceeded varchar50. A Game Session membership PostgreSQL/socket regression exposed an Account repository decoding defect: selected raw qualified jOOQ field names did not match the unqualified names consumed by readback. Its two cases executed with one failure; the later Game Session UUID proof was skipped and has no uploaded suite. The scoped corrections use quoted jOOQ identifiers, strengthen actual provenance readback assertions and keep the fixture username within its existing schema, preserving all identity guards. Consolidated Account/Game Session full checks, both boot JARs and docs passed1m43s/157tasks (42executed/13from-cache/102up-to-date). Account688unit and Game Session26cross-service cases executed cleanly; unchanged Game Session1907unit/18integration results were reused. Account251integration and Game Session17unit/152integration/54cross-service skips remain local limits. Root independently parsed/rehashed prior runner XML for44 clean issuer composition/mTLS/Redis executions; acknowledgment/capture steps and the required LOGIN case remain unavailable in that failed run. Corrected-head database execution is still required, not inferred from earlier proof or local skips. Other aggregate validation failures remain separate from these owned defects. Runtime activation and the Account-ring mount remain denied/unpublished. + +The preceding published #2945 acknowledgment checkpoint `e390e93939a22ca4340d86f5f37d7e9fecec2c31` [CI37050226916](https://github.com/benhook1013/FireMUD/actions/runs/37050226916) supplies all62 clean targeted executions: Account acknowledgment8, PostgreSQL/socket22, capture9, physical issuer mTLS14, issuer Redis8 and mock-backed LOGIN1. Root independently parsed/rehashed raw XML; both owned service jobs passed. Aggregate CI failed on Python lint, indirect dev-demo summary validation, Game Design's duplicate tenant9301 fixture, Automation formatting and their dependent gate. This closes that acknowledgment transport checkpoint's targeted execution gap, not proof of the later UUID batch, runtime registration, complete authority delivery, a real credential exchange, live readiness or activation. The following local skip reports remain local evidence, not claims that the remote cases skipped. + +The canonical identity/JOIN foundation widens shared Account membership/role storage in V45: retained rows remain unbridged until exact approved owner readback; fresh memberships store canonical UUID/source provenance without a numeric tenant alias. Canonical repository methods require a real owner transaction, locked persisted Account identity, existing approved/fresh association readback, and exact membership/role readback. Game Session V11.1 allocates a fresh instance UUID in its owner insert, preserves it on update and strictly resolves its stored identity; retained rows remain unmapped. The [canonical JOIN evidence encoding](../../architecture/microservices/account-service/api-contracts.md#canonical-uuid-join-evidence) defines the new versioned preimage at its owner; four independently reproduced vectors and exact retained-v1 implementation comparison cover framing and preservation. These components are not wired into a complete UUID catalog/pointer, scope issuance or positive JOIN/event/audit/reconciliation path. Game Session's numeric tenant source/API, complete entitlement authority and their producer/consumer and negative proofs remain open. Missing subscription authority denies, rather than provisioning a default plan. Runtime paths remain denied; Account-ring mount unpublished. The combined unapplied candidate keeps the incoming V11 public-cardinality guard, mechanically moves the UUID migration from V11 to V11.1 with identical SQL bytes, and retains V12. Deployment remains blocked until exact environment Flyway history/checksums and retained-row readback prove the correct disposition; never rewrite applied history, run repair or enable out-of-order to hide a collision. + +The corrected UUID foundation passed consolidated Account/Game Session full checks, both boot JARs, formatting, Checkstyle, SpotBugs, coverage and documentation in43s/158tasks (20executed/138up-to-date). Same-code XML includes688 Account unit executions and Game Session1,907unit/18integration/26cross-service executions, all clean; unchanged results were reused in the final gate, not executed again. Account251integration and Game Session17unit/152integration/54cross-service cases skipped locally because Docker is unavailable. The new Account membership and Game Session instance database fixtures each contain one test method with multiple assertions; neither executed locally. CI explicitly requires both methods and uploads their raw XML. Their exact-head executed PostgreSQL proof, fresh-image/live proof and complete positive JOIN remain gates. Initial compilation and fixture analyzer failures were corrected without weakening guards, assertions or filters; actionlint,25CI-scope contracts and Flyway12sets/134files passed. + +### Earlier Proof Checkpoints + +The next #2945 batch implements the unregistered [authenticated issuer acknowledgment handoff](../../architecture/microservices/account-service/api-contracts.md#issuer-installation-acknowledgment): exact certificate-derived Game Session caller, closed capture-bound request, shared versioned digest and full durable Account response, verified by Game Session only from its privately minted installation receipt. Both endpoints remain unwired; a historical acknowledgment grants neither current readiness nor admission. Consolidated Common Platform, Account and Game Session checks, both boot JARs and documentation passed in 2m14s/171 tasks (53 executed/118 up-to-date). Actual XML records Common177 and Account678 unit executions, plus Game Session1,906 unit/18 integration/26 cross-service executions, all clean. Fourteen physical issuer mTLS cases executed, including all three added acknowledgment cases. Account250 integration and Game Session17 unit/151 integration/54 cross-service nodes skipped locally; the PostgreSQL/socket class's19 skipped method nodes do not prove its22 parameterized runner cases. Exact-head runner execution, fresh-image/live proof, complete delivery and activation remain required. The Account ring mount remains unpublished. + +Exact published acknowledgment checkpoint `776b99c23c628c4e4d128077b7d829e8f631b894` [CI37045248119](https://github.com/benhook1013/FireMUD/actions/runs/37045248119) executed all52 targeted cases without skips/failures/errors: acknowledgment PostgreSQL8, PostgreSQL/socket15, capture PostgreSQL9, physical issuer mTLS11, issuer Redis8 and mock-backed LOGIN1. Root independently parsed and hashed the raw XML; the corrected Redis-authentication-refusal fixture now reached and passed original-result recovery. Aggregate CI remains red on Python lint, a Dev Tool Contract Gradle plugin-resolution failure, Game Design's separate duplicate-key fixture, Automation formatting/protobuf serialization and the dependent gate. This proves the published immutable acknowledgment storage and preceding installation components, not the later authenticated acknowledgment transport, a real LOGIN exchange, live readiness or activation. Detailed hashes and failure signatures are retained in #2945's private handoff. + +The corrected acknowledgment/decoder batch passed consolidated Common Platform, Account and Game Session full checks, both service boot JARs, formatting, static analysis, coverage and documentation in1m46s/171tasks (22executed/149up-to-date). Recorded same-code XML is clean: Common173unit, Account674unit and Game Session1,903unit/18integration/23cross-service executions; unchanged results were reused in the final gate, not executed again. All250 Account integration cases skipped locally without Docker, including the eight new acknowledgment cases; those local skips remain accurate despite the executed runner proof above. Game Session17unit/151integration/48cross-service skips remain explicit. Initial gates exposed two fixture Runnable assertion compile errors and two ignored no-op fixture accessor calls; their corrections preserve all guards. Actionlint,25CI-scope contracts,Flyway12sets/132files and exact eight-selector matching passed. Authenticated acknowledgment transport and consumer, fresh images and live/activation gates remain open. + +The same #2945 stage adds an unwired [Account issuer installation acknowledgment](../../architecture/microservices/account-service/api-contracts.md#issuer-installation-acknowledgment), immutable V44 storage and one shared strict issuer-projection decoder reused by Account and Game Session. First acknowledgment requires the exact durable capture and complete current issuer source under its fence; separate committed readback precedes a positive result. Exact retries preserve the original acknowledgment and projection bytes after later source progress. Neither acknowledgment nor capture changes source/outbox history. Ten unit cases and eight mandatory PostgreSQL cases cover transactions, full evidence, concurrency, original-result recovery, denial and database immutability/digest guards. The later authenticated transport and private Game Session consumer are implemented as described above; complete new socket/database execution remains required. This historical owner receipt does not supply current readiness, event delivery, recipient authority or activation. Proof status is recorded separately; the runtime paths remain denied and the Account ring mount unpublished. + +Exact issuer installation checkpoint `6395e56a80e21b07a7a60392937b23061e42a3fc` [CI37040803538](https://github.com/benhook1013/FireMUD/actions/runs/37040803538) finished with aggregate failure. All fifteen required PostgreSQL/socket composition cases executed without skips; fourteen passed and one failed because the new Redis-authentication-refusal fixture compared separately decoded event objects by identity. Its prepared correction compares the complete snapshot and canonical event bytes/digest without changing production guards or no-mutation/recovery assertions; corrected execution remains required. Capture PostgreSQL9, physical issuer mTLS11, issuer Redis8 and issuer authority PostgreSQL15 passed. Game Session's main check was skipped after the composition failure, so LOGIN's later missing-suite result is unavailable dependent proof, not a second executed LOGIN failure. Python, dev-demo validation, Automation formatting and Game Design duplicate-key failures remain separate concrete aggregate limits. + +The issuer installation batch passed the corrected full Game Session check/JAR, formatting, Checkstyle, SpotBugs, coverage and documentation gate in1m53s/134tasks (32executed/102up-to-date). XML proves1,903unit/18integration/23cross-service cases executed cleanly, with17/151/48 respective skips. The new installer10 and expanded transition20 unit cases ran without skips/failures/errors. The PostgreSQL/socket class compiled but its13local skipped method/container nodes do not prove its15parameterized runner cases; seven added methods compose real SQL, authenticated socket and role-bound Redis. Initial failures were the new Redis fake's shifted key/script argument decoding, an unsupported array assertion and a redundant null check; corrections preserved production denial behavior. Exact-head runner execution for the installation batch, fresh-image/live/cohort proof and durable Account acknowledgment remain required. + +The unregistered issuer reconciliation installer now composes the privately verified durable Account capture, complete current readback before a registered Redis CAS, exact persistent Redis readback and a second complete current Account readback. A valid behind projection may jump only through this explicit captured-checkpoint path; ordinary delivery stays contiguous. Exact retry preserves projection bytes and original `appliedAt`. Source races, changed bindings, poisoned/expiring/ahead projections and infrastructure failures yield no verified local receipt. Its private installation receipt is historical local evidence, not durable Account acknowledgment, live readiness or recipient authorization. Operation-bound Account acknowledgment, runtime delivery and activation remain open; focused implementation/proof results are recorded separately below and in #2945's handoff. + +Exact capture-transport head `3f7be766e39dc536b5f8a8721f332bfdc40ae97e` [CI37036423921](https://github.com/benhook1013/FireMUD/actions/runs/37036423921) passed Account and Game Session jobs. Six independently parsed raw XML suites prove48 actual executions with zero skips/failures/errors: issuer physical mTLS11, membership physical mTLS11, issuer PostgreSQL/socket8, durable capture PostgreSQL9, issuer Redis8 and mock-backed LOGIN1. Aggregate CI failed on concrete Python/dev-tool, Game Design and Automation checks. This runner proof does not cover the subsequent installer corrections, enable the live RPC or prove the real delegation exchange. + +The #2945 issuer consumer now converges its persisted fields to the [Redis owner schema](../../architecture/system-architecture-redis.md#log-of-record-vs-coordination-buffer): source `issuerAuthGeneration` maps only to stored `lastAppliedIssuerGeneration`, with canonical `outboxStreamKey` and positive `lastAppliedSourceEventId`/`lastAppliedSourceEventDigest`. Obsolete stored aliases are rejected, not supported through an unpublished compatibility mode. Source events, independent counters, contiguous advancement, full historical duplicate verification, registered Lua bytes and denial gates are unchanged. ADR 0022 links the physical-schema owner while retaining Game Session's namespace and consumer consequences. Full Game Session check/JAR and docs passed in 3m 16s: 1,875 unit, eighteen integration and eighteen cross-service cases executed cleanly; seventeen,151 and37 respective skips remain explicit. The unwired durable Account capture precursor is implemented; complete authenticated installation/readback and its acknowledgment remain open. + +Exact #2945 capture checkpoint `15aa6ef510b1ce630fbdb468cd1070c7c3c520e1` [CI37030807027](https://github.com/benhook1013/FireMUD/actions/runs/37030807027) supplied raw XML proving all nine capture PostgreSQL cases and all eight corrected issuer Redis cases executed without skips, failures or errors. Root independently parsed and hashed twelve suites totaling96 clean executions, including the existing Account/membership/tenant projections, reset/logout/issuer/tenant source regressions and one mock-backed LOGIN fixture. Local Docker skips are not substituted for that runner proof. Account and Game Session jobs passed, but aggregate CI failed in other validation jobs. These results prove the published durable capture and corrected alias expectation, not later transport edits, real delegation exchange, live deployment, complete installation or runtime activation. + +The candidate capture transport now exposes the distinct closed Account handoff described in [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#issuer-projection-reconciliation-capture), with exact certificate-derived caller/server identities, shared request-digest vectors and a privately minted Game Session receipt. Physical socket tests cover zero/positive capture and wrong caller/server identities; PostgreSQL/socket composition additionally covers original-result recovery after source advance, concurrent exact capture and no-mutation denials. The registered issuer Redis store also requires exact same-key persistent post-script readback before a positive result, including both replay branches; missing, changed, expiring or unavailable readback denies without a second script. None of these candidates registers a runtime endpoint or completes the operation-bound installation/currentness/acknowledgment protocol; executed and skipped proof remains distinguished in the PR handoff. + +Exact #2945 checkpoint `65fa112959113bc280d8f995189865cc1fff13f4` [CI37022234486](https://github.com/benhook1013/FireMUD/actions/runs/37022234486) finished with aggregate failure. Raw XML proves fourteen existing membership source cases, seven tenant PostgreSQL/Redis cases and the corrected LOGIN fixture executed cleanly without skips. All seven new membership PostgreSQL/Redis cases also executed, but one fixture expected stale source after changing a counter at an unchanged checkpoint; the implementation correctly returned quarantine. The fixture now requires canonical parsing and exact `SAME_CHECKPOINT_DISAGREEMENT`, retaining byte/no-SQL-mutation assertions and the separate real JOIN-to-LEFT valid-ahead test. Corrected runner execution remains required. The five other failed jobs have concrete Python lint, indirect dev-demo summary, Automation formatting, Game Design duplicate-tenant fixture and Entity checkout-certificate signatures; successful component proof is not aggregate success or activation. + +The existing Account PostgreSQL/Redis fixture adds a post-commit password-reset/auth-refusal composition: original source receipt, generation/fence, event and checkpoint must survive refused Redis credentials and exact source retry without another advance, ambient-transaction reprojection must deny before writes, and subsequent working Redis projection must match the exact durable result. This remains contained test-credential refusal, not a simulated network outage, production hook, Spring-proxy transaction or complete cutoff-enforcement claim. The corrected full Account check/JAR/static/docs gate passed56s; unchanged649 unit results were reused, not newly executed. All233 integration cases compiled/discovered but skipped locally, including the eighth Account projection case. Runtime activation and the Account ring mount remain denied/unpublished. + +The same #2945 stage now implements an unwired [membership current-generation projection](../../architecture/microservices/account-service/runtime-and-data.md#membership-generation-snapshot-projection) from the strict existing-only source. It preserves the exact one-tenant version map and independent generation, source version and sequence, retains complete canonical positive event bytes, and allows only a proved original non-admitting zero baseline. Its explicit Coordination client uses the existing registered single-key Lua bytes with one CAS attempt, TTL/poison/ahead rejection, exact Redis readback and fresh Account source readback; it never enrolls or changes SQL authority. The nineteen new codec/store unit cases include a later Redis writer appearing after CAS. Corrected full Account check/JAR and documentation/static gates passed in 2m 6s (102 tasks, 23 executed/79 up-to-date): 649 unit cases executed cleanly; all 232 Account integration cases compiled/discovered but skipped locally without Docker, including seven new real PostgreSQL/Redis cases. Those seven cover actual retained JOIN/LEFT/reactivation, unchanged SQL history and independent counters, repair/retry, source races, poison/TTL and narrow ACL denial; their runner execution remains required. A separate inherited LOGIN fixture race is corrected by isolating the background tick scheduler without changing runtime scheduling or authentication; its focused integration case executed cleanly locally with static checks in 34s. All runtime activation and the Account ring mount remain denied/unpublished. + +Exact #2945 source checkpoint `e90b713fc5a6dd8261b1de97fc209ea82bed6726` [CI37016801825](https://github.com/benhook1013/FireMUD/actions/runs/37016801825) has executed component proof: all twelve fresh-UUID and two current/retained membership PostgreSQL cases passed without skips/failures/errors, independently verified from raw XML. The Game Design association HTML report proves nine clean executed cases, including the deterministic malformed-signature correction; raw Game Design XML is unavailable in that artifact. Aggregate CI finished red on shared dev-demo/Ruff validation, Game Design's separately identified duplicate-tenant fixture, Automation formatting/protobuf serialization and a Game Session LOGIN mock return-type failure under bounded diagnosis. This supersedes the corresponding local execution gaps below, not the ongoing membership projection or live activation requirements. + +The existing #2945 remaining-generation stage now adds an unregistered [existing-only membership source reader](../../architecture/microservices/account-service/runtime-and-data.md#existing-membership-source-readback), not a new runtime authorization path. It preserves the Account UUID/provenance and tenant association fences, refuses ambient transactions, and reads the complete existing snapshot plus the independent membership source version and exact Account issuance fence. It cannot enroll or initialize missing authority. Already proved retained ACTIVE/INACTIVE state and existing fresh/retained never-joined baselines have focused tests; fresh positive JOIN remains unimplemented. The runtime RPC, credential/context/catalog activation and ring mount remain denied/unpublished. + +Corrected local Account full check/JAR and Game Design focused integration compilation/static checks passed in 1m 15s (96 tasks, 23 executed/73 up-to-date), with links, Markdown, formatting, actionlint and diff hygiene clean. Account unit XML proves 630 executed cases without skips/failures/errors, including eight new source-reader cases and one strict producer transaction case. All 225 Account integration cases skipped without Docker, including the expanded twelve-case fresh-UUID and two-case current/retained lifecycle suites. The nine-case Game Design retained association suite also compiled/discovered but skipped. The owned fixture now guarantees that malformed-signature bytes differ from the valid signature; it changes no verifier or production authorization behavior. Missing proof helpers and a generic assertion compilation defect were corrected, not bypassed. These new source and fixture changes still need exact-head runner execution. + +Exact #2945 tenant baseline `ef7e233b7d59eb4237871f48af19c469a9630f0d` [CI37012570963](https://github.com/benhook1013/FireMUD/actions/runs/37012570963) passed Account and executed all seven tenant PostgreSQL/Redis cases with no skips/failures/errors. Root independently parsed and hashed the raw suite XML. Aggregate CI failed on shared Ruff/dev-demo validation, Automation protobuf/configuration-cache serialization and the Game Design signature fixture above; its later missing-suite reports followed that actual test failure. This proves the tenant baseline, not the later membership source batch, live role/cohort delivery, complete cutoff enforcement or activation. + +The remaining-families candidate adds an unwired Account-owned [tenant current-generation projection](../../architecture/microservices/account-service/runtime-and-data.md#tenant-generation-snapshot-projection) from the existing fenced source reader. The tenant wrapper and Account wrapper share only private explicit-client, script-registration and byte-readback mechanics; their typed source and semantic checks remain separate. Tenant refresh cannot enroll an unknown or merely associated tenant, mutate source history, repair poisoned or expiring Redis state, or acknowledge delivered cutoff/admission. A real tenant authority mutation and its post-commit integration are still required before live use. Corrected full Account check/JAR, shared Redis checks and documentation validation passed in 1m 41s (81 tasks, 23 executed/58 up-to-date): 621 Account unit cases executed cleanly, including six tenant codec and thirteen store cases plus the unchanged twelve Account-store regressions. All 223 PostgreSQL cases skipped locally without Docker, including seven new PostgreSQL/Redis cases; every strict workflow selector matches a discovered method. Exact-head runner execution, fresh-image/live role/cohort proof and activation remain open. The earlier owned unit-import failure was corrected; existing protobuf configuration-cache warnings discarded the cache but did not fail the corrected gate. + +Exact #2938 checkpoint `4c61e8938c205e49885cc1f5bde1945e070aca2a` [CI37005842157](https://github.com/benhook1013/FireMUD/actions/runs/37005842157) passed Account, Game Session and TCP jobs. Both seven-case Account PostgreSQL/Redis and issuer Redis suites executed with no skips, failures or errors; the narrow principals' direct `EVAL` denial and all existing issuer cases are included. Fourteen uploaded suite XMLs also establish logout/source12, tenant source12, outbox6, recipient composition1, membership PostgreSQL/mTLS2 and physical mTLS11, issuer producer15 and transport6/3, reset producer6, Account application9 and retained Game Session association17 clean executions. This supersedes the corresponding pending-run requirements below, not their historical local skips. Aggregate CI remains red on separately identified shared Ruff/dev-demo validation, Automation protobuf/configuration-cache serialization and the already-routed Game Design duplicate-tenant fixture. Source delivery/application, complete credential evidence and bundles, bounded downstream enforcement, fresh-image/live cohort and activation remain unproved; the runtime RPC and credential/context/catalog paths stay denied and the Account ring mount unpublished. + 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. @@ -84,7 +138,7 @@ The corrected combined Common Security/Game Logic/Account/Common Platform/Game S Exact preceding-head [CI 36955774965](https://github.com/benhook1013/FireMUD/actions/runs/36955774965) at `8344e6ea134ccbe52a90e4c554b2fee770ad53a7` executed twelve issuer, seventeen retained-association, six reset-producer and nine reset-application PostgreSQL cases without skips/failures/errors, including the pointer regression and both required reset application assertions. Aggregate CI failed: broader TCP reported twelve of seventeen failures with `SESSION_ATTESTATION_INVALID Malformed claim: accountId`; Game Session exceeded twenty minutes after communication setup failures and supplied no broad report, so its detailed cause is not established. The TCP failure was a stale shared validator parsing the current Account UUID as a number. The correction preserves the exact canonical non-nil Account UUID, rejects malformed/numeric/nil/noncanonical identities, and leaves the separate legacy numeric runtime tenant/session/character/instance/pointer and internal-probe semantics intact. This is not a tenant migration or typed workload-context completion. Positive broad runner execution is still required. -Issuer projection/bootstrap/contiguous advancement/immutable duplicate verification, delivery and active-binding revocation remain required implementations. The accepted source-only projection contract does not require a recipient tuple/fence; admission and rebind still do. Missing role-bound Redis registration is a named infrastructure prerequisite, not proof supplied by a local script. Membership RPC, credential/context/catalog activation and the Account ring mount remain denied. Unit 1B is provisional. +Issuer projection/bootstrap/contiguous advancement/immutable duplicate verification have unwired owner-local components; complete authenticated delivery, installation acknowledgment and active-binding revocation remain required implementations. The accepted source-only projection contract does not require a recipient tuple/fence; admission and rebind still do. The [Account issuer reconciliation capture](../../architecture/microservices/account-service/api-contracts.md#issuer-projection-reconciliation-capture) candidate adds a distinct durable operation receipt in V43, rather than relabeling a source mutation or read RPC correlation ID. It binds the exact issuer, authenticated-caller identity, derived projection and stable request with a versioned byte-framed digest, captures source/checkpoint evidence under the issuer row fence, and requires separate committed readback. Exact recovery preserves the original operation and snapshot after later source progress; it never advances authority or installs Redis state. The local identity comparison is not transport authentication, and this capture service has no runtime registration. PostgreSQL execution, authenticated capture transport, current-source revalidation, exact Redis installation/readback and operation-bound acknowledgment remain gates; a historical receipt alone grants neither current authority nor admission. The narrow role-bound registration foundation is partial; deployed ACL/cohort and complete catalog proof remain open. Membership RPC, credential/context/catalog activation and the Account ring mount remain denied. Unit 1B is provisional. ### Earlier checkpoint evidence diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 3d8fe03599..8fe028a652 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -23,7 +23,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | [Authentication](../../architecture/system-architecture-authentication.md) owns target tenant-scoped selector rules; [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) records local handling. Current exact browse ordinals are snapshot-bound, but the pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` selectors are unavailable. Unique bare `worldSlug` resolution is current implementation drift; target behavior prohibits it. V2 enforces tenant-local selector uniqueness and V6 persists generated realm/namespace IDs for retained supported rows, but canonical `{tenantId, realmId}` repository addressing, retained catalog-to-realm mapping, and PostgreSQL cross-tenant proof remain open. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production discovery and scope issuance are implemented locally; positive admission and namespace-qualified roster proof remain unavailable. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target receives retryable `AUTH_UNAVAILABLE`, while unbound private selectors retain the generic hidden projection. The legacy Account grant reader is slug-only and does not prove private gameplay admission; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | -| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V11__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V12__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, V11 child cardinality guard, then V12 child tenant lookup index. The V11/V12 files preserve the child SQL bytes. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup) stays activation-blocked pending exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail migration rather than selecting or deleting a survivor. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | +| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V11__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V12__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, V11 child cardinality guard, V11.1 canonical instance UUID, then V12 child tenant lookup index. The V11/V12 files preserve the child SQL bytes. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup) stays activation-blocked pending exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail migration rather than selecting or deleting a survivor. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources @@ -112,7 +112,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - The target replacement cutover also requires one World-owned durable `cutoverHoldId`/`cutoverHoldFence` after target `ACTIVE` proof. The current implementation has no hold record or coordinated acquire/finalize/readback surface; it does not block source/target termination while the hold is unresolved, bind the hold into the pointer/audit/prepared-execution/source-cleanup/drain-fence transaction, or prove safe abort versus finalization. Expiry and contradictory evidence therefore have no implemented reconciliation proof. - The internal authority locks an existing pointer row, requires the expected `{pointerVersion, catalogRevision}` pair, and issues the existing-row update with both prior values in the database predicate. This owner-local CAS does not enable public control-plane mutation, whose path remains fail-closed; full prepared-cutover CAS/readback is unimplemented. - The internal pointer authority commits pointer state and its audit event together. `ExecutePreparedVersionCutover` currently fails closed before authority/preparation reads or execution marking, so it does not write prepared-execution state after the pointer transaction. Full target atomic retry/reconciliation, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. -- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, V11 visible public-production cardinality guard, and V12 audit-event tenant lookup index. V11/V12 preserve the child SQL bytes. Existing duplicate visible-public rows fail migration rather than choosing or deleting a survivor; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup) stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. +- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, V11 visible public-production cardinality guard, V11.1 canonical instance UUID, and V12 audit-event tenant lookup index. V11/V12 preserve the child SQL bytes. Existing duplicate visible-public rows fail migration rather than choosing or deleting a survivor; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup) stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. - An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; focused local checks and the hosted PostgreSQL pointer-cardinality/WebSocket results are recorded with #2857, while retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) { diff --git a/protos/account/v1/issuer_authority_service.proto b/protos/account/v1/issuer_authority_service.proto index b067b0f7cf..415024b516 100644 --- a/protos/account/v1/issuer_authority_service.proto +++ b/protos/account/v1/issuer_authority_service.proto @@ -5,11 +5,15 @@ package account.v1; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; -// Owner-local source evidence only; this service is not wired for runtime use. +// Owner-local issuer evidence handoffs only; this service is not wired for runtime use. // Caller and response workload identities must both be verified from mTLS. service IssuerAuthorityService { rpc ReadIssuerAuthorityForRuntime(ReadIssuerAuthorityForRuntimeRequest) returns (ReadIssuerAuthorityForRuntimeResponse); + rpc CaptureIssuerProjectionForRuntime(CaptureIssuerProjectionForRuntimeRequest) + returns (CaptureIssuerProjectionForRuntimeResponse); + rpc AcknowledgeIssuerProjectionForRuntime(AcknowledgeIssuerProjectionForRuntimeRequest) + returns (AcknowledgeIssuerProjectionForRuntimeResponse); } message ReadIssuerAuthorityForRuntimeRequest { @@ -38,3 +42,48 @@ message ReadIssuerAuthorityForRuntimeResponse { // Present exactly when the request selected a positive historical sequence. optional string requested_event_canonical_json = 5; } + +message CaptureIssuerProjectionForRuntimeRequest { + string issuer_id = 1; + string request_id = 2; +} + +message CaptureIssuerProjectionForRuntimeResponse { + string schema_version = 1; + string target_namespace = 2; + string operation_id = 3; + string request_id = 4; + string issuer_id = 5; + string caller_workload_identity = 6; + string projection_key = 7; + uint32 request_digest_version = 8; + string request_digest = 9; + IssuerAuthoritySourceSnapshot captured_source_snapshot = 10; +} + +message AcknowledgeIssuerProjectionForRuntimeRequest { + string issuer_id = 1; + string capture_operation_id = 2; + string capture_request_id = 3; + uint32 capture_request_digest_version = 4; + string capture_request_digest = 5; + string projection_key = 6; + string installed_projection_json = 7; +} + +message AcknowledgeIssuerProjectionForRuntimeResponse { + string schema_version = 1; + string target_namespace = 2; + string acknowledgment_id = 3; + string issuer_id = 4; + string caller_workload_identity = 5; + string projection_key = 6; + string capture_operation_id = 7; + string capture_request_id = 8; + uint32 capture_request_digest_version = 9; + string capture_request_digest = 10; + uint32 request_digest_version = 11; + string request_digest = 12; + string installed_projection_json = 13; + string installed_projection_sha256 = 14; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java index bf2147fa79..b1ab316c73 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountJoinDigest.java @@ -1,5 +1,10 @@ package net.firedevops.firemud.accountservice.dto; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -9,6 +14,62 @@ public final class AccountJoinDigest { private AccountJoinDigest() {} + /** + * The only entitlement-availability value from which a v2 policy-bound request digest is made. + * Callers still own the provenance and freshness checks for the value they provide. + */ + public enum EntitlementAvailabilityV2 { + AVAILABLE, + UNAVAILABLE + } + + /** Computes the policy-independent v2 digest of a complete public-production scope preimage. */ + public static String scopeV2(CanonicalJoinScopeV2 scope) { + requireScopeV2(scope); + ByteArrayOutputStream output = v2Header("account-join-scope/v2", "PUBLIC_PRODUCTION"); + appendScopeV2(output, scope); + return hashV2(output.toByteArray()); + } + + /** Computes a policy-independent v2 JOIN intent digest. */ + public static String intentV2( + String requestId, CanonicalJoinScopeV2 scope, String callerBinding) { + requireScopeV2(scope); + ByteArrayOutputStream output = v2Header("account-join-intent/v2", "JOIN"); + appendSegmentV2(output, requireV2Text("requestId", requestId)); + appendSegmentV2(output, requireV2Text("callerBinding", callerBinding)); + appendScopeV2(output, scope); + return hashV2(output.toByteArray()); + } + + /** + * Computes a v2 policy-bound JOIN request digest only for explicitly available policy evidence. + * The caller must establish the evidence's authority, target binding, and freshness. + */ + public static String requestV2( + CanonicalJoinScopeV2 scope, + String callerBinding, + EntitlementAvailabilityV2 availability, + Boolean allowPublicJoin, + Long entitlementVersion) { + requireScopeV2(scope); + if (availability != EntitlementAvailabilityV2.AVAILABLE) { + throw new IllegalArgumentException( + "A v2 JOIN digest requires available entitlement evidence"); + } + if (allowPublicJoin == null || entitlementVersion == null || entitlementVersion <= 0L) { + throw new IllegalArgumentException( + "A v2 JOIN digest requires exact available policy evidence"); + } + ByteArrayOutputStream output = v2Header("account-join-request/v2", "JOIN"); + appendSegmentV2(output, requireV2Text("callerBinding", callerBinding)); + appendScopeV2(output, scope); + appendSegmentV2(output, "AVAILABLE"); + appendSegmentV2(output, allowPublicJoin.toString()); + appendSegmentV2(output, entitlementVersion.toString()); + return hashV2(output.toByteArray()); + } + public static String scope(VerifiedJoinScope scope) { return hash( "scopeDigestVersion=v1\n" @@ -104,4 +165,79 @@ private static String hash(String preimage) { throw new IllegalStateException("SHA-256 is unavailable", ex); } } + + private static ByteArrayOutputStream v2Header(String domain, String operationKind) { + ByteArrayOutputStream output = new ByteArrayOutputStream(512); + appendSegmentV2(output, domain); + appendSegmentV2(output, "2"); + appendSegmentV2(output, operationKind); + return output; + } + + private static void appendScopeV2(ByteArrayOutputStream output, CanonicalJoinScopeV2 scope) { + appendSegmentV2(output, scope.connectScopeId()); + appendSegmentV2(output, scope.accountId().toString()); + appendSegmentV2(output, scope.tenantId().toString()); + appendSegmentV2(output, scope.realmId().toString()); + appendSegmentV2(output, scope.tenantSlug()); + appendSegmentV2(output, scope.worldSlug()); + appendSegmentV2(output, scope.realmSlug()); + appendSegmentV2(output, scope.playableStateNamespaceId().toString()); + appendSegmentV2(output, scope.playableStateScope()); + appendSegmentV2(output, scope.gameInstanceId().toString()); + appendSegmentV2(output, Long.toString(scope.catalogRevision())); + appendSegmentV2(output, Long.toString(scope.pointerVersion())); + appendSegmentV2(output, scope.evaluatedAt()); + appendSegmentV2(output, scope.connectScopeExpiresAt()); + } + + private static void appendSegmentV2(ByteArrayOutputStream output, String value) { + byte[] bytes = encodeUtf8V2(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static String requireV2Text(String field, String value) { + if (value == null || value.isEmpty()) { + throw new IllegalArgumentException(field + " is required"); + } + encodeUtf8V2(value); + return value; + } + + private static byte[] encodeUtf8V2(String value) { + if (value == null) { + throw new IllegalArgumentException("A v2 framed UTF-8 value is required"); + } + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException( + "A v2 framed value must contain well-formed Unicode", exception); + } + } + + private static void requireScopeV2(CanonicalJoinScopeV2 scope) { + if (scope == null) { + throw new IllegalArgumentException("A canonical v2 JOIN scope is required"); + } + } + + private static String hashV2(byte[] preimage) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(preimage)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java new file mode 100644 index 0000000000..7c779d3e43 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.time.DateTimeException; +import java.time.LocalDate; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Immutable, typed v2 JOIN scope preimage data. + * + *

This record is evidence data, not an authentication capability or an authorized producer. + * Constructing it does not establish caller identity, scope ownership, authority, or freshness. + * Those checks remain with the Account caller that resolves and verifies the source evidence. + */ +public record CanonicalJoinScopeV2( + String connectScopeId, + UUID accountId, + UUID tenantId, + UUID realmId, + String tenantSlug, + String worldSlug, + String realmSlug, + UUID playableStateNamespaceId, + String playableStateScope, + UUID gameInstanceId, + long catalogRevision, + long pointerVersion, + String evaluatedAt, + String connectScopeExpiresAt) { + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern UTC_RFC3339 = + Pattern.compile( + "([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.([0-9]+))?Z"); + + public CanonicalJoinScopeV2 { + connectScopeId = requireNonEmptyUtf8("connectScopeId", connectScopeId); + accountId = requireNonNilUuid("accountId", accountId); + tenantId = requireNonNilUuid("tenantId", tenantId); + realmId = requireNonNilUuid("realmId", realmId); + tenantSlug = requireNonEmptyUtf8("tenantSlug", tenantSlug); + worldSlug = requireNonEmptyUtf8("worldSlug", worldSlug); + realmSlug = requireNonEmptyUtf8("realmSlug", realmSlug); + playableStateNamespaceId = + requireNonNilUuid("playableStateNamespaceId", playableStateNamespaceId); + playableStateScope = requirePlayableStateScope(playableStateScope); + gameInstanceId = requireNonNilUuid("gameInstanceId", gameInstanceId); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be a positive BIGINT"); + } + if (pointerVersion <= 0L) { + throw new IllegalArgumentException("pointerVersion must be a positive BIGINT"); + } + evaluatedAt = requireUtcRfc3339("evaluatedAt", evaluatedAt); + connectScopeExpiresAt = requireUtcRfc3339("connectScopeExpiresAt", connectScopeExpiresAt); + } + + private static UUID requireNonNilUuid(String field, UUID value) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return value; + } + + private static String requirePlayableStateScope(String value) { + String exact = requireNonEmptyUtf8("playableStateScope", value); + if (!"SHARED".equals(exact) && !"ISOLATED".equals(exact)) { + throw new IllegalArgumentException("playableStateScope must be SHARED or ISOLATED"); + } + return exact; + } + + private static String requireUtcRfc3339(String field, String value) { + String exact = requireNonEmptyUtf8(field, value); + Matcher matcher = UTC_RFC3339.matcher(exact); + if (!matcher.matches()) { + throw new IllegalArgumentException(field + " must be exact UTC RFC3339 with a Z designator"); + } + try { + LocalDate.of( + Integer.parseInt(matcher.group(1)), + Integer.parseInt(matcher.group(2)), + Integer.parseInt(matcher.group(3))); + } catch (DateTimeException | NumberFormatException exception) { + throw new IllegalArgumentException( + field + " must contain a valid RFC3339 calendar date", exception); + } + int hour = Integer.parseInt(matcher.group(4)); + int minute = Integer.parseInt(matcher.group(5)); + int second = Integer.parseInt(matcher.group(6)); + if (hour > 23 || minute > 59 || second > 60) { + throw new IllegalArgumentException(field + " must contain a valid RFC3339 UTC time"); + } + return exact; + } + + private static String requireNonEmptyUtf8(String field, String value) { + if (value == null || value.isEmpty()) { + throw new IllegalArgumentException(field + " is required"); + } + try { + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException( + field + " must contain well-formed Unicode scalar values", exception); + } + return value; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java index 737251b618..7c24ad3bed 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.entity; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.UUID; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -15,6 +16,10 @@ public class AccountTenantMembership { private Account account; private Long tenantId; + private UUID tenantUuid; + private String tenantProvenanceKind; + private UUID tenantSourceOperationId; + private String tenantProvenanceDigest; private boolean gameplayAdmissionAllowed = true; private String lifecycleState; private long membershipVersion; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerProjectionAcknowledgmentRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerProjectionAcknowledgmentRepository.java new file mode 100644 index 0000000000..7214402c5f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerProjectionAcknowledgmentRepository.java @@ -0,0 +1,374 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.IssuerProjectionInstallationAcknowledgmentDigestV1; +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 Account-owned acknowledgments for installed issuer projections. */ +@Repository +public class AccountIssuerProjectionAcknowledgmentRepository { + private static final String TABLE = "account_issuer_projection_installation_acknowledgments"; + private static final String PROJECTION_KEY_PREFIX = "session:game:auth:issuer-generation:v1:"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final HexFormat HEX = HexFormat.of(); + private static final String SELECT_COLUMNS = + "acknowledgment_id, capture_operation_id, capture_request_id, issuer_id, " + + "caller_workload_identity, projection_key, capture_request_digest_version, " + + "capture_request_digest, request_digest_version, request_digest, " + + "installed_projection_json, installed_projection_sha256"; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The injected transaction-aware DSLContext is a shared internal collaborator.") + public AccountIssuerProjectionAcknowledgmentRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Reads the single acknowledgment bound to one immutable capture operation. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional findByCaptureOperationId(UUID captureOperationId) { + requireOwnerTransaction(); + requireUuid(captureOperationId, "capture operation ID"); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE capture_operation_id = ?", + captureOperationId); + return Optional.ofNullable(row == null ? null : toAcknowledgment(row)); + } + + /** Inserts the one immutable acknowledgment for an exact captured operation. */ + @Transactional(propagation = Propagation.MANDATORY) + public Acknowledgment insert(Acknowledgment acknowledgment) { + requireOwnerTransaction(); + validateAcknowledgment(acknowledgment); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (acknowledgment_id, capture_operation_id, capture_request_id, issuer_id, " + + "caller_workload_identity, projection_key, capture_request_digest_version, " + + "capture_request_digest, request_digest_version, request_digest, " + + "installed_projection_json, installed_projection_sha256) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + acknowledgment.acknowledgmentId(), + acknowledgment.captureOperationId(), + acknowledgment.captureRequestId(), + acknowledgment.issuerId(), + acknowledgment.callerWorkloadIdentity(), + acknowledgment.projectionKey(), + acknowledgment.captureRequestDigestVersion(), + decodeDigest(acknowledgment.captureRequestDigest(), "capture request digest"), + acknowledgment.requestDigestVersion(), + decodeDigest(acknowledgment.requestDigest(), "acknowledgment request digest"), + acknowledgment.installedProjectionUtf8(), + acknowledgment.installedProjectionSha256()); + if (inserted != 1) { + throw new IllegalStateException( + "Issuer projection installation acknowledgment was not inserted"); + } + return acknowledgment; + } + + private Acknowledgment toAcknowledgment(Record row) { + return new Acknowledgment( + requiredUuid(row.get("acknowledgment_id", UUID.class), "acknowledgment ID"), + requiredUuid(row.get("capture_operation_id", UUID.class), "capture operation ID"), + requiredUuid(row.get("capture_request_id", UUID.class), "capture request ID"), + requiredText(row.get("issuer_id", String.class), "issuer ID", 512), + requiredText( + row.get("caller_workload_identity", String.class), "caller workload identity", 512), + requiredText(row.get("projection_key", String.class), "projection key", 2048), + requiredPositive( + row.get("capture_request_digest_version", Integer.class), + "capture request digest version"), + encodeDigest(row.get("capture_request_digest", byte[].class), "capture request digest"), + requiredPositive( + row.get("request_digest_version", Integer.class), "acknowledgment digest version"), + encodeDigest(row.get("request_digest", byte[].class), "acknowledgment request digest"), + requiredBytes(row.get("installed_projection_json", byte[].class), "installed projection"), + requiredBytes( + row.get("installed_projection_sha256", byte[].class), "installed projection SHA-256")); + } + + private static void validateAcknowledgment(Acknowledgment acknowledgment) { + Objects.requireNonNull(acknowledgment, "issuer projection acknowledgment is required"); + // The value object's constructor performs the complete binding and byte-hash validation. + new Acknowledgment( + acknowledgment.acknowledgmentId(), + acknowledgment.captureOperationId(), + acknowledgment.captureRequestId(), + acknowledgment.issuerId(), + acknowledgment.callerWorkloadIdentity(), + acknowledgment.projectionKey(), + acknowledgment.captureRequestDigestVersion(), + acknowledgment.captureRequestDigest(), + acknowledgment.requestDigestVersion(), + acknowledgment.requestDigest(), + acknowledgment.installedProjectionUtf8(), + acknowledgment.installedProjectionSha256()); + } + + private void requireOwnerTransaction() { + if (dsl == null) { + throw new IllegalStateException( + "Issuer projection acknowledgment storage requires a DSLContext"); + } + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Issuer projection acknowledgment storage requires an active Account transaction"); + } + } + + private static UUID requiredUuid(UUID value, String field) { + requireUuid(value, field); + return value; + } + + private static void requireUuid(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + } + + private static int requiredPositive(Integer value, String field) { + if (value == null || value <= 0) { + throw new IllegalStateException("Stored issuer acknowledgment " + field + " is invalid"); + } + return value; + } + + private static String requiredText(String value, String field, int maximumLength) { + requireText(value, field, maximumLength); + return value; + } + + private static void requireText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + field + " must contain 1 to " + maximumLength + " characters"); + } + } + + private static byte[] requiredBytes(byte[] value, String field) { + if (value == null || value.length == 0) { + throw new IllegalStateException("Stored issuer acknowledgment " + field + " is missing"); + } + return value.clone(); + } + + private static byte[] decodeDigest(String value, String field) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException(field + " must be lowercase SHA-256 hexadecimal"); + } + return HEX.parseHex(value); + } + + private static String encodeDigest(byte[] value, String field) { + if (value == null || value.length != 32) { + throw new IllegalStateException("Stored issuer acknowledgment " + field + " is invalid"); + } + return HEX.formatHex(value); + } + + /** Complete immutable evidence retained for one successful issuer projection installation. */ + public record Acknowledgment( + UUID acknowledgmentId, + UUID captureOperationId, + UUID captureRequestId, + String issuerId, + String callerWorkloadIdentity, + String projectionKey, + int captureRequestDigestVersion, + String captureRequestDigest, + int requestDigestVersion, + String requestDigest, + byte[] installedProjectionUtf8, + byte[] installedProjectionSha256) { + public static final int REQUEST_DIGEST_VERSION = + IssuerProjectionInstallationAcknowledgmentDigestV1.VERSION; + public static final int MAX_INSTALLED_PROJECTION_UTF8_BYTES = + IssuerProjectionInstallationAcknowledgmentDigestV1.MAX_INSTALLED_PROJECTION_UTF8_BYTES; + + public Acknowledgment { + Objects.requireNonNull( + installedProjectionUtf8, "installed projection JSON bytes are required"); + Objects.requireNonNull(installedProjectionSha256, "installed projection SHA-256 is required"); + installedProjectionUtf8 = installedProjectionUtf8.clone(); + installedProjectionSha256 = installedProjectionSha256.clone(); + validate( + acknowledgmentId, + captureOperationId, + captureRequestId, + issuerId, + callerWorkloadIdentity, + projectionKey, + captureRequestDigestVersion, + captureRequestDigest, + requestDigestVersion, + requestDigest, + installedProjectionUtf8, + installedProjectionSha256); + } + + @Override + public byte[] installedProjectionUtf8() { + return installedProjectionUtf8.clone(); + } + + @Override + public byte[] installedProjectionSha256() { + return installedProjectionSha256.clone(); + } + + /** Computes the exact ten-field byte-framed acknowledgment request digest. */ + public static String requestDigestFor( + String issuerId, + String callerWorkloadIdentity, + String projectionKey, + UUID captureOperationId, + UUID captureRequestId, + int captureRequestDigestVersion, + String captureRequestDigest, + String installedProjectionJson) { + return IssuerProjectionInstallationAcknowledgmentDigestV1.digest( + issuerId, + callerWorkloadIdentity, + projectionKey, + captureOperationId, + captureRequestId, + captureRequestDigestVersion, + captureRequestDigest, + installedProjectionJson); + } + + private static void validate( + UUID acknowledgmentId, + UUID captureOperationId, + UUID captureRequestId, + String issuerId, + String callerWorkloadIdentity, + String projectionKey, + int captureRequestDigestVersion, + String captureRequestDigest, + int requestDigestVersion, + String requestDigest, + byte[] installedProjectionUtf8, + byte[] installedProjectionSha256) { + requireUuid(acknowledgmentId, "acknowledgment ID"); + requireRequestBindings( + issuerId, + callerWorkloadIdentity, + projectionKey, + captureOperationId, + captureRequestId, + captureRequestDigestVersion, + captureRequestDigest); + if (requestDigestVersion != REQUEST_DIGEST_VERSION + || requestDigest == null + || !requestDigest.matches("[0-9a-f]{64}") + || installedProjectionUtf8.length == 0 + || installedProjectionUtf8.length > MAX_INSTALLED_PROJECTION_UTF8_BYTES + || installedProjectionSha256.length != 32) { + throw new IllegalArgumentException("Issuer projection acknowledgment is malformed"); + } + String projectionJson = decodeUtf8(installedProjectionUtf8); + if (!MessageDigest.isEqual(sha256(installedProjectionUtf8), installedProjectionSha256) + || !requestDigest.equals( + requestDigestFor( + issuerId, + callerWorkloadIdentity, + projectionKey, + captureOperationId, + captureRequestId, + captureRequestDigestVersion, + captureRequestDigest, + projectionJson))) { + throw new IllegalArgumentException( + "Issuer projection acknowledgment digest does not bind its original result"); + } + } + + private static void requireRequestBindings( + String issuerId, + String callerWorkloadIdentity, + String projectionKey, + UUID captureOperationId, + UUID captureRequestId, + int captureRequestDigestVersion, + String captureRequestDigest) { + requireText(issuerId, "issuer ID", 512); + requireText(callerWorkloadIdentity, "caller workload identity", 512); + requireText(projectionKey, "projection key", 2048); + requireUuid(captureOperationId, "capture operation ID"); + requireUuid(captureRequestId, "capture request ID"); + if (!projectionKey.equals(PROJECTION_KEY_PREFIX + issuerId) + || captureRequestDigestVersion != 1 + || captureRequestDigest == null + || !captureRequestDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "Issuer projection acknowledgment capture binding is malformed"); + } + } + + private static byte[] encodeUtf8(String value) { + if (value == null) { + throw new IllegalArgumentException("Installed projection JSON is required"); + } + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] result = new byte[encoded.remaining()]; + encoded.get(result); + return result; + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException( + "Installed projection JSON is not valid Unicode", malformed); + } + } + + private static String decodeUtf8(byte[] value) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException( + "Installed projection JSON is not valid UTF-8", malformed); + } + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerProjectionReconciliationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerProjectionReconciliationRepository.java new file mode 100644 index 0000000000..04941ebeca --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerProjectionReconciliationRepository.java @@ -0,0 +1,315 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.account.authority.IssuerProjectionReconciliationRequestDigestV1; +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 Account-owned issuer projection reconciliation capture receipts. */ +@Repository +public class AccountIssuerProjectionReconciliationRepository { + private static final String TABLE = "account_issuer_projection_reconciliation_receipts"; + private static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:issuer/"; + private static final String PROJECTION_KEY_PREFIX = "session:game:auth:issuer-generation:v1:"; + private static final HexFormat HEX = HexFormat.of(); + private static final String SELECT_COLUMNS = + "operation_id, request_id, issuer_id, caller_workload_identity, projection_key, " + + "request_digest_version, request_digest, issuer_auth_generation, source_version, " + + "outbox_stream_key, outbox_sequence, event_outbox_sequence, event_id, event_digest, event_payload"; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The injected transaction-aware DSLContext is a shared internal collaborator.") + public AccountIssuerProjectionReconciliationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Reads one immutable receipt by its stable exact issuer/request identity. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional findByIssuerAndRequestId(String issuerId, UUID requestId) { + requireOwnerTransaction(); + requireText(issuerId, "issuer ID", 512); + requireRequestId(requestId); + Record row = + dsl.fetchOne( + "SELECT " + + SELECT_COLUMNS + + " FROM " + + TABLE + + " WHERE issuer_id = ? AND request_id = ?", + issuerId, + requestId); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** Inserts the one immutable receipt for an issuer/request identity. */ + @Transactional(propagation = Propagation.MANDATORY) + public Receipt insert(Receipt receipt) { + requireOwnerTransaction(); + validateReceipt(receipt); + IssuerGenerationAuthorityEvent event = receipt.capturedSource().latestEvent().orElse(null); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (operation_id, request_id, issuer_id, caller_workload_identity, projection_key, " + + "request_digest_version, request_digest, issuer_auth_generation, source_version, " + + "outbox_stream_key, outbox_sequence, event_outbox_sequence, event_id, event_digest, event_payload) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.operationId(), + receipt.requestId(), + receipt.issuerId(), + receipt.callerWorkloadIdentity(), + receipt.projectionKey(), + receipt.requestDigestVersion(), + decodeDigest(receipt.requestDigest()), + receipt.capturedSource().issuerAuthGeneration(), + receipt.capturedSource().sourceVersion(), + receipt.capturedSource().outboxStreamKey(), + receipt.capturedSource().outboxSequence(), + event == null ? null : receipt.capturedSource().outboxSequence(), + event == null ? null : event.eventId(), + event == null ? null : event.eventDigest(), + event == null ? null : event.canonicalJsonUtf8()); + if (inserted != 1) { + throw new IllegalStateException("Issuer projection reconciliation receipt was not inserted"); + } + return receipt; + } + + private Receipt toReceipt(Record row) { + UUID operationId = requiredUuid(row.get("operation_id", UUID.class), "operation ID"); + UUID requestId = requiredUuid(row.get("request_id", UUID.class), "request ID"); + String issuerId = requiredText(row.get("issuer_id", String.class), "issuer ID", 512); + String streamKey = requiredText(row.get("outbox_stream_key", String.class), "stream key", 2048); + long sequence = requiredNonnegative(row.get("outbox_sequence", Long.class), "outbox sequence"); + Long eventSequence = row.get("event_outbox_sequence", Long.class); + long generation = + requiredPositive(row.get("issuer_auth_generation", Long.class), "issuer generation"); + long sourceVersion = requiredPositive(row.get("source_version", Long.class), "source version"); + String eventId = row.get("event_id", String.class); + String eventDigest = row.get("event_digest", String.class); + byte[] payload = row.get("event_payload", byte[].class); + Optional latestEvent; + if (sequence == 0L) { + if (eventSequence != null || eventId != null || eventDigest != null || payload != null) { + throw new IllegalStateException("Zero-sequence issuer receipt contains event evidence"); + } + latestEvent = Optional.empty(); + } else { + if (eventSequence == null + || eventSequence != sequence + || eventId == null + || eventDigest == null + || payload == null + || payload.length == 0) { + throw new IllegalStateException( + "Positive issuer receipt is missing complete event evidence"); + } + IssuerGenerationAuthorityEvent event = + IssuerGenerationAuthorityEventV1Codec.verify(new String(payload, StandardCharsets.UTF_8)); + if (!MessageDigest.isEqual(payload, event.canonicalJsonUtf8()) + || !eventId.equals(event.eventId()) + || !eventDigest.equals(event.eventDigest())) { + throw new IllegalStateException( + "Issuer receipt event bytes contradict stored event fields"); + } + latestEvent = Optional.of(event); + } + IssuerAuthoritySnapshot source = + new IssuerAuthoritySnapshot( + issuerId, generation, sourceVersion, streamKey, sequence, latestEvent); + return new Receipt( + operationId, + requestId, + issuerId, + requiredText( + row.get("caller_workload_identity", String.class), "caller workload identity", 512), + requiredText(row.get("projection_key", String.class), "projection key", 2048), + requiredPositive( + row.get("request_digest_version", Integer.class), "request digest version"), + encodeDigest(row.get("request_digest", byte[].class)), + source); + } + + private static void validateReceipt(Receipt receipt) { + Objects.requireNonNull(receipt, "issuer projection reconciliation receipt is required"); + validateReceipt( + receipt.operationId(), + receipt.requestId(), + receipt.issuerId(), + receipt.callerWorkloadIdentity(), + receipt.projectionKey(), + receipt.requestDigestVersion(), + receipt.requestDigest(), + receipt.capturedSource()); + } + + private static void validateReceipt( + UUID operationId, + UUID requestId, + String issuerId, + String callerWorkloadIdentity, + String projectionKey, + int requestDigestVersion, + String requestDigest, + IssuerAuthoritySnapshot capturedSource) { + requireRequestId(operationId); + requireRequestId(requestId); + requireText(issuerId, "issuer ID", 512); + requireText(callerWorkloadIdentity, "caller workload identity", 512); + requireText(projectionKey, "projection key", 2048); + Objects.requireNonNull(capturedSource, "captured issuer source is required"); + if (requestDigest == null + || requestDigestVersion != 1 + || !projectionKey.equals(PROJECTION_KEY_PREFIX + issuerId) + || !issuerId.equals(capturedSource.issuerId()) + || !requestDigest.equals( + Receipt.requestDigestFor(issuerId, callerWorkloadIdentity, projectionKey, requestId))) { + throw new IllegalArgumentException("Issuer projection reconciliation receipt is malformed"); + } + decodeDigest(requestDigest); + IssuerGenerationAuthorityEvent event = capturedSource.latestEvent().orElse(null); + if ((capturedSource.outboxSequence() == 0L) != (event == null)) { + throw new IllegalArgumentException("Issuer receipt checkpoint and event evidence disagree"); + } + if (event != null + && (!capturedSource.outboxStreamKey().equals(event.outboxStreamKey()) + || !issuerId.equals(event.issuerId()) + || !Long.toString(capturedSource.outboxSequence()).equals(event.outboxSequence()))) { + throw new IllegalArgumentException("Issuer receipt event does not match its checkpoint"); + } + } + + private void requireOwnerTransaction() { + if (dsl == null) { + throw new IllegalStateException("Issuer reconciliation storage requires a DSLContext"); + } + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Issuer projection reconciliation storage requires an active Account transaction"); + } + } + + private static void requireRequestId(UUID value) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("A canonical non-nil reconciliation UUID is required"); + } + } + + private static UUID requiredUuid(UUID value, String field) { + requireRequestId(value); + return value; + } + + private static long requiredPositive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalStateException("Issuer reconciliation receipt " + field + " is invalid"); + } + return value; + } + + private static int requiredPositive(Integer value, String field) { + if (value == null || value <= 0) { + throw new IllegalStateException("Issuer reconciliation receipt " + field + " is invalid"); + } + return value; + } + + private static long requiredNonnegative(Long value, String field) { + if (value == null || value < 0L) { + throw new IllegalStateException("Issuer reconciliation receipt " + field + " is invalid"); + } + return value; + } + + private static String requiredText(String value, String field, int maximumLength) { + requireText(value, field, maximumLength); + return value; + } + + private static void requireText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + "Issuer reconciliation receipt " + + field + + " must contain 1 to " + + maximumLength + + " characters"); + } + } + + private static byte[] decodeDigest(String value) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Issuer reconciliation request digest is malformed"); + } + return HEX.parseHex(value); + } + + private static String encodeDigest(byte[] value) { + if (value == null || value.length != 32) { + throw new IllegalStateException("Issuer reconciliation request digest is missing or invalid"); + } + return HEX.formatHex(value); + } + + /** + * Complete immutable capture receipt; a receipt does not claim current authority after advance. + */ + public record Receipt( + UUID operationId, + UUID requestId, + String issuerId, + String callerWorkloadIdentity, + String projectionKey, + int requestDigestVersion, + String requestDigest, + IssuerAuthoritySnapshot capturedSource) { + public Receipt { + validateReceipt( + operationId, + requestId, + issuerId, + callerWorkloadIdentity, + projectionKey, + requestDigestVersion, + requestDigest, + capturedSource); + } + + /** + * Computes the exact fixed six-field byte-framed request digest defined by the Account + * contract. + */ + public static String requestDigestFor( + String issuerId, String callerWorkloadIdentity, String projectionKey, UUID requestId) { + return IssuerProjectionReconciliationRequestDigestV1.digest( + issuerId, callerWorkloadIdentity, projectionKey, requestId); + } + } + + /** The stable issuer/request key already exists with different immutable bindings. */ + public static final class IdempotencyConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public IdempotencyConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index 758d89b331..7655e5404f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -5,21 +5,43 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; +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.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; @Repository @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class AccountTenantMembershipRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String UNBRIDGED_RETAINED = "UNBRIDGED_RETAINED"; + private final DSLContext dsl; + private final AccountRepository accountRepository; + private final AccountTenantIdentityResolver tenantIdentityResolver; + private final FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository; - public AccountTenantMembershipRepository(DSLContext dsl) { + public AccountTenantMembershipRepository( + DSLContext dsl, + AccountRepository accountRepository, + AccountTenantIdentityResolver tenantIdentityResolver, + FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository) { this.dsl = dsl; + this.accountRepository = accountRepository; + this.tenantIdentityResolver = tenantIdentityResolver; + this.freshTenantIdentityAssociationRepository = freshTenantIdentityAssociationRepository; } public Optional findByAccountIdAndTenantId( @@ -34,6 +56,136 @@ public Optional findByAccountIdAndTenantId( .fetchOne(this::toEntity)); } + /** + * Reads one canonical membership by UUID identity under the Account owner transaction. The + * returned row includes its exact stored tenant source tuple; neither UUID path manufactures a + * numeric tenant selector. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCanonicalMembershipForUpdate( + UUID accountUuid, UUID tenantUuid) { + requireCanonicalOwnerTransaction(); + Account account = lockAccountByUuid(accountUuid); + requireCanonicalUuid(tenantUuid, "tenant UUID"); + Record row = + dsl.fetchOne( + "SELECT m.id, m.account_id, m.tenant_id, m.tenant_uuid, " + + "m.tenant_provenance_kind, m.tenant_source_operation_id, " + + "m.tenant_provenance_digest, m.gameplay_admission_allowed, " + + "m.lifecycle_state, m.membership_version, " + + "m.membership_authority_generation, m.authority_provenance " + + "FROM account_tenant_membership m " + + "WHERE m.account_id = ? AND m.tenant_uuid = ? FOR UPDATE", + account.getId(), + tenantUuid); + if (row == null) { + return Optional.empty(); + } + AccountTenantMembership membership = toCanonicalEntity(row, account); + requireVerifiedTenantProvenance(tenantUuid, provenanceFromMembership(membership)); + return Optional.of(membership); + } + + /** + * Writes a UUID-qualified membership only after exact Account and immutable tenant source + * readback in the surrounding Account transaction. Fresh rows persist no legacy tenant ID; + * approved retained rows preserve the supplied private bridge key. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountTenantMembership saveCanonical( + AccountTenantMembership entity, + UUID accountUuid, + UUID tenantUuid, + VerifiedTenantProvenance expectedProvenance) { + requireCanonicalOwnerTransaction(); + if (entity == null + || entity.getAccount() == null + || entity.getAccount().getId() == null + || entity.getAccount().getId() <= 0L) { + throw new IllegalArgumentException("A persisted Account row is required for membership"); + } + Account account = lockAccount(entity.getAccount().getId(), accountUuid); + requireCanonicalUuid(tenantUuid, "tenant UUID"); + VerifiedTenantProvenance provenance = + requireVerifiedTenantProvenance(tenantUuid, expectedProvenance); + if (!Objects.equals(entity.getTenantId(), provenance.legacyTenantId())) { + throw new IllegalArgumentException( + "Membership legacy tenant key differs from verified canonical provenance"); + } + + long accountId = account.getId(); + if (entity.getId() == null) { + Long membershipId = + dsl.resultQuery( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, " + + "gameplay_admission_allowed, lifecycle_state, membership_version, " + + "membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + accountId, + provenance.legacyTenantId(), + tenantUuid, + provenance.kind().name(), + provenance.sourceOperationId(), + provenance.digest(), + entity.isGameplayAdmissionAllowed(), + entity.getLifecycleState(), + entity.getMembershipVersion(), + entity.getMembershipAuthorityGeneration(), + entity.getAuthorityProvenance()) + .fetchOne(0, Long.class); + if (membershipId == null || membershipId <= 0L) { + throw new IllegalStateException( + "Canonical Account membership insert did not return its ID"); + } + entity.setId(membershipId); + } else { + requireExistingMembershipMayBindOrUpdate( + entity.getId(), accountId, entity.getTenantId(), tenantUuid, provenance); + int updated = + dsl.execute( + "UPDATE account_tenant_membership SET tenant_id = ?, tenant_uuid = ?, " + + "tenant_provenance_kind = ?, tenant_source_operation_id = ?, " + + "tenant_provenance_digest = ?, gameplay_admission_allowed = ?, " + + "lifecycle_state = ?, membership_version = ?, " + + "membership_authority_generation = ?, authority_provenance = ? " + + "WHERE id = ? AND account_id = ?", + provenance.legacyTenantId(), + tenantUuid, + provenance.kind().name(), + provenance.sourceOperationId(), + provenance.digest(), + entity.isGameplayAdmissionAllowed(), + entity.getLifecycleState(), + entity.getMembershipVersion(), + entity.getMembershipAuthorityGeneration(), + entity.getAuthorityProvenance(), + entity.getId(), + accountId); + if (updated != 1) { + throw JooqAccountRepositorySupport.staleWrite("account_tenant_membership", entity.getId()); + } + } + + AccountTenantMembership readback = + findCanonicalMembershipForUpdate(accountUuid, tenantUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical Account membership was not readable after its write")); + if (!sameMembershipState(entity, readback) + || !Objects.equals(entity.getId(), readback.getId()) + || !Objects.equals(entity.getTenantId(), readback.getTenantId()) + || !tenantUuid.equals(readback.getTenantUuid()) + || !provenanceFromMembership(readback).equals(provenance)) { + throw new IllegalStateException( + "Canonical Account membership readback differs from its write"); + } + copyIdentity(readback, entity); + return readback; + } + /** Reads and locks the exact membership row for a JOIN reconciliation proof. */ public Optional findJoinProofForUpdate(long accountId, long tenantId) { return dsl.select( @@ -82,13 +234,22 @@ public boolean existsByAccountId(Long accountId) { public List findByAccountId(Long accountId) { return baseSelect() - .where(ACCOUNT_TENANT_MEMBERSHIP.ACCOUNT_ID.eq(accountId)) + .where( + ACCOUNT_TENANT_MEMBERSHIP + .ACCOUNT_ID + .eq(accountId) + .and(ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID.isNotNull())) .orderBy(ACCOUNT_TENANT_MEMBERSHIP.ID.asc()) .fetch(this::toEntity); } public AccountTenantMembership save(AccountTenantMembership entity) { Long accountId = entity.getAccount() == null ? null : entity.getAccount().getId(); + if (entity.getTenantId() == null + || "FRESH_GAME_DESIGN".equals(entity.getTenantProvenanceKind())) { + throw new IllegalArgumentException( + "Numeric Account membership writes require a retained tenant selector"); + } if (entity.getId() == null) { Long id = dsl.insertInto(ACCOUNT_TENANT_MEMBERSHIP) @@ -162,6 +323,17 @@ private org.jooq.SelectOnConditionStep baseSelect() { ACCOUNT_TENANT_MEMBERSHIP.ID, ACCOUNT_TENANT_MEMBERSHIP.ACCOUNT_ID, ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID, + org.jooq.impl.DSL.field( + org.jooq.impl.DSL.name("account_tenant_membership", "tenant_uuid"), UUID.class), + org.jooq.impl.DSL.field( + org.jooq.impl.DSL.name("account_tenant_membership", "tenant_provenance_kind"), + String.class), + org.jooq.impl.DSL.field( + org.jooq.impl.DSL.name("account_tenant_membership", "tenant_source_operation_id"), + UUID.class), + org.jooq.impl.DSL.field( + org.jooq.impl.DSL.name("account_tenant_membership", "tenant_provenance_digest"), + String.class), ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED, ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE, ACCOUNT_TENANT_MEMBERSHIP.MEMBERSHIP_VERSION, @@ -192,6 +364,10 @@ private AccountTenantMembership toEntity(Record record) { record.get(ACCOUNTS.EMAIL_VERIFIED), record.get(ACCOUNTS.LOGIN_AUTH_MODES))); membership.setTenantId(record.get(ACCOUNT_TENANT_MEMBERSHIP.TENANT_ID)); + membership.setTenantUuid(record.get("tenant_uuid", UUID.class)); + membership.setTenantProvenanceKind(record.get("tenant_provenance_kind", String.class)); + membership.setTenantSourceOperationId(record.get("tenant_source_operation_id", UUID.class)); + membership.setTenantProvenanceDigest(record.get("tenant_provenance_digest", String.class)); membership.setGameplayAdmissionAllowed( Boolean.TRUE.equals(record.get(ACCOUNT_TENANT_MEMBERSHIP.GAMEPLAY_ADMISSION_ALLOWED))); membership.setLifecycleState(record.get(ACCOUNT_TENANT_MEMBERSHIP.LIFECYCLE_STATE)); @@ -202,6 +378,180 @@ private AccountTenantMembership toEntity(Record record) { return membership; } + private Account lockAccountByUuid(UUID accountUuid) { + requireCanonicalUuid(accountUuid, "Account UUID"); + Account indexed = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Canonical Account identity is absent")); + Account locked = lockAccount(indexed.getId(), accountUuid); + if (!Objects.equals(indexed.getId(), locked.getId()) + || indexed.getAccountUuidProvenance() != locked.getAccountUuidProvenance() + || !Objects.equals( + indexed.getAccountUuidSourceNumericId(), locked.getAccountUuidSourceNumericId())) { + throw new IllegalStateException("Canonical Account identity changed at its row fence"); + } + return locked; + } + + private Account lockAccount(long accountId, UUID expectedAccountUuid) { + requireCanonicalUuid(expectedAccountUuid, "Account UUID"); + Account account = + accountRepository + .findByIdForUpdate(accountId) + .orElseThrow(() -> new IllegalStateException("Canonical Account row is absent")); + if (!expectedAccountUuid.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() == null + || !Objects.equals(account.getAccountUuidSourceNumericId(), account.getId())) { + throw new IllegalStateException( + "Canonical Account UUID does not exactly identify its persisted private row"); + } + return account; + } + + private VerifiedTenantProvenance requireVerifiedTenantProvenance( + UUID tenantUuid, VerifiedTenantProvenance expected) { + if (expected == null) { + throw new IllegalArgumentException("Verified canonical tenant provenance is required"); + } + VerifiedTenantProvenance actual; + if (expected.kind() == TenantProvenanceKind.APPROVED_RETAINED) { + var association = tenantIdentityResolver.resolve(tenantUuid); + actual = + new VerifiedTenantProvenance( + association.legacyTenantId(), + TenantProvenanceKind.APPROVED_RETAINED, + association.operationId(), + association.manifestDigest()); + } else if (expected.kind() == TenantProvenanceKind.FRESH_GAME_DESIGN) { + FreshTenantCreationEvidence association = + freshTenantIdentityAssociationRepository + .read(tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Fresh Account tenant association is absent")); + actual = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + association.operationId(), + association.evidenceDigest()); + } else { + throw new IllegalArgumentException("Canonical membership requires an approved or fresh UUID"); + } + if (!actual.equals(expected)) { + throw new IllegalStateException( + "Supplied canonical tenant provenance differs from immutable source readback"); + } + return actual; + } + + private void requireExistingMembershipMayBindOrUpdate( + long membershipId, + long accountId, + Long legacyTenantId, + UUID tenantUuid, + VerifiedTenantProvenance provenance) { + Record existing = + dsl.fetchOne( + "SELECT tenant_id, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest " + + "FROM account_tenant_membership " + + "WHERE id = ? AND account_id = ? FOR UPDATE", + membershipId, + accountId); + if (existing == null + || !Objects.equals(existing.get("tenant_id", Long.class), legacyTenantId)) { + throw JooqAccountRepositorySupport.staleWrite("account_tenant_membership", membershipId); + } + String kind = existing.get("tenant_provenance_kind", String.class); + if (UNBRIDGED_RETAINED.equals(kind)) { + if (provenance.kind() != TenantProvenanceKind.APPROVED_RETAINED + || existing.get("tenant_uuid", UUID.class) != null + || existing.get("tenant_source_operation_id", UUID.class) != null + || existing.get("tenant_provenance_digest", String.class) != null) { + throw new IllegalStateException( + "Only an exact approved retained association may bind an unbridged membership"); + } + return; + } + if (!tenantUuid.equals(existing.get("tenant_uuid", UUID.class)) + || !provenance.kind().name().equals(kind) + || !provenance + .sourceOperationId() + .equals(existing.get("tenant_source_operation_id", UUID.class)) + || !provenance.digest().equals(existing.get("tenant_provenance_digest", String.class))) { + throw new IllegalStateException( + "Canonical Account membership identity differs from its immutable stored provenance"); + } + } + + private AccountTenantMembership toCanonicalEntity(Record record, Account account) { + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setId(record.get("id", Long.class)); + membership.setAccount(account); + membership.setTenantId(record.get("tenant_id", Long.class)); + membership.setTenantUuid(record.get("tenant_uuid", UUID.class)); + membership.setTenantProvenanceKind(record.get("tenant_provenance_kind", String.class)); + membership.setTenantSourceOperationId(record.get("tenant_source_operation_id", UUID.class)); + membership.setTenantProvenanceDigest(record.get("tenant_provenance_digest", String.class)); + membership.setGameplayAdmissionAllowed( + Boolean.TRUE.equals(record.get("gameplay_admission_allowed", Boolean.class))); + membership.setLifecycleState(record.get("lifecycle_state", String.class)); + membership.setMembershipVersion(record.get("membership_version", Long.class)); + membership.setMembershipAuthorityGeneration( + record.get("membership_authority_generation", Long.class)); + membership.setAuthorityProvenance(record.get("authority_provenance", String.class)); + return membership; + } + + private VerifiedTenantProvenance provenanceFromMembership(AccountTenantMembership membership) { + if (membership.getTenantProvenanceKind() == null + || UNBRIDGED_RETAINED.equals(membership.getTenantProvenanceKind())) { + throw new IllegalStateException( + "Canonical Account membership lacks authenticated tenant provenance"); + } + try { + return new VerifiedTenantProvenance( + membership.getTenantId(), + TenantProvenanceKind.valueOf(membership.getTenantProvenanceKind()), + membership.getTenantSourceOperationId(), + membership.getTenantProvenanceDigest()); + } catch (IllegalArgumentException ex) { + throw new IllegalStateException("Canonical Account membership provenance is malformed", ex); + } + } + + private boolean sameMembershipState( + AccountTenantMembership expected, AccountTenantMembership actual) { + return Objects.equals(expected.getAccount().getId(), actual.getAccount().getId()) + && expected.isGameplayAdmissionAllowed() == actual.isGameplayAdmissionAllowed() + && Objects.equals(expected.getLifecycleState(), actual.getLifecycleState()) + && expected.getMembershipVersion() == actual.getMembershipVersion() + && expected.getMembershipAuthorityGeneration() == actual.getMembershipAuthorityGeneration() + && Objects.equals(expected.getAuthorityProvenance(), actual.getAuthorityProvenance()); + } + + private void copyIdentity(AccountTenantMembership source, AccountTenantMembership target) { + target.setTenantId(source.getTenantId()); + target.setTenantUuid(source.getTenantUuid()); + target.setTenantProvenanceKind(source.getTenantProvenanceKind()); + target.setTenantSourceOperationId(source.getTenantSourceOperationId()); + target.setTenantProvenanceDigest(source.getTenantProvenanceDigest()); + } + + private void requireCanonicalUuid(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil canonical UUID"); + } + } + + private void requireCanonicalOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical Account membership access requires an active owner transaction"); + } + } + public record JoinMembershipProof( long membershipId, long accountId, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepository.java index ec4e2c3245..1bfa8ddd42 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepository.java @@ -7,14 +7,20 @@ import java.util.Comparator; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; 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; /** * Persists the current, Account-owned role snapshot for one tenant membership. @@ -29,6 +35,8 @@ justification = "Injected DSLContext is an internal Spring collaborator.") public class AccountTenantMembershipRoleSnapshotRepository { private static final int MAX_ROLE_IDENTIFIER_LENGTH = 128; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String UNBRIDGED_RETAINED = "UNBRIDGED_RETAINED"; private static final String SNAPSHOT_TABLE = "account_tenant_membership_role_snapshots"; private static final String ROLE_TABLE = "account_tenant_membership_role_snapshot_roles"; private static final Comparator ROLE_IDENTIFIER_BYTE_COMPARATOR = @@ -55,24 +63,8 @@ public Optional findForUpdate( validatePositive(membershipId, "membership ID"); validatePositive(expectedMembershipVersion, "membership version"); - Record membership = - dsl.fetchOne( - "SELECT id, account_id, tenant_id, membership_version " - + "FROM account_tenant_membership " - + "WHERE id = ? AND account_id = ? AND tenant_id = ? FOR UPDATE", - membershipId, - accountId, - tenantId); - if (membership == null) { - throw new IllegalStateException("Account membership identity is missing or mismatched"); - } - requireExactPositive(membership.get("id", Long.class), membershipId, "membership ID"); - requireExactPositive(membership.get("account_id", Long.class), accountId, "account ID"); - requireExactPositive(membership.get("tenant_id", Long.class), tenantId, "tenant ID"); - requireExactPositive( - membership.get("membership_version", Long.class), - expectedMembershipVersion, - "membership version"); + MembershipIdentity identity = + lockRetainedMembership(accountId, tenantId, membershipId, expectedMembershipVersion); Record header = dsl.fetchOne( @@ -102,7 +94,36 @@ public Optional findForUpdate( .map(row -> requiredRole(row.get("role_identifier", String.class))) .toList(); return Optional.of( - new RoleSnapshot(accountId, tenantId, membershipId, expectedMembershipVersion, roles)); + new RoleSnapshot( + identity.accountId(), + identity.tenantId(), + identity.membershipId(), + expectedMembershipVersion, + roles, + identity.accountUuid(), + identity.tenantUuid(), + identity.tenantProvenance())); + } + + /** + * Reads one exact canonical role snapshot while locking its UUID-qualified membership row and + * header. Returned provenance is the complete source tuple stored on that membership row. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findForCanonicalUpdate( + UUID accountUuid, + UUID tenantUuid, + VerifiedTenantProvenance expectedProvenance, + long membershipId, + long expectedMembershipVersion) { + requireCanonicalOwnerTransaction(); + requireCanonicalIdentity(accountUuid, tenantUuid, expectedProvenance); + validatePositive(membershipId, "membership ID"); + validatePositive(expectedMembershipVersion, "membership version"); + MembershipIdentity identity = + lockCanonicalMembership( + accountUuid, tenantUuid, expectedProvenance, membershipId, expectedMembershipVersion); + return readLockedSnapshot(identity, expectedMembershipVersion); } /** Replaces one exact current snapshot in the caller's JOIN transaction. */ @@ -127,19 +148,8 @@ public RoleSnapshot replace( validatePositive(snapshotVersion, "role snapshot version"); List canonicalRoles = canonicalizeRoleSet(roleIdentifiers); - Record current = - dsl.fetchOne( - "SELECT id, account_id, tenant_id, membership_version " - + "FROM account_tenant_membership " - + "WHERE id = ? AND account_id = ? AND tenant_id = ? FOR UPDATE", - membershipId, - accountId, - tenantId); - if (current == null) { - throw new IllegalStateException("Account membership identity is missing or mismatched"); - } - requireExactPositive( - current.get("membership_version", Long.class), snapshotVersion, "membership version"); + MembershipIdentity identity = + lockRetainedMembership(accountId, tenantId, membershipId, snapshotVersion); dsl.execute("DELETE FROM " + ROLE_TABLE + " WHERE membership_id = ?", membershipId); int headerRows = @@ -166,7 +176,310 @@ public RoleSnapshot replace( throw new IllegalStateException("Account role snapshot row was not persisted"); } } - return new RoleSnapshot(accountId, tenantId, membershipId, snapshotVersion, canonicalRoles); + RoleSnapshot snapshot = + new RoleSnapshot( + identity.accountId(), + identity.tenantId(), + identity.membershipId(), + snapshotVersion, + canonicalRoles, + identity.accountUuid(), + identity.tenantUuid(), + identity.tenantProvenance()); + requireSnapshotReadback(snapshot, readLockedSnapshot(identity, snapshotVersion)); + return snapshot; + } + + /** Replaces and reads back one exact UUID-qualified membership role snapshot. */ + @Transactional(propagation = Propagation.MANDATORY) + public RoleSnapshot replaceCanonical( + AccountTenantMembership membership, + UUID accountUuid, + UUID tenantUuid, + VerifiedTenantProvenance expectedProvenance, + long snapshotVersion, + Collection roleIdentifiers) { + requireCanonicalOwnerTransaction(); + if (membership == null + || membership.getAccount() == null + || membership.getAccount().getId() == null + || membership.getId() == null) { + throw new IllegalArgumentException("A persisted Account membership is required"); + } + requireCanonicalIdentity(accountUuid, tenantUuid, expectedProvenance); + validatePositive(membership.getAccount().getId(), "account ID"); + validatePositive(membership.getId(), "membership ID"); + validatePositive(snapshotVersion, "role snapshot version"); + if (membership.getMembershipVersion() != snapshotVersion + || !Objects.equals(membership.getTenantUuid(), tenantUuid) + || !provenanceFromMembership(membership).equals(expectedProvenance)) { + throw new IllegalStateException( + "Canonical role write differs from the exact membership identity or version"); + } + MembershipIdentity identity = + lockCanonicalMembership( + accountUuid, tenantUuid, expectedProvenance, membership.getId(), snapshotVersion); + if (identity.accountId() != membership.getAccount().getId() + || !Objects.equals(identity.tenantId(), membership.getTenantId())) { + throw new IllegalStateException( + "Canonical role write membership differs from its persisted account row"); + } + List canonicalRoles = canonicalizeRoleSet(roleIdentifiers); + + dsl.execute("DELETE FROM " + ROLE_TABLE + " WHERE membership_id = ?", membership.getId()); + int headerRows = + dsl.execute( + "INSERT INTO " + + SNAPSHOT_TABLE + + " (membership_id, snapshot_version) VALUES (?, ?) " + + "ON CONFLICT (membership_id) DO UPDATE SET snapshot_version = EXCLUDED.snapshot_version", + membership.getId(), + snapshotVersion); + if (headerRows != 1) { + throw new IllegalStateException("Account role snapshot header was not persisted"); + } + for (String role : canonicalRoles) { + int roleRows = + dsl.execute( + "INSERT INTO " + + ROLE_TABLE + + " (membership_id, snapshot_version, role_identifier) VALUES (?, ?, ?)", + membership.getId(), + snapshotVersion, + role); + if (roleRows != 1) { + throw new IllegalStateException("Account role snapshot row was not persisted"); + } + } + + RoleSnapshot expected = + new RoleSnapshot( + identity.accountId(), + identity.tenantId(), + identity.membershipId(), + snapshotVersion, + canonicalRoles, + identity.accountUuid(), + identity.tenantUuid(), + identity.tenantProvenance()); + RoleSnapshot readback = + findForCanonicalUpdate( + accountUuid, tenantUuid, expectedProvenance, membership.getId(), snapshotVersion) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical role snapshot header is absent after its write")); + requireSnapshotReadback(expected, Optional.of(readback)); + return readback; + } + + private Optional readLockedSnapshot( + MembershipIdentity identity, long expectedMembershipVersion) { + Record header = + dsl.fetchOne( + "SELECT membership_id, snapshot_version FROM " + + SNAPSHOT_TABLE + + " WHERE membership_id = ? FOR UPDATE", + identity.membershipId()); + if (header == null) { + return Optional.empty(); + } + requireExactPositive( + header.get("membership_id", Long.class), identity.membershipId(), "membership ID"); + requireExactPositive( + header.get("snapshot_version", Long.class), + expectedMembershipVersion, + "role snapshot version"); + List roles = + dsl + .fetch( + "SELECT role_identifier FROM " + + ROLE_TABLE + + " WHERE membership_id = ? AND snapshot_version = ?" + + " ORDER BY convert_to(role_identifier, 'UTF8')", + identity.membershipId(), + expectedMembershipVersion) + .stream() + .map(row -> requiredRole(row.get("role_identifier", String.class))) + .toList(); + return Optional.of( + new RoleSnapshot( + identity.accountId(), + identity.tenantId(), + identity.membershipId(), + expectedMembershipVersion, + roles, + identity.accountUuid(), + identity.tenantUuid(), + identity.tenantProvenance())); + } + + private MembershipIdentity lockRetainedMembership( + long accountId, long tenantId, long membershipId, long expectedMembershipVersion) { + Record row = + dsl.fetchOne( + membershipIdentitySelect() + + "WHERE m.id = ? AND m.account_id = ? AND m.tenant_id = ? FOR UPDATE OF m", + membershipId, + accountId, + tenantId); + if (row == null) { + throw new IllegalStateException("Account membership identity is missing or mismatched"); + } + MembershipIdentity identity = toMembershipIdentity(row); + requireExactPositive(identity.membershipId(), membershipId, "membership ID"); + requireExactPositive(identity.accountId(), accountId, "account ID"); + requireExactPositive(identity.tenantId(), tenantId, "tenant ID"); + requireExactPositive( + identity.membershipVersion(), expectedMembershipVersion, "membership version"); + return identity; + } + + private MembershipIdentity lockCanonicalMembership( + UUID accountUuid, + UUID tenantUuid, + VerifiedTenantProvenance expectedProvenance, + long membershipId, + long expectedMembershipVersion) { + Record row = + dsl.fetchOne( + membershipIdentitySelect() + + "WHERE m.id = ? AND a.account_uuid = ? AND m.tenant_uuid = ? FOR UPDATE OF m", + membershipId, + accountUuid, + tenantUuid); + if (row == null) { + throw new IllegalStateException( + "Canonical Account membership identity is missing or mismatched"); + } + MembershipIdentity identity = toMembershipIdentity(row); + requireCanonicalIdentity(accountUuid, tenantUuid, expectedProvenance); + requireExactPositive(identity.membershipId(), membershipId, "membership ID"); + if (!accountUuid.equals(identity.accountUuid()) + || !tenantUuid.equals(identity.tenantUuid()) + || !expectedProvenance.equals(identity.tenantProvenance()) + || !Objects.equals(identity.tenantId(), expectedProvenance.legacyTenantId())) { + throw new IllegalStateException( + "Canonical Account membership differs from exact UUID identity or stored provenance"); + } + requireExactPositive( + identity.membershipVersion(), expectedMembershipVersion, "membership version"); + return identity; + } + + private String membershipIdentitySelect() { + return "SELECT m.id, m.account_id, m.tenant_id, m.tenant_uuid, " + + "m.tenant_provenance_kind, m.tenant_source_operation_id, " + + "m.tenant_provenance_digest, m.membership_version, a.account_uuid, " + + "a.account_uuid_provenance, a.account_uuid_source_numeric_id " + + "FROM account_tenant_membership m JOIN accounts a ON a.id = m.account_id "; + } + + private MembershipIdentity toMembershipIdentity(Record row) { + Long accountId = row.get("account_id", Long.class); + UUID accountUuid = row.get("account_uuid", UUID.class); + String accountProvenance = row.get("account_uuid_provenance", String.class); + Long accountSource = row.get("account_uuid_source_numeric_id", Long.class); + if (accountId == null + || accountId <= 0L + || accountUuid == null + || NIL_UUID.equals(accountUuid) + || accountProvenance == null + || accountSource == null + || !accountId.equals(accountSource)) { + throw new IllegalStateException("Canonical Account row identity is incomplete or mismatched"); + } + AccountIdentityProvenance.fromStorageValue(accountProvenance); + Long tenantId = row.get("tenant_id", Long.class); + UUID tenantUuid = row.get("tenant_uuid", UUID.class); + String tenantKind = row.get("tenant_provenance_kind", String.class); + UUID sourceOperationId = row.get("tenant_source_operation_id", UUID.class); + String sourceDigest = row.get("tenant_provenance_digest", String.class); + VerifiedTenantProvenance provenance = + tenantProvenance(tenantId, tenantUuid, tenantKind, sourceOperationId, sourceDigest); + return new MembershipIdentity( + row.get("id", Long.class), + accountId, + tenantId, + tenantUuid, + tenantKind, + sourceOperationId, + sourceDigest, + row.get("membership_version", Long.class), + accountUuid, + provenance); + } + + private VerifiedTenantProvenance tenantProvenance( + Long tenantId, + UUID tenantUuid, + String tenantKind, + UUID sourceOperationId, + String sourceDigest) { + if (UNBRIDGED_RETAINED.equals(tenantKind)) { + if (tenantId == null + || tenantUuid != null + || sourceOperationId != null + || sourceDigest != null) { + throw new IllegalStateException("Unbridged Account membership identity is contradictory"); + } + return null; + } + try { + if (tenantUuid == null || NIL_UUID.equals(tenantUuid) || tenantKind == null) { + throw new IllegalStateException("Canonical Account tenant UUID is absent or nil"); + } + return new VerifiedTenantProvenance( + tenantId, TenantProvenanceKind.valueOf(tenantKind), sourceOperationId, sourceDigest); + } catch (IllegalArgumentException ex) { + throw new IllegalStateException("Canonical Account tenant provenance is malformed", ex); + } + } + + private VerifiedTenantProvenance provenanceFromMembership(AccountTenantMembership membership) { + return tenantProvenance( + membership.getTenantId(), + membership.getTenantUuid(), + membership.getTenantProvenanceKind(), + membership.getTenantSourceOperationId(), + membership.getTenantProvenanceDigest()); + } + + private void requireCanonicalIdentity( + UUID accountUuid, UUID tenantUuid, VerifiedTenantProvenance provenance) { + requireNonNil(accountUuid, "Account UUID"); + requireNonNil(tenantUuid, "tenant UUID"); + if (provenance == null + || (provenance.kind() != TenantProvenanceKind.APPROVED_RETAINED + && provenance.kind() != TenantProvenanceKind.FRESH_GAME_DESIGN)) { + throw new IllegalArgumentException( + "Canonical role identity requires verified UUID provenance"); + } + } + + private void requireSnapshotReadback(RoleSnapshot expected, Optional readback) { + RoleSnapshot actual = + readback.orElseThrow( + () -> + new IllegalStateException( + "Account role snapshot header is absent after its write")); + if (!expected.equals(actual)) { + throw new IllegalStateException( + "Account role snapshot readback differs from its exact write"); + } + } + + private void requireNonNil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil canonical UUID"); + } + } + + private void requireCanonicalOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical Account role snapshot access requires an active owner transaction"); + } } /** Sorts and validates a role set exactly as the canonical unsigned-byte comparator requires. */ @@ -273,17 +586,61 @@ private static void requireExactPositive(Long actual, long expected, String name } public record RoleSnapshot( - long accountId, long tenantId, long membershipId, long snapshotVersion, List roles) { + long accountId, + Long tenantId, + long membershipId, + long snapshotVersion, + List roles, + UUID accountUuid, + UUID tenantUuid, + VerifiedTenantProvenance tenantProvenance) { public RoleSnapshot { - if (accountId <= 0L || tenantId <= 0L || membershipId <= 0L || snapshotVersion <= 0L) { + if (accountId <= 0L + || (tenantId != null && tenantId <= 0L) + || membershipId <= 0L + || snapshotVersion <= 0L) { throw new IllegalArgumentException("Role snapshot identity and version must be positive"); } + if (tenantUuid == null) { + if (tenantId == null || tenantProvenance != null) { + throw new IllegalArgumentException( + "Legacy role snapshot must retain its numeric tenant selector only"); + } + } else if (NIL_UUID.equals(tenantUuid) + || accountUuid == null + || NIL_UUID.equals(accountUuid) + || tenantProvenance == null + || !Objects.equals(tenantId, tenantProvenance.legacyTenantId())) { + throw new IllegalArgumentException( + "Canonical role snapshot must retain exact UUID identity and source provenance"); + } roles = requireCanonicalRoleSet(roles); } + public RoleSnapshot( + long accountId, + long tenantId, + long membershipId, + long snapshotVersion, + List roles) { + this(accountId, tenantId, membershipId, snapshotVersion, roles, null, null, null); + } + @Override public List roles() { return List.copyOf(roles); } } + + private record MembershipIdentity( + long membershipId, + long accountId, + Long tenantId, + UUID tenantUuid, + String tenantProvenanceKind, + UUID tenantSourceOperationId, + String tenantProvenanceDigest, + long membershipVersion, + UUID accountUuid, + VerifiedTenantProvenance tenantProvenance) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java index 1685b850f9..5eeca3130b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java @@ -151,6 +151,31 @@ public IssuerAuthorityEventReadback readCommittedEvent( return readback; } + /** + * Reads the current issuer source inside the reconciliation service's already-owned transaction. + * + *

This package-private bridge preserves the same issuer-row fence while a reconciliation + * receipt is selected or inserted. It does not expose another public read contract. + */ + IssuerAuthoritySnapshot readCurrentForProjectionReconciliation(String requestedIssuerId) { + requireExactIssuer(requestedIssuerId); + requireActiveOwnerTransaction(); + return readCurrentInTransaction(); + } + + /** + * Reads one retained positive source event under the reconciliation transaction's issuer fence. + */ + IssuerAuthorityEventReadback readCommittedEventForProjectionReconciliation( + String requestedIssuerId, long outboxSequence) { + requireExactIssuer(requestedIssuerId); + if (outboxSequence <= 0L) { + throw new IllegalArgumentException("Issuer outbox sequence must be positive"); + } + requireActiveOwnerTransaction(); + return readCommittedEventInTransaction(outboxSequence); + } + private IssuerGenerationAuthorityEvent advanceInOwnerTransaction( UUID requestId, long expectedGeneration, long expectedSourceVersion) { ScopeState current = readLockedIssuerState(); @@ -542,6 +567,13 @@ private void requireNoAmbientTransaction() { } } + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Issuer reconciliation source access requires an active Account owner transaction"); + } + } + private static long incrementExact(long value, String field) { try { return Math.addExact(value, 1L); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcService.java index aacbd66f86..bbe4b2e902 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcService.java @@ -3,27 +3,45 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.sql.SQLTransientException; +import java.util.HexFormat; import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.account.v1.AcknowledgeIssuerProjectionForRuntimeRequest; +import net.firedevops.firemud.account.v1.AcknowledgeIssuerProjectionForRuntimeResponse; +import net.firedevops.firemud.account.v1.CaptureIssuerProjectionForRuntimeRequest; +import net.firedevops.firemud.account.v1.CaptureIssuerProjectionForRuntimeResponse; 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.accountservice.repository.AccountIssuerProjectionAcknowledgmentRepository.Acknowledgment; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository.Receipt; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.common.account.authority.IssuerAuthorityProjectionV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerAuthorityProjectionV1Codec.Projection; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.account.authority.IssuerProjectionInstallationAcknowledgmentDigestV1; +import net.firedevops.firemud.common.account.authority.IssuerProjectionReconciliationRequestDigestV1; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.springframework.dao.TransientDataAccessException; /** - * Unwired transport candidate for Account-owned issuer source readback. + * Unwired transport candidate for Account-owned issuer source evidence and installation ACKs. * - *

This implementation exposes no runtime bean. Its only successful response is derived from a - * complete local producer readback and an exact certificate-derived Game Session peer identity. + *

This implementation exposes no runtime bean. Successful responses require complete local + * owner-service evidence and the exact certificate-derived Game Session peer identity. */ public final class AccountIssuerAuthorityGrpcService extends IssuerAuthorityServiceGrpc.IssuerAuthorityServiceImplBase { @@ -32,15 +50,31 @@ public final class AccountIssuerAuthorityGrpcService private static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; private static final String READBACK_SCHEMA_VERSION = "account-auth-issuer-source-readback/v1"; + private static final String CAPTURE_SCHEMA_VERSION = "account-auth-issuer-projection-capture/v1"; + private static final String ACKNOWLEDGMENT_SCHEMA_VERSION = + "account-auth-issuer-projection-installation-ack/v1"; + private static final String PROJECTION_KEY_PREFIX = "session:game:auth:issuer-generation:v1:"; + private static final UUID NIL_UUID = new UUID(0L, 0L); private final AccountIssuerAuthorityEventProducer producer; + private final AccountIssuerProjectionReconciliationService captureService; + private final AccountIssuerProjectionAcknowledgmentService acknowledgmentService; private final String workloadNamespace; private final String expectedGameSessionPeerUri; public AccountIssuerAuthorityGrpcService( - AccountIssuerAuthorityEventProducer producer, String workloadNamespace) { + AccountIssuerAuthorityEventProducer producer, + AccountIssuerProjectionReconciliationService captureService, + AccountIssuerProjectionAcknowledgmentService acknowledgmentService, + String workloadNamespace) { this.producer = Objects.requireNonNull(producer, "issuer authority producer is required"); + this.captureService = + Objects.requireNonNull( + captureService, "issuer projection reconciliation service is required"); + this.acknowledgmentService = + Objects.requireNonNull( + acknowledgmentService, "issuer projection acknowledgment service is required"); if (workloadNamespace == null || workloadNamespace.isBlank()) { throw new IllegalArgumentException("Account workload namespace is required"); } @@ -55,6 +89,122 @@ public AccountIssuerAuthorityGrpcService( this.expectedGameSessionPeerUri = expectedPeer.uri(); } + @Override + public void acknowledgeIssuerProjectionForRuntime( + AcknowledgeIssuerProjectionForRuntimeRequest request, + StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !expectedGameSessionPeerUri.equals(peer.uri())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Game Session workload identity is required") + .asRuntimeException()); + return; + } + + final AcknowledgmentSelection selection; + try { + selection = validateAcknowledgmentRequest(request); + } catch (InvalidRequestException invalidRequest) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Issuer projection acknowledgment request is invalid") + .asRuntimeException()); + return; + } + + final Acknowledgment acknowledgment; + try { + acknowledgment = + acknowledgmentService.acknowledge( + selection.issuerId(), + peer.uri(), + selection.captureOperationId(), + selection.captureRequestId(), + selection.captureRequestDigestVersion(), + selection.captureRequestDigest(), + selection.installedProjectionJson()); + } catch (RuntimeException acknowledgmentFailure) { + Status.Code code = acknowledgmentFailureCode(acknowledgmentFailure); + String description = + switch (code) { + case INVALID_ARGUMENT -> "Issuer projection acknowledgment request is invalid"; + case ALREADY_EXISTS -> + "Issuer projection acknowledgment conflicts with its original capture or result"; + case PERMISSION_DENIED -> "Verified Game Session workload identity is required"; + case UNAVAILABLE -> "Issuer projection acknowledgment owner is temporarily unavailable"; + case FAILED_PRECONDITION -> + "Issuer projection acknowledgment evidence is stale or unavailable"; + default -> "Issuer projection acknowledgment evidence is unavailable"; + }; + responseObserver.onError( + Status.fromCode(code).withDescription(description).asRuntimeException()); + return; + } + + final AcknowledgeIssuerProjectionForRuntimeResponse response; + try { + response = encodeAcknowledgment(selection, peer.uri(), acknowledgment); + } catch (RuntimeException invalidEvidence) { + responseObserver.onError( + Status.DATA_LOSS + .withDescription("Issuer projection acknowledgment evidence is contradictory") + .asRuntimeException()); + return; + } + + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + @Override + public void captureIssuerProjectionForRuntime( + CaptureIssuerProjectionForRuntimeRequest request, + StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !expectedGameSessionPeerUri.equals(peer.uri())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified Game Session workload identity is required") + .asRuntimeException()); + return; + } + + final CaptureSelection selection; + try { + selection = validateCaptureRequest(request); + } catch (InvalidRequestException invalidRequest) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Issuer projection capture request is invalid") + .asRuntimeException()); + return; + } + + final CaptureIssuerProjectionForRuntimeResponse response; + try { + Receipt receipt = + captureService.capture(selection.issuerId(), peer.uri(), selection.requestId()); + response = encodeCapture(selection, peer.uri(), receipt); + } catch (RuntimeException captureFailure) { + Status.Code code = captureFailureCode(captureFailure); + String description = + switch (code) { + case INVALID_ARGUMENT -> "Issuer projection capture request is invalid"; + case ALREADY_EXISTS -> "Issuer projection capture request conflicts with its receipt"; + case PERMISSION_DENIED -> "Verified Game Session workload identity is required"; + case UNAVAILABLE -> "Issuer projection source is temporarily unavailable"; + default -> "Issuer projection receipt is unavailable or contradictory"; + }; + responseObserver.onError( + Status.fromCode(code).withDescription(description).asRuntimeException()); + return; + } + + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + @Override public void readIssuerAuthorityForRuntime( ReadIssuerAuthorityForRuntimeRequest request, @@ -157,7 +307,7 @@ private ReadIssuerAuthorityForRuntimeResponse readAndEncode(RequestSelection sel currentSnapshot = producer.readCurrent(selection.issuerId()); } - validateCurrentSnapshot(currentSnapshot, selection.issuerId()); + validateSourceSnapshot(currentSnapshot, selection.issuerId()); if (selection.requestedSequence().isPresent()) { validateHistoricalEvent( requestedEvent, currentSnapshot, selection.requestedSequence().orElseThrow()); @@ -187,7 +337,268 @@ private ReadIssuerAuthorityForRuntimeResponse readAndEncode(RequestSelection sel return response.build(); } - private static void validateCurrentSnapshot(IssuerAuthoritySnapshot snapshot, String issuerId) { + private CaptureSelection validateCaptureRequest( + CaptureIssuerProjectionForRuntimeRequest request) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) { + throw new InvalidRequestException(); + } + if (request.getIssuerId().isBlank()) { + throw new InvalidRequestException(); + } + + UUID requestId; + try { + requestId = UUID.fromString(request.getRequestId()); + } catch (IllegalArgumentException malformed) { + throw new InvalidRequestException(); + } + if (NIL_UUID.equals(requestId) || !requestId.toString().equals(request.getRequestId())) { + throw new InvalidRequestException(); + } + return new CaptureSelection(request.getIssuerId(), requestId); + } + + private AcknowledgmentSelection validateAcknowledgmentRequest( + AcknowledgeIssuerProjectionForRuntimeRequest request) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) { + throw new InvalidRequestException(); + } + if (request.getIssuerId().isBlank() + || request.getIssuerId().length() > 512 + || request.getCaptureRequestDigestVersion() + != IssuerProjectionInstallationAcknowledgmentDigestV1.VERSION + || !request.getProjectionKey().equals(PROJECTION_KEY_PREFIX + request.getIssuerId()) + || !request.getCaptureRequestDigest().matches("[0-9a-f]{64}")) { + throw new InvalidRequestException(); + } + + UUID captureOperationId = parseCanonicalNonNilUuid(request.getCaptureOperationId()); + UUID captureRequestId = parseCanonicalNonNilUuid(request.getCaptureRequestId()); + final byte[] projectionBytes; + final Projection projection; + if (request.getInstalledProjectionJson().length() + > IssuerProjectionInstallationAcknowledgmentDigestV1.MAX_INSTALLED_PROJECTION_UTF8_BYTES) { + throw new InvalidRequestException(); + } + try { + projectionBytes = strictUtf8(request.getInstalledProjectionJson()); + if (projectionBytes.length == 0 + || projectionBytes.length + > IssuerProjectionInstallationAcknowledgmentDigestV1 + .MAX_INSTALLED_PROJECTION_UTF8_BYTES) { + throw new InvalidRequestException(); + } + projection = IssuerAuthorityProjectionV1Codec.verify(request.getInstalledProjectionJson()); + } catch (IllegalArgumentException malformedProjection) { + throw new InvalidRequestException(); + } + if (!request.getIssuerId().equals(projection.issuerId())) { + throw new InvalidRequestException(); + } + + return new AcknowledgmentSelection( + request.getIssuerId(), + captureOperationId, + captureRequestId, + request.getCaptureRequestDigestVersion(), + request.getCaptureRequestDigest(), + request.getProjectionKey(), + request.getInstalledProjectionJson(), + projectionBytes, + projection); + } + + private AcknowledgeIssuerProjectionForRuntimeResponse encodeAcknowledgment( + AcknowledgmentSelection selection, String callerIdentity, Acknowledgment acknowledgment) { + if (acknowledgment == null + || acknowledgment.acknowledgmentId() == null + || NIL_UUID.equals(acknowledgment.acknowledgmentId()) + || !selection.captureOperationId().equals(acknowledgment.captureOperationId()) + || !selection.captureRequestId().equals(acknowledgment.captureRequestId()) + || !selection.issuerId().equals(acknowledgment.issuerId()) + || !callerIdentity.equals(acknowledgment.callerWorkloadIdentity()) + || !selection.projectionKey().equals(acknowledgment.projectionKey()) + || selection.captureRequestDigestVersion() != acknowledgment.captureRequestDigestVersion() + || !selection.captureRequestDigest().equals(acknowledgment.captureRequestDigest()) + || acknowledgment.requestDigestVersion() + != IssuerProjectionInstallationAcknowledgmentDigestV1.VERSION) { + throw new IllegalStateException("Issuer installation acknowledgment bindings are incomplete"); + } + + byte[] installedProjection = acknowledgment.installedProjectionUtf8(); + byte[] installedProjectionSha256 = acknowledgment.installedProjectionSha256(); + if (installedProjection.length == 0 + || installedProjection.length + > IssuerProjectionInstallationAcknowledgmentDigestV1.MAX_INSTALLED_PROJECTION_UTF8_BYTES + || installedProjectionSha256.length != 32) { + throw new IllegalStateException("Issuer installation acknowledgment bytes are malformed"); + } + String projectionJson = strictUtf8(installedProjection); + Projection returnedProjection = IssuerAuthorityProjectionV1Codec.verify(projectionJson); + String expectedRequestDigest = + IssuerProjectionInstallationAcknowledgmentDigestV1.digest( + selection.issuerId(), + callerIdentity, + selection.projectionKey(), + selection.captureOperationId(), + selection.captureRequestId(), + selection.captureRequestDigestVersion(), + selection.captureRequestDigest(), + selection.installedProjectionJson()); + if (!MessageDigest.isEqual(installedProjection, selection.installedProjectionBytes()) + || !MessageDigest.isEqual(sha256(installedProjection), installedProjectionSha256) + || !expectedRequestDigest.equals(acknowledgment.requestDigest()) + || !sameProjection(selection.projection(), returnedProjection)) { + throw new IllegalStateException( + "Issuer installation acknowledgment returned bytes or digest evidence that differs from the request"); + } + + return AcknowledgeIssuerProjectionForRuntimeResponse.newBuilder() + .setSchemaVersion(ACKNOWLEDGMENT_SCHEMA_VERSION) + .setTargetNamespace(workloadNamespace) + .setAcknowledgmentId(acknowledgment.acknowledgmentId().toString()) + .setIssuerId(acknowledgment.issuerId()) + .setCallerWorkloadIdentity(acknowledgment.callerWorkloadIdentity()) + .setProjectionKey(acknowledgment.projectionKey()) + .setCaptureOperationId(acknowledgment.captureOperationId().toString()) + .setCaptureRequestId(acknowledgment.captureRequestId().toString()) + .setCaptureRequestDigestVersion(acknowledgment.captureRequestDigestVersion()) + .setCaptureRequestDigest(acknowledgment.captureRequestDigest()) + .setRequestDigestVersion(acknowledgment.requestDigestVersion()) + .setRequestDigest(acknowledgment.requestDigest()) + .setInstalledProjectionJson(projectionJson) + .setInstalledProjectionSha256(HexFormat.of().formatHex(installedProjectionSha256)) + .build(); + } + + private static boolean sameProjection(Projection expected, Projection actual) { + if (expected == null + || actual == null + || !expected.issuerId().equals(actual.issuerId()) + || !expected.generation().equals(actual.generation()) + || !expected.sourceVersion().equals(actual.sourceVersion()) + || !expected.sequence().equals(actual.sequence()) + || !expected.streamKey().equals(actual.streamKey()) + || !expected.appliedAt().equals(actual.appliedAt()) + || expected.latestEvent().isPresent() != actual.latestEvent().isPresent()) { + return false; + } + return expected.latestEvent().isEmpty() + || sameCanonicalEvent( + expected.latestEvent().orElseThrow(), actual.latestEvent().orElseThrow()); + } + + private static UUID parseCanonicalNonNilUuid(String value) { + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException malformed) { + throw new InvalidRequestException(); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new InvalidRequestException(); + } + return parsed; + } + + private static byte[] strictUtf8(String value) { + if (value == null) { + throw new InvalidRequestException(); + } + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException malformed) { + throw new InvalidRequestException(); + } + } + + private static String strictUtf8(byte[] value) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalStateException( + "Issuer acknowledgment projection bytes are not UTF-8", malformed); + } + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private CaptureIssuerProjectionForRuntimeResponse encodeCapture( + CaptureSelection selection, String callerIdentity, Receipt receipt) { + if (receipt == null + || receipt.operationId() == null + || NIL_UUID.equals(receipt.operationId()) + || !selection.requestId().equals(receipt.requestId()) + || !selection.issuerId().equals(receipt.issuerId()) + || !callerIdentity.equals(receipt.callerWorkloadIdentity()) + || !(PROJECTION_KEY_PREFIX + selection.issuerId()).equals(receipt.projectionKey()) + || receipt.requestDigestVersion() + != IssuerProjectionReconciliationRequestDigestV1.VERSION) { + throw new IllegalStateException( + "Issuer projection receipt bindings are incomplete or mismatched"); + } + + String expectedDigest = + IssuerProjectionReconciliationRequestDigestV1.digest( + selection.issuerId(), + callerIdentity, + PROJECTION_KEY_PREFIX + selection.issuerId(), + selection.requestId()); + if (!expectedDigest.equals(receipt.requestDigest())) { + throw new IllegalStateException("Issuer projection receipt digest is mismatched"); + } + + IssuerAuthoritySnapshot captured = receipt.capturedSource(); + validateSourceSnapshot(captured, selection.issuerId()); + return CaptureIssuerProjectionForRuntimeResponse.newBuilder() + .setSchemaVersion(CAPTURE_SCHEMA_VERSION) + .setTargetNamespace(workloadNamespace) + .setOperationId(receipt.operationId().toString()) + .setRequestId(selection.requestId().toString()) + .setIssuerId(receipt.issuerId()) + .setCallerWorkloadIdentity(receipt.callerWorkloadIdentity()) + .setProjectionKey(receipt.projectionKey()) + .setRequestDigestVersion(receipt.requestDigestVersion()) + .setRequestDigest(receipt.requestDigest()) + .setCapturedSourceSnapshot(encodeSourceSnapshot(captured)) + .build(); + } + + private IssuerAuthoritySourceSnapshot encodeSourceSnapshot(IssuerAuthoritySnapshot source) { + IssuerAuthoritySourceSnapshot.Builder snapshotResponse = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(source.issuerId()) + .setSourceScope(SOURCE_SCOPE_PREFIX + source.issuerId()) + .setOutboxStreamKey(source.outboxStreamKey()) + .setIssuerAuthGeneration(Long.toString(source.issuerAuthGeneration())) + .setSourceVersion(Long.toString(source.sourceVersion())) + .setOutboxSequence(Long.toString(source.outboxSequence())); + source + .latestEvent() + .ifPresent(event -> snapshotResponse.setLatestEventCanonicalJson(event.canonicalJson())); + return snapshotResponse.build(); + } + + private static void validateSourceSnapshot(IssuerAuthoritySnapshot snapshot, String issuerId) { if (snapshot == null || !issuerId.equals(snapshot.issuerId()) || snapshot.issuerAuthGeneration() <= 0L @@ -302,6 +713,42 @@ private static Status.Code sourceFailureCode(Throwable failure) { return Status.Code.FAILED_PRECONDITION; } + private static Status.Code captureFailureCode(Throwable failure) { + if (isExactIssuerMismatch(failure)) { + return Status.Code.INVALID_ARGUMENT; + } + if (failure + instanceof AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException) { + return Status.Code.ALREADY_EXISTS; + } + if (failure instanceof SecurityException) { + return Status.Code.PERMISSION_DENIED; + } + return sourceFailureCode(failure); + } + + private static Status.Code acknowledgmentFailureCode(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof TransientDataAccessException || cause instanceof SQLTransientException) { + return Status.Code.UNAVAILABLE; + } + } + if (isExactIssuerMismatch(failure)) { + return Status.Code.INVALID_ARGUMENT; + } + if (failure + instanceof AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException) { + return Status.Code.ALREADY_EXISTS; + } + if (failure instanceof SecurityException) { + return Status.Code.PERMISSION_DENIED; + } + if (failure instanceof IllegalArgumentException) { + return Status.Code.INVALID_ARGUMENT; + } + return Status.Code.FAILED_PRECONDITION; + } + private static boolean isExactIssuerMismatch(Throwable failure) { return failure instanceof AccountIssuerAuthorityEventProducer.IssuerMismatchException; } @@ -315,6 +762,40 @@ private record RequestSelection( } } + private record CaptureSelection(String issuerId, UUID requestId) { + private CaptureSelection { + Objects.requireNonNull(issuerId, "issuerId"); + Objects.requireNonNull(requestId, "requestId"); + } + } + + private record AcknowledgmentSelection( + String issuerId, + UUID captureOperationId, + UUID captureRequestId, + int captureRequestDigestVersion, + String captureRequestDigest, + String projectionKey, + String installedProjectionJson, + byte[] installedProjectionBytes, + Projection projection) { + private AcknowledgmentSelection { + Objects.requireNonNull(issuerId, "issuerId"); + Objects.requireNonNull(captureOperationId, "captureOperationId"); + Objects.requireNonNull(captureRequestId, "captureRequestId"); + Objects.requireNonNull(captureRequestDigest, "captureRequestDigest"); + Objects.requireNonNull(projectionKey, "projectionKey"); + Objects.requireNonNull(installedProjectionJson, "installedProjectionJson"); + installedProjectionBytes = installedProjectionBytes.clone(); + Objects.requireNonNull(projection, "projection"); + } + + @Override + public byte[] installedProjectionBytes() { + return installedProjectionBytes.clone(); + } + } + private static final class InvalidRequestException extends RuntimeException { private static final long serialVersionUID = 1L; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionAcknowledgmentService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionAcknowledgmentService.java new file mode 100644 index 0000000000..305f452ed5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionAcknowledgmentService.java @@ -0,0 +1,399 @@ +package net.firedevops.firemud.accountservice.service; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionAcknowledgmentRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionAcknowledgmentRepository.Acknowledgment; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository.Receipt; +import net.firedevops.firemud.common.account.authority.IssuerAuthorityProjectionV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerAuthorityProjectionV1Codec.Projection; +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 durable acknowledgment of an installed issuer projection. + * + *

The supplied workload identity must come from an authenticated exact-method transport + * certificate check performed by the caller. Comparing it with the configured identity here is only + * a binding check and does not authenticate an in-process or caller-asserted value. + */ +public final class AccountIssuerProjectionAcknowledgmentService { + private static final int MAX_ISSUER_ID_LENGTH = 512; + private static final int MAX_WORKLOAD_IDENTITY_LENGTH = 512; + private static final String PROJECTION_KEY_PREFIX = "session:game:auth:issuer-generation:v1:"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final String exactIssuerId; + private final String exactGameSessionWorkloadIdentity; + private final AccountIssuerProjectionReconciliationService captureService; + private final AccountIssuerProjectionAcknowledgmentRepository repository; + private final TransactionTemplate ownerTransaction; + + public AccountIssuerProjectionAcknowledgmentService( + String exactIssuerId, + String exactGameSessionWorkloadIdentity, + AccountIssuerProjectionReconciliationService captureService, + AccountIssuerProjectionAcknowledgmentRepository repository, + PlatformTransactionManager transactionManager) { + this.exactIssuerId = + requireConfiguredText(exactIssuerId, "exact Account issuer ID", MAX_ISSUER_ID_LENGTH); + this.exactGameSessionWorkloadIdentity = + requireConfiguredText( + exactGameSessionWorkloadIdentity, + "exact Game Session workload identity", + MAX_WORKLOAD_IDENTITY_LENGTH); + this.captureService = + Objects.requireNonNull(captureService, "issuer reconciliation capture service is required"); + this.repository = + Objects.requireNonNull(repository, "issuer acknowledgment repository 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); + } + + /** + * Records or recovers the durable acknowledgment for one exact captured installation. + * + *

The capture operation/request/digest values and installed projection JSON are stable retry + * evidence. The caller must retain and reuse all of them after an uncertain response. + */ + public Acknowledgment acknowledge( + String requestedIssuerId, + String authenticatedWorkloadIdentity, + UUID captureOperationId, + UUID captureRequestId, + int captureRequestDigestVersion, + String captureRequestDigest, + String installedProjectionJson) { + requireExactIssuer(requestedIssuerId); + requireAuthenticatedWorkloadIdentity(authenticatedWorkloadIdentity); + requireUuid(captureOperationId, "capture operation ID"); + requireUuid(captureRequestId, "capture request ID"); + requireCaptureRequestDigest(captureRequestDigestVersion, captureRequestDigest); + requireNoAmbientTransaction(); + + byte[] projectionBytes = encodeUtf8(installedProjectionJson); + Projection projection = IssuerAuthorityProjectionV1Codec.verify(installedProjectionJson); + String requestDigest = + Acknowledgment.requestDigestFor( + exactIssuerId, + exactGameSessionWorkloadIdentity, + projectionKey(), + captureOperationId, + captureRequestId, + captureRequestDigestVersion, + captureRequestDigest, + installedProjectionJson); + + Acknowledgment transactionResult = + requireTransactionResult( + ownerTransaction.execute( + status -> + acknowledgeInOwnerTransaction( + authenticatedWorkloadIdentity, + captureOperationId, + captureRequestId, + captureRequestDigestVersion, + captureRequestDigest, + requestDigest, + projectionBytes, + projection))); + Acknowledgment committedResult = + requireTransactionResult( + ownerTransaction.execute( + status -> + readCommittedAcknowledgmentInOwnerTransaction( + authenticatedWorkloadIdentity, + captureOperationId, + captureRequestId, + captureRequestDigestVersion, + captureRequestDigest, + requestDigest, + projectionBytes, + projection))); + if (!sameAcknowledgment(transactionResult, committedResult)) { + throw new IllegalStateException( + "Post-commit issuer installation acknowledgment differs from the owner transaction result"); + } + return committedResult; + } + + private Acknowledgment acknowledgeInOwnerTransaction( + String callerIdentity, + UUID captureOperationId, + UUID captureRequestId, + int captureRequestDigestVersion, + String captureRequestDigest, + String requestDigest, + byte[] projectionBytes, + Projection projection) { + AccountIssuerProjectionReconciliationService.CaptureReadback captureReadback = + captureService.readCapturedForAcknowledgmentInOwnerTransaction( + exactIssuerId, callerIdentity, captureRequestId); + Receipt capture = captureReadback.receipt(); + requireCaptureBinding( + capture, + callerIdentity, + captureOperationId, + captureRequestId, + captureRequestDigestVersion, + captureRequestDigest); + + Acknowledgment prior = repository.findByCaptureOperationId(captureOperationId).orElse(null); + if (prior != null) { + requireExactRetry(prior, capture, callerIdentity, requestDigest, projectionBytes); + requireProjectionMatchesCapture(projection, capture); + return prior; + } + + requireProjectionMatchesCapture(projection, capture); + if (!AccountIssuerProjectionReconciliationService.sameSnapshot( + capture.capturedSource(), captureReadback.currentSnapshot())) { + throw new IllegalStateException( + "First issuer installation acknowledgment requires the captured source to remain current"); + } + + Acknowledgment candidate = + new Acknowledgment( + UUID.randomUUID(), + captureOperationId, + captureRequestId, + exactIssuerId, + callerIdentity, + projectionKey(), + captureRequestDigestVersion, + captureRequestDigest, + Acknowledgment.REQUEST_DIGEST_VERSION, + requestDigest, + projectionBytes, + sha256(projectionBytes)); + Acknowledgment inserted = repository.insert(candidate); + if (!sameAcknowledgment(candidate, inserted)) { + throw new IllegalStateException( + "Inserted issuer installation acknowledgment differs from its candidate"); + } + Acknowledgment stored = + repository + .findByCaptureOperationId(captureOperationId) + .orElseThrow( + () -> + new IllegalStateException( + "Issuer installation acknowledgment is missing before transaction commit")); + if (!sameAcknowledgment(candidate, stored)) { + throw new IllegalStateException( + "Transaction-local issuer installation acknowledgment readback differs from insert"); + } + return stored; + } + + private Acknowledgment readCommittedAcknowledgmentInOwnerTransaction( + String callerIdentity, + UUID captureOperationId, + UUID captureRequestId, + int captureRequestDigestVersion, + String captureRequestDigest, + String requestDigest, + byte[] projectionBytes, + Projection projection) { + // Retained capture validation runs under a fresh issuer fence before durable ack readback. + AccountIssuerProjectionReconciliationService.CaptureReadback captureReadback = + captureService.readCapturedForAcknowledgmentInOwnerTransaction( + exactIssuerId, callerIdentity, captureRequestId); + Receipt capture = captureReadback.receipt(); + requireCaptureBinding( + capture, + callerIdentity, + captureOperationId, + captureRequestId, + captureRequestDigestVersion, + captureRequestDigest); + requireProjectionMatchesCapture(projection, capture); + + Acknowledgment committed = + repository + .findByCaptureOperationId(captureOperationId) + .orElseThrow( + () -> + new IllegalStateException( + "Post-commit issuer installation acknowledgment readback is missing")); + requireExactRetry(committed, capture, callerIdentity, requestDigest, projectionBytes); + return committed; + } + + private void requireCaptureBinding( + Receipt capture, + String callerIdentity, + UUID captureOperationId, + UUID captureRequestId, + int captureRequestDigestVersion, + String captureRequestDigest) { + if (!captureOperationId.equals(capture.operationId()) + || !captureRequestId.equals(capture.requestId()) + || !exactIssuerId.equals(capture.issuerId()) + || !callerIdentity.equals(capture.callerWorkloadIdentity()) + || !projectionKey().equals(capture.projectionKey()) + || captureRequestDigestVersion != capture.requestDigestVersion() + || !captureRequestDigest.equals(capture.requestDigest())) { + throw new AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException( + "Issuer installation acknowledgment changed its original capture binding"); + } + } + + private void requireExactRetry( + Acknowledgment acknowledgment, + Receipt capture, + String callerIdentity, + String requestDigest, + byte[] projectionBytes) { + boolean matches = + acknowledgment.captureOperationId().equals(capture.operationId()) + && acknowledgment.captureRequestId().equals(capture.requestId()) + && acknowledgment.issuerId().equals(exactIssuerId) + && acknowledgment.callerWorkloadIdentity().equals(callerIdentity) + && acknowledgment.projectionKey().equals(projectionKey()) + && acknowledgment.captureRequestDigestVersion() == capture.requestDigestVersion() + && acknowledgment.captureRequestDigest().equals(capture.requestDigest()) + && acknowledgment.requestDigestVersion() == Acknowledgment.REQUEST_DIGEST_VERSION + && acknowledgment.requestDigest().equals(requestDigest) + && MessageDigest.isEqual(acknowledgment.installedProjectionUtf8(), projectionBytes); + if (!matches) { + throw new AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException( + "Issuer installation acknowledgment request identity was reused with changed projection bytes or bindings"); + } + } + + private void requireProjectionMatchesCapture(Projection projection, Receipt capture) { + var source = capture.capturedSource(); + if (!exactIssuerId.equals(projection.issuerId()) + || !source.outboxStreamKey().equals(projection.streamKey()) + || !BigInteger.valueOf(source.issuerAuthGeneration()).equals(projection.generation()) + || !BigInteger.valueOf(source.sourceVersion()).equals(projection.sourceVersion()) + || !BigInteger.valueOf(source.outboxSequence()).equals(projection.sequence()) + || source.latestEvent().isPresent() != projection.latestEvent().isPresent() + || (source.latestEvent().isPresent() + && !AccountIssuerProjectionReconciliationService.sameEvent( + source.latestEvent().orElseThrow(), projection.latestEvent().orElseThrow()))) { + throw new IllegalArgumentException( + "Installed issuer projection does not exactly match the captured checkpoint and event"); + } + } + + private String projectionKey() { + return PROJECTION_KEY_PREFIX + exactIssuerId; + } + + private void requireExactIssuer(String requestedIssuerId) { + if (!exactIssuerId.equals(requestedIssuerId)) { + throw new AccountIssuerAuthorityEventProducer.IssuerMismatchException(); + } + } + + private void requireAuthenticatedWorkloadIdentity(String identity) { + if (!exactGameSessionWorkloadIdentity.equals(identity)) { + throw new SecurityException( + "Issuer installation acknowledgment requires the exact authenticated Game Session workload identity"); + } + } + + private static void requireCaptureRequestDigest(int version, String digest) { + if (version != 1 || digest == null || !digest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "Issuer installation acknowledgment requires the exact version-1 capture request digest"); + } + } + + private static void requireUuid(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Issuer installation acknowledgment must own its Account transactions without an ambient transaction"); + } + } + + private static String requireConfiguredText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + field + " must contain 1 to " + maximumLength + " characters"); + } + return value; + } + + private static byte[] encodeUtf8(String value) { + if (value == null) { + throw new IllegalArgumentException("Installed projection JSON is required"); + } + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] result = new byte[encoded.remaining()]; + encoded.get(result); + if (result.length == 0 + || result.length > Acknowledgment.MAX_INSTALLED_PROJECTION_UTF8_BYTES) { + throw new IllegalArgumentException( + "Installed projection JSON must contain 1 to " + + Acknowledgment.MAX_INSTALLED_PROJECTION_UTF8_BYTES + + " UTF-8 bytes"); + } + return result; + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException( + "Installed projection JSON is not valid Unicode", malformed); + } + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static boolean sameAcknowledgment(Acknowledgment first, Acknowledgment second) { + return first != null + && second != null + && first.acknowledgmentId().equals(second.acknowledgmentId()) + && first.captureOperationId().equals(second.captureOperationId()) + && first.captureRequestId().equals(second.captureRequestId()) + && first.issuerId().equals(second.issuerId()) + && first.callerWorkloadIdentity().equals(second.callerWorkloadIdentity()) + && first.projectionKey().equals(second.projectionKey()) + && first.captureRequestDigestVersion() == second.captureRequestDigestVersion() + && first.captureRequestDigest().equals(second.captureRequestDigest()) + && first.requestDigestVersion() == second.requestDigestVersion() + && first.requestDigest().equals(second.requestDigest()) + && MessageDigest.isEqual(first.installedProjectionUtf8(), second.installedProjectionUtf8()) + && MessageDigest.isEqual( + first.installedProjectionSha256(), second.installedProjectionSha256()); + } + + private static Acknowledgment requireTransactionResult(Acknowledgment acknowledgment) { + if (acknowledgment == null) { + throw new IllegalStateException( + "Issuer installation acknowledgment transaction returned no result"); + } + return acknowledgment; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionReconciliationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionReconciliationService.java new file mode 100644 index 0000000000..92151ee7a9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionReconciliationService.java @@ -0,0 +1,324 @@ +package net.firedevops.firemud.accountservice.service; + +import java.security.MessageDigest; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository.Receipt; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +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 capture of an immutable issuer source snapshot for later projection repair. + * + *

The supplied workload identity must come from an authenticated exact-method transport + * certificate check performed by the caller. Comparing it with the configured identity here is only + * a binding check and does not authenticate an in-process or caller-asserted value. + */ +public final class AccountIssuerProjectionReconciliationService { + private static final int MAX_ISSUER_ID_LENGTH = 512; + private static final int MAX_WORKLOAD_IDENTITY_LENGTH = 512; + private static final String PROJECTION_KEY_PREFIX = "session:game:auth:issuer-generation:v1:"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final String exactIssuerId; + private final String exactGameSessionWorkloadIdentity; + private final AccountIssuerAuthorityEventProducer source; + private final AccountIssuerProjectionReconciliationRepository repository; + private final TransactionTemplate ownerTransaction; + + public AccountIssuerProjectionReconciliationService( + String exactIssuerId, + String exactGameSessionWorkloadIdentity, + AccountIssuerAuthorityEventProducer source, + AccountIssuerProjectionReconciliationRepository repository, + PlatformTransactionManager transactionManager) { + this.exactIssuerId = + requireConfiguredText(exactIssuerId, "exact Account issuer ID", MAX_ISSUER_ID_LENGTH); + this.exactGameSessionWorkloadIdentity = + requireConfiguredText( + exactGameSessionWorkloadIdentity, + "exact Game Session workload identity", + MAX_WORKLOAD_IDENTITY_LENGTH); + this.source = Objects.requireNonNull(source, "issuer authority source is required"); + this.repository = + Objects.requireNonNull(repository, "issuer reconciliation repository 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); + } + + /** + * Captures the current exact issuer source or recovers the immutable original receipt. + * + *

The caller must retain and reuse {@code requestId} after an uncertain response. The + * authenticated workload identity argument must be provided only after transport authentication; + * this local method's exact string comparison is not proof of that authentication. + */ + public Receipt capture( + String requestedIssuerId, String authenticatedWorkloadIdentity, UUID requestId) { + requireExactIssuer(requestedIssuerId); + requireAuthenticatedWorkloadIdentity(authenticatedWorkloadIdentity); + requireRequestId(requestId); + requireNoAmbientTransaction(); + + Receipt transactionResult = + requireTransactionResult( + ownerTransaction.execute( + status -> captureInOwnerTransaction(authenticatedWorkloadIdentity, requestId))); + Receipt committedResult = + requireTransactionResult( + ownerTransaction.execute( + status -> + readCommittedReceiptInOwnerTransaction( + authenticatedWorkloadIdentity, requestId))); + if (!sameReceipt(transactionResult, committedResult)) { + throw new IllegalStateException( + "Post-commit issuer reconciliation receipt differs from the owner transaction result"); + } + return committedResult; + } + + private Receipt captureInOwnerTransaction(String callerIdentity, UUID requestId) { + // This call takes and retains the issuer row fence before receipt lookup or insertion. + IssuerAuthoritySnapshot current = source.readCurrentForProjectionReconciliation(exactIssuerId); + Optional prior = repository.findByIssuerAndRequestId(exactIssuerId, requestId); + if (prior.isPresent()) { + Receipt recovered = prior.orElseThrow(); + requireOriginalBindings(recovered, callerIdentity, requestId); + requireRetainedEvidence(recovered, current); + return recovered; + } + + String projectionKey = PROJECTION_KEY_PREFIX + exactIssuerId; + Receipt candidate = + new Receipt( + UUID.randomUUID(), + requestId, + exactIssuerId, + callerIdentity, + projectionKey, + 1, + Receipt.requestDigestFor(exactIssuerId, callerIdentity, projectionKey, requestId), + current); + Receipt inserted = repository.insert(candidate); + if (!sameReceipt(candidate, inserted)) { + throw new IllegalStateException( + "Inserted issuer reconciliation receipt differs from its candidate"); + } + Receipt stored = + repository + .findByIssuerAndRequestId(exactIssuerId, requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Issuer reconciliation receipt is missing before transaction commit")); + if (!sameReceipt(candidate, stored)) { + throw new IllegalStateException( + "Transaction-local issuer reconciliation receipt readback differs from insert"); + } + return stored; + } + + private Receipt readCommittedReceiptInOwnerTransaction(String callerIdentity, UUID requestId) { + // Reacquire the issuer fence in a new READ_COMMITTED transaction before reading the receipt. + IssuerAuthoritySnapshot current = source.readCurrentForProjectionReconciliation(exactIssuerId); + Receipt committed = + repository + .findByIssuerAndRequestId(exactIssuerId, requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Post-commit issuer reconciliation receipt readback is missing")); + requireOriginalBindings(committed, callerIdentity, requestId); + requireRetainedEvidence(committed, current); + return committed; + } + + /** + * Reads and validates the exact original capture while retaining the issuer fence for an + * acknowledgment owner transaction. + * + *

This is an internal bridge for the installation acknowledgment. The caller must own its + * explicit Account transaction; this method does not open or join one. + */ + CaptureReadback readCapturedForAcknowledgmentInOwnerTransaction( + String requestedIssuerId, String authenticatedWorkloadIdentity, UUID requestId) { + requireExactIssuer(requestedIssuerId); + requireAuthenticatedWorkloadIdentity(authenticatedWorkloadIdentity); + requireRequestId(requestId); + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Issuer acknowledgment capture read requires an active Account owner transaction"); + } + + // Keep the same issuer fence used by capture held through capture and retained-history reads. + IssuerAuthoritySnapshot current = source.readCurrentForProjectionReconciliation(exactIssuerId); + Receipt receipt = + repository + .findByIssuerAndRequestId(exactIssuerId, requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Issuer projection acknowledgment references a missing capture")); + requireOriginalBindings(receipt, authenticatedWorkloadIdentity, requestId); + requireRetainedEvidence(receipt, current); + return new CaptureReadback(receipt, current); + } + + private void requireOriginalBindings(Receipt receipt, String callerIdentity, UUID requestId) { + String projectionKey = PROJECTION_KEY_PREFIX + exactIssuerId; + String expectedDigest = + Receipt.requestDigestFor(exactIssuerId, callerIdentity, projectionKey, requestId); + if (!requestId.equals(receipt.requestId()) + || !exactIssuerId.equals(receipt.issuerId()) + || !callerIdentity.equals(receipt.callerWorkloadIdentity()) + || !projectionKey.equals(receipt.projectionKey()) + || receipt.requestDigestVersion() != 1 + || !expectedDigest.equals(receipt.requestDigest())) { + throw new AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException( + "Issuer reconciliation request identity was reused with changed caller or projection bindings"); + } + } + + private void requireRetainedEvidence(Receipt receipt, IssuerAuthoritySnapshot current) { + IssuerAuthoritySnapshot captured = receipt.capturedSource(); + if (!exactIssuerId.equals(current.issuerId()) + || !exactIssuerId.equals(captured.issuerId()) + || !captured.outboxStreamKey().equals(current.outboxStreamKey()) + || current.issuerAuthGeneration() < captured.issuerAuthGeneration() + || current.sourceVersion() < captured.sourceVersion() + || current.outboxSequence() < captured.outboxSequence()) { + throw new IllegalStateException( + "Issuer reconciliation receipt source evidence is ahead of or detached from current source"); + } + if (current.outboxSequence() == captured.outboxSequence()) { + if (!sameSnapshot(captured, current)) { + throw new IllegalStateException( + "Issuer reconciliation receipt contradicts the current source checkpoint"); + } + return; + } + if (captured.outboxSequence() == 0L) { + // The durable receipt records the proved pristine baseline; later fenced progress is + // expected. + return; + } + + IssuerAuthorityEventReadback historical = + source.readCommittedEventForProjectionReconciliation( + exactIssuerId, captured.outboxSequence()); + if (!sameSnapshot(current, historical.currentSnapshot()) + || captured.latestEvent().isEmpty() + || !sameEvent(captured.latestEvent().orElseThrow(), historical.requestedEvent())) { + throw new IllegalStateException( + "Issuer reconciliation receipt's captured event is missing or contradicts retained source evidence"); + } + } + + private void requireExactIssuer(String requestedIssuerId) { + if (!exactIssuerId.equals(requestedIssuerId)) { + throw new AccountIssuerAuthorityEventProducer.IssuerMismatchException(); + } + } + + private void requireAuthenticatedWorkloadIdentity(String identity) { + if (!exactGameSessionWorkloadIdentity.equals(identity)) { + throw new SecurityException( + "Issuer reconciliation capture requires the exact authenticated Game Session workload identity"); + } + } + + private static void requireRequestId(UUID requestId) { + if (requestId == null || NIL_UUID.equals(requestId)) { + throw new IllegalArgumentException( + "Issuer reconciliation request ID must be a canonical non-nil UUID"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Issuer reconciliation capture must own its Account transaction without an ambient transaction"); + } + } + + private static String requireConfiguredText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + field + " must contain 1 to " + maximumLength + " characters"); + } + return value; + } + + static boolean sameSnapshot(IssuerAuthoritySnapshot first, IssuerAuthoritySnapshot second) { + if (first == null || second == null) { + return false; + } + if (!first.issuerId().equals(second.issuerId()) + || first.issuerAuthGeneration() != second.issuerAuthGeneration() + || first.sourceVersion() != second.sourceVersion() + || !first.outboxStreamKey().equals(second.outboxStreamKey()) + || first.outboxSequence() != second.outboxSequence() + || first.latestEvent().isPresent() != second.latestEvent().isPresent()) { + return false; + } + return first.latestEvent().isEmpty() + || sameEvent(first.latestEvent().orElseThrow(), second.latestEvent().orElseThrow()); + } + + static boolean sameEvent( + IssuerGenerationAuthorityEvent first, IssuerGenerationAuthorityEvent 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.issuerId().equals(second.issuerId()) + && first.sourceScope().equals(second.sourceScope()) + && first.outboxStreamKey().equals(second.outboxStreamKey()) + && first.outboxSequence().equals(second.outboxSequence()) + && first.issuerAuthGeneration().equals(second.issuerAuthGeneration()) + && first.sourceVersion().equals(second.sourceVersion()) + && first.eventDigest().equals(second.eventDigest()) + && MessageDigest.isEqual(first.canonicalJsonUtf8(), second.canonicalJsonUtf8()); + } + + private static boolean sameReceipt(Receipt first, Receipt second) { + return first != null + && second != null + && first.operationId().equals(second.operationId()) + && first.requestId().equals(second.requestId()) + && first.issuerId().equals(second.issuerId()) + && first.callerWorkloadIdentity().equals(second.callerWorkloadIdentity()) + && first.projectionKey().equals(second.projectionKey()) + && first.requestDigestVersion() == second.requestDigestVersion() + && MessageDigest.isEqual( + first.requestDigest().getBytes(java.nio.charset.StandardCharsets.US_ASCII), + second.requestDigest().getBytes(java.nio.charset.StandardCharsets.US_ASCII)) + && sameSnapshot(first.capturedSource(), second.capturedSource()); + } + + private static Receipt requireTransactionResult(Receipt receipt) { + if (receipt == null) { + throw new IllegalStateException("Issuer reconciliation transaction returned no receipt"); + } + return receipt; + } + + record CaptureReadback(Receipt receipt, IssuerAuthoritySnapshot currentSnapshot) { + CaptureReadback { + Objects.requireNonNull(receipt, "issuer reconciliation receipt is required"); + Objects.requireNonNull(currentSnapshot, "current issuer snapshot is required"); + } + } +} 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 41da470be0..8fd88fd96d 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 @@ -613,24 +613,7 @@ public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( if (currentMembership.isPresent()) { PositiveMembershipSnapshot positive = readCurrentPairBoundPositiveMembershipSnapshot(accountId, legacyTenantId); - return new RuntimeMembershipSnapshotDto( - positive.accountId(), - positive.tenantId(), - positive.accountId(), - positive.tenantId(), - positive.membershipExists(), - positive.gameplayAdmissionAllowed(), - new RuntimeMembershipSnapshotDto.MembershipBaseline( - positive.membershipLifecycleState(), - positive.membershipVersion(), - positive.membershipAuthorityGeneration()), - positive.roles(), - positive.authorityTuple(), - positive.issuanceFence(), - positive.evaluatedAt(), - positive.outboxCheckpoints(), - positive.outboxSourceEvidence(), - positive.authorityEvent()); + return toRuntimeMembershipSnapshot(positive); } NeverJoinedMembershipSnapshot absent = @@ -663,6 +646,27 @@ public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( @Transactional(propagation = Propagation.MANDATORY) public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( UUID accountUuid, UUID tenantUuid) { + return readUuidRuntimeMembershipSnapshot( + accountUuid, tenantUuid, MembershipSnapshotReadMode.ENROLL_IF_NEEDED); + } + + /** + * Reads current membership source evidence only when the exact Account/tenant pair is already + * enrolled. This is an owner-local projection source read, not authorization or RPC activation. + * + *

Unlike the runtime snapshot preparation path, this method never initializes a generation, + * enrolls a pair baseline, or changes membership authority. Missing or contradictory existing + * evidence fails closed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public RuntimeMembershipSnapshotDto readExistingRuntimeMembershipSnapshot( + UUID accountUuid, UUID tenantUuid) { + return readUuidRuntimeMembershipSnapshot( + accountUuid, tenantUuid, MembershipSnapshotReadMode.EXISTING_ONLY); + } + + private RuntimeMembershipSnapshotDto readUuidRuntimeMembershipSnapshot( + UUID accountUuid, UUID tenantUuid, MembershipSnapshotReadMode readMode) { requireActiveOwnerTransaction(); requireCanonicalUuidInput(accountUuid, "Account UUID"); requireCanonicalUuidInput(tenantUuid, "tenant UUID"); @@ -695,9 +699,33 @@ public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( Optional freshAssociation = freshTenantIdentityAssociationRepository.read(tenantUuid); if (freshAssociation.isPresent()) { - NeverJoinedMembershipSnapshot absent = - readFreshNeverJoinedMembershipSnapshot(accountUuid, tenantUuid); - return toRuntimeMembershipSnapshot(absent); + FreshTenantCreationEvidence evidence = freshAssociation.orElseThrow(); + if (readMode == MembershipSnapshotReadMode.ENROLL_IF_NEEDED) { + NeverJoinedMembershipSnapshot absent = + readFreshNeverJoinedMembershipSnapshot(accountUuid, tenantUuid); + return toRuntimeMembershipSnapshot(absent); + } + if (!tenantUuid.equals(evidence.canonicalTenantId())) { + throw new IllegalStateException( + "Fresh Game Design tenant association differs from its canonical UUID scope"); + } + + RuntimeMembershipSnapshotDto existing = + readExistingFreshNeverJoinedMembershipSnapshot(accountUuid, tenantUuid, evidence); + verifyExistingRuntimeSnapshotIdentity(existing, accountUuid, tenantUuid); + requireUnchangedAccountIdentity(initialAccount, accountUuid); + FreshTenantCreationEvidence finalAssociation = + freshTenantIdentityAssociationRepository + .read(tenantUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Fresh Game Design tenant association disappeared during readback")); + if (!evidence.equals(finalAssociation)) { + throw new IllegalStateException( + "Fresh Game Design tenant association changed during membership readback"); + } + return existing; } ApprovedAssociation retainedAssociation = tenantIdentityResolver.resolve(tenantUuid); @@ -706,18 +734,143 @@ public RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot( throw new IllegalStateException( "Retained tenant UUID has no exact private numeric association"); } + + if (readMode == MembershipSnapshotReadMode.ENROLL_IF_NEEDED) { + RuntimeMembershipSnapshotDto retained = + readRuntimeMembershipSnapshot(accountId, retainedAssociation.legacyTenantId()); + if (!accountUuid.toString().equals(retained.accountUuid()) + || !tenantUuid.toString().equals(retained.tenantUuid()) + || !accountUuid.toString().equals(retained.requestAccountUuid()) + || !tenantUuid.toString().equals(retained.requestTenantUuid())) { + throw new IllegalStateException( + "Retained numeric membership readback differs from its exact canonical UUID request"); + } + return retained; + } + RuntimeMembershipSnapshotDto retained = - readRuntimeMembershipSnapshot(accountId, retainedAssociation.legacyTenantId()); - if (!accountUuid.toString().equals(retained.accountUuid()) - || !tenantUuid.toString().equals(retained.tenantUuid()) - || !accountUuid.toString().equals(retained.requestAccountUuid()) - || !tenantUuid.toString().equals(retained.requestTenantUuid())) { + readExistingRetainedRuntimeMembershipSnapshot( + accountId, retainedAssociation.legacyTenantId()); + verifyExistingRuntimeSnapshotIdentity(retained, accountUuid, tenantUuid); + + Account finalAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Runtime snapshot Account row disappeared before readback")); + requirePersistedAccountIdentity(finalAccount, accountUuid); + if (!Objects.equals(initialAccount.getId(), finalAccount.getId()) + || initialAccount.getAccountUuidProvenance() != finalAccount.getAccountUuidProvenance() + || !Objects.equals( + initialAccount.getAccountUuidSourceNumericId(), + finalAccount.getAccountUuidSourceNumericId()) + || !retainedAssociation.equals(tenantIdentityResolver.resolve(tenantUuid))) { throw new IllegalStateException( - "Retained numeric membership readback differs from its exact canonical UUID request"); + "Canonical Account or retained tenant identity changed during membership readback"); } return retained; } + private RuntimeMembershipSnapshotDto readExistingFreshNeverJoinedMembershipSnapshot( + UUID accountUuid, UUID tenantUuid, FreshTenantCreationEvidence evidence) { + VerifiedTenantProvenance provenance = freshTenantProvenance(evidence); + + // Preserve the source reader's canonical upstream lock order before inspecting the existing + // pair. This path performs no initializer or enrollment call. + CompositeSnapshot upstream = lockUpstreamAuthorityScopes(accountUuid, tenantUuid); + readCurrentUpstreamSourceEvidence(accountUuid, tenantUuid, upstream); + pairAuthorityRepository + .readForUpdate(accountUuid, tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Fresh Account membership pair baseline is absent")); + + return toRuntimeMembershipSnapshot( + assembleNeverJoinedMembershipSnapshot(accountUuid, tenantUuid, provenance)); + } + + private RuntimeMembershipSnapshotDto readExistingRetainedRuntimeMembershipSnapshot( + long accountId, long legacyTenantId) { + Optional currentMembership = + membershipRepository.findJoinProofForUpdate(accountId, legacyTenantId); + if (currentMembership.isEmpty()) { + return toRuntimeMembershipSnapshot( + readNeverJoinedMembershipSnapshot(accountId, legacyTenantId)); + } + + JoinMembershipProof membership = currentMembership.orElseThrow(); + return switch (membership.lifecycleState()) { + case "ACTIVE" -> + toRuntimeMembershipSnapshot( + readCurrentPairBoundPositiveMembershipSnapshot(accountId, legacyTenantId)); + case "INACTIVE" -> readCurrentPairBoundInactiveMembershipSnapshot(accountId, legacyTenantId); + default -> + throw new IllegalStateException( + "Current Account membership lifecycle is not a supported existing state"); + }; + } + + private RuntimeMembershipSnapshotDto toRuntimeMembershipSnapshot( + PositiveMembershipSnapshot positive) { + return new RuntimeMembershipSnapshotDto( + positive.accountId(), + positive.tenantId(), + positive.accountId(), + positive.tenantId(), + positive.membershipExists(), + positive.gameplayAdmissionAllowed(), + new RuntimeMembershipSnapshotDto.MembershipBaseline( + positive.membershipLifecycleState(), + positive.membershipVersion(), + positive.membershipAuthorityGeneration()), + positive.roles(), + positive.authorityTuple(), + positive.issuanceFence(), + positive.evaluatedAt(), + positive.outboxCheckpoints(), + positive.outboxSourceEvidence(), + positive.authorityEvent()); + } + + private void verifyExistingRuntimeSnapshotIdentity( + RuntimeMembershipSnapshotDto snapshot, UUID accountUuid, UUID tenantUuid) { + if (!accountUuid.toString().equals(snapshot.accountUuid()) + || !tenantUuid.toString().equals(snapshot.tenantUuid()) + || !accountUuid.toString().equals(snapshot.requestAccountUuid()) + || !tenantUuid.toString().equals(snapshot.requestTenantUuid())) { + throw new IllegalStateException( + "Account membership readback differs from its exact canonical UUID request"); + } + } + + private void requireUnchangedAccountIdentity(Account initialAccount, UUID accountUuid) { + Account finalAccount = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Runtime snapshot Account row disappeared before readback")); + requirePersistedAccountIdentity(finalAccount, accountUuid); + if (!Objects.equals(initialAccount.getId(), finalAccount.getId()) + || initialAccount.getAccountUuidProvenance() != finalAccount.getAccountUuidProvenance() + || !Objects.equals( + initialAccount.getAccountUuidSourceNumericId(), + finalAccount.getAccountUuidSourceNumericId())) { + throw new IllegalStateException( + "Canonical Account identity changed during membership readback"); + } + } + + private VerifiedTenantProvenance freshTenantProvenance(FreshTenantCreationEvidence evidence) { + return new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + evidence.operationId(), + evidence.evidenceDigest()); + } + private RuntimeMembershipSnapshotDto toRuntimeMembershipSnapshot( NeverJoinedMembershipSnapshot absent) { return new RuntimeMembershipSnapshotDto( @@ -2553,6 +2706,11 @@ private record Identity( UUID tenantUuid, ApprovedAssociation association) {} + private enum MembershipSnapshotReadMode { + ENROLL_IF_NEEDED, + EXISTING_ONLY + } + private record CurrentSourceProof( OutboxCheckpointEntry checkpoint, Optional sourceEvidence) { private CurrentSourceProof { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipSourceReader.java new file mode 100644 index 0000000000..81159464eb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipSourceReader.java @@ -0,0 +1,126 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered owner-local read of current membership authority for derived projection work. + * + *

The returned state is source evidence only. It does not authorize gameplay, expose a runtime + * RPC, or enable membership delivery. + */ +public final class AccountMembershipSourceReader { + private final AccountMembershipAuthorityEventProducer membershipProducer; + private final AccountAuthorityGenerationRepository generationRepository; + private final TransactionTemplate ownerTransaction; + + public AccountMembershipSourceReader( + AccountMembershipAuthorityEventProducer membershipProducer, + AccountAuthorityGenerationRepository generationRepository, + PlatformTransactionManager transactionManager) { + this.membershipProducer = + Objects.requireNonNull(membershipProducer, "membership source producer is required"); + this.generationRepository = + Objects.requireNonNull(generationRepository, "authority-generation repository 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); + } + + /** Reads one exact, pre-enrolled membership source and its current generation state. */ + public MembershipSourceSnapshot readCurrent(UUID accountId, UUID tenantId) { + requireCanonicalUuid(accountId, "Account UUID"); + requireCanonicalUuid(tenantId, "tenant UUID"); + requireNoAmbientTransaction(); + + MembershipSourceSnapshot snapshot = + ownerTransaction.execute( + status -> { + RuntimeMembershipSnapshotDto membership = + membershipProducer.readExistingRuntimeMembershipSnapshot(accountId, tenantId); + ScopeState sourceState = + generationRepository.read(AuthorityScope.membership(accountId, tenantId)); + return new MembershipSourceSnapshot(accountId, tenantId, membership, sourceState); + }); + if (snapshot == null) { + throw new IllegalStateException("Account membership source transaction returned no state"); + } + return snapshot; + } + + private void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account membership source reader cannot join an ambient transaction"); + } + } + + private void requireCanonicalUuid(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must be a non-nil UUID"); + } + } + + /** Exact membership authority state, event snapshot, and independent durable source counters. */ + public record MembershipSourceSnapshot( + UUID accountId, + UUID tenantId, + RuntimeMembershipSnapshotDto snapshot, + ScopeState sourceState) { + public MembershipSourceSnapshot { + Objects.requireNonNull(accountId, "Account UUID is required"); + Objects.requireNonNull(tenantId, "tenant UUID is required"); + Objects.requireNonNull(snapshot, "current membership snapshot is required"); + Objects.requireNonNull(sourceState, "membership authority source state is required"); + + AuthorityScope expectedScope = AuthorityScope.membership(accountId, tenantId); + if (!expectedScope.equals(sourceState.scope()) + || sourceState.generation() <= 0L + || sourceState.sourceVersion() <= 0L) { + throw new IllegalArgumentException( + "Membership authority source state differs from its exact scope"); + } + if (new UUID(0L, 0L).equals(accountId) + || new UUID(0L, 0L).equals(tenantId) + || sourceState.issuanceFence() == null + || !accountId.equals(sourceState.issuanceFence().accountId()) + || sourceState.issuanceFence().value() <= 0L + || sourceState.issuanceFence().sourceVersion() <= 0L) { + throw new IllegalArgumentException( + "Membership source state has no exact positive Account issuance fence"); + } + if (!accountId.toString().equals(snapshot.accountUuid()) + || !tenantId.toString().equals(snapshot.tenantUuid()) + || !accountId.toString().equals(snapshot.requestAccountUuid()) + || !tenantId.toString().equals(snapshot.requestTenantUuid())) { + throw new IllegalArgumentException( + "Membership snapshot differs from its exact Account/tenant source scope"); + } + if (!Long.toString(sourceState.issuanceFence().value()).equals(snapshot.issuanceFence())) { + throw new IllegalArgumentException( + "Membership snapshot issuance fence differs from its Account source state"); + } + + Map versions = snapshot.membershipBaseline().membershipVersion(); + if (versions.size() != 1 + || !versions.containsKey(tenantId.toString()) + || !Long.toString(sourceState.generation()) + .equals(snapshot.membershipBaseline().membershipAuthorityGeneration())) { + throw new IllegalArgumentException( + "Membership snapshot version map or generation differs from its source state"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java new file mode 100644 index 0000000000..7d620f23f5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java @@ -0,0 +1,186 @@ +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.Objects; +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; + +/** Private Redis mechanics shared only by Account's typed current-generation projection stores. */ +final class CurrentGenerationProjectionRedisSupport { + private static final Duration COMMAND_TIMEOUT = Duration.ofSeconds(3); + private static final String RESOURCE_PATH = "redis/account_generation_projection_cas.lua"; + private static final byte[] CAS_SCRIPT_BYTES = scriptBytes(); + private static final String CAS_SCRIPT_SHA1 = digest("SHA-1", CAS_SCRIPT_BYTES); + private static final String CAS_SCRIPT_SHA256 = digest("SHA-256", CAS_SCRIPT_BYTES); + + private CurrentGenerationProjectionRedisSupport() {} + + static InitializedClient initialize(String host, int port, String principal, String password) { + if (!"account_coord_app".equals(principal)) { + throw new IllegalArgumentException( + "Account current-generation Redis principal must be account_coord_app"); + } + RedisStandaloneConfiguration redisConfiguration = new RedisStandaloneConfiguration(host, port); + redisConfiguration.setUsername(principal); + redisConfiguration.setPassword(RedisPassword.of(password)); + LettuceClientConfiguration clientConfiguration = + LettuceClientConfiguration.builder().commandTimeout(COMMAND_TIMEOUT).build(); + + LettuceConnectionFactory connectionFactory = + new LettuceConnectionFactory(redisConfiguration, clientConfiguration); + connectionFactory.afterPropertiesSet(); + StringRedisTemplate template = new StringRedisTemplate(connectionFactory); + template.afterPropertiesSet(); + return new InitializedClient(connectionFactory, template); + } + + static void verifyScriptDigest(RedisScriptDescriptor descriptor) { + requireSupportedDescriptor(descriptor); + if (!CAS_SCRIPT_SHA256.equals(descriptor.sha256())) { + throw new IllegalStateException( + "Account current-generation projection Lua resource digest differs from its registration"); + } + } + + static StoredValue readStoredValue(StringRedisTemplate template, String key) { + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + return template.execute( + (RedisCallback) + connection -> { + byte[] value = connection.stringCommands().get(keyBytes); + long ttlMillis = value == null ? -2L : connection.keyCommands().pTtl(keyBytes); + return new StoredValue(value, ttlMillis); + }); + } + + static String executeRegistered( + StringRedisTemplate template, + RedisInvocationContract invocation, + RedisScriptDescriptor expectedDescriptor, + String key, + String expectedMode, + String expectedBytes, + String candidateBytes) { + requireSupportedDescriptor(expectedDescriptor); + if (invocation == null || invocation.descriptor() != expectedDescriptor) { + throw new IllegalStateException( + "Account current-generation invocation is not its registered owner contract"); + } + verifyScriptDigest(expectedDescriptor); + 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 template.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 current-generation projection script"); + } + Object result = + connection + .scriptingCommands() + .evalSha( + loadedSha, + ReturnType.VALUE, + 1, + keyBytes, + expectedModeBytes, + expectedBytesUtf8, + candidateBytesUtf8); + return decodeScriptResult(result); + }); + } + + 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 void requireSupportedDescriptor(RedisScriptDescriptor descriptor) { + if (descriptor != AccountGenerationProjectionRedisContract.descriptor() + && descriptor != TenantGenerationProjectionRedisContract.descriptor() + && descriptor != MembershipGenerationProjectionRedisContract.descriptor()) { + throw new IllegalStateException( + "Only Account, tenant, and membership current-generation projection scripts may use this client"); + } + if (!"account-service".equals(descriptor.owner()) + || !"account_coord_app".equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !RESOURCE_PATH.equals(descriptor.resourcePath())) { + throw new IllegalStateException( + "Account current-generation script descriptor has an invalid owner or resource"); + } + } + + private static byte[] scriptBytes() { + try (var input = new ClassPathResource(RESOURCE_PATH).getInputStream()) { + return input.readAllBytes(); + } catch (IOException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new ExceptionInInitializerError(exception); + } + } + + 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"); + } + + record InitializedClient( + LettuceConnectionFactory connectionFactory, StringRedisTemplate template) { + InitializedClient { + Objects.requireNonNull(connectionFactory, "connection factory is required"); + Objects.requireNonNull(template, "Redis template is required"); + } + } + + record StoredValue(byte[] bytes, long ttlMillis) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/MembershipGenerationProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/MembershipGenerationProjection.java new file mode 100644 index 0000000000..c3aa07e757 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/MembershipGenerationProjection.java @@ -0,0 +1,353 @@ +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.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashSet; +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.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountMembershipSourceReader.MembershipSourceSnapshot; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; + +/** Closed current-snapshot projection of one already-enrolled Account membership source. */ +public record MembershipGenerationProjection( + String accountId, + String tenantId, + String membershipAuthorityGeneration, + String sourceVersion, + Map membershipVersion, + String outboxStreamKey, + String outboxSequence, + Optional sourceEvent) { + public static final String SCHEMA_VERSION = "account-auth-membership-generation-projection/v1"; + public static final String KEY_PREFIX = "session:auth:generation:membership:"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:membership/"; + 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", + "tenantId", + "membershipAuthorityGeneration", + "sourceVersion", + "membershipVersion", + "outboxStreamKey", + "outboxSequence"); + private static final Set ALL_FIELDS = + Set.of( + "schemaVersion", + "accountId", + "tenantId", + "membershipAuthorityGeneration", + "sourceVersion", + "membershipVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent"); + + public MembershipGenerationProjection { + requireCanonicalUuid(accountId, "accountId"); + requireCanonicalUuid(tenantId, "tenantId"); + requirePositiveDecimal(membershipAuthorityGeneration, "membershipAuthorityGeneration"); + requirePositiveDecimal(sourceVersion, "sourceVersion"); + requireNonNegativeDecimal(outboxSequence, "outboxSequence"); + membershipVersion = Map.copyOf(Objects.requireNonNull(membershipVersion, "membershipVersion")); + if (membershipVersion.size() != 1 || !membershipVersion.containsKey(tenantId)) { + throw new IllegalArgumentException( + "Membership projection version map must contain exactly its tenantId key"); + } + requirePositiveDecimal(membershipVersion.get(tenantId), "membershipVersion"); + if (!streamKeyForPair(accountId, tenantId).equals(outboxStreamKey)) { + throw new IllegalArgumentException("Membership 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(membershipAuthorityGeneration) + || !"1".equals(sourceVersion) + || !"1".equals(membershipVersion.get(tenantId)) + || sourceEvent.isPresent()) { + throw new IllegalArgumentException( + "Membership sequence zero requires the original 1/1 generation/source baseline, " + + "version 1 and no event"); + } + } else { + if (sourceEvent.isEmpty()) { + throw new IllegalArgumentException( + "Positive membership source sequence requires its exact event"); + } + validateSourceEvent( + sourceEvent.orElseThrow(), + accountId, + tenantId, + membershipAuthorityGeneration, + membershipVersion, + outboxStreamKey, + outboxSequence); + } + } + + /** Builds a candidate only from the owner-local, existing-only Account source reader. */ + public static MembershipGenerationProjection fromSource(MembershipSourceSnapshot source) { + Objects.requireNonNull(source, "Account membership source snapshot is required"); + AuthorityScope expectedScope = AuthorityScope.membership(source.accountId(), source.tenantId()); + if (!expectedScope.equals(source.sourceState().scope()) + || source.sourceState().scope().kind() != ScopeKind.MEMBERSHIP + || source.sourceState().generation() <= 0L + || source.sourceState().sourceVersion() <= 0L) { + throw new IllegalArgumentException("Membership source snapshot has a different scope"); + } + + RuntimeMembershipSnapshotDto snapshot = source.snapshot(); + String accountId = source.accountId().toString(); + String tenantId = source.tenantId().toString(); + String streamKey = streamKeyForPair(accountId, tenantId); + List membershipCheckpoints = + snapshot.outboxCheckpoints().stream() + .filter(checkpoint -> streamKey.equals(checkpoint.outboxStreamKey())) + .toList(); + if (membershipCheckpoints.size() != 1) { + throw new IllegalArgumentException( + "Membership source snapshot must contain one exact membership checkpoint"); + } + OutboxCheckpointEntry checkpoint = membershipCheckpoints.getFirst(); + List membershipEvidence = + snapshot.outboxSourceEvidence().stream() + .filter(evidence -> streamKey.equals(evidence.outboxStreamKey())) + .toList(); + MembershipEvent event = snapshot.requireConsistentSourceEvent(); + + Optional eventJson; + if (event == null) { + if (!"0".equals(checkpoint.outboxSequence()) + || !membershipEvidence.isEmpty() + || snapshot.membershipExists() + || !"MISSING".equals(snapshot.membershipBaseline().membershipLifecycleState()) + || !snapshot.roles().isEmpty() + || source.sourceState().generation() != 1L + || source.sourceState().sourceVersion() != 1L + || !"1".equals(snapshot.membershipBaseline().membershipVersion().get(tenantId))) { + throw new IllegalArgumentException( + "Membership source without an event is not the proved existing sequence-zero baseline"); + } + eventJson = Optional.empty(); + } else { + String canonicalJson = event.canonicalJson(); + MembershipEvent verified = MembershipAuthorityEventV1Codec.verify(canonicalJson); + if (!Arrays.equals( + verified.canonicalJsonUtf8(), canonicalJson.getBytes(StandardCharsets.UTF_8)) + || !verified.canonicalJson().equals(canonicalJson) + || membershipEvidence.size() != 1 + || !verified.eventId().equals(membershipEvidence.getFirst().eventId()) + || !verified.eventDigest().equals(membershipEvidence.getFirst().eventDigest()) + || !verified.outboxSequence().equals(membershipEvidence.getFirst().outboxSequence()) + || !canonicalJson.equals(membershipEvidence.getFirst().canonicalEventJson()) + || !verified.outboxSequence().equals(checkpoint.outboxSequence()) + || !snapshot.membershipExists()) { + throw new IllegalArgumentException( + "Membership source event differs from its exact canonical checkpoint evidence"); + } + eventJson = Optional.of(canonicalJson); + } + + return new MembershipGenerationProjection( + accountId, + tenantId, + Long.toString(source.sourceState().generation()), + Long.toString(source.sourceState().sourceVersion()), + snapshot.membershipBaseline().membershipVersion(), + streamKey, + checkpoint.outboxSequence(), + eventJson); + } + + /** Parses the closed wire shape, requiring canonical JSON and all exact source bindings. */ + public static MembershipGenerationProjection parse(String json) { + Objects.requireNonNull(json, "projection JSON is required"); + final JsonNode root; + try { + root = JSON.readTree(json); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Membership generation projection JSON is malformed", exception); + } + if (!(root instanceof ObjectNode object)) { + throw new IllegalArgumentException("Membership 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("Membership projection has unknown or missing fields"); + } + if (fields.contains("sourceEvent") && !fields.equals(ALL_FIELDS)) { + throw new IllegalArgumentException("Membership projection has unknown or missing fields"); + } + if (!SCHEMA_VERSION.equals(requireText(object, "schemaVersion"))) { + throw new IllegalArgumentException("Membership projection schemaVersion is unsupported"); + } + + String tenantId = requireText(object, "tenantId"); + JsonNode versionNode = object.get("membershipVersion"); + if (!(versionNode instanceof ObjectNode versions) || versions.size() != 1) { + throw new IllegalArgumentException( + "Membership projection membershipVersion must be a one-tenant object"); + } + Map versionMap = Map.of(tenantId, requireText(versions, tenantId)); + Optional event = + fields.contains("sourceEvent") + ? Optional.of(requireText(object, "sourceEvent")) + : Optional.empty(); + MembershipGenerationProjection projection = + new MembershipGenerationProjection( + requireText(object, "accountId"), + tenantId, + requireText(object, "membershipAuthorityGeneration"), + requireText(object, "sourceVersion"), + versionMap, + requireText(object, "outboxStreamKey"), + requireText(object, "outboxSequence"), + event); + if (!projection.toJson().equals(json)) { + throw new IllegalArgumentException("Membership projection JSON is not canonical"); + } + return projection; + } + + public String key() { + return KEY_PREFIX + accountId + ":" + tenantId; + } + + public String toJson() { + ObjectNode object = JSON.createObjectNode(); + object.put("schemaVersion", SCHEMA_VERSION); + object.put("accountId", accountId); + object.put("tenantId", tenantId); + object.put("membershipAuthorityGeneration", membershipAuthorityGeneration); + object.put("sourceVersion", sourceVersion); + ObjectNode versions = object.putObject("membershipVersion"); + versions.put(tenantId, membershipVersion.get(tenantId)); + 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("Membership projection cannot be serialized", exception); + } + } + + public BigInteger generationValue() { + return new BigInteger(membershipAuthorityGeneration); + } + + public BigInteger sourceVersionValue() { + return new BigInteger(sourceVersion); + } + + public BigInteger membershipVersionValue() { + return new BigInteger(membershipVersion.get(tenantId)); + } + + public BigInteger outboxSequenceValue() { + return new BigInteger(outboxSequence); + } + + static String keyForPair(UUID accountId, UUID tenantId) { + requireNonNilUuid(accountId, "Account UUID"); + requireNonNilUuid(tenantId, "tenant UUID"); + return KEY_PREFIX + accountId + ":" + tenantId; + } + + private static String streamKeyForPair(String accountId, String tenantId) { + return STREAM_PREFIX + accountId + "/" + tenantId; + } + + private static void validateSourceEvent( + String eventJson, + String accountId, + String tenantId, + String generation, + Map membershipVersion, + String streamKey, + String sequence) { + MembershipEvent event = MembershipAuthorityEventV1Codec.verify(eventJson); + if (!event.canonicalJson().equals(eventJson) + || !Arrays.equals(event.canonicalJsonUtf8(), eventJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Membership source event JSON is not canonical"); + } + if (!accountId.equals(event.accountId()) + || !tenantId.equals(event.tenantId()) + || !("membership/" + accountId + "/" + tenantId).equals(event.sourceScope()) + || !streamKey.equals(event.outboxStreamKey()) + || !sequence.equals(event.outboxSequence()) + || !generation.equals(event.membershipAuthorityGeneration()) + || !membershipVersion.equals(event.membershipVersion())) { + throw new IllegalArgumentException( + "Membership source event does not match its exact projection checkpoint"); + } + } + + private static String requireText(ObjectNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Membership projection " + field + " must be a string"); + } + return value.textValue(); + } + + private static void requireCanonicalUuid(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + try { + UUID parsed = UUID.fromString(value); + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static void requireNonNilUuid(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must be a non-nil UUID"); + } + } + + 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/MembershipGenerationProjectionRedisContract.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/MembershipGenerationProjectionRedisContract.java new file mode 100644 index 0000000000..655746a34a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/MembershipGenerationProjectionRedisContract.java @@ -0,0 +1,125 @@ +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 CAS for one exact membership-generation pair. */ +public final class MembershipGenerationProjectionRedisContract { + public static final String SCRIPT_ID = "account.membership-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 = MembershipGenerationProjection.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 MembershipGenerationProjectionRedisContract() {} + + public static RedisScriptDescriptor descriptor() { + return DESCRIPTOR; + } + + /** Declarative registry only; executable access stays private to the owner store. */ + public static RedisContractRegistry registry() { + return REGISTRY; + } + + static RedisInvocationContract prepareInvocation( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + Objects.requireNonNull(key, "Membership generation key is required"); + requireCanonicalMembershipKey(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 requireCanonicalMembershipKey(String key) { + if (!key.startsWith(KEY_PREFIX)) { + throw new IllegalArgumentException("Membership generation key is outside its owner prefix"); + } + String pair = key.substring(KEY_PREFIX.length()); + int separator = pair.indexOf(':'); + if (separator <= 0 || separator != pair.lastIndexOf(':') || separator == pair.length() - 1) { + throw new IllegalArgumentException( + "Membership generation key must contain one canonical Account/tenant UUID pair"); + } + requireCanonicalUuid(pair.substring(0, separator)); + requireCanonicalUuid(pair.substring(separator + 1)); + } + + private static void requireCanonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException( + "Membership generation key must use canonical non-nil UUIDs"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Membership generation key must use canonical non-nil UUIDs", malformed); + } + } + + private static RedisScriptDescriptor createDescriptor() { + return new RedisScriptDescriptor( + SCRIPT_ID, + RESOURCE_PATH, + RESOURCE_SHA256, + OWNER, + PRINCIPAL, + ROLE, + List.of( + new KeySpec( + "membershipGenerationProjection", 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 existing membership source.", + CompatibilityLevel.COMPATIBLE, + List.of(new SupportedCoexistence("v1", "v1")), + null); + } +} 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 index b405321f48..fd072b32f5 100644 --- 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 @@ -1,27 +1,16 @@ 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; /** @@ -29,11 +18,6 @@ * 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; @@ -61,22 +45,16 @@ public synchronized void init() { 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; + CurrentGenerationProjectionRedisSupport.verifyScriptDigest( + AccountGenerationProjectionRedisContract.descriptor()); + CurrentGenerationProjectionRedisSupport.InitializedClient client = + CurrentGenerationProjectionRedisSupport.initialize( + coordinationEndpoint.host(), + coordinationEndpoint.port(), + coordinationEndpoint.principal(), + coordinationEndpoint.password()); + connectionFactory = client.connectionFactory(); + redisTemplate = client.template(); } /** @@ -95,7 +73,7 @@ public synchronized ApplyResult refreshCurrent(UUID accountId) { String candidateJson = candidate.toJson(); byte[] candidateBytes = candidateJson.getBytes(StandardCharsets.UTF_8); - StoredValue observed = readStoredValue(key); + CurrentGenerationProjectionRedisSupport.StoredValue observed = readStoredValue(key); if (observed.bytes() != null && observed.ttlMillis() != -1L) { return quarantined("TTL_PRESENT", Optional.empty()); } @@ -153,7 +131,7 @@ public synchronized ApplyResult refreshCurrent(UUID accountId) { + Objects.toString(scriptResult, "null")); } - StoredValue readback = readStoredValue(key); + CurrentGenerationProjectionRedisSupport.StoredValue readback = readStoredValue(key); if (readback.bytes() == null) { return new ApplyResult( Outcome.STALE, Optional.empty(), Optional.of("REDIS_READBACK_MISSING")); @@ -218,51 +196,18 @@ private String executeRegistered( 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); - }); + return CurrentGenerationProjectionRedisSupport.executeRegistered( + redisTemplate, + invocation, + AccountGenerationProjectionRedisContract.descriptor(), + key, + expectedMode, + expectedBytes, + candidateBytes); } - 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 CurrentGenerationProjectionRedisSupport.StoredValue readStoredValue(String key) { + return CurrentGenerationProjectionRedisSupport.readStoredValue(redisTemplate, key); } private void requireInitialized() { @@ -272,72 +217,8 @@ private void requireInitialized() { } } - 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"); + return CurrentGenerationProjectionRedisSupport.decodeUtf8(value); } private static void validateDistinctEndpoints( @@ -371,8 +252,6 @@ private static ApplyResult quarantined(String detail, Optional snapshot) { + return new ApplyResult(Outcome.QUARANTINED, snapshot, Optional.of(detail)); + } + + 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 (!MembershipGenerationProjectionRedisContract.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/RedisTenantGenerationProjectionStore.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/RedisTenantGenerationProjectionStore.java new file mode 100644 index 0000000000..65a30c770a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/RedisTenantGenerationProjectionStore.java @@ -0,0 +1,323 @@ +package net.firedevops.firemud.accountservice.service; + +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisInvocationContract; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.StringRedisTemplate; + +/** + * Explicitly initialized, unwired Account-owned store for the current tenant-generation projection. + */ +public final class RedisTenantGenerationProjectionStore implements AutoCloseable { + private final AccountTenantAuthorityEventProducer source; + 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 RedisTenantGenerationProjectionStore( + AccountTenantAuthorityEventProducer source, + CoordinationEndpoint coordination, + CacheRateLimitEndpoint cache) { + this.source = Objects.requireNonNull(source, "Tenant authority source 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("Tenant generation projection store is closed"); + } + if (connectionFactory != null) { + return; + } + CurrentGenerationProjectionRedisSupport.verifyScriptDigest( + TenantGenerationProjectionRedisContract.descriptor()); + CurrentGenerationProjectionRedisSupport.InitializedClient client = + CurrentGenerationProjectionRedisSupport.initialize( + coordinationEndpoint.host(), + coordinationEndpoint.port(), + coordinationEndpoint.principal(), + coordinationEndpoint.password()); + connectionFactory = client.connectionFactory(); + redisTemplate = client.template(); + } + + /** + * Reprojects one exact current Account tenant 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 tenantId) { + requireInitialized(); + String key = TenantGenerationProjection.keyForTenant(tenantId); + TenantGenerationProjection candidate = + TenantGenerationProjection.fromSource(source.readCurrent(tenantId)); + if (!key.equals(candidate.key())) { + return quarantined("TENANT_SOURCE_IDENTITY_MISMATCH", Optional.empty()); + } + String candidateJson = candidate.toJson(); + byte[] candidateBytes = candidateJson.getBytes(StandardCharsets.UTF_8); + + CurrentGenerationProjectionRedisSupport.StoredValue observed = readStoredValue(key); + if (observed.bytes() != null && observed.ttlMillis() != -1L) { + return quarantined("TTL_PRESENT", Optional.empty()); + } + + TenantGenerationProjection stored = null; + String storedJson = null; + if (observed.bytes() != null) { + try { + storedJson = CurrentGenerationProjectionRedisSupport.decodeUtf8(observed.bytes()); + stored = TenantGenerationProjection.parse(storedJson); + } catch (CharacterCodingException | IllegalArgumentException malformed) { + return quarantined("MALFORMED_STORED_PROJECTION", Optional.empty()); + } + if (!key.equals(stored.key())) { + return quarantined("STORED_TENANT_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 tenant generation projection script rejected its invocation"); + } + if (!"APPLIED".equals(scriptResult) && !"REPLAY".equals(scriptResult)) { + throw new IllegalStateException( + "Unknown registered tenant generation projection script result: " + + Objects.toString(scriptResult, "null")); + } + + CurrentGenerationProjectionRedisSupport.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()); + } + + TenantGenerationProjection current = + TenantGenerationProjection.fromSource(source.readCurrent(tenantId)); + if (!candidate.equals(current)) { + return new ApplyResult( + Outcome.SOURCE_CHANGED, + Optional.of(new ProjectionSnapshot(key, candidateJson)), + Optional.of("ACCOUNT_TENANT_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 = CurrentGenerationProjectionRedisSupport.decodeUtf8(bytes); + TenantGenerationProjection projection = TenantGenerationProjection.parse(json); + if (!key.equals(projection.key())) { + return quarantined("READBACK_TENANT_ID_MISMATCH", Optional.empty()); + } + return new ApplyResult( + Outcome.STALE, + Optional.of(new ProjectionSnapshot(key, json)), + Optional.of("REDIS_READBACK_CHANGED")); + } catch (CharacterCodingException | IllegalArgumentException malformed) { + return quarantined("MALFORMED_REDIS_READBACK", Optional.empty()); + } + } + + private static boolean isRegression( + TenantGenerationProjection candidate, TenantGenerationProjection 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 = + TenantGenerationProjectionRedisContract.prepareInvocation( + key, expectedMode, expectedBytes, candidateBytes); + return CurrentGenerationProjectionRedisSupport.executeRegistered( + redisTemplate, + invocation, + TenantGenerationProjectionRedisContract.descriptor(), + key, + expectedMode, + expectedBytes, + candidateBytes); + } + + private CurrentGenerationProjectionRedisSupport.StoredValue readStoredValue(String key) { + return CurrentGenerationProjectionRedisSupport.readStoredValue(redisTemplate, key); + } + + private void requireInitialized() { + if (closed || redisTemplate == null) { + throw new IllegalStateException( + "Tenant generation 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 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)); + } + + 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 (!TenantGenerationProjectionRedisContract.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/TenantGenerationProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/TenantGenerationProjection.java new file mode 100644 index 0000000000..c4ade74113 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/TenantGenerationProjection.java @@ -0,0 +1,272 @@ +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.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.common.account.authority.TenantGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent; + +/** Closed current-snapshot projection of one durable Account tenant-generation source. */ +public record TenantGenerationProjection( + String tenantId, + String tenantAuthorityGeneration, + String sourceVersion, + String outboxStreamKey, + String outboxSequence, + Optional sourceEvent) { + public static final String SCHEMA_VERSION = "account-auth-tenant-generation-projection/v1"; + public static final String KEY_PREFIX = "session:auth:generation:tenant:"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:tenant/"; + 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", + "tenantId", + "tenantAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence"); + private static final Set ALL_FIELDS = + Set.of( + "schemaVersion", + "tenantId", + "tenantAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent"); + + public TenantGenerationProjection { + requireCanonicalTenantId(tenantId); + requirePositiveDecimal(tenantAuthorityGeneration, "tenantAuthorityGeneration"); + requirePositiveDecimal(sourceVersion, "sourceVersion"); + requireNonNegativeDecimal(outboxSequence, "outboxSequence"); + if (!streamKeyForTenant(tenantId).equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Tenant generation projection stream key is not canonical"); + } + sourceEvent = Objects.requireNonNull(sourceEvent, "sourceEvent optional is required"); + + BigInteger generation = new BigInteger(tenantAuthorityGeneration); + BigInteger version = new BigInteger(sourceVersion); + BigInteger sequence = new BigInteger(outboxSequence); + if (sequence.signum() == 0) { + if (!BigInteger.ONE.equals(generation) + || !BigInteger.ONE.equals(version) + || sourceEvent.isPresent()) { + throw new IllegalArgumentException( + "Tenant sequence zero requires the original 1/1 source baseline and no event"); + } + } else { + if (!generation.equals(version) + || !generation.equals(sequence.add(BigInteger.ONE)) + || sourceEvent.isEmpty()) { + throw new IllegalArgumentException( + "Positive tenant projection requires generation=sourceVersion=sequence+1 " + + "and its exact event"); + } + validateSourceEvent( + sourceEvent.orElseThrow(), + tenantId, + tenantAuthorityGeneration, + sourceVersion, + outboxStreamKey, + outboxSequence); + } + } + + /** Builds projection evidence only from Account's owner-local current durable readback. */ + public static TenantGenerationProjection fromSource( + AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot source) { + Objects.requireNonNull(source, "Tenant source snapshot is required"); + String tenantText = source.tenantId().toString(); + String generation = Long.toString(source.tenantAuthorityGeneration()); + String version = Long.toString(source.sourceVersion()); + String sequence = Long.toString(source.outboxSequence()); + Optional event = + source + .latestEvent() + .map( + evidence -> { + TenantGenerationAuthorityEvent verified = + TenantGenerationAuthorityEventV1Codec.verify(evidence.canonicalJson()); + if (!verified.eventDigest().equals(evidence.eventDigest()) + || !verified.canonicalJson().equals(evidence.canonicalJson()) + || !java.util.Arrays.equals( + verified.canonicalJsonUtf8(), evidence.canonicalJsonUtf8())) { + throw new IllegalArgumentException( + "Tenant source event differs from its closed codec readback"); + } + return verified.canonicalJson(); + }); + return new TenantGenerationProjection( + tenantText, generation, version, source.outboxStreamKey(), sequence, event); + } + + /** + * Parses the closed wire shape and rejects noncanonical JSON and all alternate representations. + */ + public static TenantGenerationProjection parse(String json) { + Objects.requireNonNull(json, "projection JSON is required"); + final JsonNode root; + try { + root = JSON.readTree(json); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Tenant generation projection JSON is malformed", exception); + } + if (!(root instanceof ObjectNode object)) { + throw new IllegalArgumentException("Tenant 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( + "Tenant generation projection has unknown or missing fields"); + } + if (fields.contains("sourceEvent") && !fields.equals(ALL_FIELDS)) { + throw new IllegalArgumentException( + "Tenant generation projection has unknown or missing fields"); + } + if (!SCHEMA_VERSION.equals(requireText(object, "schemaVersion"))) { + throw new IllegalArgumentException( + "Tenant generation projection schemaVersion is unsupported"); + } + Optional event = + fields.contains("sourceEvent") + ? Optional.of(requireText(object, "sourceEvent")) + : Optional.empty(); + TenantGenerationProjection projection = + new TenantGenerationProjection( + requireText(object, "tenantId"), + requireText(object, "tenantAuthorityGeneration"), + requireText(object, "sourceVersion"), + requireText(object, "outboxStreamKey"), + requireText(object, "outboxSequence"), + event); + if (!projection.toJson().equals(json)) { + throw new IllegalArgumentException("Tenant generation projection JSON is not canonical"); + } + return projection; + } + + public String key() { + return KEY_PREFIX + tenantId; + } + + public String toJson() { + ObjectNode object = JSON.createObjectNode(); + object.put("schemaVersion", SCHEMA_VERSION); + object.put("tenantId", tenantId); + object.put("tenantAuthorityGeneration", tenantAuthorityGeneration); + 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( + "Tenant generation projection cannot be serialized", exception); + } + } + + public BigInteger generationValue() { + return new BigInteger(tenantAuthorityGeneration); + } + + public BigInteger sourceVersionValue() { + return new BigInteger(sourceVersion); + } + + public BigInteger outboxSequenceValue() { + return new BigInteger(outboxSequence); + } + + static String keyForTenant(UUID tenantId) { + Objects.requireNonNull(tenantId, "Tenant UUID is required"); + if (new UUID(0L, 0L).equals(tenantId)) { + throw new IllegalArgumentException("A canonical non-nil tenant UUID is required"); + } + return KEY_PREFIX + tenantId; + } + + private static String streamKeyForTenant(String tenantId) { + return STREAM_PREFIX + tenantId; + } + + private static void validateSourceEvent( + String eventJson, + String tenantId, + String generation, + String sourceVersion, + String streamKey, + String sequence) { + TenantGenerationAuthorityEvent event = TenantGenerationAuthorityEventV1Codec.verify(eventJson); + if (!event.canonicalJson().equals(eventJson)) { + throw new IllegalArgumentException("Tenant source event JSON is not canonical"); + } + if (!tenantId.equals(event.tenantId()) + || !("tenant/" + tenantId).equals(event.sourceScope()) + || !generation.equals(event.tenantAuthorityGeneration()) + || !sourceVersion.equals(event.sourceVersion()) + || !streamKey.equals(event.outboxStreamKey()) + || !sequence.equals(event.outboxSequence())) { + throw new IllegalArgumentException( + "Tenant 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( + "Tenant generation projection " + field + " must be a string"); + } + return value.textValue(); + } + + private static void requireCanonicalTenantId(String value) { + Objects.requireNonNull(value, "tenantId is required"); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException( + "Tenant generation projection tenantId is not canonical"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Tenant generation projection tenantId 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/TenantGenerationProjectionRedisContract.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/TenantGenerationProjectionRedisContract.java new file mode 100644 index 0000000000..7a8d8c18cd --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/TenantGenerationProjectionRedisContract.java @@ -0,0 +1,114 @@ +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 tenant generation projection. */ +public final class TenantGenerationProjectionRedisContract { + public static final String SCRIPT_ID = "account.tenant-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 = TenantGenerationProjection.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 TenantGenerationProjectionRedisContract() {} + + 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, "Tenant generation key is required"); + requireCanonicalTenantKey(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 requireCanonicalTenantKey(String key) { + if (!key.startsWith(KEY_PREFIX)) { + throw new IllegalArgumentException("Tenant generation key is outside its owner prefix"); + } + String tenantId = key.substring(KEY_PREFIX.length()); + try { + UUID parsed = UUID.fromString(tenantId); + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(tenantId)) { + throw new IllegalArgumentException( + "Tenant generation key must use a canonical non-nil UUID"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Tenant 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("tenantGenerationProjection", 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/resources/db/migration/V43__issuer_projection_reconciliation_receipts.sql b/services/account-service/src/main/resources/db/migration/V43__issuer_projection_reconciliation_receipts.sql new file mode 100644 index 0000000000..46d251deec --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V43__issuer_projection_reconciliation_receipts.sql @@ -0,0 +1,106 @@ +-- Durable Account receipt identity for exact issuer projection snapshot captures. +CREATE TABLE account_issuer_projection_reconciliation_receipts ( + operation_id UUID NOT NULL, + request_id UUID NOT NULL, + issuer_id VARCHAR(512) NOT NULL, + caller_workload_identity VARCHAR(512) NOT NULL, + projection_key VARCHAR(2048) NOT NULL, + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + issuer_auth_generation BIGINT NOT NULL, + source_version BIGINT NOT NULL, + outbox_stream_key VARCHAR(2048) NOT NULL, + outbox_sequence BIGINT NOT NULL, + event_outbox_sequence BIGINT, + event_id VARCHAR(512), + event_digest VARCHAR(71), + event_payload BYTEA, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_issuer_projection_reconciliation_operation_pk PRIMARY KEY (operation_id), + CONSTRAINT account_issuer_projection_reconciliation_request_uq UNIQUE (issuer_id, request_id), + CONSTRAINT account_issuer_projection_reconciliation_identity_check CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND length(btrim(issuer_id)) BETWEEN 1 AND 512 + AND length(btrim(caller_workload_identity)) BETWEEN 1 AND 512 + AND projection_key = 'session:game:auth:issuer-generation:v1:' || issuer_id + AND request_digest_version = 1 + AND octet_length(request_digest) = 32 + AND issuer_auth_generation > 0 + AND source_version > 0 + AND outbox_stream_key = 'account:auth-authority:v1:issuer/' || issuer_id + AND outbox_sequence >= 0 + ), + CONSTRAINT account_issuer_projection_reconciliation_checkpoint_check CHECK ( + (outbox_sequence = 0 + AND issuer_auth_generation = 1 + AND source_version = 1 + AND event_id IS NULL + AND event_digest IS NULL + AND event_outbox_sequence IS NULL + AND event_payload IS NULL) + OR + (outbox_sequence > 0 + AND event_id IS NOT NULL + AND length(btrim(event_id)) BETWEEN 1 AND 512 + AND event_outbox_sequence IS NOT NULL + AND event_outbox_sequence = outbox_sequence + AND event_digest IS NOT NULL + AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND event_payload IS NOT NULL + AND octet_length(event_payload) > 0) + ), + CONSTRAINT account_issuer_projection_reconciliation_outbox_fk + FOREIGN KEY (outbox_stream_key, event_outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT +); + +-- [jooq ignore start] +CREATE FUNCTION account_issuer_projection_reconciliation_event_binding_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + stored_event_id TEXT; + stored_event_digest TEXT; + stored_payload BYTEA; +BEGIN + IF NEW.outbox_sequence > 0 THEN + SELECT event_id, event_digest, payload + INTO stored_event_id, stored_event_digest, stored_payload + FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.outbox_stream_key + AND outbox_sequence = NEW.outbox_sequence; + IF stored_event_id IS DISTINCT FROM NEW.event_id + OR stored_event_digest IS DISTINCT FROM NEW.event_digest + OR stored_payload IS DISTINCT FROM NEW.event_payload THEN + RAISE EXCEPTION 'Issuer reconciliation receipt differs from its source event' + USING ERRCODE = '23514', + CONSTRAINT = 'account_issuer_projection_reconciliation_event_binding'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_issuer_projection_reconciliation_event_binding + BEFORE INSERT ON account_issuer_projection_reconciliation_receipts + FOR EACH ROW EXECUTE FUNCTION account_issuer_projection_reconciliation_event_binding_guard(); + +CREATE FUNCTION account_issuer_projection_reconciliation_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Issuer projection reconciliation receipts are immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'account_issuer_projection_reconciliation_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_issuer_projection_reconciliation_immutable + BEFORE UPDATE OR DELETE ON account_issuer_projection_reconciliation_receipts + FOR EACH ROW EXECUTE FUNCTION account_issuer_projection_reconciliation_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V44__issuer_projection_installation_acknowledgments.sql b/services/account-service/src/main/resources/db/migration/V44__issuer_projection_installation_acknowledgments.sql new file mode 100644 index 0000000000..29ea3c3fc8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V44__issuer_projection_installation_acknowledgments.sql @@ -0,0 +1,127 @@ +-- Durable Account acknowledgment of a Game Session issuer-projection installation. +-- [jooq ignore start] +CREATE FUNCTION account_issuer_install_ack_frame_text(value TEXT) +RETURNS BYTEA +LANGUAGE SQL +IMMUTABLE +STRICT +AS $$ + SELECT convert_to( + octet_length(convert_to(value, 'UTF8'))::TEXT || ':', 'UTF8') + || convert_to(value, 'UTF8') +$$; + +CREATE FUNCTION account_issuer_install_ack_frame_bytes(value BYTEA) +RETURNS BYTEA +LANGUAGE SQL +IMMUTABLE +STRICT +AS $$ + SELECT convert_to(octet_length(value)::TEXT || ':', 'UTF8') || value +$$; +-- [jooq ignore stop] + +CREATE TABLE account_issuer_projection_installation_acknowledgments ( + acknowledgment_id UUID NOT NULL, + capture_operation_id UUID NOT NULL, + capture_request_id UUID NOT NULL, + issuer_id VARCHAR(512) NOT NULL, + caller_workload_identity VARCHAR(512) NOT NULL, + projection_key VARCHAR(2048) NOT NULL, + capture_request_digest_version INTEGER NOT NULL, + capture_request_digest BYTEA NOT NULL, + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + installed_projection_json BYTEA NOT NULL, + installed_projection_sha256 BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_issuer_install_ack_pk + PRIMARY KEY (acknowledgment_id), + CONSTRAINT account_issuer_install_ack_capture_uq + UNIQUE (capture_operation_id), + CONSTRAINT account_issuer_install_ack_capture_fk + FOREIGN KEY (capture_operation_id) + REFERENCES account_issuer_projection_reconciliation_receipts (operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_issuer_install_ack_binding_check CHECK ( + acknowledgment_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND capture_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND capture_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND length(btrim(issuer_id)) BETWEEN 1 AND 512 + AND length(btrim(caller_workload_identity)) BETWEEN 1 AND 512 + AND projection_key = 'session:game:auth:issuer-generation:v1:' || issuer_id + AND capture_request_digest_version = 1 + AND octet_length(capture_request_digest) = 32 + AND request_digest_version = 1 + AND octet_length(request_digest) = 32 + AND octet_length(installed_projection_json) BETWEEN 1 AND 65536 + AND octet_length(installed_projection_sha256) = 32 + AND installed_projection_sha256 = sha256(installed_projection_json) + ), + CONSTRAINT account_issuer_install_ack_digest_check CHECK ( + request_digest = sha256( + account_issuer_install_ack_frame_text( + 'issuer-projection-installation-ack/v1') + || account_issuer_install_ack_frame_text( + 'ISSUER_PROJECTION_INSTALLATION_ACK') + || account_issuer_install_ack_frame_text(issuer_id) + || account_issuer_install_ack_frame_text(caller_workload_identity) + || account_issuer_install_ack_frame_text(projection_key) + || account_issuer_install_ack_frame_text(capture_operation_id::TEXT) + || account_issuer_install_ack_frame_text(capture_request_id::TEXT) + || account_issuer_install_ack_frame_text( + capture_request_digest_version::TEXT) + || account_issuer_install_ack_frame_text( + encode(capture_request_digest, 'hex')) + || account_issuer_install_ack_frame_bytes(installed_projection_json) + ) + ) +); + +-- [jooq ignore start] +CREATE FUNCTION account_issuer_install_ack_capture_binding_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + capture_row account_issuer_projection_reconciliation_receipts%ROWTYPE; +BEGIN + SELECT * + INTO capture_row + FROM account_issuer_projection_reconciliation_receipts + WHERE operation_id = NEW.capture_operation_id; + IF NOT FOUND + OR capture_row.request_id IS DISTINCT FROM NEW.capture_request_id + OR capture_row.issuer_id IS DISTINCT FROM NEW.issuer_id + OR capture_row.caller_workload_identity IS DISTINCT FROM NEW.caller_workload_identity + OR capture_row.projection_key IS DISTINCT FROM NEW.projection_key + OR capture_row.request_digest_version IS DISTINCT FROM NEW.capture_request_digest_version + OR capture_row.request_digest IS DISTINCT FROM NEW.capture_request_digest THEN + RAISE EXCEPTION 'Issuer projection acknowledgment differs from its exact capture binding' + USING ERRCODE = '23514', + CONSTRAINT = 'account_issuer_install_ack_capture_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_issuer_install_ack_capture_binding + BEFORE INSERT ON account_issuer_projection_installation_acknowledgments + FOR EACH ROW EXECUTE FUNCTION account_issuer_install_ack_capture_binding_guard(); + +CREATE FUNCTION account_issuer_install_ack_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Issuer projection installation acknowledgments are immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'account_issuer_install_ack_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_issuer_install_ack_immutable + BEFORE UPDATE OR DELETE ON account_issuer_projection_installation_acknowledgments + FOR EACH ROW EXECUTE FUNCTION account_issuer_install_ack_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V45__canonical_uuid_membership_identity.sql b/services/account-service/src/main/resources/db/migration/V45__canonical_uuid_membership_identity.sql new file mode 100644 index 0000000000..9aa1900624 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V45__canonical_uuid_membership_identity.sql @@ -0,0 +1,127 @@ +-- Preserve existing numeric membership rows as unbridged history. Only an +-- Account-owned canonical writer may attach one of the immutable tenant sources. +ALTER TABLE account_tenant_membership + ADD COLUMN tenant_uuid UUID, + ADD COLUMN tenant_provenance_kind VARCHAR(32) NOT NULL DEFAULT 'UNBRIDGED_RETAINED', + ADD COLUMN tenant_source_operation_id UUID, + ADD COLUMN tenant_provenance_digest VARCHAR(71); + +ALTER TABLE account_tenant_membership + ALTER COLUMN tenant_id DROP NOT NULL; + +ALTER TABLE account_tenant_membership + ADD CONSTRAINT account_tenant_membership_tenant_identity_check + CHECK ( + (tenant_provenance_kind = 'UNBRIDGED_RETAINED' + AND tenant_id IS NOT NULL + AND tenant_uuid IS NULL + AND tenant_source_operation_id IS NULL + AND tenant_provenance_digest IS NULL) + OR + (tenant_provenance_kind = 'APPROVED_RETAINED' + AND tenant_id IS NOT NULL + AND tenant_id > 0 + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_source_operation_id IS NOT NULL + AND tenant_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_provenance_digest IS NOT NULL + AND tenant_provenance_digest ~ '^sha256:[0-9a-f]{64}$') + OR + (tenant_provenance_kind = 'FRESH_GAME_DESIGN' + AND tenant_id IS NULL + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_source_operation_id IS NOT NULL + AND tenant_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_provenance_digest IS NOT NULL + AND tenant_provenance_digest ~ '^sha256:[0-9a-f]{64}$') + ); + +CREATE UNIQUE INDEX account_tenant_membership_canonical_identity_uq + ON account_tenant_membership (account_id, tenant_uuid) + WHERE tenant_uuid IS NOT NULL; + +-- The discriminator and source tuple are durable membership identity. Existing +-- rows may be bound exactly once to their authenticated retained association; +-- fresh identity is created only on a new UUID-only row. +-- [jooq ignore start] +CREATE FUNCTION validate_account_membership_tenant_identity() RETURNS trigger AS $$ +DECLARE + source_matches BOOLEAN := FALSE; +BEGIN + IF TG_OP = 'UPDATE' THEN + IF NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id THEN + RAISE EXCEPTION 'Account membership storage identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.tenant_provenance_kind <> 'UNBRIDGED_RETAINED' THEN + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.tenant_provenance_kind IS DISTINCT FROM OLD.tenant_provenance_kind + OR NEW.tenant_source_operation_id IS DISTINCT FROM OLD.tenant_source_operation_id + OR NEW.tenant_provenance_digest IS DISTINCT FROM OLD.tenant_provenance_digest THEN + RAISE EXCEPTION 'Canonical Account membership tenant identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.tenant_provenance_kind = 'UNBRIDGED_RETAINED' + AND NEW.tenant_uuid IS NULL + AND NEW.tenant_source_operation_id IS NULL + AND NEW.tenant_provenance_digest IS NULL THEN + RETURN NEW; + END IF; + END IF; + + IF NEW.tenant_provenance_kind = 'UNBRIDGED_RETAINED' THEN + RETURN NEW; + ELSIF NEW.tenant_provenance_kind = 'APPROVED_RETAINED' THEN + SELECT EXISTS ( + SELECT 1 + FROM account_approved_legacy_tenant_associations retained + WHERE retained.legacy_tenant_id = NEW.tenant_id + AND retained.canonical_tenant_id = NEW.tenant_uuid + AND retained.operation_id = NEW.tenant_source_operation_id + AND retained.manifest_digest = NEW.tenant_provenance_digest + ) INTO source_matches; + ELSIF NEW.tenant_provenance_kind = 'FRESH_GAME_DESIGN' THEN + SELECT EXISTS ( + SELECT 1 + FROM account_fresh_tenant_identity_associations fresh + WHERE fresh.canonical_tenant_id = NEW.tenant_uuid + AND fresh.operation_id = NEW.tenant_source_operation_id + AND fresh.evidence_digest = NEW.tenant_provenance_digest + AND EXISTS ( + SELECT 1 + FROM account_canonical_tenant_identity_claims claim + WHERE claim.canonical_tenant_id = fresh.canonical_tenant_id + AND claim.identity_kind = NEW.tenant_provenance_kind + AND claim.source_operation_id = fresh.operation_id + AND claim.source_target_namespace = fresh.target_namespace + AND claim.source_creation_request_id = fresh.creation_request_id + AND claim.source_request_digest = fresh.request_digest + AND claim.source_game_row_id = fresh.source_game_row_id + AND claim.source_game_tenant_key = fresh.source_game_tenant_key + AND claim.source_provenance_kind = fresh.provenance_kind + AND claim.source_evidence_digest = fresh.evidence_digest + AND claim.source_account_legacy_tenant_id IS NULL + AND claim.source_manifest_digest IS NULL + ) + ) INTO source_matches; + END IF; + + IF NOT source_matches THEN + RAISE EXCEPTION 'Account membership tenant identity has no exact immutable source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_tenant_membership_tenant_identity_guard + BEFORE INSERT OR UPDATE ON account_tenant_membership + FOR EACH ROW EXECUTE FUNCTION validate_account_membership_tenant_identity(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java index 991b713942..0c7bcb0e75 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java @@ -19,6 +19,7 @@ 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; @@ -34,6 +35,8 @@ 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.AccountMembershipSourceReader; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.accountservice.service.AccountTenantAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; @@ -97,6 +100,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AccountService accountService; @Autowired private AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; + @Autowired private AccountMembershipLifecycleService membershipLifecycleService; @Autowired private AccountAuthorityGenerationRepository authorityGenerationRepository; @Autowired private AccountAuthorityOutboxRepository authorityOutboxRepository; @Autowired private AccountRepository accountRepository; @@ -120,6 +124,53 @@ void postJoinSnapshotCarriesCurrentCompositeSourcesWithoutRewritingMembershipEve RuntimeMembershipSnapshotDto before = readRuntimeMembershipSnapshot(fixture); var immutableMembershipEvent = before.sourceEvent(); byte[] immutableMembershipBytes = immutableMembershipEvent.canonicalJsonUtf8(); + Map membershipRowBeforeSourceRead = membershipRow(fixture); + Map membershipPairBeforeSourceRead = membershipPairAuthorityRow(fixture); + Map membershipGenerationBeforeSourceRead = membershipGenerationRow(fixture); + long fenceBeforeSourceRead = accountIssuanceFence(fixture); + Map fenceRowBeforeSourceRead = accountIssuanceFenceRow(fixture); + var beforeMembershipSource = + membershipSourceReader().readCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(beforeMembershipSource.accountId()).isEqualTo(fixture.accountUuid()); + assertThat(beforeMembershipSource.tenantId()).isEqualTo(fixture.tenantUuid()); + assertThat(beforeMembershipSource.sourceState().scope()) + .isEqualTo(AuthorityScope.membership(fixture.accountUuid(), fixture.tenantUuid())); + assertThat(beforeMembershipSource.sourceState().generation()).isEqualTo(1L); + assertThat(beforeMembershipSource.sourceState().sourceVersion()).isEqualTo(1L); + assertThat(beforeMembershipSource.sourceState().issuanceFence().accountId()) + .isEqualTo(fixture.accountUuid()); + assertThat(beforeMembershipSource.sourceState().issuanceFence().value()) + .isEqualTo(fenceBeforeSourceRead); + assertThat(beforeMembershipSource.snapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat( + beforeMembershipSource.snapshot().membershipBaseline().membershipAuthorityGeneration()) + .isEqualTo("1"); + assertThat(beforeMembershipSource.snapshot().sourceEvent().eventId()) + .isEqualTo(immutableMembershipEvent.eventId()); + assertThat(beforeMembershipSource.snapshot().sourceEvent().outboxSequence()).isEqualTo("1"); + assertThat(beforeMembershipSource.snapshot().sourceEvent().eventDigest()) + .isEqualTo(immutableMembershipEvent.eventDigest()); + assertThat(beforeMembershipSource.snapshot().sourceEvent().outboxStreamKey()) + .isEqualTo(membershipStreamKey(fixture)); + assertThat(beforeMembershipSource.snapshot().sourceEvent().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(beforeMembershipSource.snapshot().sourceEvent().membershipAuthorityGeneration()) + .isEqualTo("1"); + assertThat(beforeMembershipSource.snapshot().sourceEvent().canonicalJsonUtf8()) + .containsExactly(immutableMembershipBytes); + assertThat(beforeMembershipSource.snapshot().outboxCheckpoints()) + .isEqualTo(before.outboxCheckpoints()); + assertThat(beforeMembershipSource.snapshot().outboxSourceEvidence()) + .isEqualTo(before.outboxSourceEvidence()); + assertThat(membershipRow(fixture)).isEqualTo(membershipRowBeforeSourceRead); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(membershipPairBeforeSourceRead); + assertThat(membershipGenerationRow(fixture)).isEqualTo(membershipGenerationBeforeSourceRead); + assertThat(accountIssuanceFence(fixture)).isEqualTo(fenceBeforeSourceRead); + assertThat(accountIssuanceFenceRow(fixture)).isEqualTo(fenceRowBeforeSourceRead); + assertThat(countMembershipRows(fixture)).isEqualTo(1L); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(1L); + assertThat(countStreamEvents(membershipStreamKey(fixture))).isEqualTo(1L); assertThat(before.membershipExists()).isTrue(); assertThat(before.gameplayAdmissionAllowed()).isTrue(); assertThat(before.authorityTuple().issuerAuthGeneration()).isEqualTo("1"); @@ -258,6 +309,50 @@ void postJoinSnapshotCarriesCurrentCompositeSourcesWithoutRewritingMembershipEve assertThat(readback.sourceEvent().canonicalJsonUtf8()) .containsExactly(immutableMembershipBytes); + var retainedZeroFixture = fixture(); + RuntimeMembershipSnapshotDto retainedZeroBefore = + readRuntimeMembershipSnapshot(retainedZeroFixture); + Map retainedZeroPair = membershipPairAuthorityRow(retainedZeroFixture); + Map retainedZeroMembershipGeneration = + membershipGenerationRow(retainedZeroFixture); + long retainedZeroFence = accountIssuanceFence(retainedZeroFixture); + Map retainedZeroFenceRow = accountIssuanceFenceRow(retainedZeroFixture); + long retainedZeroTenantGeneration = + readTenantAuthority(retainedZeroFixture.tenantUuid()).generation(); + var retainedZero = + membershipSourceReader() + .readCurrent(retainedZeroFixture.accountUuid(), retainedZeroFixture.tenantUuid()); + assertThat(retainedZero.accountId()).isEqualTo(retainedZeroFixture.accountUuid()); + assertThat(retainedZero.tenantId()).isEqualTo(retainedZeroFixture.tenantUuid()); + assertThat(retainedZero.sourceState().scope()) + .isEqualTo( + AuthorityScope.membership( + retainedZeroFixture.accountUuid(), retainedZeroFixture.tenantUuid())); + assertThat(retainedZero.sourceState().generation()).isEqualTo(1L); + assertThat(retainedZero.sourceState().sourceVersion()).isEqualTo(1L); + assertThat(retainedZero.sourceState().issuanceFence().value()).isEqualTo(retainedZeroFence); + assertThat(retainedZero.snapshot().membershipExists()).isFalse(); + assertThat(retainedZero.snapshot().gameplayAdmissionAllowed()).isFalse(); + assertThat(retainedZero.snapshot().membershipBaseline().membershipLifecycleState()) + .isEqualTo("MISSING"); + assertThat(retainedZero.snapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(retainedZeroFixture.tenantUuid().toString(), "1")); + assertThat(retainedZero.snapshot().sourceEvent()).isNull(); + assertThat(retainedZero.snapshot().outboxCheckpoints()) + .isEqualTo(retainedZeroBefore.outboxCheckpoints()); + assertThat(retainedZero.snapshot().outboxSourceEvidence()) + .isEqualTo(retainedZeroBefore.outboxSourceEvidence()); + assertThat(membershipPairAuthorityRow(retainedZeroFixture)).isEqualTo(retainedZeroPair); + assertThat(membershipGenerationRow(retainedZeroFixture)) + .isEqualTo(retainedZeroMembershipGeneration); + assertThat(readTenantAuthority(retainedZeroFixture.tenantUuid()).generation()) + .isEqualTo(retainedZeroTenantGeneration); + assertThat(accountIssuanceFence(retainedZeroFixture)).isEqualTo(retainedZeroFence); + assertThat(accountIssuanceFenceRow(retainedZeroFixture)).isEqualTo(retainedZeroFenceRow); + assertThat(countMembershipRows(retainedZeroFixture)).isZero(); + assertThat(countMembershipTransitionReceipts(retainedZeroFixture)).isZero(); + assertThat(countStreamEvents(membershipStreamKey(retainedZeroFixture))).isZero(); + JoinFixture neverJoined = fixture(); UUID neverJoinedTenantRequestId = UUID.randomUUID(); var neverJoinedTenantEvent = @@ -306,6 +401,129 @@ void postJoinSnapshotCarriesCurrentCompositeSourcesWithoutRewritingMembershipEve assertThat(membershipEventBytes(fixture)).containsExactly(immutableMembershipBytes); } + @Test + void membershipSourceReaderReadsRetainedInactiveRetryAndReactivationWithoutMutation() { + JoinFixture fixture = fixture(); + JoinPublicProductionResult joined = join(fixture); + assertThat(joined.success()).isTrue(); + + String leftRequestId = "membership-source-left-" + UUID.randomUUID(); + MembershipTransitionReceipt committedLeft = + membershipLifecycleService.leave(fixture.accountId(), fixture.tenantId(), leftRequestId); + Map inactiveMembership = membershipRow(fixture); + Map inactivePair = membershipPairAuthorityRow(fixture); + Map inactiveGeneration = membershipGenerationRow(fixture); + long inactiveFence = accountIssuanceFence(fixture); + Map inactiveFenceRow = accountIssuanceFenceRow(fixture); + byte[] leftEventBytes = membershipEventBytes(fixture, 2L); + long inactiveReceiptCount = countMembershipTransitionReceipts(fixture); + long inactiveEventCount = countStreamEvents(membershipStreamKey(fixture)); + + var inactive = + membershipSourceReader().readCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(inactive.sourceState().scope()) + .isEqualTo(AuthorityScope.membership(fixture.accountUuid(), fixture.tenantUuid())); + assertThat(inactive.sourceState().generation()).isEqualTo(2L); + assertThat(inactive.sourceState().sourceVersion()).isEqualTo(2L); + assertThat(inactive.sourceState().issuanceFence().value()).isEqualTo(inactiveFence); + assertThat(inactive.snapshot().membershipExists()).isTrue(); + assertThat(inactive.snapshot().gameplayAdmissionAllowed()).isFalse(); + assertThat(inactive.snapshot().membershipBaseline().membershipLifecycleState()) + .isEqualTo("INACTIVE"); + assertThat(inactive.snapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "3")); + assertThat(inactive.snapshot().membershipBaseline().membershipAuthorityGeneration()) + .isEqualTo("2"); + assertThat(inactive.snapshot().sourceEvent().requestId()).isEqualTo(leftRequestId); + assertThat(inactive.snapshot().sourceEvent().outboxSequence()).isEqualTo("2"); + assertThat(inactive.snapshot().sourceEvent().canonicalJsonUtf8()) + .containsExactly(leftEventBytes); + assertThat(inactive.snapshot().outboxCheckpoints()) + .contains( + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + membershipStreamKey(fixture), "2")); + assertThat(inactive.snapshot().outboxSourceEvidence()) + .anySatisfy( + evidence -> { + assertThat(evidence.outboxStreamKey()).isEqualTo(membershipStreamKey(fixture)); + assertThat(evidence.outboxSequence()).isEqualTo("2"); + assertThat(evidence.eventDigest()) + .isEqualTo(inactive.snapshot().sourceEvent().eventDigest()); + assertThat(evidence.canonicalEventJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(leftEventBytes); + }); + assertThat(membershipRow(fixture)).isEqualTo(inactiveMembership); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(inactivePair); + assertThat(membershipGenerationRow(fixture)).isEqualTo(inactiveGeneration); + assertThat(accountIssuanceFence(fixture)).isEqualTo(inactiveFence); + assertThat(accountIssuanceFenceRow(fixture)).isEqualTo(inactiveFenceRow); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(inactiveReceiptCount); + assertThat(countStreamEvents(membershipStreamKey(fixture))).isEqualTo(inactiveEventCount); + + assertThat( + membershipLifecycleService.leave( + fixture.accountId(), fixture.tenantId(), leftRequestId)) + .isEqualTo(committedLeft); + var inactiveRetry = + membershipSourceReader().readCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(inactiveRetry.snapshot().membershipBaseline()) + .isEqualTo(inactive.snapshot().membershipBaseline()); + assertThat(inactiveRetry.snapshot().sourceEvent().canonicalJsonUtf8()) + .containsExactly(leftEventBytes); + assertThat(membershipRow(fixture)).isEqualTo(inactiveMembership); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(inactivePair); + assertThat(membershipGenerationRow(fixture)).isEqualTo(inactiveGeneration); + assertThat(accountIssuanceFence(fixture)).isEqualTo(inactiveFence); + assertThat(accountIssuanceFenceRow(fixture)).isEqualTo(inactiveFenceRow); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(inactiveReceiptCount); + assertThat(countStreamEvents(membershipStreamKey(fixture))).isEqualTo(inactiveEventCount); + + JoinFixture reactivation = fixtureForMembership(fixture); + JoinPublicProductionResult reactivated = join(reactivation); + assertThat(reactivated.success()).isTrue(); + assertThat(reactivated.outcomeCode()).isEqualTo("JOINED"); + var active = membershipSourceReader().readCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(active.sourceState().generation()).isEqualTo(3L); + assertThat(active.sourceState().sourceVersion()).isEqualTo(3L); + assertThat(active.snapshot().membershipExists()).isTrue(); + assertThat(active.snapshot().gameplayAdmissionAllowed()).isTrue(); + assertThat(active.snapshot().membershipBaseline().membershipLifecycleState()) + .isEqualTo("ACTIVE"); + assertThat(active.snapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "4")); + assertThat(active.snapshot().membershipBaseline().membershipAuthorityGeneration()) + .isEqualTo("3"); + assertThat(active.snapshot().outboxCheckpoints()) + .contains( + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + membershipStreamKey(fixture), "3")); + + Map activeMembership = membershipRow(fixture); + Map activePair = membershipPairAuthorityRow(fixture); + Map activeGeneration = membershipGenerationRow(fixture); + long activeFence = accountIssuanceFence(fixture); + Map activeFenceRow = accountIssuanceFenceRow(fixture); + long activeReceiptCount = countMembershipTransitionReceipts(fixture); + long activeEventCount = countStreamEvents(membershipStreamKey(fixture)); + assertThat( + membershipLifecycleService.leave( + fixture.accountId(), fixture.tenantId(), leftRequestId)) + .isEqualTo(committedLeft); + var activeRetry = + membershipSourceReader().readCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(activeRetry.snapshot().membershipBaseline()) + .isEqualTo(active.snapshot().membershipBaseline()); + assertThat(activeRetry.snapshot().sourceEvent().canonicalJsonUtf8()) + .containsExactly(active.snapshot().sourceEvent().canonicalJsonUtf8()); + assertThat(membershipRow(fixture)).isEqualTo(activeMembership); + assertThat(membershipPairAuthorityRow(fixture)).isEqualTo(activePair); + assertThat(membershipGenerationRow(fixture)).isEqualTo(activeGeneration); + assertThat(accountIssuanceFence(fixture)).isEqualTo(activeFence); + assertThat(accountIssuanceFenceRow(fixture)).isEqualTo(activeFenceRow); + assertThat(countMembershipTransitionReceipts(fixture)).isEqualTo(activeReceiptCount); + assertThat(countStreamEvents(membershipStreamKey(fixture))).isEqualTo(activeEventCount); + } + private JoinFixture fixture() { String suffix = UUID.randomUUID().toString(); long accountId = @@ -400,6 +618,45 @@ private JoinPublicProductionResult join(JoinFixture fixture) { new JoinPublicProductionRequest(fixture.scope().connectScopeId(), fixture.requestId())); } + private JoinFixture fixtureForMembership(JoinFixture original) { + String requestId = "current-authority-reactivate-" + UUID.randomUUID(); + DirectTextCallerContext caller = + new DirectTextCallerContext( + original.accountId(), + original.tenantId(), + REALM_ID, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "current-authority-reactivate-session-" + UUID.randomUUID(), + requestId); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + original.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( + original.accountId(), + original.accountUuid(), + original.tenantId(), + original.tenantUuid(), + requestId, + caller, + scope); + } + + private AccountMembershipSourceReader membershipSourceReader() { + return new AccountMembershipSourceReader( + membershipAuthorityEventProducer, authorityGenerationRepository, transactionManager); + } + private RuntimeMembershipSnapshotDto readRuntimeMembershipSnapshot(JoinFixture fixture) { return new TransactionTemplate(transactionManager) .execute( @@ -413,6 +670,11 @@ private ScopeState readAccountAuthority(UUID accountUuid) { .execute(status -> authorityGenerationRepository.read(AuthorityScope.account(accountUuid))); } + private ScopeState readTenantAuthority(UUID tenantUuid) { + return new TransactionTemplate(transactionManager) + .execute(status -> authorityGenerationRepository.read(AuthorityScope.tenant(tenantUuid))); + } + private Account readAccount(long accountId) { return new TransactionTemplate(transactionManager) .execute(status -> accountRepository.findById(accountId).orElseThrow()); @@ -433,11 +695,16 @@ private AccountLogoutAllAuthorityEventProducer logoutProducer() { } 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 = 1", - membershipStreamKey(fixture)) + + "AND outbox_sequence = ?", + membershipStreamKey(fixture), + sequence) .fetchOne()) .get("payload", byte[].class); } @@ -452,6 +719,74 @@ private long countMembershipRows(JoinFixture fixture) { .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.tenantId()) + .fetchOne(0, Long.class)); + } + + private Map membershipRow(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT xmin::text AS row_xmin, * FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private Map membershipPairAuthorityRow(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT xmin::text AS row_xmin, * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private Map membershipGenerationRow(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT xmin::text AS row_xmin, * FROM account_authority_generations " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + + private long accountIssuanceFence(JoinFixture fixture) { + Long fence = + dsl.resultQuery( + "SELECT issuance_fence FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + fixture.accountUuid()) + .fetchOne(0, Long.class); + assertThat(fence).isNotNull(); + return fence; + } + + private Map accountIssuanceFenceRow(JoinFixture fixture) { + var row = + dsl.resultQuery( + "SELECT xmin::text AS row_xmin, * FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + fixture.accountUuid()) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + private long countStreamEvents(String streamKey) { return Objects.requireNonNull( dsl.resultQuery( 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 c16fd9529d..991fb851f2 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 @@ -32,6 +32,7 @@ import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipSourceReader; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; @@ -182,6 +183,35 @@ void strictExistingMembershipReadDeniesFreshAssociationWithoutEnrollmentOrMutati UUID tenantUuid = UUID.randomUUID(); FreshTenantCreationEvidence evidence = importFreshTenantAssociation(tenantUuid); long originalIssuanceFence = issuanceFence(account.accountUuid()); + Map originalIssuanceFenceRow = issuanceFenceRow(account.accountUuid()); + long originalTenantGeneration = authorityGeneration("TENANT", null, tenantUuid); + Map originalAccountAuthorityRow = + authorityGenerationRow("ACCOUNT", account.accountUuid(), null).orElseThrow(); + Map originalTenantAuthorityRow = + authorityGenerationRow("TENANT", null, tenantUuid).orElseThrow(); + + assertThatThrownBy( + () -> membershipSourceReader().readCurrent(account.accountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class); + Optional initialAssociationReadback = + new TransactionTemplate(transactionManager) + .execute(status -> freshAssociationRepository.read(tenantUuid)); + assertThat(initialAssociationReadback).contains(evidence); + assertThat(countMembershipPairAuthorities(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipAuthorityGenerations(account.accountUuid(), tenantUuid)).isZero(); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(authorityGeneration("TENANT", null, tenantUuid)).isEqualTo(originalTenantGeneration); + assertThat(authorityGenerationRow("ACCOUNT", account.accountUuid(), null)) + .contains(originalAccountAuthorityRow); + assertThat(authorityGenerationRow("TENANT", null, tenantUuid)) + .contains(originalTenantAuthorityRow); + assertThat(issuanceFence(account.accountUuid())).isEqualTo(originalIssuanceFence); + assertThat(issuanceFenceRow(account.accountUuid())).isEqualTo(originalIssuanceFenceRow); assertThatThrownBy( () -> @@ -280,6 +310,56 @@ void canonicalRuntimeReadUsesFreshUuidAssociationWithoutInventingRetainedAlias() .isZero(); assertThat(issuanceFence(account.accountUuid())).isEqualTo(originalIssuanceFence); + Map enrolledPair = + membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + long enrolledTenantGeneration = authorityGeneration("TENANT", null, tenantUuid); + Map enrolledTenantAuthorityRow = + authorityGenerationRow("TENANT", null, tenantUuid).orElseThrow(); + long enrolledFence = issuanceFence(account.accountUuid()); + Map enrolledFenceRow = issuanceFenceRow(account.accountUuid()); + long membershipGeneration = + authorityGeneration("MEMBERSHIP", account.accountUuid(), tenantUuid); + Map enrolledMembershipAuthorityRow = + authorityGenerationRow("MEMBERSHIP", account.accountUuid(), tenantUuid).orElseThrow(); + var existing = membershipSourceReader().readCurrent(account.accountUuid(), tenantUuid); + assertThat(existing.accountId()).isEqualTo(account.accountUuid()); + assertThat(existing.tenantId()).isEqualTo(tenantUuid); + assertThat(existing.sourceState().scope()) + .isEqualTo( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.accountUuid(), tenantUuid)); + assertThat(existing.sourceState().generation()).isEqualTo(1L); + assertThat(existing.sourceState().sourceVersion()).isEqualTo(1L); + assertThat(existing.sourceState().issuanceFence().accountId()).isEqualTo(account.accountUuid()); + assertThat(existing.sourceState().issuanceFence().value()).isEqualTo(enrolledFence); + assertThat(existing.snapshot().accountUuid()).isEqualTo(account.accountUuid().toString()); + assertThat(existing.snapshot().tenantUuid()).isEqualTo(tenantUuid.toString()); + assertThat(existing.snapshot().membershipExists()).isFalse(); + assertThat(existing.snapshot().gameplayAdmissionAllowed()).isFalse(); + assertThat(existing.snapshot().membershipBaseline().membershipLifecycleState()) + .isEqualTo("MISSING"); + assertThat(existing.snapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(tenantUuid.toString(), "1")); + assertThat(existing.snapshot().sourceEvent()).isNull(); + assertThat(existing.snapshot().outboxSourceEvidence()).isEmpty(); + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)) + .isEqualTo(enrolledPair); + assertThat(authorityGeneration("TENANT", null, tenantUuid)).isEqualTo(enrolledTenantGeneration); + assertThat(authorityGeneration("MEMBERSHIP", account.accountUuid(), tenantUuid)) + .isEqualTo(membershipGeneration); + assertThat(authorityGenerationRow("TENANT", null, tenantUuid)) + .contains(enrolledTenantAuthorityRow); + assertThat(authorityGenerationRow("MEMBERSHIP", account.accountUuid(), tenantUuid)) + .contains(enrolledMembershipAuthorityRow); + assertThat(issuanceFence(account.accountUuid())).isEqualTo(enrolledFence); + assertThat(issuanceFenceRow(account.accountUuid())).isEqualTo(enrolledFenceRow); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + RuntimeMembershipSnapshotDto retry = readRuntimeMembershipSnapshot(account.accountUuid(), tenantUuid); assertThat(retry.requestAccountUuid()).isEqualTo(first.requestAccountUuid()); @@ -298,7 +378,13 @@ void canonicalRuntimeReadUsesFreshUuidAssociationWithoutInventingRetainedAlias() void canonicalRuntimeReadRejectsUnmappedTenantUuidWithoutEnrollment() { AccountFixture account = accountFixture(); UUID unmappedTenantUuid = UUID.randomUUID(); + long originalIssuanceFence = issuanceFence(account.accountUuid()); + Map originalIssuanceFenceRow = issuanceFenceRow(account.accountUuid()); + assertThatThrownBy( + () -> membershipSourceReader().readCurrent(account.accountUuid(), unmappedTenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("approved Account tenant association is absent"); assertThatThrownBy( () -> readRuntimeMembershipSnapshot(account.accountUuid(), unmappedTenantUuid)) .isInstanceOf(IllegalStateException.class) @@ -306,8 +392,46 @@ void canonicalRuntimeReadRejectsUnmappedTenantUuidWithoutEnrollment() { assertThat(countMembershipPairAuthorities(account.accountUuid(), unmappedTenantUuid)).isZero(); assertThat(countMembershipAuthorityGenerations(account.accountUuid(), unmappedTenantUuid)) .isZero(); + assertThat(countAuthorityGenerations("TENANT", null, unmappedTenantUuid)).isZero(); assertThat(countMembershipsForAccount(account.accountId())).isZero(); assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), unmappedTenantUuid))) + .isZero(); + assertThat( + countAuthorityStreams(membershipStreamKey(account.accountUuid(), unmappedTenantUuid))) + .isZero(); + assertThat(issuanceFence(account.accountUuid())).isEqualTo(originalIssuanceFence); + assertThat(issuanceFenceRow(account.accountUuid())).isEqualTo(originalIssuanceFenceRow); + } + + @Test + void membershipSourceReaderRejectsAmbientAccountTransaction() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + readFreshNeverJoinedMembershipSnapshot(account.accountUuid(), tenantUuid); + Map pairBefore = membershipPairAuthorityRow(account.accountUuid(), tenantUuid); + long fenceBefore = issuanceFence(account.accountUuid()); + Map fenceRowBefore = issuanceFenceRow(account.accountUuid()); + + assertThatThrownBy( + () -> + new TransactionTemplate(transactionManager) + .execute( + status -> + membershipSourceReader() + .readCurrent(account.accountUuid(), tenantUuid))) + .isInstanceOf(IllegalStateException.class); + + assertThat(membershipPairAuthorityRow(account.accountUuid(), tenantUuid)).isEqualTo(pairBefore); + assertThat(issuanceFence(account.accountUuid())).isEqualTo(fenceBefore); + assertThat(issuanceFenceRow(account.accountUuid())).isEqualTo(fenceRowBefore); + assertThat(countMembershipsForAccount(account.accountId())).isZero(); + assertThat(countMembershipTransitionReceiptsForAccount(account.accountId())).isZero(); + assertThat(countAuthorityEvents(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); + assertThat(countAuthorityStreams(membershipStreamKey(account.accountUuid(), tenantUuid))) + .isZero(); } @Test @@ -582,6 +706,11 @@ private AccountFixture accountFixture() { return new AccountFixture(accountId, accountUuid); } + private AccountMembershipSourceReader membershipSourceReader() { + return new AccountMembershipSourceReader( + producer, authorityGenerationRepository, transactionManager); + } + private FreshTenantCreationEvidence importFreshTenantAssociation(UUID canonicalTenantUuid) { UUID creationRequestId = UUID.randomUUID(); UUID operationId = UUID.randomUUID(); @@ -688,6 +817,32 @@ private long authorityGeneration(String scopeKind, UUID accountUuid, UUID tenant .fetchOne(0, Long.class)); } + private Optional> authorityGenerationRow( + String scopeKind, UUID accountUuid, UUID tenantUuid) { + var row = + dsl.resultQuery( + "SELECT xmin::text AS row_xmin, * FROM account_authority_generations " + + "WHERE scope_kind = ? AND account_uuid IS NOT DISTINCT FROM ? " + + "AND tenant_uuid IS NOT DISTINCT FROM ?", + scopeKind, + accountUuid, + tenantUuid) + .fetchOne(); + return Optional.ofNullable(row).map(value -> value.intoMap()); + } + + private long countAuthorityGenerations(String scopeKind, UUID accountUuid, UUID tenantUuid) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_authority_generations " + + "WHERE scope_kind = ? AND account_uuid IS NOT DISTINCT FROM ? " + + "AND tenant_uuid IS NOT DISTINCT FROM ?", + scopeKind, + accountUuid, + tenantUuid) + .fetchOne(0, Long.class)); + } + private long issuanceFence(UUID accountUuid) { return Objects.requireNonNull( dsl.resultQuery( @@ -697,6 +852,17 @@ private long issuanceFence(UUID accountUuid) { .fetchOne(0, Long.class)); } + private Map issuanceFenceRow(UUID accountUuid) { + var row = + dsl.resultQuery( + "SELECT xmin::text AS row_xmin, * FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + accountUuid) + .fetchOne(); + assertThat(row).isNotNull(); + return row.intoMap(); + } + private long countMembershipsForAccount(long accountId) { return Objects.requireNonNull( dsl.resultQuery( 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 index 690192cddf..6876a5b674 100644 --- 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 @@ -39,6 +39,7 @@ 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.PasswordResetReceipt; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; @@ -73,6 +74,7 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -282,6 +284,105 @@ void projectsActualPasswordResetAndLogoutAllCheckpointsWithoutRewritingSqlHistor assertThat(sqlState(fixture, seed)).isEqualTo(afterBothProducers); } + @Test + void committedPasswordResetReceiptSurvivesCoordinationAuthFailureExactRetryAndProjection() { + Fixture fixture = newFixture(); + Seed seed = seedAccount(fixture); + AccountAuthoritySourceReader reader = sourceReader(fixture); + String tokenHash = sha256Hex(seed.rawToken()); + + reset(fixture, seed.rawToken(), "committed-reset-password"); + PasswordResetReceipt committedReceipt = passwordResetReceipt(fixture, tokenHash); + ScopeState committedAuthority = readAuthority(fixture, seed.accountUuid()); + var committedEvent = event(fixture, seed.accountUuid(), committedReceipt.outboxSequence()); + var committedCheckpoint = + transaction( + fixture.transaction(), + () -> + fixture.outbox().readCheckpoint(committedReceipt.outboxStreamKey()).orElseThrow()); + SqlState committedSql = sqlState(fixture, seed); + + assertThat(committedAuthority.generation()).isEqualTo(2L); + assertThat(committedAuthority.sourceVersion()).isEqualTo(2L); + assertThat(committedAuthority.issuanceFence().value()).isEqualTo(2L); + assertThat(committedAuthority.issuanceFence().sourceVersion()).isEqualTo(2L); + assertThat(committedEvent.outboxSequence()).isEqualTo(committedReceipt.outboxSequence()); + assertThat(committedEvent.eventId()).isEqualTo(committedReceipt.eventId()); + assertThat(committedEvent.eventDigest()).isEqualTo(committedReceipt.eventDigest()); + assertThat(committedCheckpoint.outboxSequence()).isEqualTo(committedReceipt.outboxSequence()); + assertThat(committedCheckpoint.sourceEventId()).isEqualTo(committedReceipt.eventId()); + assertThat(committedCheckpoint.sourceEventDigest()).isEqualTo(committedReceipt.eventDigest()); + + RedisAccountGenerationProjectionStore deniedCoordinationStore = + new RedisAccountGenerationProjectionStore( + reader, + new CoordinationEndpoint( + redis.getHost(), + redis.getMappedPort(6379), + "account_coord_app", + "deliberately-invalid-test-credential"), + new CacheRateLimitEndpoint("cache.invalid.test", 6380)); + stores.add(deniedCoordinationStore); + deniedCoordinationStore.init(); + + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThatThrownBy(() -> deniedCoordinationStore.refreshCurrent(seed.accountUuid())) + .satisfies( + failure -> + assertThat(exceptionMessageChain(failure)) + .contains("WRONGPASS", "invalid username-password pair")); + assertThat(adminTemplate.opsForValue().get(key(seed.accountUuid()))).isNull(); + assertThat(sqlState(fixture, seed)).isEqualTo(committedSql); + assertThat(passwordResetReceipt(fixture, tokenHash)).isEqualTo(committedReceipt); + assertThat(readAuthority(fixture, seed.accountUuid())).isEqualTo(committedAuthority); + assertThat(event(fixture, seed.accountUuid(), committedReceipt.outboxSequence())) + .isEqualTo(committedEvent); + assertThat( + transaction( + fixture.transaction(), + () -> + fixture + .outbox() + .readCheckpoint(committedReceipt.outboxStreamKey()) + .orElseThrow())) + .isEqualTo(committedCheckpoint); + + reset(fixture, seed.rawToken(), "committed-reset-password"); + assertThat(sqlState(fixture, seed)).isEqualTo(committedSql); + assertThat(passwordResetReceipt(fixture, tokenHash)).isEqualTo(committedReceipt); + assertThat(readAuthority(fixture, seed.accountUuid())).isEqualTo(committedAuthority); + assertThat(event(fixture, seed.accountUuid(), committedReceipt.outboxSequence())) + .isEqualTo(committedEvent); + + RedisAccountGenerationProjectionStore availableStore = store(reader); + assertThatThrownBy( + () -> + transaction( + fixture.transaction(), () -> availableStore.refreshCurrent(seed.accountUuid()))) + .hasMessageContaining("without an ambient transaction"); + assertThat(adminTemplate.opsForValue().get(key(seed.accountUuid()))).isNull(); + + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + ApplyResult projection = availableStore.refreshCurrent(seed.accountUuid()); + assertThat(projection.outcome()).isEqualTo(Outcome.APPLIED); + ProjectionSnapshot projected = projection.snapshot().orElseThrow(); + JsonNode projectedJson = parse(projected.json()); + assertThat(projected.key()).isEqualTo(key(seed.accountUuid())); + assertThat(projectedJson.path("accountId").asText()).isEqualTo(seed.accountUuid().toString()); + assertThat(projectedJson.path("accountAuthorityGeneration").asText()).isEqualTo("2"); + assertThat(projectedJson.path("sourceVersion").asText()).isEqualTo("2"); + assertThat(projectedJson.path("outboxStreamKey").asText()) + .isEqualTo(committedReceipt.outboxStreamKey()); + assertThat(projectedJson.path("outboxSequence").asText()) + .isEqualTo(Long.toString(committedReceipt.outboxSequence())); + assertThat(projectedJson.path("sourceEvent").asText()) + .isEqualTo(new String(committedEvent.payload(), StandardCharsets.UTF_8)); + assertThat(adminTemplate.opsForValue().get(projected.key())).isEqualTo(projected.json()); + assertThat(adminTemplate.getExpire(projected.key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + assertThat(sqlState(fixture, seed)).isEqualTo(committedSql); + assertThat(passwordResetReceipt(fixture, tokenHash)).isEqualTo(committedReceipt); + } + @Test void unknownAccountCannotSynthesizeProjectionOrChangeSourceRows() { Fixture fixture = newFixture(); @@ -634,6 +735,12 @@ private Account account(Fixture fixture, long accountId) { fixture.transaction(), () -> fixture.accounts().findById(accountId).orElseThrow()); } + private PasswordResetReceipt passwordResetReceipt(Fixture fixture, String tokenHash) { + return transaction( + fixture.transaction(), + () -> fixture.resetOperations().findByTokenHash(tokenHash).orElseThrow()); + } + private ScopeState readAuthority(Fixture fixture, UUID accountUuid) { return transaction( fixture.transaction(), () -> fixture.authority().read(AuthorityScope.account(accountUuid))); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerProjectionAcknowledgmentPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerProjectionAcknowledgmentPostgresIntegrationTest.java new file mode 100644 index 0000000000..1db3c94291 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerProjectionAcknowledgmentPostgresIntegrationTest.java @@ -0,0 +1,1150 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import 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.AccountIssuerProjectionAcknowledgmentRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionAcknowledgmentRepository.Acknowledgment; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository.Receipt; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.accountservice.service.AccountIssuerProjectionAcknowledgmentService; +import net.firedevops.firemud.accountservice.service.AccountIssuerProjectionReconciliationService; +import net.firedevops.firemud.common.account.authority.IssuerAuthorityProjectionV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.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 IssuerProjectionAcknowledgmentPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "issuer_ack_pg"; + private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String OTHER_ISSUER_ID = "https://other.example.test/issuer"; + private static final String STREAM_KEY = "account:auth-authority:v1:issuer/" + ISSUER_ID; + private static final String PROJECTION_KEY = + "session:game:auth:issuer-generation:v1:" + ISSUER_ID; + private static final String GAME_SESSION_ID = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String OTHER_GAME_SESSION_ID = + "spiffe://firemud/ns/other/sa/game-session-service"; + private static final String APPLIED_AT = "2026-10-03T00:00:00Z"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final ObjectMapper JSON = new ObjectMapper(); + private static final HexFormat HEX = HexFormat.of(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void acknowledgesProvedZeroBaselineWithExactBytesAndNoSourceMutation() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + Receipt capture = + fixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + String projection = projectionJson(capture.capturedSource(), APPLIED_AT) + " \n"; + SourceHistory before = sourceHistory(fixture); + List capturesBefore = captureHistory(fixture); + + Acknowledgment acknowledgment = acknowledge(fixture, capture, projection); + + assertThat(capture.capturedSource().issuerAuthGeneration()).isEqualTo(1L); + assertThat(capture.capturedSource().sourceVersion()).isEqualTo(1L); + assertThat(capture.capturedSource().outboxSequence()).isZero(); + assertThat(capture.capturedSource().latestEvent()).isEmpty(); + assertAcknowledgment(capture, projection, acknowledgment); + assertStoredAcknowledgment(fixture, capture, acknowledgment, projection); + assertThat(countAcknowledgments(fixture)).isEqualTo(1L); + assertThat(sourceHistory(fixture)).isEqualTo(before); + assertThat(captureHistory(fixture)).isEqualTo(capturesBefore); + } + + @Test + void acknowledgesCompletePositiveCheckpointAndRetainsSourceHistory() { + Fixture fixture = newFixture(); + IssuerGenerationAuthorityEvent sourceEvent = seedNonSequenceAlignedPositiveState(fixture); + Receipt capture = + fixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + String projection = projectionJson(capture.capturedSource(), APPLIED_AT); + SourceHistory before = sourceHistory(fixture); + List capturesBefore = captureHistory(fixture); + + Acknowledgment acknowledgment = acknowledge(fixture, capture, projection); + + IssuerAuthoritySnapshot captured = capture.capturedSource(); + assertThat(captured.issuerAuthGeneration()).isEqualTo(4L); + assertThat(captured.sourceVersion()).isEqualTo(8L); + assertThat(captured.outboxSequence()).isEqualTo(1L); + assertThat(captured.issuerAuthGeneration()).isNotEqualTo(captured.outboxSequence() + 1L); + assertThat(captured.latestEvent()).isPresent(); + assertSameEvent(sourceEvent, captured.latestEvent().orElseThrow()); + assertAcknowledgment(capture, projection, acknowledgment); + assertStoredAcknowledgment(fixture, capture, acknowledgment, projection); + assertThat(countAcknowledgments(fixture)).isEqualTo(1L); + assertThat(sourceHistory(fixture)).isEqualTo(before); + assertThat(captureHistory(fixture)).isEqualTo(capturesBefore); + } + + @Test + void concurrentExactAcknowledgmentsReturnOneDurableOriginalResult() throws Exception { + Fixture fixture = newFixture(); + seedIssuer(fixture); + Receipt capture = + fixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + String projection = projectionJson(capture.capturedSource(), APPLIED_AT); + SourceHistory before = sourceHistory(fixture); + List capturesBefore = captureHistory(fixture); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + await(start); + return acknowledge(fixture, capture, projection); + }); + Future second = + executor.submit( + () -> { + await(start); + return acknowledge(fixture, capture, projection); + }); + start.countDown(); + Acknowledgment firstResult = first.get(45, TimeUnit.SECONDS); + Acknowledgment secondResult = second.get(45, TimeUnit.SECONDS); + + assertSameAcknowledgment(firstResult, secondResult); + assertThat(countAcknowledgments(fixture)).isEqualTo(1L); + assertStoredAcknowledgment(fixture, capture, firstResult, projection); + assertThat(sourceHistory(fixture)).isEqualTo(before); + assertThat(captureHistory(fixture)).isEqualTo(capturesBefore); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void exactRetryAfterLaterSourceAdvanceReturnsOriginalAcknowledgment() { + Fixture fixture = newFixture(); + seedNonSequenceAlignedPositiveState(fixture); + Receipt capture = + fixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + String projection = projectionJson(capture.capturedSource(), APPLIED_AT); + List capturesBefore = captureHistory(fixture); + SourceHistory beforeAcknowledgment = sourceHistory(fixture); + + Acknowledgment original = acknowledge(fixture, capture, projection); + assertThat(sourceHistory(fixture)).isEqualTo(beforeAcknowledgment); + IssuerGenerationAuthorityEvent later = + fixture.source().advance(ISSUER_ID, UUID.randomUUID(), 4L, 8L); + SourceHistory afterAdvance = sourceHistory(fixture); + Acknowledgment retry = acknowledge(fixture, capture, projection); + + assertThat(later.issuerAuthGeneration()).isEqualTo("5"); + assertThat(later.sourceVersion()).isEqualTo("9"); + assertThat(later.outboxSequence()).isEqualTo("2"); + assertSameAcknowledgment(original, retry); + assertThat(countAcknowledgments(fixture)).isEqualTo(1L); + assertStoredAcknowledgment(fixture, capture, original, projection); + assertThat(sourceHistory(fixture)).isEqualTo(afterAdvance); + assertThat(captureHistory(fixture)).isEqualTo(capturesBefore); + } + + @Test + void committedAcknowledgmentWithMissingPostCommitReadbackRecoversOnExactRetry() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + Receipt capture = + fixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + String projection = projectionJson(capture.capturedSource(), APPLIED_AT); + List capturesBefore = captureHistory(fixture); + AtomicInteger acknowledgmentReads = new AtomicInteger(); + AccountIssuerProjectionAcknowledgmentRepository hideOneCommittedRead = + new AccountIssuerProjectionAcknowledgmentRepository(fixture.transactionDsl()) { + @Override + public Optional findByCaptureOperationId(UUID captureOperationId) { + if (acknowledgmentReads.incrementAndGet() == 3) { + return Optional.empty(); + } + return super.findByCaptureOperationId(captureOperationId); + } + }; + AccountIssuerProjectionAcknowledgmentService service = + fixture.acknowledgmentService(hideOneCommittedRead); + SourceHistory before = sourceHistory(fixture); + + assertThatThrownBy(() -> acknowledge(service, capture, projection)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Post-commit issuer installation acknowledgment readback is missing"); + + assertThat(countAcknowledgments(fixture)).isEqualTo(1L); + Acknowledgment original = readAcknowledgment(fixture, capture.operationId()); + assertAcknowledgment(capture, projection, original); + Acknowledgment recovered = acknowledge(service, capture, projection); + assertSameAcknowledgment(original, recovered); + assertThat(countAcknowledgments(fixture)).isEqualTo(1L); + assertStoredAcknowledgment(fixture, capture, original, projection); + assertThat(sourceHistory(fixture)).isEqualTo(before); + assertThat(captureHistory(fixture)).isEqualTo(capturesBefore); + } + + @Test + void staleFirstAcknowledgmentAndChangedBindingsOrProjectionEvidenceDenyWithoutInsertion() { + Fixture staleFixture = newFixture(); + seedNonSequenceAlignedPositiveState(staleFixture); + Receipt staleCapture = + staleFixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + String staleProjection = projectionJson(staleCapture.capturedSource(), APPLIED_AT); + staleFixture.source().advance(ISSUER_ID, UUID.randomUUID(), 4L, 8L); + SourceHistory staleHistory = sourceHistory(staleFixture); + List staleCaptures = captureHistory(staleFixture); + assertThatThrownBy(() -> acknowledge(staleFixture, staleCapture, staleProjection)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("captured source to remain current"); + assertThat(countAcknowledgments(staleFixture)).isZero(); + assertThat(sourceHistory(staleFixture)).isEqualTo(staleHistory); + assertThat(captureHistory(staleFixture)).isEqualTo(staleCaptures); + + Fixture fixture = newFixture(); + IssuerGenerationAuthorityEvent sourceEvent = seedNonSequenceAlignedPositiveState(fixture); + Receipt capture = + fixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + String projection = projectionJson(capture.capturedSource(), APPLIED_AT); + SourceHistory beforeDenials = sourceHistory(fixture); + List capturesBeforeDenials = captureHistory(fixture); + + assertDenied( + fixture, + AccountIssuerAuthorityEventProducer.IssuerMismatchException.class, + () -> acknowledge(fixture, OTHER_ISSUER_ID, GAME_SESSION_ID, capture, projection)); + assertDenied( + fixture, + SecurityException.class, + () -> acknowledge(fixture, ISSUER_ID, OTHER_GAME_SESSION_ID, capture, projection)); + assertDenied( + fixture, + IdempotencyConflictException.class, + () -> + acknowledge( + fixture, + ISSUER_ID, + GAME_SESSION_ID, + UUID.randomUUID(), + capture.requestId(), + capture.requestDigestVersion(), + capture.requestDigest(), + projection)); + assertDenied( + fixture, + IllegalStateException.class, + () -> + acknowledge( + fixture, + ISSUER_ID, + GAME_SESSION_ID, + capture.operationId(), + UUID.randomUUID(), + capture.requestDigestVersion(), + capture.requestDigest(), + projection)); + assertDenied( + fixture, + IllegalArgumentException.class, + () -> + acknowledge( + fixture, + ISSUER_ID, + GAME_SESSION_ID, + capture.operationId(), + capture.requestId(), + 2, + capture.requestDigest(), + projection)); + assertDenied( + fixture, + IdempotencyConflictException.class, + () -> + acknowledge( + fixture, + ISSUER_ID, + GAME_SESSION_ID, + capture.operationId(), + capture.requestId(), + capture.requestDigestVersion(), + "f".repeat(64), + projection)); + + String incompleteProjection = "{\"schemaVersion\":\"game-session-auth-issuer-projection/v1\"}"; + assertDenied( + fixture, + IllegalArgumentException.class, + () -> acknowledge(fixture, capture, incompleteProjection)); + assertDenied( + fixture, + IllegalArgumentException.class, + () -> + acknowledge( + fixture, + capture, + projectionJson( + ISSUER_ID, + "5", + "1", + STREAM_KEY, + APPLIED_AT, + sealEvent(sourceEvent, UUID.randomUUID(), 5L, 8L, 1L)))); + assertDenied( + fixture, + IllegalArgumentException.class, + () -> + acknowledge( + fixture, + capture, + projectionJson( + ISSUER_ID, + "4", + "2", + STREAM_KEY, + APPLIED_AT, + sealEvent(sourceEvent, UUID.randomUUID(), 4L, 8L, 2L)))); + assertDenied( + fixture, + IllegalArgumentException.class, + () -> + acknowledge( + fixture, + capture, + projectionJson( + ISSUER_ID, "4", "1", STREAM_KEY + "/wrong", APPLIED_AT, sourceEvent))); + assertDenied( + fixture, + IllegalArgumentException.class, + () -> + acknowledge( + fixture, + capture, + projectionJson( + ISSUER_ID, + "4", + "1", + STREAM_KEY, + APPLIED_AT, + sealEvent(sourceEvent, UUID.randomUUID(), 4L, 8L, 1L)))); + assertDenied( + fixture, + IllegalArgumentException.class, + () -> + acknowledge( + fixture, + capture, + projectionJson( + ISSUER_ID, + "4", + "1", + STREAM_KEY, + APPLIED_AT, + sealEvent(sourceEvent, UUID.randomUUID(), 4L, 9L, 1L)))); + assertThat(countAcknowledgments(fixture)).isZero(); + assertThat(sourceHistory(fixture)).isEqualTo(beforeDenials); + assertThat(captureHistory(fixture)).isEqualTo(capturesBeforeDenials); + + Acknowledgment original = acknowledge(fixture, capture, projection); + String changedAppliedAt = projectionJson(capture.capturedSource(), "2026-10-03T00:00:01Z"); + assertDenied( + fixture, + IdempotencyConflictException.class, + () -> acknowledge(fixture, capture, changedAppliedAt)); + assertDenied( + fixture, + IdempotencyConflictException.class, + () -> acknowledge(fixture, capture, projection + " ")); + assertThat(countAcknowledgments(fixture)).isEqualTo(1L); + assertStoredAcknowledgment(fixture, capture, original, projection); + assertThat(sourceHistory(fixture)).isEqualTo(beforeDenials); + assertThat(captureHistory(fixture)).isEqualTo(capturesBeforeDenials); + } + + @Test + void ambientTransactionsAndDirectSqlGuardsRejectAcknowledgmentMutation() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + Receipt capture = + fixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + String projection = projectionJson(capture.capturedSource(), APPLIED_AT); + Receipt badHashCapture = + fixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + Receipt nullCapture = + fixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + Receipt longCapture = + fixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + SourceHistory before = sourceHistory(fixture); + List capturesBefore = captureHistory(fixture); + + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> { + acknowledge(fixture, capture, projection); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must own its Account transactions without an ambient transaction"); + assertThat(countAcknowledgments(fixture)).isZero(); + + Acknowledgment mismatchedCapture = candidate(capture, projection); + assertThatThrownBy( + () -> + insertRawAcknowledgment( + fixture, + mismatchedCapture, + UUID.randomUUID(), + mismatchedCapture.installedProjectionUtf8(), + mismatchedCapture.installedProjectionSha256())) + .isInstanceOf(DataAccessException.class) + .satisfies( + failure -> + assertPostgresConstraint(failure, "account_issuer_install_ack_capture_binding")); + + Acknowledgment badHashCandidate = candidate(badHashCapture, projection); + assertSqlConstraint( + () -> + insertRawAcknowledgment( + fixture, + badHashCandidate, + badHashCandidate.captureRequestId(), + badHashCandidate.installedProjectionUtf8(), + new byte[32]), + "account_issuer_install_ack_binding_check"); + + Acknowledgment nullCandidate = candidate(nullCapture, projection); + assertThatThrownBy( + () -> + insertRawAcknowledgment( + fixture, + nullCandidate, + nullCandidate.captureRequestId(), + null, + nullCandidate.installedProjectionSha256())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("installed_projection_json"); + + Acknowledgment longCandidate = candidate(longCapture, projection); + byte[] oversized = new byte[Acknowledgment.MAX_INSTALLED_PROJECTION_UTF8_BYTES + 1]; + Arrays.fill(oversized, (byte) 'x'); + assertSqlConstraint( + () -> + insertRawAcknowledgment( + fixture, + longCandidate, + longCandidate.captureRequestId(), + oversized, + longCandidate.installedProjectionSha256()), + "account_issuer_install_ack_binding_check"); + + assertThat(countAcknowledgments(fixture)).isZero(); + assertThat(sourceHistory(fixture)).isEqualTo(before); + assertThat(captureHistory(fixture)).isEqualTo(capturesBefore); + } + + @Test + void storedAcknowledgmentRejectsDirectUpdateAndDelete() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + Receipt capture = + fixture.captureService().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + String projection = projectionJson(capture.capturedSource(), APPLIED_AT); + Acknowledgment acknowledgment = acknowledge(fixture, capture, projection); + SourceHistory before = sourceHistory(fixture); + List capturesBefore = captureHistory(fixture); + + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_issuer_projection_installation_acknowledgments " + + "SET request_digest_version = request_digest_version " + + "WHERE acknowledgment_id = ?", + acknowledgment.acknowledgmentId())) + .isInstanceOf(DataAccessException.class) + .satisfies( + failure -> assertPostgresConstraint(failure, "account_issuer_install_ack_immutable")); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_issuer_projection_installation_acknowledgments " + + "WHERE acknowledgment_id = ?", + acknowledgment.acknowledgmentId())) + .isInstanceOf(DataAccessException.class) + .satisfies( + failure -> assertPostgresConstraint(failure, "account_issuer_install_ack_immutable")); + + assertThat(countAcknowledgments(fixture)).isEqualTo(1L); + assertStoredAcknowledgment(fixture, capture, acknowledgment, projection); + assertThat(sourceHistory(fixture)).isEqualTo(before); + assertThat(captureHistory(fixture)).isEqualTo(capturesBefore); + } + + 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()); + org.flywaydb.core.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); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(transactionDsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl); + AccountIssuerProjectionReconciliationRepository captures = + new AccountIssuerProjectionReconciliationRepository(transactionDsl); + AccountIssuerProjectionAcknowledgmentRepository acknowledgments = + new AccountIssuerProjectionAcknowledgmentRepository(transactionDsl); + AccountIssuerAuthorityEventProducer source = + new AccountIssuerAuthorityEventProducer( + ISSUER_ID, generations, outbox, transactionDsl, transactionManager); + return new Fixture( + setupDsl, + transactionDsl, + transactionManager, + transaction, + generations, + outbox, + captures, + acknowledgments, + source); + } + + private void seedIssuer(Fixture fixture) { + transaction( + fixture.transaction(), + () -> { + fixture.generations().initializeIssuerIfAbsent(ISSUER_ID); + return null; + }); + } + + private IssuerGenerationAuthorityEvent seedNonSequenceAlignedPositiveState(Fixture fixture) { + fixture + .setupDsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, issuer_id, account_uuid, tenant_uuid, generation, source_version) " + + "VALUES ('ISSUER', ?, NULL, NULL, 3, 7)", + ISSUER_ID); + UUID sourceRequestId = UUID.randomUUID(); + transaction( + fixture.transaction(), + () -> { + ScopeState current = fixture.generations().read(AuthorityScope.issuer(ISSUER_ID)); + ScopeState advanced = fixture.generations().advance(current, null); + assertThat(advanced.generation()).isEqualTo(4L); + assertThat(advanced.sourceVersion()).isEqualTo(8L); + appendSeedEvent(fixture, sourceRequestId, 4L, 8L); + return null; + }); + return fixture.source().readCurrent(ISSUER_ID).latestEvent().orElseThrow(); + } + + private void appendSeedEvent( + Fixture fixture, UUID requestId, long generation, long sourceVersion) { + String requestText = requestId.toString(); + String eventId = "account-issuer-authority-event-v1:" + requestText; + fixture + .outbox() + .append( + STREAM_KEY, + requestText, + sequence -> { + IssuerGenerationAuthorityEvent event = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + eventId, + "requestId", + requestText, + "issuerId", + ISSUER_ID, + "sourceScope", + "issuer/" + ISSUER_ID, + "outboxStreamKey", + STREAM_KEY, + "outboxSequence", + Long.toString(sequence), + "issuerAuthGeneration", + Long.toString(generation), + "sourceVersion", + Long.toString(sourceVersion))); + return new AccountAuthorityOutboxRepository.EventEvidence( + event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + }); + } + + private IssuerGenerationAuthorityEvent sealEvent( + IssuerGenerationAuthorityEvent source, + UUID requestId, + long generation, + long sourceVersion, + long sequence) { + String requestText = requestId.toString(); + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + "account-issuer-authority-event-v1:" + requestText, + "requestId", + requestText, + "issuerId", + source.issuerId(), + "sourceScope", + source.sourceScope(), + "outboxStreamKey", + source.outboxStreamKey(), + "outboxSequence", + Long.toString(sequence), + "issuerAuthGeneration", + Long.toString(generation), + "sourceVersion", + Long.toString(sourceVersion))); + } + + private String projectionJson(IssuerAuthoritySnapshot source, String appliedAt) { + return projectionJson( + source.issuerId(), + Long.toString(source.issuerAuthGeneration()), + Long.toString(source.outboxSequence()), + source.outboxStreamKey(), + appliedAt, + source.latestEvent().orElse(null)); + } + + private String projectionJson( + String issuerId, + String generation, + String sequence, + String streamKey, + String appliedAt, + IssuerGenerationAuthorityEvent event) { + Map projection = new LinkedHashMap<>(); + projection.put("schemaVersion", IssuerAuthorityProjectionV1Codec.SCHEMA_VERSION); + projection.put("issuerId", issuerId); + projection.put("lastAppliedIssuerGeneration", generation); + projection.put("lastAppliedSourceOutboxSequence", sequence); + projection.put("outboxStreamKey", streamKey); + projection.put("appliedAt", appliedAt); + if (event == null) { + projection.put("appliedSourceEvidence", Map.of()); + } else { + projection.put("lastAppliedSourceEventId", event.eventId()); + projection.put("lastAppliedSourceEventDigest", event.eventDigest()); + projection.put( + "appliedSourceEvidence", + Map.of(sequence, new String(event.canonicalJsonUtf8(), StandardCharsets.UTF_8))); + } + try { + return JSON.writeValueAsString(projection); + } catch (JsonProcessingException exception) { + throw new IllegalStateException( + "Issuer projection test JSON could not be encoded", exception); + } + } + + private Acknowledgment acknowledge(Fixture fixture, Receipt capture, String projectionJson) { + return acknowledge(fixture.acknowledgmentService(), capture, projectionJson); + } + + private Acknowledgment acknowledge( + AccountIssuerProjectionAcknowledgmentService service, + Receipt capture, + String projectionJson) { + return acknowledge( + service, + ISSUER_ID, + GAME_SESSION_ID, + capture.operationId(), + capture.requestId(), + capture.requestDigestVersion(), + capture.requestDigest(), + projectionJson); + } + + private Acknowledgment acknowledge( + Fixture fixture, + String issuerId, + String callerIdentity, + Receipt capture, + String projectionJson) { + return acknowledge( + fixture.acknowledgmentService(), + issuerId, + callerIdentity, + capture.operationId(), + capture.requestId(), + capture.requestDigestVersion(), + capture.requestDigest(), + projectionJson); + } + + private Acknowledgment acknowledge( + Fixture fixture, + String issuerId, + String callerIdentity, + UUID operationId, + UUID requestId, + int captureDigestVersion, + String captureDigest, + String projectionJson) { + return acknowledge( + fixture.acknowledgmentService(), + issuerId, + callerIdentity, + operationId, + requestId, + captureDigestVersion, + captureDigest, + projectionJson); + } + + private Acknowledgment acknowledge( + AccountIssuerProjectionAcknowledgmentService service, + String issuerId, + String callerIdentity, + UUID operationId, + UUID requestId, + int captureDigestVersion, + String captureDigest, + String projectionJson) { + return service.acknowledge( + issuerId, + callerIdentity, + operationId, + requestId, + captureDigestVersion, + captureDigest, + projectionJson); + } + + private void assertDenied(Fixture fixture, Class expected, Runnable action) { + long acknowledgmentsBefore = countAcknowledgments(fixture); + assertThatThrownBy(action::run).isInstanceOf(expected); + assertThat(countAcknowledgments(fixture)).isEqualTo(acknowledgmentsBefore); + } + + private Acknowledgment candidate(Receipt capture, String projectionJson) { + byte[] projectionBytes = projectionJson.getBytes(StandardCharsets.UTF_8); + return new Acknowledgment( + UUID.randomUUID(), + capture.operationId(), + capture.requestId(), + capture.issuerId(), + capture.callerWorkloadIdentity(), + capture.projectionKey(), + capture.requestDigestVersion(), + capture.requestDigest(), + Acknowledgment.REQUEST_DIGEST_VERSION, + expectedAcknowledgmentDigest(capture, projectionJson), + projectionBytes, + sha256(projectionBytes)); + } + + private void assertAcknowledgment( + Receipt capture, String projectionJson, Acknowledgment acknowledgment) { + assertThat(acknowledgment.acknowledgmentId()).isNotEqualTo(NIL_UUID); + assertThat(acknowledgment.acknowledgmentId()) + .isNotEqualTo(capture.operationId()) + .isNotEqualTo(capture.requestId()); + assertThat(acknowledgment.captureOperationId()).isEqualTo(capture.operationId()); + assertThat(acknowledgment.captureRequestId()).isEqualTo(capture.requestId()); + assertThat(acknowledgment.issuerId()).isEqualTo(ISSUER_ID); + assertThat(acknowledgment.callerWorkloadIdentity()).isEqualTo(GAME_SESSION_ID); + assertThat(acknowledgment.projectionKey()).isEqualTo(PROJECTION_KEY); + assertThat(acknowledgment.captureRequestDigestVersion()).isEqualTo(1); + assertThat(acknowledgment.captureRequestDigest()).isEqualTo(capture.requestDigest()); + assertThat(acknowledgment.requestDigestVersion()).isEqualTo(1); + assertThat(acknowledgment.requestDigest()) + .isEqualTo(expectedAcknowledgmentDigest(capture, projectionJson)); + byte[] projectionBytes = projectionJson.getBytes(StandardCharsets.UTF_8); + assertThat(acknowledgment.installedProjectionUtf8()).containsExactly(projectionBytes); + assertThat(acknowledgment.installedProjectionSha256()).containsExactly(sha256(projectionBytes)); + } + + private String expectedAcknowledgmentDigest(Receipt capture, String projectionJson) { + String[] fields = { + "issuer-projection-installation-ack/v1", + "ISSUER_PROJECTION_INSTALLATION_ACK", + capture.issuerId(), + capture.callerWorkloadIdentity(), + capture.projectionKey(), + capture.operationId().toString(), + capture.requestId().toString(), + Integer.toString(capture.requestDigestVersion()), + capture.requestDigest(), + projectionJson + }; + ByteArrayOutputStream framed = new ByteArrayOutputStream(); + for (String field : fields) { + byte[] bytes = field.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + framed.write(':'); + framed.writeBytes(bytes); + } + return HEX.formatHex(sha256(framed.toByteArray())); + } + + private void assertStoredAcknowledgment( + Fixture fixture, Receipt capture, Acknowledgment expected, String projectionJson) { + Acknowledgment repositoryReadback = readAcknowledgment(fixture, capture.operationId()); + assertSameAcknowledgment(expected, repositoryReadback); + assertAcknowledgment(capture, projectionJson, repositoryReadback); + + Record row = + fixture + .setupDsl() + .fetchOne( + "SELECT acknowledgment_id, capture_operation_id, capture_request_id, issuer_id, " + + "caller_workload_identity, projection_key, capture_request_digest_version, " + + "capture_request_digest, request_digest_version, request_digest, " + + "installed_projection_json, installed_projection_sha256 " + + "FROM account_issuer_projection_installation_acknowledgments " + + "WHERE capture_operation_id = ?", + capture.operationId()); + assertThat(row).isNotNull(); + assertThat(row.get("acknowledgment_id", UUID.class)).isEqualTo(expected.acknowledgmentId()); + assertThat(row.get("capture_operation_id", UUID.class)) + .isEqualTo(expected.captureOperationId()); + assertThat(row.get("capture_request_id", UUID.class)).isEqualTo(expected.captureRequestId()); + assertThat(row.get("issuer_id", String.class)).isEqualTo(expected.issuerId()); + assertThat(row.get("caller_workload_identity", String.class)) + .isEqualTo(expected.callerWorkloadIdentity()); + assertThat(row.get("projection_key", String.class)).isEqualTo(expected.projectionKey()); + assertThat(row.get("capture_request_digest_version", Integer.class)).isEqualTo(1); + assertThat(HEX.formatHex(row.get("capture_request_digest", byte[].class))) + .isEqualTo(expected.captureRequestDigest()); + assertThat(row.get("request_digest_version", Integer.class)).isEqualTo(1); + assertThat(HEX.formatHex(row.get("request_digest", byte[].class))) + .isEqualTo(expected.requestDigest()); + assertThat(row.get("installed_projection_json", byte[].class)) + .containsExactly(projectionJson.getBytes(StandardCharsets.UTF_8)); + assertThat(row.get("installed_projection_sha256", byte[].class)) + .containsExactly(sha256(projectionJson.getBytes(StandardCharsets.UTF_8))); + } + + private Acknowledgment readAcknowledgment(Fixture fixture, UUID captureOperationId) { + return transaction( + fixture.transaction(), + () -> fixture.acknowledgments().findByCaptureOperationId(captureOperationId).orElseThrow()); + } + + private void assertSameAcknowledgment(Acknowledgment expected, Acknowledgment actual) { + assertThat(actual.acknowledgmentId()).isEqualTo(expected.acknowledgmentId()); + assertThat(actual.captureOperationId()).isEqualTo(expected.captureOperationId()); + assertThat(actual.captureRequestId()).isEqualTo(expected.captureRequestId()); + assertThat(actual.issuerId()).isEqualTo(expected.issuerId()); + assertThat(actual.callerWorkloadIdentity()).isEqualTo(expected.callerWorkloadIdentity()); + assertThat(actual.projectionKey()).isEqualTo(expected.projectionKey()); + assertThat(actual.captureRequestDigestVersion()) + .isEqualTo(expected.captureRequestDigestVersion()); + assertThat(actual.captureRequestDigest()).isEqualTo(expected.captureRequestDigest()); + assertThat(actual.requestDigestVersion()).isEqualTo(expected.requestDigestVersion()); + assertThat(actual.requestDigest()).isEqualTo(expected.requestDigest()); + assertThat(actual.installedProjectionUtf8()) + .containsExactly(expected.installedProjectionUtf8()); + assertThat(actual.installedProjectionSha256()) + .containsExactly(expected.installedProjectionSha256()); + } + + private void insertRawAcknowledgment( + Fixture fixture, + Acknowledgment acknowledgment, + UUID requestId, + byte[] installedProjection, + byte[] installedProjectionSha256) { + fixture + .setupDsl() + .execute( + "INSERT INTO account_issuer_projection_installation_acknowledgments " + + "(acknowledgment_id, capture_operation_id, capture_request_id, issuer_id, " + + "caller_workload_identity, projection_key, capture_request_digest_version, " + + "capture_request_digest, request_digest_version, request_digest, " + + "installed_projection_json, installed_projection_sha256) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + acknowledgment.acknowledgmentId(), + acknowledgment.captureOperationId(), + requestId, + acknowledgment.issuerId(), + acknowledgment.callerWorkloadIdentity(), + acknowledgment.projectionKey(), + acknowledgment.captureRequestDigestVersion(), + HEX.parseHex(acknowledgment.captureRequestDigest()), + acknowledgment.requestDigestVersion(), + HEX.parseHex(acknowledgment.requestDigest()), + installedProjection, + installedProjectionSha256); + } + + private void assertSqlConstraint(Runnable action, String constraint) { + assertThatThrownBy(action::run) + .isInstanceOf(DataAccessException.class) + .satisfies(failure -> assertPostgresConstraint(failure, constraint)); + } + + private void assertPostgresConstraint(Throwable failure, String expectedConstraint) { + Throwable cause = failure; + while (cause != null && !(cause instanceof PSQLException)) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(PSQLException.class); + PSQLException postgresFailure = (PSQLException) cause; + assertThat(postgresFailure.getServerErrorMessage().getConstraint()) + .isEqualTo(expectedConstraint); + } + + private SourceHistory sourceHistory(Fixture fixture) { + Record authority = + fixture + .setupDsl() + .fetchOne( + "SELECT generation, source_version FROM account_authority_generations " + + "WHERE scope_kind = 'ISSUER' AND issuer_id = ?", + ISSUER_ID); + List streams = new ArrayList<>(); + for (Record row : + fixture + .setupDsl() + .fetch( + "SELECT outbox_stream_key, last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + STREAM_KEY)) { + streams.add( + new OutboxStream( + row.get("outbox_stream_key", String.class), row.get("last_sequence", Long.class))); + } + List events = new ArrayList<>(); + for (Record row : + fixture + .setupDsl() + .fetch( + "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", + STREAM_KEY)) { + events.add( + new OutboxEvent( + row.get("outbox_stream_key", String.class), + 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 SourceHistory( + authority == null ? null : authority.get("generation", Long.class), + authority == null ? null : authority.get("source_version", Long.class), + streams, + events); + } + + private long countAcknowledgments(Fixture fixture) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_issuer_projection_installation_acknowledgments") + .fetchOne(0, Long.class)); + } + + private List captureHistory(Fixture fixture) { + List captures = new ArrayList<>(); + for (Record row : + fixture + .setupDsl() + .fetch( + "SELECT operation_id, request_id, issuer_id, caller_workload_identity, " + + "projection_key, request_digest_version, request_digest, " + + "issuer_auth_generation, source_version, outbox_stream_key, outbox_sequence, " + + "event_outbox_sequence, event_id, event_digest, event_payload " + + "FROM account_issuer_projection_reconciliation_receipts " + + "ORDER BY issuer_id, request_id")) { + byte[] eventPayload = row.get("event_payload", byte[].class); + captures.add( + new CaptureEvidence( + row.get("operation_id", UUID.class), + row.get("request_id", UUID.class), + row.get("issuer_id", String.class), + row.get("caller_workload_identity", String.class), + row.get("projection_key", String.class), + row.get("request_digest_version", Integer.class), + HEX.formatHex(row.get("request_digest", byte[].class)), + row.get("issuer_auth_generation", Long.class), + row.get("source_version", Long.class), + row.get("outbox_stream_key", String.class), + row.get("outbox_sequence", Long.class), + row.get("event_outbox_sequence", Long.class), + row.get("event_id", String.class), + row.get("event_digest", String.class), + eventPayload == null ? null : new String(eventPayload, StandardCharsets.UTF_8))); + } + return captures; + } + + private void assertSameEvent( + IssuerGenerationAuthorityEvent expected, IssuerGenerationAuthorityEvent 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.issuerId()).isEqualTo(expected.issuerId()); + assertThat(actual.sourceScope()).isEqualTo(expected.sourceScope()); + assertThat(actual.outboxStreamKey()).isEqualTo(expected.outboxStreamKey()); + assertThat(actual.outboxSequence()).isEqualTo(expected.outboxSequence()); + assertThat(actual.issuerAuthGeneration()).isEqualTo(expected.issuerAuthGeneration()); + assertThat(actual.sourceVersion()).isEqualTo(expected.sourceVersion()); + assertThat(actual.eventDigest()).isEqualTo(expected.eventDigest()); + assertThat(actual.canonicalJsonUtf8()).containsExactly(expected.canonicalJsonUtf8()); + } + + private byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Issuer acknowledgment PostgreSQL barrier timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Issuer acknowledgment PostgreSQL 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, + AccountIssuerProjectionReconciliationRepository captures, + AccountIssuerProjectionAcknowledgmentRepository acknowledgments, + AccountIssuerAuthorityEventProducer source) { + private AccountIssuerProjectionReconciliationService captureService() { + return new AccountIssuerProjectionReconciliationService( + ISSUER_ID, GAME_SESSION_ID, source, captures, transactionManager); + } + + private AccountIssuerProjectionAcknowledgmentService acknowledgmentService() { + return acknowledgmentService(acknowledgments); + } + + private AccountIssuerProjectionAcknowledgmentService acknowledgmentService( + AccountIssuerProjectionAcknowledgmentRepository repository) { + return new AccountIssuerProjectionAcknowledgmentService( + ISSUER_ID, GAME_SESSION_ID, captureService(), repository, transactionManager); + } + } + + private record OutboxStream(String streamKey, Long lastSequence) {} + + private record OutboxEvent( + String streamKey, + Long sequence, + String requestId, + String eventId, + String eventDigest, + String canonicalJson) {} + + private record SourceHistory( + Long generation, Long sourceVersion, List streams, List events) {} + + private record CaptureEvidence( + UUID operationId, + UUID requestId, + String issuerId, + String callerWorkloadIdentity, + String projectionKey, + Integer requestDigestVersion, + String requestDigest, + Long issuerAuthGeneration, + Long sourceVersion, + String streamKey, + Long sequence, + Long eventSequence, + String eventId, + String eventDigest, + String canonicalEventJson) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerProjectionReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerProjectionReconciliationPostgresIntegrationTest.java new file mode 100644 index 0000000000..74f4f28372 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerProjectionReconciliationPostgresIntegrationTest.java @@ -0,0 +1,808 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +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.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +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.AccountIssuerProjectionReconciliationRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository.Receipt; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.accountservice.service.AccountIssuerProjectionReconciliationService; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +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 IssuerProjectionReconciliationPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "issuer_reconcile_pg"; + private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String OTHER_ISSUER_ID = "https://other.example.test/issuer"; + private static final String STREAM_KEY = "account:auth-authority:v1:issuer/" + ISSUER_ID; + private static final String PROJECTION_KEY = + "session:game:auth:issuer-generation:v1:" + ISSUER_ID; + private static final String GAME_SESSION_ID = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String OTHER_GAME_SESSION_ID = + "spiffe://firemud/ns/other/sa/game-session-service"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void capturesProvedZeroBaselineWithoutSourceOrOutboxWrites() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + StoredState before = snapshot(fixture); + UUID requestId = UUID.randomUUID(); + + Receipt receipt = fixture.service().capture(ISSUER_ID, GAME_SESSION_ID, requestId); + + assertThat(receipt.operationId()).isNotEqualTo(NIL_UUID).isNotEqualTo(requestId); + assertThat(receipt.requestId()).isEqualTo(requestId); + assertThat(receipt.issuerId()).isEqualTo(ISSUER_ID); + assertThat(receipt.callerWorkloadIdentity()).isEqualTo(GAME_SESSION_ID); + assertThat(receipt.projectionKey()).isEqualTo(PROJECTION_KEY); + assertThat(receipt.requestDigestVersion()).isEqualTo(1); + assertThat(receipt.requestDigest()) + .isEqualTo(expectedRequestDigest(ISSUER_ID, GAME_SESSION_ID, PROJECTION_KEY, requestId)); + assertZeroSnapshot(receipt.capturedSource()); + assertThat(snapshot(fixture)).isEqualTo(before.withReceiptCount(1L)); + assertStoredReceipt(fixture, receipt); + } + + @Test + void capturesCompletePositiveCheckpointWithIndependentSourceCounters() { + Fixture fixture = newFixture(); + IssuerGenerationAuthorityEvent sourceEvent = seedNonSequenceAlignedPositiveState(fixture); + UUID requestId = UUID.randomUUID(); + + Receipt receipt = fixture.service().capture(ISSUER_ID, GAME_SESSION_ID, requestId); + + IssuerAuthoritySnapshot captured = receipt.capturedSource(); + assertThat(captured.issuerId()).isEqualTo(ISSUER_ID); + assertThat(captured.issuerAuthGeneration()).isEqualTo(4L); + assertThat(captured.sourceVersion()).isEqualTo(8L); + assertThat(captured.outboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(captured.outboxSequence()).isEqualTo(1L); + assertThat(captured.issuerAuthGeneration()).isNotEqualTo(captured.outboxSequence() + 1L); + assertThat(captured.latestEvent()).isPresent(); + assertSameEvent(sourceEvent, captured.latestEvent().orElseThrow()); + assertThat(receipt.operationId()).isNotEqualTo(NIL_UUID).isNotEqualTo(requestId); + assertThat(receipt.requestDigest()) + .isEqualTo(expectedRequestDigest(ISSUER_ID, GAME_SESSION_ID, PROJECTION_KEY, requestId)); + assertStoredReceipt(fixture, receipt); + } + + @Test + void databaseRejectsIncompleteAndContradictoryPositiveReceiptEvidenceWithoutMutation() { + Fixture fixture = newFixture(); + IssuerGenerationAuthorityEvent sourceEvent = seedNonSequenceAlignedPositiveState(fixture); + Receipt original = fixture.service().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + StoredState committed = snapshot(fixture); + IssuerAuthoritySnapshot source = original.capturedSource(); + + // Each raw setup DSL statement runs independently in autocommit mode. A rejected insert + // therefore cannot leave the PostgreSQL transaction aborted for the next guard case. + UUID missingDigestRequest = UUID.randomUUID(); + assertReceiptInsertRejected( + fixture, + original, + UUID.randomUUID(), + missingDigestRequest, + source.outboxSequence(), + sourceEvent.eventId(), + null, + sourceEvent.canonicalJsonUtf8(), + "Issuer reconciliation receipt differs from its source event", + committed); + + UUID missingEventSequenceRequest = UUID.randomUUID(); + assertReceiptInsertRejected( + fixture, + original, + UUID.randomUUID(), + missingEventSequenceRequest, + null, + sourceEvent.eventId(), + sourceEvent.eventDigest(), + sourceEvent.canonicalJsonUtf8(), + "account_issuer_projection_reconciliation_checkpoint_check", + committed); + + IssuerGenerationAuthorityEvent contradictoryEvent = contradictoryCanonicalEvent(sourceEvent); + assertReceiptInsertRejected( + fixture, + original, + UUID.randomUUID(), + UUID.randomUUID(), + source.outboxSequence(), + contradictoryEvent.eventId(), + contradictoryEvent.eventDigest(), + contradictoryEvent.canonicalJsonUtf8(), + "Issuer reconciliation receipt differs from its source event", + committed); + + assertThat(snapshot(fixture)).isEqualTo(committed); + assertThat(countReceipts(fixture)).isEqualTo(1L); + assertThat(countEvents(fixture)).isEqualTo(1L); + assertStoredReceipt(fixture, original); + } + + @Test + void committedCaptureWithLostPostCommitReadbackRecoversTheSameReceipt() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + AtomicInteger receiptReads = new AtomicInteger(); + AccountIssuerProjectionReconciliationRepository hideOnePostCommitRead = + new AccountIssuerProjectionReconciliationRepository(fixture.transactionDsl()) { + @Override + public Optional findByIssuerAndRequestId(String issuerId, UUID requestId) { + if (receiptReads.incrementAndGet() == 3) { + return Optional.empty(); + } + return super.findByIssuerAndRequestId(issuerId, requestId); + } + }; + AccountIssuerProjectionReconciliationService service = + fixture.service(hideOnePostCommitRead, GAME_SESSION_ID); + UUID requestId = UUID.randomUUID(); + StoredState before = snapshot(fixture); + + assertThatThrownBy(() -> service.capture(ISSUER_ID, GAME_SESSION_ID, requestId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Post-commit issuer reconciliation receipt readback is missing"); + + StoredState committed = snapshot(fixture); + assertThat(committed).isEqualTo(before.withReceiptCount(1L)); + Receipt recovered = service.capture(ISSUER_ID, GAME_SESSION_ID, requestId); + + assertThat(recovered.operationId()).isNotEqualTo(NIL_UUID).isNotEqualTo(requestId); + assertThat(recovered.capturedSource().outboxSequence()).isZero(); + assertStoredReceipt(fixture, recovered); + assertThat(snapshot(fixture)).isEqualTo(committed); + } + + @Test + void exactRetryReturnsOriginalPositiveReceiptAfterLaterSourceAdvance() { + Fixture fixture = newFixture(); + IssuerGenerationAuthorityEvent firstSourceEvent = seedNonSequenceAlignedPositiveState(fixture); + UUID requestId = UUID.randomUUID(); + Receipt original = fixture.service().capture(ISSUER_ID, GAME_SESSION_ID, requestId); + IssuerGenerationAuthorityEvent laterSourceEvent = + fixture.source().advance(ISSUER_ID, UUID.randomUUID(), 4L, 8L); + + Receipt retry = fixture.service().capture(ISSUER_ID, GAME_SESSION_ID, requestId); + + assertSameReceipt(original, retry); + assertThat(original.capturedSource().outboxSequence()).isEqualTo(1L); + assertThat(original.capturedSource().issuerAuthGeneration()).isEqualTo(4L); + assertThat(original.capturedSource().sourceVersion()).isEqualTo(8L); + assertSameEvent(firstSourceEvent, original.capturedSource().latestEvent().orElseThrow()); + assertThat(laterSourceEvent.outboxSequence()).isEqualTo("2"); + IssuerAuthoritySnapshot current = fixture.source().readCurrent(ISSUER_ID); + assertThat(current.outboxSequence()).isEqualTo(2L); + assertThat(current.issuerAuthGeneration()).isEqualTo(5L); + assertThat(current.sourceVersion()).isEqualTo(9L); + assertSameEvent(laterSourceEvent, current.latestEvent().orElseThrow()); + assertThat(countReceipts(fixture)).isEqualTo(1L); + assertStoredReceipt(fixture, original); + } + + @Test + void concurrentExactCapturesReturnOneDurableOperation() throws Exception { + Fixture fixture = newFixture(); + seedIssuer(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(() -> concurrentCapture(fixture, requestId, ready, start)); + Future second = + executor.submit(() -> concurrentCapture(fixture, requestId, ready, start)); + assertThat(ready.await(20, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + Receipt firstResult = first.get(45, TimeUnit.SECONDS); + Receipt secondResult = second.get(45, TimeUnit.SECONDS); + + assertSameReceipt(firstResult, secondResult); + assertThat(firstResult.operationId()).isNotEqualTo(NIL_UUID).isNotEqualTo(requestId); + assertStoredReceipt(fixture, firstResult); + } finally { + start.countDown(); + executor.shutdownNow(); + } + + assertThat(countReceipts(fixture)).isEqualTo(1L); + assertThat(countEvents(fixture)).isZero(); + assertThat(countStreams(fixture)).isZero(); + } + + @Test + void captureAndSourceAdvanceSerializeOnOneIssuerFenceWithoutHybridSnapshot() throws Exception { + Fixture fixture = newFixture(); + seedIssuer(fixture); + CountDownLatch insertEntered = new CountDownLatch(1); + CountDownLatch releaseInsert = new CountDownLatch(1); + AtomicBoolean blockFirstInsert = new AtomicBoolean(true); + AccountIssuerProjectionReconciliationRepository blockingRepository = + new AccountIssuerProjectionReconciliationRepository(fixture.transactionDsl()) { + @Override + public Receipt insert(Receipt receipt) { + if (blockFirstInsert.compareAndSet(true, false)) { + insertEntered.countDown(); + await(releaseInsert); + } + return super.insert(receipt); + } + }; + AccountIssuerProjectionReconciliationService service = + fixture.service(blockingRepository, GAME_SESSION_ID); + UUID requestId = UUID.randomUUID(); + UUID advanceRequestId = UUID.randomUUID(); + CountDownLatch advanceStarted = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future capture = + executor.submit(() -> service.capture(ISSUER_ID, GAME_SESSION_ID, requestId)); + assertThat(insertEntered.await(20, TimeUnit.SECONDS)).isTrue(); + Future advance = + executor.submit( + () -> { + advanceStarted.countDown(); + return fixture.source().advance(ISSUER_ID, advanceRequestId, 1L, 1L); + }); + assertThat(advanceStarted.await(20, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(() -> advance.get(300, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + + releaseInsert.countDown(); + Receipt captured = capture.get(45, TimeUnit.SECONDS); + IssuerGenerationAuthorityEvent advanced = advance.get(45, TimeUnit.SECONDS); + + assertZeroSnapshot(captured.capturedSource()); + assertThat(advanced.outboxSequence()).isEqualTo("1"); + assertThat(advanced.issuerAuthGeneration()).isEqualTo("2"); + assertThat(advanced.sourceVersion()).isEqualTo("2"); + IssuerAuthoritySnapshot current = fixture.source().readCurrent(ISSUER_ID); + assertThat(current.outboxSequence()).isEqualTo(1L); + assertThat(current.issuerAuthGeneration()).isEqualTo(2L); + assertThat(current.sourceVersion()).isEqualTo(2L); + assertSameEvent(advanced, current.latestEvent().orElseThrow()); + assertThat(captured.capturedSource().outboxSequence()).isZero(); + assertThat(countReceipts(fixture)).isEqualTo(1L); + assertStoredReceipt(fixture, captured); + Receipt zeroReceiptRetry = service.capture(ISSUER_ID, GAME_SESSION_ID, requestId); + assertSameReceipt(captured, zeroReceiptRetry); + assertThat(zeroReceiptRetry.capturedSource().outboxSequence()).isZero(); + } finally { + releaseInsert.countDown(); + executor.shutdownNow(); + } + } + + @Test + void invalidBindingsAndMissingAuthorityDenyWithoutEnrollment() { + // These local string comparisons do not prove certificate authentication of a transport peer. + Fixture fixture = newFixture(); + seedIssuer(fixture); + StoredState before = snapshot(fixture); + UUID requestId = UUID.randomUUID(); + + assertThatThrownBy(() -> fixture.service().capture(ISSUER_ID, GAME_SESSION_ID, NIL_UUID)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> fixture.service().capture(OTHER_ISSUER_ID, GAME_SESSION_ID, requestId)) + .isInstanceOf(AccountIssuerAuthorityEventProducer.IssuerMismatchException.class); + assertThatThrownBy(() -> fixture.service().capture(ISSUER_ID, OTHER_GAME_SESSION_ID, requestId)) + .isInstanceOf(SecurityException.class); + assertThat(snapshot(fixture)).isEqualTo(before); + + Receipt original = fixture.service().capture(ISSUER_ID, GAME_SESSION_ID, requestId); + AccountIssuerProjectionReconciliationService changedCallerService = + fixture.service(fixture.receipts(), OTHER_GAME_SESSION_ID); + assertThatThrownBy( + () -> changedCallerService.capture(ISSUER_ID, OTHER_GAME_SESSION_ID, requestId)) + .isInstanceOf(IdempotencyConflictException.class); + assertThat(countReceipts(fixture)).isEqualTo(1L); + assertStoredReceipt(fixture, original); + + Fixture missingAuthority = newFixture(); + assertThatThrownBy( + () -> missingAuthority.service().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + assertThat(snapshot(missingAuthority).generation()).isNull(); + assertThat(snapshot(missingAuthority).sourceVersion()).isNull(); + assertThat(countIssuerRows(missingAuthority)).isZero(); + assertThat(countEvents(missingAuthority)).isZero(); + assertThat(countStreams(missingAuthority)).isZero(); + assertThat(countReceipts(missingAuthority)).isZero(); + } + + @Test + void durableReceiptsRejectUpdateAndDelete() { + Fixture fixture = newFixture(); + seedIssuer(fixture); + Receipt receipt = fixture.service().capture(ISSUER_ID, GAME_SESSION_ID, UUID.randomUUID()); + StoredState committed = snapshot(fixture); + + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_issuer_projection_reconciliation_receipts " + + "SET caller_workload_identity = ? WHERE operation_id = ?", + OTHER_GAME_SESSION_ID, + receipt.operationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Issuer projection reconciliation receipts are immutable"); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_issuer_projection_reconciliation_receipts " + + "WHERE operation_id = ?", + receipt.operationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Issuer projection reconciliation receipts are immutable"); + + assertThat(snapshot(fixture)).isEqualTo(committed); + assertStoredReceipt(fixture, receipt); + } + + 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()); + org.flywaydb.core.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); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(transactionDsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl); + AccountIssuerProjectionReconciliationRepository receipts = + new AccountIssuerProjectionReconciliationRepository(transactionDsl); + AccountIssuerAuthorityEventProducer source = + new AccountIssuerAuthorityEventProducer( + ISSUER_ID, generations, outbox, transactionDsl, transactionManager); + return new Fixture( + setupDsl, + transactionDsl, + transactionManager, + transaction, + generations, + outbox, + receipts, + source); + } + + private void seedIssuer(Fixture fixture) { + transaction( + fixture.transaction(), + () -> { + fixture.generations().initializeIssuerIfAbsent(ISSUER_ID); + return null; + }); + } + + private IssuerGenerationAuthorityEvent seedNonSequenceAlignedPositiveState(Fixture fixture) { + fixture + .setupDsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, issuer_id, account_uuid, tenant_uuid, generation, source_version) " + + "VALUES ('ISSUER', ?, NULL, NULL, 3, 7)", + ISSUER_ID); + UUID sourceRequestId = UUID.randomUUID(); + transaction( + fixture.transaction(), + () -> { + ScopeState current = fixture.generations().read(AuthorityScope.issuer(ISSUER_ID)); + ScopeState advanced = fixture.generations().advance(current, null); + assertThat(advanced.generation()).isEqualTo(4L); + assertThat(advanced.sourceVersion()).isEqualTo(8L); + appendSeedEvent(fixture, sourceRequestId, 4L, 8L); + return null; + }); + return fixture.source().readCurrent(ISSUER_ID).latestEvent().orElseThrow(); + } + + private void appendSeedEvent( + Fixture fixture, UUID requestId, long generation, long sourceVersion) { + String requestText = requestId.toString(); + String eventId = "account-issuer-authority-event-v1:" + requestText; + fixture + .outbox() + .append( + STREAM_KEY, + requestText, + sequence -> { + IssuerGenerationAuthorityEvent event = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + eventId, + "requestId", + requestText, + "issuerId", + ISSUER_ID, + "sourceScope", + "issuer/" + ISSUER_ID, + "outboxStreamKey", + STREAM_KEY, + "outboxSequence", + Long.toString(sequence), + "issuerAuthGeneration", + Long.toString(generation), + "sourceVersion", + Long.toString(sourceVersion))); + return new AccountAuthorityOutboxRepository.EventEvidence( + event.eventId(), event.eventDigest(), event.canonicalJsonUtf8()); + }); + } + + private IssuerGenerationAuthorityEvent contradictoryCanonicalEvent( + IssuerGenerationAuthorityEvent sourceEvent) { + String requestId = UUID.randomUUID().toString(); + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + "account-issuer-authority-event-v1:" + requestId, + "requestId", + requestId, + "issuerId", + sourceEvent.issuerId(), + "sourceScope", + sourceEvent.sourceScope(), + "outboxStreamKey", + sourceEvent.outboxStreamKey(), + "outboxSequence", + sourceEvent.outboxSequence(), + "issuerAuthGeneration", + sourceEvent.issuerAuthGeneration(), + "sourceVersion", + sourceEvent.sourceVersion())); + } + + private void assertReceiptInsertRejected( + Fixture fixture, + Receipt binding, + UUID operationId, + UUID requestId, + Long eventSequence, + String eventId, + String eventDigest, + byte[] eventPayload, + String expectedSqlGuard, + StoredState expectedState) { + IssuerAuthoritySnapshot source = binding.capturedSource(); + byte[] requestDigest = + HexFormat.of() + .parseHex( + expectedRequestDigest( + binding.issuerId(), + binding.callerWorkloadIdentity(), + binding.projectionKey(), + requestId)); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "INSERT INTO account_issuer_projection_reconciliation_receipts " + + "(operation_id, request_id, issuer_id, caller_workload_identity, " + + "projection_key, request_digest_version, request_digest, " + + "issuer_auth_generation, source_version, outbox_stream_key, " + + "outbox_sequence, event_outbox_sequence, event_id, event_digest, event_payload) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, CAST(? AS BIGINT), ?, ?, ?)", + operationId, + requestId, + binding.issuerId(), + binding.callerWorkloadIdentity(), + binding.projectionKey(), + requestDigest, + source.issuerAuthGeneration(), + source.sourceVersion(), + source.outboxStreamKey(), + source.outboxSequence(), + eventSequence, + eventId, + eventDigest, + eventPayload)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining(expectedSqlGuard); + assertThat(snapshot(fixture)).isEqualTo(expectedState); + } + + private Receipt concurrentCapture( + Fixture fixture, UUID requestId, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + return fixture.service().capture(ISSUER_ID, GAME_SESSION_ID, requestId); + } + + private void assertZeroSnapshot(IssuerAuthoritySnapshot snapshot) { + assertThat(snapshot.issuerId()).isEqualTo(ISSUER_ID); + assertThat(snapshot.issuerAuthGeneration()).isEqualTo(1L); + assertThat(snapshot.sourceVersion()).isEqualTo(1L); + assertThat(snapshot.outboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(snapshot.outboxSequence()).isZero(); + assertThat(snapshot.latestEvent()).isEmpty(); + } + + private void assertStoredReceipt(Fixture fixture, Receipt expected) { + Record stored = + fixture + .setupDsl() + .fetchOne( + "SELECT operation_id, request_id, issuer_id, caller_workload_identity, " + + "projection_key, request_digest_version, request_digest, " + + "issuer_auth_generation, source_version, outbox_stream_key, " + + "outbox_sequence, event_outbox_sequence, event_id, event_digest, event_payload " + + "FROM account_issuer_projection_reconciliation_receipts " + + "WHERE issuer_id = ? AND request_id = ?", + expected.issuerId(), + expected.requestId()); + assertThat(stored).isNotNull(); + assertThat(stored.get("operation_id", UUID.class)).isEqualTo(expected.operationId()); + assertThat(stored.get("request_id", UUID.class)).isEqualTo(expected.requestId()); + assertThat(stored.get("issuer_id", String.class)).isEqualTo(expected.issuerId()); + assertThat(stored.get("caller_workload_identity", String.class)) + .isEqualTo(expected.callerWorkloadIdentity()); + assertThat(stored.get("projection_key", String.class)).isEqualTo(expected.projectionKey()); + assertThat(stored.get("request_digest_version", Integer.class)) + .isEqualTo(expected.requestDigestVersion()); + assertThat(HexFormat.of().formatHex(stored.get("request_digest", byte[].class))) + .isEqualTo(expected.requestDigest()); + + IssuerAuthoritySnapshot source = expected.capturedSource(); + assertThat(stored.get("issuer_auth_generation", Long.class)) + .isEqualTo(source.issuerAuthGeneration()); + assertThat(stored.get("source_version", Long.class)).isEqualTo(source.sourceVersion()); + assertThat(stored.get("outbox_stream_key", String.class)).isEqualTo(source.outboxStreamKey()); + assertThat(stored.get("outbox_sequence", Long.class)).isEqualTo(source.outboxSequence()); + if (source.outboxSequence() == 0L) { + assertThat(stored.get("event_outbox_sequence", Long.class)).isNull(); + assertThat(stored.get("event_id", String.class)).isNull(); + assertThat(stored.get("event_digest", String.class)).isNull(); + assertThat(stored.get("event_payload", byte[].class)).isNull(); + assertThat(source.latestEvent()).isEmpty(); + } else { + IssuerGenerationAuthorityEvent event = source.latestEvent().orElseThrow(); + assertThat(stored.get("event_outbox_sequence", Long.class)) + .isEqualTo(source.outboxSequence()); + assertThat(stored.get("event_id", String.class)).isEqualTo(event.eventId()); + assertThat(stored.get("event_digest", String.class)).isEqualTo(event.eventDigest()); + assertThat(stored.get("event_payload", byte[].class)) + .containsExactly(event.canonicalJsonUtf8()); + assertThat(event.issuerId()).isEqualTo(ISSUER_ID); + assertThat(event.sourceScope()).isEqualTo("issuer/" + ISSUER_ID); + assertThat(event.outboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(event.eventDigest()).matches("sha256:[0-9a-f]{64}"); + } + } + + private void assertSameReceipt(Receipt expected, Receipt actual) { + assertThat(actual.operationId()).isEqualTo(expected.operationId()); + assertThat(actual.requestId()).isEqualTo(expected.requestId()); + assertThat(actual.issuerId()).isEqualTo(expected.issuerId()); + assertThat(actual.callerWorkloadIdentity()).isEqualTo(expected.callerWorkloadIdentity()); + assertThat(actual.projectionKey()).isEqualTo(expected.projectionKey()); + assertThat(actual.requestDigestVersion()).isEqualTo(expected.requestDigestVersion()); + assertThat(actual.requestDigest()).isEqualTo(expected.requestDigest()); + assertSameSnapshot(expected.capturedSource(), actual.capturedSource()); + } + + private void assertSameSnapshot( + IssuerAuthoritySnapshot expected, IssuerAuthoritySnapshot actual) { + assertThat(actual.issuerId()).isEqualTo(expected.issuerId()); + assertThat(actual.issuerAuthGeneration()).isEqualTo(expected.issuerAuthGeneration()); + assertThat(actual.sourceVersion()).isEqualTo(expected.sourceVersion()); + assertThat(actual.outboxStreamKey()).isEqualTo(expected.outboxStreamKey()); + assertThat(actual.outboxSequence()).isEqualTo(expected.outboxSequence()); + assertThat(actual.latestEvent().isPresent()).isEqualTo(expected.latestEvent().isPresent()); + if (expected.latestEvent().isPresent()) { + assertSameEvent(expected.latestEvent().orElseThrow(), actual.latestEvent().orElseThrow()); + } + } + + private void assertSameEvent( + IssuerGenerationAuthorityEvent expected, IssuerGenerationAuthorityEvent actual) { + assertThat(actual.schemaVersion()).isEqualTo(expected.schemaVersion()); + assertThat(actual.eventType()).isEqualTo(IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE); + assertThat(actual.eventType()).isEqualTo(expected.eventType()); + assertThat(actual.eventId()).isEqualTo(expected.eventId()); + assertThat(actual.requestId()).isEqualTo(expected.requestId()); + assertThat(actual.issuerId()).isEqualTo(expected.issuerId()); + assertThat(actual.sourceScope()).isEqualTo(expected.sourceScope()); + assertThat(actual.outboxStreamKey()).isEqualTo(expected.outboxStreamKey()); + assertThat(actual.outboxSequence()).isEqualTo(expected.outboxSequence()); + assertThat(actual.issuerAuthGeneration()).isEqualTo(expected.issuerAuthGeneration()); + assertThat(actual.sourceVersion()).isEqualTo(expected.sourceVersion()); + assertThat(actual.eventDigest()).isEqualTo(expected.eventDigest()); + assertThat(actual.canonicalJsonUtf8()).containsExactly(expected.canonicalJsonUtf8()); + } + + private StoredState snapshot(Fixture fixture) { + Record authority = + fixture + .setupDsl() + .fetchOne( + "SELECT generation, source_version FROM account_authority_generations " + + "WHERE scope_kind = 'ISSUER' AND issuer_id = ?", + ISSUER_ID); + return new StoredState( + authority == null ? null : authority.get("generation", Long.class), + authority == null ? null : authority.get("source_version", Long.class), + countEvents(fixture), + countStreams(fixture), + countReceipts(fixture)); + } + + private long countIssuerRows(Fixture fixture) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_authority_generations " + + "WHERE scope_kind = 'ISSUER' AND issuer_id = ?", + ISSUER_ID) + .fetchOne(0, Long.class)); + } + + private long countEvents(Fixture fixture) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + STREAM_KEY) + .fetchOne(0, Long.class)); + } + + private long countStreams(Fixture fixture) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_streams WHERE outbox_stream_key = ?", + STREAM_KEY) + .fetchOne(0, Long.class)); + } + + private long countReceipts(Fixture fixture) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery("SELECT COUNT(*) FROM account_issuer_projection_reconciliation_receipts") + .fetchOne(0, Long.class)); + } + + private String expectedRequestDigest( + String issuerId, String callerIdentity, String projectionKey, UUID requestId) { + String[] fields = { + "issuer-projection-reconciliation-request/v1", + "ISSUER_PROJECTION_SNAPSHOT_CAPTURE", + issuerId, + callerIdentity, + projectionKey, + requestId.toString() + }; + ByteArrayOutputStream framed = new ByteArrayOutputStream(); + for (String field : fields) { + byte[] bytes = field.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + framed.write(':'); + framed.writeBytes(bytes); + } + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(framed.toByteArray())); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Issuer reconciliation PostgreSQL barrier timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Issuer reconciliation PostgreSQL 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, + AccountIssuerProjectionReconciliationRepository receipts, + AccountIssuerAuthorityEventProducer source) { + private AccountIssuerProjectionReconciliationService service() { + return service(receipts, GAME_SESSION_ID); + } + + private AccountIssuerProjectionReconciliationService service( + AccountIssuerProjectionReconciliationRepository repository, String callerIdentity) { + return new AccountIssuerProjectionReconciliationService( + ISSUER_ID, callerIdentity, source, repository, transactionManager); + } + } + + private record StoredState( + Long generation, Long sourceVersion, long eventCount, long streamCount, long receiptCount) { + private StoredState withReceiptCount(long newReceiptCount) { + return new StoredState(generation, sourceVersion, eventCount, streamCount, newReceiptCount); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/MembershipGenerationProjectionPostgresRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/MembershipGenerationProjectionPostgresRedisIntegrationTest.java new file mode 100644 index 0000000000..b2f4c9b1cb --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/MembershipGenerationProjectionPostgresRedisIntegrationTest.java @@ -0,0 +1,1328 @@ +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.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +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.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.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.concurrent.atomic.AtomicReference; +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.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.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountMembershipLifecycleService; +import net.firedevops.firemud.accountservice.service.AccountMembershipSourceReader; +import net.firedevops.firemud.accountservice.service.AccountMembershipSourceReader.MembershipSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.MembershipGenerationProjection; +import net.firedevops.firemud.accountservice.service.RedisMembershipGenerationProjectionStore; +import net.firedevops.firemud.accountservice.service.RedisMembershipGenerationProjectionStore.ApplyResult; +import net.firedevops.firemud.accountservice.service.RedisMembershipGenerationProjectionStore.CacheRateLimitEndpoint; +import net.firedevops.firemud.accountservice.service.RedisMembershipGenerationProjectionStore.CoordinationEndpoint; +import net.firedevops.firemud.accountservice.service.RedisMembershipGenerationProjectionStore.Outcome; +import net.firedevops.firemud.accountservice.service.RedisMembershipGenerationProjectionStore.ProjectionSnapshot; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ResolveLegacyAccountTenantAssociationResponse; +import 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.jooq.Field; +import org.jooq.Record; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +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.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; + +/** + * Account-owned membership-generation projection proof over real Account SQL and isolated Redis. + */ +@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=membership-generation-projection-test" + }) +class MembershipGenerationProjectionPostgresRedisIntegrationTest { + private static final String WORKLOAD_NAMESPACE = "membership-generation-projection-test"; + private static final String WORLD_SLUG = "membership-projection-proof-world"; + private static final String REALM_SLUG = "production"; + private static final String NAMESPACE_ID = "membership-projection-proof-namespace"; + private static final UUID REALM_ID = UUID.fromString("7bda1169-a8a3-4b43-96a4-53f8579ac164"); + private static final long GAME_INSTANCE_ID = 79L; + private static final long CATALOG_REVISION = 31L; + private static final long POINTER_VERSION = 13L; + private static final String AUTHORITY_STREAM_PREFIX = "account:auth-authority:v1:"; + private static final String MEMBERSHIP_KEY_PREFIX = MembershipGenerationProjection.KEY_PREFIX; + private static final String COORD_PASSWORD = "membership-generation-projection-secret"; + 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, + "~" + MEMBERSHIP_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; + + @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + @Autowired private AccountMembershipAuthorityEventProducer membershipAuthorityEventProducer; + @Autowired private AccountMembershipLifecycleService membershipLifecycleService; + @Autowired private AccountAuthorityGenerationRepository authorityGenerationRepository; + @Autowired private ApprovedLegacyTenantAssociationRepository tenantAssociationRepository; + @Autowired private FreshTenantIdentityAssociationRepository freshAssociationRepository; + @Autowired private LegacyTenantSourceEvidence legacyTenantSourceEvidence; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @org.junit.jupiter.api.BeforeEach + void startTestOnlyRedisReadbackClients() { + 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(); + } + + @org.junit.jupiter.api.AfterEach + void closeRedisClients() { + stores.forEach(RedisMembershipGenerationProjectionStore::close); + stores.clear(); + if (adminConnectionFactory != null) { + adminConnectionFactory.destroy(); + } + if (ownerConnectionFactory != null) { + ownerConnectionFactory.destroy(); + } + } + + @org.junit.jupiter.api.Test + void existingOnlyZeroBaselineProjectsWithoutAdmissionOrSqlMutation() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + enrollFreshNeverJoinedBaseline(account.accountUuid(), tenantUuid); + + AccountMembershipSourceReader reader = membershipSourceReader(); + MembershipSourceSnapshot source = reader.readCurrent(account.accountUuid(), tenantUuid); + assertSourceAxes(source, "MISSING", false, 1L, 1L, "1", "0", false); + assertThat(source.snapshot().roles()).isEmpty(); + assertThat(source.snapshot().sourceEvent()).isNull(); + SourceSqlState beforeProjection = sourceSqlState(account, tenantUuid, null); + + ApplyResult result = store(reader).refreshCurrent(account.accountUuid(), tenantUuid); + + ProjectionSnapshot projection = + assertProjection( + result, Outcome.APPLIED, account.accountUuid(), tenantUuid, 1L, 1L, "1", "0", null); + assertThat(sourceSqlState(account, tenantUuid, null)).isEqualTo(beforeProjection); + assertThat(projection.json()) + .doesNotContain("membershipExists", "gameplayAdmissionAllowed", "roles"); + } + + @org.junit.jupiter.api.Test + void unknownAndAssociatedUnenrolledPairsCannotSynthesizeProjectionState() { + AccountFixture account = accountFixture(); + UUID unknownTenant = UUID.randomUUID(); + UUID associatedUnenrolledTenant = UUID.randomUUID(); + importFreshTenantAssociation(associatedUnenrolledTenant); + AccountMembershipSourceReader reader = membershipSourceReader(); + RedisMembershipGenerationProjectionStore store = store(reader); + + SourceSqlState unknownBefore = sourceSqlState(account, unknownTenant, null); + assertThatThrownBy(() -> reader.readCurrent(account.accountUuid(), unknownTenant)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> store.refreshCurrent(account.accountUuid(), unknownTenant)) + .isInstanceOf(IllegalStateException.class); + assertThat(sourceSqlState(account, unknownTenant, null)).isEqualTo(unknownBefore); + assertThat(adminTemplate.opsForValue().get(key(account.accountUuid(), unknownTenant))).isNull(); + + SourceSqlState associatedBefore = sourceSqlState(account, associatedUnenrolledTenant, null); + assertThat(associatedBefore.pairAuthority()).isEmpty(); + assertThat( + associatedBefore.generationRows().stream() + .filter(row -> "MEMBERSHIP".equals(row.get("scope_kind"))) + .toList()) + .isEmpty(); + assertThatThrownBy(() -> reader.readCurrent(account.accountUuid(), associatedUnenrolledTenant)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Fresh Account membership pair baseline is absent"); + assertThatThrownBy( + () -> store.refreshCurrent(account.accountUuid(), associatedUnenrolledTenant)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Fresh Account membership pair baseline is absent"); + assertThat(sourceSqlState(account, associatedUnenrolledTenant, null)) + .isEqualTo(associatedBefore); + assertThat( + adminTemplate.opsForValue().get(key(account.accountUuid(), associatedUnenrolledTenant))) + .isNull(); + assertThat(associatedBefore.memberships()).isEmpty(); + assertThat(associatedBefore.transitionReceipts()).isEmpty(); + assertThat(associatedBefore.membershipEvents()).isEmpty(); + } + + @org.junit.jupiter.api.Test + void retainedJoinLeftAndReactivationProjectExactIndependentSourceAxes() { + JoinFixture fixture = retainedJoinFixture(); + assertThat(join(fixture).success()).isTrue(); + + AccountMembershipSourceReader reader = membershipSourceReader(); + RedisMembershipGenerationProjectionStore store = store(reader); + MembershipSourceSnapshot joined = + reader.readCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertSourceAxes(joined, "ACTIVE", true, 1L, 1L, "2", "1", true); + SourceSqlState afterJoin = + sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId()); + ApplyResult firstJoin = store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + ProjectionSnapshot joinProjection = + assertProjection( + firstJoin, + Outcome.APPLIED, + fixture.accountUuid(), + fixture.tenantUuid(), + 1L, + 1L, + "2", + "1", + joined.snapshot().sourceEvent().canonicalJson()); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(afterJoin); + + ApplyResult joinRetry = store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(joinRetry.outcome()).isEqualTo(Outcome.REPLAYED); + assertThat(joinRetry.snapshot()).contains(joinProjection); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(afterJoin); + + assertThat(adminTemplate.delete(joinProjection.key())).isTrue(); + ApplyResult joinRepair = store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(joinRepair.outcome()).isEqualTo(Outcome.APPLIED); + assertThat(joinRepair.snapshot()).contains(joinProjection); + assertRedisExactWithoutTtl(joinProjection); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(afterJoin); + + String leftRequestId = "projection-left-" + compactUuid(); + MembershipTransitionReceipt leftReceipt = + membershipLifecycleService.leave( + fixture.accountId(), fixture.legacyTenantId(), leftRequestId); + MembershipSourceSnapshot left = reader.readCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertSourceAxes(left, "INACTIVE", false, 2L, 2L, "3", "2", true); + SourceSqlState afterLeft = + sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId()); + ApplyResult leftProjectionResult = + store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + ProjectionSnapshot leftProjection = + assertProjection( + leftProjectionResult, + Outcome.APPLIED, + fixture.accountUuid(), + fixture.tenantUuid(), + 2L, + 2L, + "3", + "2", + left.snapshot().sourceEvent().canonicalJson()); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(afterLeft); + + ApplyResult leftRetry = store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(leftRetry.outcome()).isEqualTo(Outcome.REPLAYED); + assertThat(leftRetry.snapshot()).contains(leftProjection); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(afterLeft); + + JoinFixture reactivation = nextJoinAttempt(fixture, "projection-reactivate-"); + assertThat(join(reactivation).success()).isTrue(); + MembershipSourceSnapshot active = + reader.readCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertSourceAxes(active, "ACTIVE", true, 3L, 3L, "4", "3", true); + SourceSqlState afterReactivation = + sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId()); + ApplyResult reactivationResult = + store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + ProjectionSnapshot activeProjection = + assertProjection( + reactivationResult, + Outcome.APPLIED, + fixture.accountUuid(), + fixture.tenantUuid(), + 3L, + 3L, + "4", + "3", + active.snapshot().sourceEvent().canonicalJson()); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(afterReactivation); + + assertThat( + membershipLifecycleService.leave( + fixture.accountId(), fixture.legacyTenantId(), leftRequestId)) + .isEqualTo(leftReceipt); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(afterReactivation); + ApplyResult historicalLeftRetry = + store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(historicalLeftRetry.outcome()).isEqualTo(Outcome.REPLAYED); + assertThat(historicalLeftRetry.snapshot()).contains(activeProjection); + assertRedisExactWithoutTtl(activeProjection); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(afterReactivation); + assertThat(adminTemplate.opsForValue().get(leftProjection.key())) + .isEqualTo(activeProjection.json()); + } + + @org.junit.jupiter.api.Test + void sourceAdvanceBetweenCandidateAndFreshReadbackReturnsNonconverged() { + JoinFixture fixture = retainedJoinFixture(); + assertThat(join(fixture).success()).isTrue(); + + AccountMembershipSourceReader delegate = membershipSourceReader(); + AccountMembershipSourceReader interleavedReader = mock(AccountMembershipSourceReader.class); + AtomicInteger sourceReads = new AtomicInteger(); + AtomicReference stateAfterRealLeave = new AtomicReference<>(); + String leftRequestId = "projection-race-left-" + compactUuid(); + doAnswer( + invocation -> { + UUID accountUuid = invocation.getArgument(0); + UUID tenantUuid = invocation.getArgument(1); + MembershipSourceSnapshot candidate = delegate.readCurrent(accountUuid, tenantUuid); + if (sourceReads.incrementAndGet() == 1) { + membershipLifecycleService.leave( + fixture.accountId(), fixture.legacyTenantId(), leftRequestId); + stateAfterRealLeave.set( + sourceSqlState( + fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())); + } + return candidate; + }) + .when(interleavedReader) + .readCurrent(any(UUID.class), any(UUID.class)); + + ApplyResult result = + store(interleavedReader).refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + + assertThat(result.outcome()).isEqualTo(Outcome.SOURCE_CHANGED); + ProjectionSnapshot candidate = result.snapshot().orElseThrow(); + assertThat(candidate.key()).isEqualTo(key(fixture.accountUuid(), fixture.tenantUuid())); + assertThat(parse(candidate.json()).path("outboxSequence").asText()).isEqualTo("1"); + assertThat(adminTemplate.opsForValue().get(candidate.key())).isEqualTo(candidate.json()); + assertThat(adminTemplate.getExpire(candidate.key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + assertThat(stateAfterRealLeave.get()).isNotNull(); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(stateAfterRealLeave.get()); + MembershipSourceSnapshot current = + delegate.readCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertSourceAxes(current, "INACTIVE", false, 2L, 2L, "3", "2", true); + } + + @org.junit.jupiter.api.Test + void staleCandidateCannotReplaceNewerSourceProjection() throws Exception { + JoinFixture fixture = retainedJoinFixture(); + assertThat(join(fixture).success()).isTrue(); + + AccountMembershipSourceReader delegate = membershipSourceReader(); + AccountMembershipSourceReader delayedReader = mock(AccountMembershipSourceReader.class); + CountDownLatch candidateRead = new CountDownLatch(1); + CountDownLatch continueStaleCandidate = new CountDownLatch(1); + AtomicInteger reads = new AtomicInteger(); + doAnswer( + invocation -> { + MembershipSourceSnapshot candidate = + delegate.readCurrent(invocation.getArgument(0), invocation.getArgument(1)); + if (reads.incrementAndGet() == 1) { + candidateRead.countDown(); + await(continueStaleCandidate); + } + return candidate; + }) + .when(delayedReader) + .readCurrent(any(UUID.class), any(UUID.class)); + + RedisMembershipGenerationProjectionStore staleStore = store(delayedReader); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + var staleRefresh = + executor.submit( + () -> staleStore.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid())); + assertThat(candidateRead.await(20, TimeUnit.SECONDS)).isTrue(); + + String leftRequestId = "projection-stale-left-" + compactUuid(); + membershipLifecycleService.leave( + fixture.accountId(), fixture.legacyTenantId(), leftRequestId); + SourceSqlState afterLeft = + sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId()); + ProjectionSnapshot current = + assertProjection( + store(delegate).refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()), + Outcome.APPLIED, + fixture.accountUuid(), + fixture.tenantUuid(), + 2L, + 2L, + "3", + "2", + delegate + .readCurrent(fixture.accountUuid(), fixture.tenantUuid()) + .snapshot() + .sourceEvent() + .canonicalJson()); + + continueStaleCandidate.countDown(); + ApplyResult staleResult = staleRefresh.get(45, TimeUnit.SECONDS); + assertThat(staleResult.outcome()).isEqualTo(Outcome.STALE_SOURCE); + assertThat(staleResult.outcome()).isNotIn(Outcome.APPLIED, Outcome.REPLAYED); + assertThat(adminTemplate.opsForValue().get(current.key())).isEqualTo(current.json()); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(afterLeft); + } finally { + continueStaleCandidate.countDown(); + executor.shutdownNow(); + } + } + + @org.junit.jupiter.api.Test + void aheadMalformedSameCheckpointAndExpiringRedisStatesAreDeniedWithoutSourceWrites() + throws Exception { + JoinFixture fixture = retainedJoinFixture(); + assertThat(join(fixture).success()).isTrue(); + AccountMembershipSourceReader reader = membershipSourceReader(); + RedisMembershipGenerationProjectionStore store = store(reader); + ProjectionSnapshot current = + assertProjection( + store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()), + Outcome.APPLIED, + fixture.accountUuid(), + fixture.tenantUuid(), + 1L, + 1L, + "2", + "1", + reader + .readCurrent(fixture.accountUuid(), fixture.tenantUuid()) + .snapshot() + .sourceEvent() + .canonicalJson()); + SourceSqlState sourceBeforePoison = + sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId()); + + String malformed = "{\"schemaVersion\":\"unknown\"}"; + adminTemplate.opsForValue().set(current.key(), malformed); + ApplyResult malformedResult = store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(malformedResult.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(adminTemplate.opsForValue().get(current.key())).isEqualTo(malformed); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(sourceBeforePoison); + + adminTemplate.opsForValue().set(current.key(), current.json()); + assertThat(adminTemplate.expire(current.key(), 30L, TimeUnit.SECONDS)).isTrue(); + Long ttlBefore = adminTemplate.getExpire(current.key(), TimeUnit.MILLISECONDS); + assertThat(ttlBefore).isPositive(); + ApplyResult ttlResult = store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(ttlResult.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(adminTemplate.opsForValue().get(current.key())).isEqualTo(current.json()); + assertThat(adminTemplate.getExpire(current.key(), TimeUnit.MILLISECONDS)) + .isPositive() + .isLessThanOrEqualTo(ttlBefore); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(sourceBeforePoison); + + assertThat(adminTemplate.persist(current.key())).isTrue(); + ObjectNode ahead = (ObjectNode) parse(current.json()); + ahead.put("sourceVersion", "2"); + String aheadJson = writeJson(ahead); + // This is contradictory ahead-counter evidence at the unchanged checkpoint, not a later source. + assertThat(MembershipGenerationProjection.parse(aheadJson).toJson()).isEqualTo(aheadJson); + adminTemplate.opsForValue().set(current.key(), aheadJson); + ApplyResult aheadResult = store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(aheadResult.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(aheadResult.detail()).contains("SAME_CHECKPOINT_DISAGREEMENT"); + assertThat(adminTemplate.opsForValue().get(current.key())).isEqualTo(aheadJson); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(sourceBeforePoison); + + adminTemplate.opsForValue().set(current.key(), current.json()); + String conflictingJson = sameCheckpointPoison(current); + adminTemplate.opsForValue().set(current.key(), conflictingJson); + ApplyResult conflictResult = store.refreshCurrent(fixture.accountUuid(), fixture.tenantUuid()); + assertThat(conflictResult.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(conflictResult.detail()).contains("SAME_CHECKPOINT_DISAGREEMENT"); + assertThat(adminTemplate.opsForValue().get(current.key())).isEqualTo(conflictingJson); + assertThat(sourceSqlState(fixture.account(), fixture.tenantUuid(), fixture.legacyTenantId())) + .isEqualTo(sourceBeforePoison); + } + + @org.junit.jupiter.api.Test + void coordinationPrincipalCannotReadOtherOwnersOrInvokeEval() { + AccountFixture account = accountFixture(); + UUID tenantUuid = UUID.randomUUID(); + importFreshTenantAssociation(tenantUuid); + enrollFreshNeverJoinedBaseline(account.accountUuid(), tenantUuid); + ProjectionSnapshot projection = + store(membershipSourceReader()) + .refreshCurrent(account.accountUuid(), tenantUuid) + .snapshot() + .orElseThrow(); + + String accountKey = "session:auth:generation:account:" + account.accountUuid(); + String tenantKey = "session:auth:generation:tenant:" + tenantUuid; + String gameSessionIssuerKey = + "session:game:auth:issuer-generation:v1:" + AccountServiceImpl.ACCOUNT_JWT_ISSUER; + adminTemplate.opsForValue().set(accountKey, "admin-only-account-marker"); + adminTemplate.opsForValue().set(tenantKey, "admin-only-tenant-marker"); + adminTemplate.opsForValue().set(gameSessionIssuerKey, "admin-only-game-session-marker"); + + assertThat(ownerTemplate.opsForValue().get(projection.key())).isEqualTo(projection.json()); + assertDeniedKeyRead(accountKey); + assertDeniedKeyRead(tenantKey); + assertDeniedKeyRead(gameSessionIssuerKey); + assertThatThrownBy( + () -> + ownerTemplate.execute( + (RedisCallback) + connection -> + connection + .scriptingCommands() + .eval( + "return 1".getBytes(StandardCharsets.UTF_8), + ReturnType.INTEGER, + 0))) + .satisfies(failure -> assertThat(exceptionMessageChain(failure)).contains("NOPERM")); + assertThat(adminTemplate.delete(List.of(accountKey, tenantKey, gameSessionIssuerKey))) + .isEqualTo(3L); + } + + private AccountMembershipSourceReader membershipSourceReader() { + return new AccountMembershipSourceReader( + membershipAuthorityEventProducer, authorityGenerationRepository, transactionManager); + } + + private RedisMembershipGenerationProjectionStore store(AccountMembershipSourceReader reader) { + RedisMembershipGenerationProjectionStore store = + new RedisMembershipGenerationProjectionStore( + reader, + new CoordinationEndpoint( + redis.getHost(), redis.getMappedPort(6379), "account_coord_app", COORD_PASSWORD), + new CacheRateLimitEndpoint("cache.invalid.test", 6380)); + store.init(); + stores.add(store); + return store; + } + + private AccountFixture accountFixture() { + String suffix = compactUuid(); + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES (?, ?, ?) RETURNING id", + "mgp-" + suffix, + "membership-projection-" + suffix + "@example.com", + "integration-proof-hash") + .fetchOne(0, Long.class)); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + initializeAccountAuthority(accountUuid); + return new AccountFixture(accountId, accountUuid); + } + + private void initializeAccountAuthority(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); + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + authorityGenerationRepository.initializeIssuerIfAbsent( + AccountServiceImpl.ACCOUNT_JWT_ISSUER)); + } + + private FreshTenantCreationEvidence importFreshTenantAssociation(UUID tenantUuid) { + UUID creationRequestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String targetNamespace = WORKLOAD_NAMESPACE; + String sourceGameTenantKey = "fresh-" + compactUuid(); + String requestDigest = + GameTenantCreationDigest.requestDigest( + targetNamespace, + creationRequestId, + sourceGameTenantKey, + "Fresh membership projection fixture", + null); + long sourceGameRowId = positiveRandomLong(); + String provenanceKind = "NEW_GAME_ROW"; + FreshTenantCreationEvidence evidence = + new FreshTenantCreationEvidence( + 1, + targetNamespace, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + targetNamespace, + creationRequestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> { + freshAssociationRepository.importVerified(evidence); + authorityGenerationRepository.initializeTenantIfAbsent(tenantUuid); + }); + return evidence; + } + + private void enrollFreshNeverJoinedBaseline(UUID accountUuid, UUID tenantUuid) { + new TransactionTemplate(transactionManager) + .execute( + status -> + membershipAuthorityEventProducer.readFreshNeverJoinedMembershipSnapshot( + accountUuid, tenantUuid)); + } + + private JoinFixture retainedJoinFixture() { + String suffix = compactUuid(); + long accountId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) " + + "VALUES (?, ?, ?) RETURNING id", + "mgp-" + suffix, + "membership-projection-" + suffix + "@example.com", + "integration-proof-hash") + .fetchOne(0, Long.class)); + UUID accountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", accountId) + .fetchOne(0, UUID.class)); + initializeAccountAuthority(accountUuid); + + long legacyTenantId = positiveRandomLong(); + seedRetainedV26TenantEvidence(legacyTenantId, suffix); + dsl.execute( + "INSERT INTO subscription " + + "(account_id, tenant_id, plan_id, status, entitlement_version) " + + "VALUES (?, ?, 'membership-projection-proof', 'active', 1)", + accountId, + legacyTenantId); + UUID tenantUuid = UUID.randomUUID(); + tenantAssociationRepository.importApproved( + legacyTenantId, + approvedTenantAssociation( + legacyTenantId, tenantUuid, legacyTenantSourceEvidence.digest(legacyTenantId), suffix)); + + GameplayRealm realm = + GameplayRealm.newBuilder() + .setTenantId(Long.toString(legacyTenantId)) + .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(legacyTenantId)) + .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(legacyTenantId, WORLD_SLUG, REALM_SLUG)) + .thenReturn(pointer); + + String requestId = "membership-projection-join-" + suffix; + DirectTextCallerContext caller = + new DirectTextCallerContext( + accountId, + legacyTenantId, + REALM_ID, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "membership-projection-session-" + suffix, + requestId); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + legacyTenantId, + 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( + new AccountFixture(accountId, accountUuid), + accountId, + accountUuid, + legacyTenantId, + tenantUuid, + requestId, + caller, + scope); + } + + private JoinFixture nextJoinAttempt(JoinFixture original, String requestPrefix) { + String requestId = requestPrefix + compactUuid(); + DirectTextCallerContext caller = + new DirectTextCallerContext( + original.accountId(), + original.legacyTenantId(), + REALM_ID, + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "membership-projection-session-" + compactUuid(), + requestId); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + original.legacyTenantId(), + 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( + original.account(), + original.accountId(), + original.accountUuid(), + original.legacyTenantId(), + original.tenantUuid(), + requestId, + caller, + scope); + } + + private JoinPublicProductionResult join(JoinFixture fixture) { + return accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.scope().connectScopeId(), fixture.requestId())); + } + + 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, + "membership-projection-donor-" + suffix + "@example.com", + "integration-proof-hash", + tenantId) + .fetchOne(0, Long.class)); + UUID donorAccountUuid = + Objects.requireNonNull( + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", donorAccountId) + .fetchOne(0, UUID.class)); + initializeAccountAuthority(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 ResolveLegacyAccountTenantAssociationResponse approvedTenantAssociation( + long legacyTenantId, UUID tenantUuid, String evidenceDigest, String suffix) { + String sourceLegacyGameTenantId = "legacy-game-" + suffix.substring(0, 16); + 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-membership-projection-proof") + .setSignedAt("2026-09-26T00:00:00Z") + .setOperationEntryCount(1) + .setManifestSchemaVersion(1) + .build(); + } + + private void assertSourceAxes( + MembershipSourceSnapshot source, + String lifecycle, + boolean admitted, + long generation, + long sourceVersion, + String membershipVersion, + String sequence, + boolean eventExpected) { + UUID tenantUuid = source.tenantId(); + String streamKey = membershipStreamKey(source.accountId(), tenantUuid); + assertThat(source.sourceState().scope()) + .isEqualTo(AuthorityScope.membership(source.accountId(), tenantUuid)); + assertThat(source.sourceState().generation()).isEqualTo(generation); + assertThat(source.sourceState().sourceVersion()).isEqualTo(sourceVersion); + assertThat(source.sourceState().issuanceFence()).isNotNull(); + assertThat(source.sourceState().issuanceFence().accountId()).isEqualTo(source.accountId()); + assertThat(source.snapshot().accountUuid()).isEqualTo(source.accountId().toString()); + assertThat(source.snapshot().tenantUuid()).isEqualTo(tenantUuid.toString()); + assertThat(source.snapshot().requestAccountUuid()).isEqualTo(source.accountId().toString()); + assertThat(source.snapshot().requestTenantUuid()).isEqualTo(tenantUuid.toString()); + assertThat(source.snapshot().membershipExists()).isEqualTo(eventExpected); + assertThat(source.snapshot().gameplayAdmissionAllowed()).isEqualTo(admitted); + assertThat(source.snapshot().membershipBaseline().membershipLifecycleState()) + .isEqualTo(lifecycle); + assertThat(source.snapshot().membershipBaseline().membershipAuthorityGeneration()) + .isEqualTo(Long.toString(generation)); + assertThat(source.snapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(tenantUuid.toString(), membershipVersion)); + List checkpoints = + source.snapshot().outboxCheckpoints().stream() + .filter(entry -> streamKey.equals(entry.outboxStreamKey())) + .toList(); + assertThat(checkpoints).hasSize(1); + assertThat(checkpoints.getFirst().outboxSequence()).isEqualTo(sequence); + + MembershipEvent event = source.snapshot().sourceEvent(); + if (!eventExpected) { + assertThat(event).isNull(); + assertThat(source.snapshot().roles()).isEmpty(); + assertThat(sequence).isEqualTo("0"); + return; + } + + assertThat(event).isNotNull(); + assertThat(event.accountId()).isEqualTo(source.accountId().toString()); + assertThat(event.tenantId()).isEqualTo(tenantUuid.toString()); + assertThat(event.outboxStreamKey()).isEqualTo(streamKey); + assertThat(event.outboxSequence()).isEqualTo(sequence); + assertThat(event.membershipAuthorityGeneration()).isEqualTo(Long.toString(generation)); + assertThat(event.membershipVersion()) + .isEqualTo(Map.of(tenantUuid.toString(), membershipVersion)); + assertStoredEventExact(source, event); + } + + private void assertStoredEventExact(MembershipSourceSnapshot source, MembershipEvent event) { + Record row = + dsl.resultQuery( + "SELECT event_id, event_digest, encode(payload, 'hex') AS payload_hex " + + "FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = ?", + event.outboxStreamKey(), + Long.parseLong(event.outboxSequence())) + .fetchOne(); + assertThat(row).isNotNull(); + byte[] payload = HexFormat.of().parseHex(row.get("payload_hex", String.class)); + String payloadJson = new String(payload, StandardCharsets.UTF_8); + assertThat(event.eventId()).isEqualTo(row.get("event_id", String.class)); + assertThat(event.eventDigest()).isEqualTo(row.get("event_digest", String.class)); + assertThat(event.canonicalJson()).isEqualTo(payloadJson); + assertThat(event.canonicalJsonUtf8()).containsExactly(payload); + assertThat(MembershipAuthorityEventV1Codec.verify(payloadJson).eventDigest()) + .isEqualTo(event.eventDigest()); + assertThat(source.snapshot().outboxSourceEvidence()) + .anySatisfy( + evidence -> { + assertThat(evidence.outboxStreamKey()).isEqualTo(event.outboxStreamKey()); + assertThat(evidence.outboxSequence()).isEqualTo(event.outboxSequence()); + assertThat(evidence.eventId()).isEqualTo(event.eventId()); + assertThat(evidence.eventDigest()).isEqualTo(event.eventDigest()); + assertThat(evidence.canonicalEventJson()).isEqualTo(payloadJson); + }); + } + + private ProjectionSnapshot assertProjection( + ApplyResult result, + Outcome expectedOutcome, + UUID accountUuid, + UUID tenantUuid, + long generation, + long sourceVersion, + String membershipVersion, + String sequence, + String sourceEvent) { + assertThat(result.outcome()).isEqualTo(expectedOutcome); + ProjectionSnapshot projection = result.snapshot().orElseThrow(); + assertThat(projection.key()).isEqualTo(key(accountUuid, tenantUuid)); + assertRedisExactWithoutTtl(projection); + JsonNode json = parse(projection.json()); + assertThat(json.path("schemaVersion").asText()) + .isEqualTo("account-auth-membership-generation-projection/v1"); + assertThat(json.path("accountId").asText()).isEqualTo(accountUuid.toString()); + assertThat(json.path("tenantId").asText()).isEqualTo(tenantUuid.toString()); + assertThat(json.path("membershipAuthorityGeneration").asText()) + .isEqualTo(Long.toString(generation)); + assertThat(json.path("sourceVersion").asText()).isEqualTo(Long.toString(sourceVersion)); + assertThat(json.path("membershipVersion").size()).isEqualTo(1); + assertThat(json.path("membershipVersion").path(tenantUuid.toString()).asText()) + .isEqualTo(membershipVersion); + assertThat(json.path("outboxStreamKey").asText()) + .isEqualTo(membershipStreamKey(accountUuid, tenantUuid)); + assertThat(json.path("outboxSequence").asText()).isEqualTo(sequence); + if (sourceEvent == null) { + assertThat(json.has("sourceEvent")).isFalse(); + assertThat(fields(json)) + .containsExactlyInAnyOrder( + "schemaVersion", + "accountId", + "tenantId", + "membershipAuthorityGeneration", + "sourceVersion", + "membershipVersion", + "outboxStreamKey", + "outboxSequence"); + } else { + assertThat(json.path("sourceEvent").asText()).isEqualTo(sourceEvent); + assertThat(fields(json)) + .containsExactlyInAnyOrder( + "schemaVersion", + "accountId", + "tenantId", + "membershipAuthorityGeneration", + "sourceVersion", + "membershipVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent"); + MembershipEvent parsedEvent = + MembershipAuthorityEventV1Codec.verify(json.path("sourceEvent").asText()); + assertThat(parsedEvent.canonicalJson()).isEqualTo(sourceEvent); + assertThat(parsedEvent.outboxSequence()).isEqualTo(sequence); + assertThat(parsedEvent.membershipVersion()) + .isEqualTo(Map.of(tenantUuid.toString(), membershipVersion)); + assertThat(parsedEvent.membershipAuthorityGeneration()).isEqualTo(Long.toString(generation)); + } + return projection; + } + + private void assertRedisExactWithoutTtl(ProjectionSnapshot projection) { + assertThat(adminTemplate.opsForValue().get(projection.key())).isEqualTo(projection.json()); + assertThat(adminTemplate.getExpire(projection.key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + + private String sameCheckpointPoison(ProjectionSnapshot projection) throws Exception { + JsonNode current = parse(projection.json()); + String eventJson = current.path("sourceEvent").asText(); + Map eventPreimage = + JSON.readValue(eventJson, new TypeReference>() {}); + eventPreimage.remove("eventDigest"); + eventPreimage.put("issuanceFence", "999"); + String poisonedEvent = MembershipAuthorityEventV1Codec.seal(eventPreimage).canonicalJson(); + ObjectNode poisonedProjection = (ObjectNode) parse(projection.json()); + poisonedProjection.put("sourceEvent", poisonedEvent); + String poisonedJson = writeJson(poisonedProjection); + assertThat(MembershipGenerationProjection.parse(poisonedJson).toJson()).isEqualTo(poisonedJson); + return poisonedJson; + } + + private SourceSqlState sourceSqlState( + AccountFixture account, UUID tenantUuid, Long legacyTenantId) { + UUID accountUuid = account.accountUuid(); + long accountId = account.accountId(); + String membershipStream = membershipStreamKey(accountUuid, tenantUuid); + List sourceStreamKeys = + List.of( + membershipStream, + AUTHORITY_STREAM_PREFIX + "account/" + accountUuid, + AUTHORITY_STREAM_PREFIX + "tenant/" + tenantUuid, + AUTHORITY_STREAM_PREFIX + "issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER); + List> membershipRows = + legacyTenantId == null + ? queryRows( + "SELECT xmin::text AS row_xmin, * FROM account_tenant_membership " + + "WHERE account_id = ? ORDER BY id", + accountId) + : queryRows( + "SELECT xmin::text AS row_xmin, * FROM account_tenant_membership " + + "WHERE account_id = ? AND tenant_id = ? ORDER BY id", + accountId, + legacyTenantId); + List> receipts = + legacyTenantId == null + ? queryRows( + "SELECT xmin::text AS row_xmin, * FROM account_membership_transition_receipts " + + "WHERE account_id = ? ORDER BY tenant_id, receipt_sequence", + accountId) + : queryRows( + "SELECT xmin::text AS row_xmin, * FROM account_membership_transition_receipts " + + "WHERE account_id = ? AND tenant_id = ? ORDER BY receipt_sequence", + accountId, + legacyTenantId); + List> receiptHeads = + legacyTenantId == null + ? queryRows( + "SELECT xmin::text AS row_xmin, * " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? ORDER BY tenant_id", + accountId) + : queryRows( + "SELECT xmin::text AS row_xmin, * " + + "FROM account_membership_transition_receipt_stream_heads " + + "WHERE account_id = ? AND tenant_id = ?", + accountId, + legacyTenantId); + List> roleSnapshots = + legacyTenantId == null + ? queryRows( + "SELECT s.xmin::text AS row_xmin, s.membership_id, s.snapshot_version " + + "FROM account_tenant_membership_role_snapshots s " + + "JOIN account_tenant_membership m ON m.id = s.membership_id " + + "WHERE m.account_id = ? ORDER BY s.membership_id", + accountId) + : queryRows( + "SELECT s.xmin::text AS row_xmin, s.membership_id, s.snapshot_version " + + "FROM account_tenant_membership_role_snapshots s " + + "JOIN account_tenant_membership m ON m.id = s.membership_id " + + "WHERE m.account_id = ? AND m.tenant_id = ? ORDER BY s.membership_id", + accountId, + legacyTenantId); + List> roleIdentifiers = + legacyTenantId == null + ? queryRows( + "SELECT r.xmin::text AS row_xmin, r.membership_id, r.snapshot_version, " + + "r.role_identifier FROM account_tenant_membership_role_snapshot_roles r " + + "JOIN account_tenant_membership m ON m.id = r.membership_id " + + "WHERE m.account_id = ? ORDER BY r.membership_id, r.role_identifier", + accountId) + : queryRows( + "SELECT r.xmin::text AS row_xmin, r.membership_id, r.snapshot_version, " + + "r.role_identifier FROM account_tenant_membership_role_snapshot_roles r " + + "JOIN account_tenant_membership m ON m.id = r.membership_id " + + "WHERE m.account_id = ? AND m.tenant_id = ? " + + "ORDER BY r.membership_id, r.role_identifier", + accountId, + legacyTenantId); + List> auditRows = + legacyTenantId == null + ? List.of() + : queryRows( + "SELECT xmin::text AS row_xmin, * FROM account_audit_outbox " + + "WHERE scope = 'tenant' AND tenant_id = ? ORDER BY audit_event_id", + legacyTenantId); + + return new SourceSqlState( + queryRow( + "SELECT xmin::text AS row_xmin, id, account_uuid FROM accounts WHERE id = ?", + accountId), + queryRow( + "SELECT xmin::text AS row_xmin, * FROM account_authority_issuance_fences " + + "WHERE account_uuid = ?", + accountUuid), + queryRows( + "SELECT xmin::text AS row_xmin, * FROM account_authority_generations " + + "WHERE (scope_kind = 'ACCOUNT' AND account_uuid = ?) " + + "OR (scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ?) " + + "OR (scope_kind = 'TENANT' AND tenant_uuid = ?) " + + "OR (scope_kind = 'ISSUER' AND issuer_id = ?) ORDER BY scope_kind, tenant_uuid", + accountUuid, + accountUuid, + tenantUuid, + tenantUuid, + AccountServiceImpl.ACCOUNT_JWT_ISSUER), + queryRow( + "SELECT xmin::text AS row_xmin, * FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + accountUuid, + tenantUuid), + queryRows( + "SELECT xmin::text AS row_xmin, * FROM account_fresh_tenant_identity_associations " + + "WHERE canonical_tenant_id = ?", + tenantUuid), + queryRows( + "SELECT xmin::text AS row_xmin, * FROM account_canonical_tenant_identity_claims " + + "WHERE canonical_tenant_id = ?", + tenantUuid), + legacyTenantId == null + ? List.of() + : queryRows( + "SELECT xmin::text AS row_xmin, * " + + "FROM account_approved_legacy_tenant_associations " + + "WHERE legacy_tenant_id = ?", + legacyTenantId), + membershipRows, + roleSnapshots, + roleIdentifiers, + receipts, + receiptHeads, + queryRows( + "SELECT xmin::text AS row_xmin, * FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key IN (?, ?, ?, ?) ORDER BY outbox_stream_key", + sourceStreamKeys.toArray()), + queryRows( + "SELECT xmin::text AS row_xmin, outbox_stream_key, request_id, outbox_sequence, " + + "event_id, event_digest, encode(payload, 'hex') AS payload_hex " + + "FROM account_authority_outbox_events WHERE outbox_stream_key IN (?, ?, ?, ?) " + + "ORDER BY outbox_stream_key, outbox_sequence", + sourceStreamKeys.toArray()), + auditRows); + } + + private Map queryRow(String sql, Object... bindings) { + Record row = dsl.resultQuery(sql, bindings).fetchOne(); + return row == null ? Map.of() : stableMap(row); + } + + private List> queryRows(String sql, Object... bindings) { + return dsl.resultQuery(sql, bindings).fetch(this::stableMap); + } + + private Map stableMap(Record row) { + Map values = new LinkedHashMap<>(); + for (Field field : row.fields()) { + Object value = row.get(field); + values.put( + field.getName(), value instanceof byte[] bytes ? HexFormat.of().formatHex(bytes) : value); + } + return Collections.unmodifiableMap(values); + } + + private void assertDeniedKeyRead(String key) { + assertThatThrownBy(() -> ownerTemplate.opsForValue().get(key)) + .satisfies(failure -> assertThat(exceptionMessageChain(failure)).contains("NOPERM")); + } + + private String exceptionMessageChain(Throwable failure) { + StringBuilder messages = new StringBuilder(); + Throwable current = failure; + while (current != null) { + if (current.getMessage() != 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("Timed out waiting for membership projection race latch"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Membership projection race was interrupted", interrupted); + } + } + + private JsonNode parse(String json) { + try { + return JSON.readTree(json); + } catch (Exception malformed) { + throw new IllegalArgumentException("Projection JSON is malformed", malformed); + } + } + + private String writeJson(JsonNode json) { + try { + return JSON.writeValueAsString(json); + } catch (Exception malformed) { + throw new IllegalArgumentException("Projection JSON cannot be serialized", malformed); + } + } + + private Set fields(JsonNode json) { + Set names = new java.util.HashSet<>(); + json.fieldNames().forEachRemaining(names::add); + return names; + } + + private String key(UUID accountUuid, UUID tenantUuid) { + return MEMBERSHIP_KEY_PREFIX + accountUuid + ":" + tenantUuid; + } + + private String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { + return AUTHORITY_STREAM_PREFIX + "membership/" + accountUuid + "/" + tenantUuid; + } + + private String compactUuid() { + return UUID.randomUUID().toString().replace("-", "").substring(0, 20); + } + + private long positiveRandomLong() { + long candidate = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return candidate == 0L ? 1L : candidate; + } + + private record AccountFixture(long accountId, UUID accountUuid) {} + + private record JoinFixture( + AccountFixture account, + long accountId, + UUID accountUuid, + long legacyTenantId, + UUID tenantUuid, + String requestId, + DirectTextCallerContext caller, + DirectTextJoinScope scope) {} + + private record SourceSqlState( + Map accountRow, + Map issuanceFence, + List> generationRows, + Map pairAuthority, + List> freshTenantAssociations, + List> freshTenantClaims, + List> retainedTenantAssociations, + List> memberships, + List> roleSnapshots, + List> roleIdentifiers, + List> transitionReceipts, + List> transitionReceiptHeads, + List> authorityStreams, + List> membershipEvents, + List> auditRows) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantGenerationProjectionPostgresRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantGenerationProjectionPostgresRedisIntegrationTest.java new file mode 100644 index 0000000000..8be04fa68a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantGenerationProjectionPostgresRedisIntegrationTest.java @@ -0,0 +1,793 @@ +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.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.nio.charset.StandardCharsets; +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.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +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.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountTenantAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.RedisTenantGenerationProjectionStore; +import net.firedevops.firemud.accountservice.service.RedisTenantGenerationProjectionStore.ApplyResult; +import net.firedevops.firemud.accountservice.service.RedisTenantGenerationProjectionStore.CacheRateLimitEndpoint; +import net.firedevops.firemud.accountservice.service.RedisTenantGenerationProjectionStore.CoordinationEndpoint; +import net.firedevops.firemud.accountservice.service.RedisTenantGenerationProjectionStore.Outcome; +import net.firedevops.firemud.accountservice.service.RedisTenantGenerationProjectionStore.ProjectionSnapshot; +import net.firedevops.firemud.accountservice.service.TenantGenerationProjection; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec; +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.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 tenant-generation projection proof over real SQL and isolated Coordination Redis. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class TenantGenerationProjectionPostgresRedisIntegrationTest { + private static final String SCHEMA_PREFIX = "tenant_gen_projection"; + private static final String TEST_NAMESPACE = "account-service"; + private static final String REQUEST_DIGEST = "sha256:" + "a".repeat(64); + private static final String KEY_PREFIX = "session:auth:generation:tenant:"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:tenant/"; + private static final String EVENT_ID_PREFIX = "account-tenant-generation-event-v1:"; + private static final String COORD_PASSWORD = "tenant-generation-projection-integration-secret"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final AtomicLong SOURCE_GAME_ROW_SEQUENCE = new AtomicLong(730L); + + @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(RedisTenantGenerationProjectionStore::close); + stores.clear(); + if (adminConnectionFactory != null) { + adminConnectionFactory.destroy(); + } + if (ownerConnectionFactory != null) { + ownerConnectionFactory.destroy(); + } + } + + @Test + void installsOnlyTheProvenPristineTenantBaselineAndReadsBackExactBytes() { + Fixture fixture = newFixture(); + UUID tenantId = UUID.randomUUID(); + seed(fixture, tenantId); + AccountTenantAuthorityEventProducer producer = fixture.producer(); + AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot baseline = + producer.readCurrent(tenantId); + + assertThat(baseline.tenantAuthorityGeneration()).isEqualTo(1L); + assertThat(baseline.sourceVersion()).isEqualTo(1L); + assertThat(baseline.outboxSequence()).isZero(); + assertThat(baseline.latestEvent()).isEmpty(); + SqlState before = sqlState(fixture, tenantId); + ApplyResult result = store(producer).refreshCurrent(tenantId); + + assertThat(result.outcome()).isEqualTo(Outcome.APPLIED); + ProjectionSnapshot projection = result.snapshot().orElseThrow(); + assertThat(projection.key()).isEqualTo(key(tenantId)); + JsonNode json = parse(projection.json()); + assertThat(json.path("schemaVersion").asText()) + .isEqualTo("account-auth-tenant-generation-projection/v1"); + assertThat(json.path("tenantId").asText()).isEqualTo(tenantId.toString()); + assertThat(json.path("tenantAuthorityGeneration").asText()).isEqualTo("1"); + assertThat(json.path("sourceVersion").asText()).isEqualTo("1"); + assertThat(json.path("outboxStreamKey").asText()).isEqualTo(streamKey(tenantId)); + assertThat(json.path("outboxSequence").asText()).isEqualTo("0"); + assertThat(json.has("sourceEvent")).isFalse(); + assertThat(fields(json)) + .containsExactlyInAnyOrder( + "schemaVersion", + "tenantId", + "tenantAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence"); + assertThat(adminTemplate.opsForValue().get(projection.key())).isEqualTo(projection.json()); + assertThat(adminTemplate.getExpire(projection.key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + assertThat(sqlState(fixture, tenantId)).isEqualTo(before); + } + + @Test + void projectsCompleteSourceEventReplaysExactlyAndRepairsOnlyTheMissingRedisKey() { + Fixture fixture = newFixture(); + UUID tenantId = UUID.randomUUID(); + seed(fixture, tenantId); + AccountTenantAuthorityEventProducer producer = fixture.producer(); + RedisTenantGenerationProjectionStore store = store(producer); + store.refreshCurrent(tenantId); + ScopeState accountAuthorityBeforeAdvance = + readAuthority(fixture, AuthorityScope.account(fixture.accountUuid())); + AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot baseline = + producer.readCurrent(tenantId); + + UUID requestId = UUID.randomUUID(); + var event = producer.advance(tenantId, requestId, 1L, 1L); + var exactRetry = producer.advance(tenantId, requestId, 1L, 1L); + assertSameEvent(event, exactRetry); + SqlState afterSourceAdvance = sqlState(fixture, tenantId); + + ApplyResult projected = store.refreshCurrent(tenantId); + assertThat(projected.outcome()).isEqualTo(Outcome.APPLIED); + ProjectionSnapshot installed = projected.snapshot().orElseThrow(); + JsonNode json = parse(installed.json()); + assertThat(json.path("tenantAuthorityGeneration").asText()).isEqualTo("2"); + assertThat(json.path("sourceVersion").asText()).isEqualTo("2"); + assertThat(json.path("outboxStreamKey").asText()).isEqualTo(baseline.outboxStreamKey()); + assertThat(json.path("outboxSequence").asText()).isEqualTo("1"); + assertThat(json.path("sourceEvent").asText()).isEqualTo(event.canonicalJson()); + assertThat(fields(json)) + .containsExactlyInAnyOrder( + "schemaVersion", + "tenantId", + "tenantAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent"); + assertThat( + TenantGenerationAuthorityEventV1Codec.verify(json.path("sourceEvent").asText()) + .canonicalJson()) + .isEqualTo(event.canonicalJson()); + assertThat(adminTemplate.opsForValue().get(installed.key())).isEqualTo(installed.json()); + assertThat(adminTemplate.getExpire(installed.key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + assertThat(event.canonicalJson()) + .doesNotContain("recipientAccount", "membership", "issuanceFence", "billing"); + assertThat(afterSourceAdvance.accountAuthority()).isEqualTo(accountAuthorityBeforeAdvance); + assertThat(sqlState(fixture, tenantId)).isEqualTo(afterSourceAdvance); + + ApplyResult replay = store.refreshCurrent(tenantId); + assertThat(replay.outcome()).isEqualTo(Outcome.REPLAYED); + assertThat(replay.snapshot()).contains(installed); + assertThat(sqlState(fixture, tenantId)).isEqualTo(afterSourceAdvance); + + assertThat(adminTemplate.delete(installed.key())).isTrue(); + ApplyResult repaired = store.refreshCurrent(tenantId); + assertThat(repaired.outcome()).isEqualTo(Outcome.APPLIED); + assertThat(repaired.snapshot()).contains(installed); + assertThat(adminTemplate.opsForValue().get(installed.key())).isEqualTo(installed.json()); + assertThat(sqlState(fixture, tenantId)).isEqualTo(afterSourceAdvance); + } + + @Test + void unknownAndAssociatedButUnenrolledTenantsCannotSynthesizeABaseline() { + Fixture fixture = newFixture(); + UUID enrolledTenant = UUID.randomUUID(); + UUID unknownTenant = UUID.randomUUID(); + UUID associatedUnenrolledTenant = UUID.randomUUID(); + seed(fixture, enrolledTenant); + importAssociationOnly(fixture, associatedUnenrolledTenant); + RedisTenantGenerationProjectionStore store = store(fixture.producer()); + + assertThatThrownBy(() -> store.refreshCurrent(unknownTenant)) + .isInstanceOf(IllegalStateException.class); + assertThat(adminTemplate.opsForValue().get(key(unknownTenant))).isNull(); + assertThatThrownBy(() -> store.refreshCurrent(associatedUnenrolledTenant)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account authority generation is missing"); + assertThat(adminTemplate.opsForValue().get(key(associatedUnenrolledTenant))).isNull(); + assertThat(countTenantGenerations(fixture)).isEqualTo(1L); + assertThat(countTenantEvents(fixture)).isZero(); + assertThat(countTenantStreams(fixture)).isZero(); + assertThat(count(fixture, "account_fresh_tenant_identity_associations")).isEqualTo(2L); + } + + @Test + void sourceAdvanceAfterCandidateReadReturnsNonconvergedWithoutChangingSqlHistory() { + Fixture fixture = newFixture(); + UUID tenantId = UUID.randomUUID(); + seed(fixture, tenantId); + AccountTenantAuthorityEventProducer delegate = fixture.producer(); + UUID requestId = UUID.randomUUID(); + AtomicInteger reads = new AtomicInteger(); + AtomicReference sourceAfterAdvance = new AtomicReference<>(); + AccountTenantAuthorityEventProducer controlledProducer = + forwardingProducer( + delegate, + (id, current) -> { + if (reads.incrementAndGet() == 1) { + delegate.advance( + id, requestId, current.tenantAuthorityGeneration(), current.sourceVersion()); + sourceAfterAdvance.set(sqlState(fixture, id)); + } + }); + RedisTenantGenerationProjectionStore store = store(controlledProducer); + + ApplyResult result = store.refreshCurrent(tenantId); + + assertThat(result.outcome()).isEqualTo(Outcome.SOURCE_CHANGED); + assertThat(result.snapshot()).isPresent(); + JsonNode installed = parse(adminTemplate.opsForValue().get(key(tenantId))); + assertThat(installed.path("tenantAuthorityGeneration").asText()).isEqualTo("1"); + assertThat(installed.path("sourceVersion").asText()).isEqualTo("1"); + assertThat(installed.path("outboxSequence").asText()).isEqualTo("0"); + assertThat(delegate.readCurrent(tenantId).tenantAuthorityGeneration()).isEqualTo(2L); + assertThat(sourceAfterAdvance.get()).isNotNull(); + assertThat(sourceAfterAdvance.get().tenantEventHistory()).hasSize(1); + assertThat(sqlState(fixture, tenantId)).isEqualTo(sourceAfterAdvance.get()); + } + + @Test + void staleCandidateCannotReplaceAProjectionFromANewerTenantCommit() throws Exception { + Fixture fixture = newFixture(); + UUID tenantId = UUID.randomUUID(); + seed(fixture, tenantId); + AccountTenantAuthorityEventProducer delegate = fixture.producer(); + CountDownLatch staleReadReturned = new CountDownLatch(1); + CountDownLatch releaseStaleCandidate = new CountDownLatch(1); + AtomicInteger reads = new AtomicInteger(); + AccountTenantAuthorityEventProducer controlledProducer = + forwardingProducer( + delegate, + (id, current) -> { + if (reads.incrementAndGet() == 1) { + staleReadReturned.countDown(); + await(releaseStaleCandidate); + } + }); + RedisTenantGenerationProjectionStore staleStore = store(controlledProducer); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + var staleRefresh = executor.submit(() -> staleStore.refreshCurrent(tenantId)); + assertThat(staleReadReturned.await(20, TimeUnit.SECONDS)).isTrue(); + + delegate.advance(tenantId, UUID.randomUUID(), 1L, 1L); + ApplyResult current = store(delegate).refreshCurrent(tenantId); + assertThat(current.outcome()).isEqualTo(Outcome.APPLIED); + String newerBytes = current.snapshot().orElseThrow().json(); + assertThat(parse(newerBytes).path("outboxSequence").asText()).isEqualTo("1"); + SqlState sourceBeforeStaleFinish = sqlState(fixture, tenantId); + + releaseStaleCandidate.countDown(); + ApplyResult staleResult = staleRefresh.get(45, TimeUnit.SECONDS); + assertThat(staleResult.outcome()).isIn(Outcome.STALE, Outcome.STALE_SOURCE); + assertThat(staleResult.outcome()).isNotIn(Outcome.APPLIED, Outcome.REPLAYED); + assertThat(adminTemplate.opsForValue().get(key(tenantId))).isEqualTo(newerBytes); + assertThat(sqlState(fixture, tenantId)).isEqualTo(sourceBeforeStaleFinish); + } finally { + releaseStaleCandidate.countDown(); + executor.shutdownNow(); + } + } + + @Test + void malformedExpiringAheadAndSameCheckpointRedisValuesAreQuarantinedWithoutWrites() { + Fixture fixture = newFixture(); + UUID tenantId = UUID.randomUUID(); + seed(fixture, tenantId); + AccountTenantAuthorityEventProducer producer = fixture.producer(); + RedisTenantGenerationProjectionStore store = store(producer); + store.refreshCurrent(tenantId); + var sourceEvent = producer.advance(tenantId, UUID.randomUUID(), 1L, 1L); + ProjectionSnapshot current = store.refreshCurrent(tenantId).snapshot().orElseThrow(); + SqlState sourceBeforePoison = sqlState(fixture, tenantId); + + adminTemplate.opsForValue().set(current.key(), "{\"schemaVersion\":\"unknown\"}"); + String malformed = adminTemplate.opsForValue().get(current.key()); + ApplyResult malformedResult = store.refreshCurrent(tenantId); + assertThat(malformedResult.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(adminTemplate.opsForValue().get(current.key())).isEqualTo(malformed); + + adminTemplate.opsForValue().set(current.key(), current.json()); + adminTemplate.expire(current.key(), 30L, TimeUnit.SECONDS); + Long ttlBefore = adminTemplate.getExpire(current.key(), TimeUnit.MILLISECONDS); + ApplyResult ttlResult = store.refreshCurrent(tenantId); + assertThat(ttlResult.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(adminTemplate.opsForValue().get(current.key())).isEqualTo(current.json()); + assertThat(adminTemplate.getExpire(current.key(), TimeUnit.MILLISECONDS)) + .isPositive() + .isLessThanOrEqualTo(ttlBefore); + + adminTemplate.persist(current.key()); + TenantGenerationProjection ahead = + syntheticProjection(tenantId, 999L, 999L, 998L, UUID.randomUUID()); + TenantGenerationProjection.parse(ahead.toJson()); + adminTemplate.opsForValue().set(current.key(), ahead.toJson()); + ApplyResult aheadResult = store.refreshCurrent(tenantId); + assertThat(aheadResult.outcome()).isEqualTo(Outcome.STALE_SOURCE); + assertThat(adminTemplate.opsForValue().get(current.key())).isEqualTo(ahead.toJson()); + + TenantGenerationProjection conflicting = + syntheticProjection(tenantId, 2L, 2L, 1L, UUID.randomUUID()); + TenantGenerationProjection.parse(conflicting.toJson()); + adminTemplate.opsForValue().set(current.key(), conflicting.toJson()); + ApplyResult conflictResult = store.refreshCurrent(tenantId); + assertThat(conflictResult.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(conflictResult.detail()).contains("SAME_CHECKPOINT_DISAGREEMENT"); + assertThat(adminTemplate.opsForValue().get(current.key())).isEqualTo(conflicting.toJson()); + assertThat(sqlState(fixture, tenantId)).isEqualTo(sourceBeforePoison); + assertThat(sourceEvent.canonicalJson()) + .isEqualTo(producer.readCurrent(tenantId).latestEvent().orElseThrow().canonicalJson()); + } + + @Test + void accountCoordinationPrincipalCanUseOnlyTenantProjectionKeysAndCannotInvokeEval() { + Fixture fixture = newFixture(); + UUID tenantId = UUID.randomUUID(); + seed(fixture, tenantId); + store(fixture.producer()).refreshCurrent(tenantId); + + assertThatThrownBy( + () -> + ownerTemplate.execute( + (RedisCallback) + connection -> + connection + .scriptingCommands() + .eval( + "return 1".getBytes(StandardCharsets.UTF_8), + ReturnType.INTEGER, + 0))) + .satisfies(failure -> assertThat(exceptionMessageChain(failure)).contains("NOPERM")); + assertThatThrownBy( + () -> + ownerTemplate + .opsForValue() + .get("session:auth:generation:account:" + UUID.randomUUID())) + .satisfies(failure -> assertThat(exceptionMessageChain(failure)).contains("NOPERM")); + assertThat(ownerTemplate.opsForValue().get(key(tenantId))).isNotNull(); + } + + 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(); + 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 source fixture UUID was not persisted"); + } + + 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, + account.get("account_uuid", UUID.class)); + } + + private void seed(Fixture fixture, UUID tenantId) { + FreshTenantCreationEvidence association = tenantEvidence(tenantId); + transaction( + fixture.transaction(), + () -> { + fixture.associations().importVerified(association); + fixture.generations().initializeTenantIfAbsent(tenantId); + fixture.generations().initialize(AuthorityScope.account(fixture.accountUuid())); + return null; + }); + } + + private void importAssociationOnly(Fixture fixture, UUID tenantId) { + FreshTenantCreationEvidence association = tenantEvidence(tenantId); + transaction( + fixture.transaction(), + () -> { + fixture.associations().importVerified(association); + return null; + }); + } + + private FreshTenantCreationEvidence tenantEvidence(UUID tenantId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceGameTenantKey = "tn-" + UUID.randomUUID().toString().replace("-", ""); + long sourceGameRowId = SOURCE_GAME_ROW_SEQUENCE.incrementAndGet(); + 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 RedisTenantGenerationProjectionStore store(AccountTenantAuthorityEventProducer producer) { + RedisTenantGenerationProjectionStore store = + new RedisTenantGenerationProjectionStore( + producer, + new CoordinationEndpoint( + redis.getHost(), redis.getMappedPort(6379), "account_coord_app", COORD_PASSWORD), + new CacheRateLimitEndpoint("cache.invalid.test", 6380)); + store.init(); + stores.add(store); + return store; + } + + private AccountTenantAuthorityEventProducer forwardingProducer( + AccountTenantAuthorityEventProducer delegate, SourceReadHook hook) { + AccountTenantAuthorityEventProducer forwarding = + mock(AccountTenantAuthorityEventProducer.class); + when(forwarding.readCurrent(any(UUID.class))) + .thenAnswer( + invocation -> { + UUID tenantId = invocation.getArgument(0); + var current = delegate.readCurrent(tenantId); + hook.afterRead(tenantId, current); + return current; + }); + return forwarding; + } + + private TenantGenerationProjection syntheticProjection( + UUID tenantId, long generation, long sourceVersion, long sequence, UUID requestId) { + String tenantText = tenantId.toString(); + String tenantScope = "tenant/" + tenantText; + String projectionStreamKey = streamKey(tenantId); + var event = + TenantGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + TenantGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + EVENT_ID_PREFIX + requestId, + "requestId", + requestId.toString(), + "tenantId", + tenantText, + "sourceScope", + tenantScope, + "outboxStreamKey", + projectionStreamKey, + "outboxSequence", + Long.toString(sequence), + "tenantAuthorityGeneration", + Long.toString(generation), + "sourceVersion", + Long.toString(sourceVersion))); + return new TenantGenerationProjection( + tenantText, + Long.toString(generation), + Long.toString(sourceVersion), + projectionStreamKey, + Long.toString(sequence), + Optional.of(event.canonicalJson())); + } + + private SqlState sqlState(Fixture fixture, UUID tenantId) { + ScopeState tenantState = readAuthority(fixture, AuthorityScope.tenant(tenantId)); + ScopeState accountState = readAuthority(fixture, AuthorityScope.account(fixture.accountUuid())); + return new SqlState( + tenantState, + accountState, + rows(fixture, tenantId), + tenantEventHistory(fixture, tenantId), + countTenantStreams(fixture)); + } + + private List tenantEventHistory(Fixture fixture, UUID tenantId) { + String stream = streamKey(tenantId); + return fixture + .setupDsl() + .resultQuery( + "SELECT outbox_stream_key, request_id, outbox_sequence, event_id, event_digest, payload " + + "FROM account_authority_outbox_events WHERE outbox_stream_key = ? ORDER BY outbox_sequence", + stream) + .fetch( + row -> + new StoredRow( + row.get("outbox_stream_key", String.class), + row.get("request_id", String.class), + row.get("outbox_sequence", Long.class), + row.get("event_id", String.class), + row.get("event_digest", String.class), + HexFormat.of().formatHex(row.get("payload", byte[].class)))); + } + + private SourceRows rows(Fixture fixture, UUID tenantId) { + return new SourceRows( + countWhere( + fixture, "account_fresh_tenant_identity_associations", "canonical_tenant_id", tenantId), + countWhere( + fixture, "account_canonical_tenant_identity_claims", "canonical_tenant_id", tenantId), + countWhere(fixture, "account_authority_generations", "tenant_uuid", tenantId), + countWhere( + fixture, "account_authority_outbox_streams", "outbox_stream_key", streamKey(tenantId)), + countWhere(fixture, "account_membership_pair_authority", "tenant_uuid", tenantId), + count(fixture, "account_membership_transition_receipts")); + } + + private long countTenantGenerations(Fixture fixture) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_authority_generations WHERE scope_kind = 'TENANT'") + .fetchOne(0, Long.class), + "Tenant generation count is missing"); + } + + private long countTenantEvents(Fixture fixture) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key LIKE 'account:auth-authority:v1:tenant/%'") + .fetchOne(0, Long.class), + "Tenant outbox event count 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 outbox stream count is missing"); + } + + private long countWhere(Fixture fixture, String table, String column, Object value) { + return Objects.requireNonNull( + fixture + .setupDsl() + .resultQuery("SELECT COUNT(*) FROM " + table + " WHERE " + column + " = ?", value) + .fetchOne(0, Long.class), + "SQL row count is missing for " + table); + } + + private long count(Fixture fixture, String table) { + return Objects.requireNonNull( + fixture.setupDsl().resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class), + "SQL row count is missing for " + table); + } + + private ScopeState readAuthority(Fixture fixture, AuthorityScope scope) { + return transaction(fixture.transaction(), () -> fixture.generations().read(scope)); + } + + private void assertSameEvent( + TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent expected, + TenantGenerationAuthorityEventV1Codec.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 JsonNode parse(String json) { + try { + return JSON.readTree(json); + } catch (Exception malformed) { + throw new IllegalArgumentException("Redis projection JSON is malformed", malformed); + } + } + + private Set fields(JsonNode json) { + Set fields = new HashSet<>(); + json.fieldNames().forEachRemaining(fields::add); + return fields; + } + + private String key(UUID tenantId) { + return KEY_PREFIX + tenantId; + } + + private String streamKey(UUID tenantId) { + return STREAM_PREFIX + tenantId; + } + + private String exceptionMessageChain(Throwable failure) { + StringBuilder messages = new StringBuilder(); + Throwable current = failure; + while (current != null) { + if (current.getMessage() != 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("Tenant projection race barrier timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Tenant projection race 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 new AccountTenantAuthorityEventProducer( + generations, outbox, transactionDsl, transactionManager); + } + } + + @FunctionalInterface + private interface SourceReadHook { + void afterRead( + UUID tenantId, AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot snapshot); + } + + private record SourceRows( + long freshAssociationRows, + long canonicalClaimRows, + long tenantGenerationRows, + long outboxStreamRows, + long membershipAuthorityRows, + long membershipReceiptRows) {} + + private record StoredRow( + String streamKey, + String requestId, + long sequence, + String eventId, + String eventDigest, + String payloadHex) {} + + private record SqlState( + ScopeState tenantAuthority, + ScopeState accountAuthority, + SourceRows rows, + List tenantEventHistory, + long tenantStreamCount) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index a71471b42b..351bd24b6f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -29,6 +29,7 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; import org.jooq.DSLContext; +import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; @@ -101,8 +102,25 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); AccountJoinOperationRepository joinOperations = new AccountJoinOperationRepository(transactionAwareDsl); + LegacyTenantSourceEvidence legacyTenantSourceEvidence = + new LegacyTenantSourceEvidence(transactionAwareDsl); + AccountAuthorityGenerationRepository authorityGenerationRepository = + new AccountAuthorityGenerationRepository(transactionAwareDsl); + ApprovedLegacyTenantAssociationRepository approvedTenantAssociations = + new ApprovedLegacyTenantAssociationRepository( + transactionAwareDsl, + legacyTenantSourceEvidence, + "account-service", + authorityGenerationRepository); + AccountTenantIdentityResolver tenantIdentityResolver = + new AccountTenantIdentityResolver( + approvedTenantAssociations, legacyTenantSourceEvidence, "account-service"); AccountTenantMembershipRepository memberships = - new AccountTenantMembershipRepository(transactionAwareDsl); + new AccountTenantMembershipRepository( + transactionAwareDsl, + new AccountRepository(transactionAwareDsl), + tenantIdentityResolver, + new FreshTenantIdentityAssociationRepository(transactionAwareDsl, "account-service")); AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(transactionAwareDsl); AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(transactionAwareDsl); long accountId = @@ -588,7 +606,21 @@ void expiredConnectScopeCleanupPreservesEveryReferencedStatusAndMalformedEvidenc JdbcTemplate jdbc = new JdbcTemplate(dataSource); AccountConnectScopeRepository scopes = new AccountConnectScopeRepository(dsl); AccountJoinOperationRepository joinOperations = new AccountJoinOperationRepository(dsl); - AccountTenantMembershipRepository memberships = new AccountTenantMembershipRepository(dsl); + LegacyTenantSourceEvidence sourceEvidence = new LegacyTenantSourceEvidence(dsl); + AccountAuthorityGenerationRepository authorityGenerations = + new AccountAuthorityGenerationRepository(dsl); + ApprovedLegacyTenantAssociationRepository approvedTenantAssociations = + new ApprovedLegacyTenantAssociationRepository( + dsl, sourceEvidence, "account-service", authorityGenerations); + AccountTenantIdentityResolver tenantIdentityResolver = + new AccountTenantIdentityResolver( + approvedTenantAssociations, sourceEvidence, "account-service"); + AccountTenantMembershipRepository memberships = + new AccountTenantMembershipRepository( + dsl, + new AccountRepository(dsl), + tenantIdentityResolver, + new FreshTenantIdentityAssociationRepository(dsl, "account-service")); long accountId = Objects.requireNonNull( jdbc.queryForObject( @@ -1379,18 +1411,41 @@ void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { .isEqualTo(profileBefore); assertThat( jsonRow( - "SELECT to_jsonb(m)::text FROM " + "SELECT (to_jsonb(m) - 'tenant_uuid' - 'tenant_provenance_kind' " + + "- 'tenant_source_operation_id' - 'tenant_provenance_digest')::text FROM " + schema + ".account_tenant_membership m WHERE account_id = ?", firstAccountId)) .isEqualTo(membershipBefore); assertThat( jsonRow( - "SELECT to_jsonb(m)::text FROM " + "SELECT (to_jsonb(m) - 'tenant_uuid' - 'tenant_provenance_kind' " + + "- 'tenant_source_operation_id' - 'tenant_provenance_digest')::text FROM " + schema + ".account_tenant_membership m WHERE account_id = ?", secondAccountId)) .isEqualTo(explicitMembershipBefore); + String membershipTenantIdentityQuery = + "SELECT tenant_uuid, tenant_provenance_kind, tenant_source_operation_id, " + + "tenant_provenance_digest FROM " + + schema + + ".account_tenant_membership WHERE account_id = ?"; + Record firstMembershipAfter = + Objects.requireNonNull( + dsl.resultQuery(membershipTenantIdentityQuery, firstAccountId).fetchOne()); + assertThat(firstMembershipAfter.get("tenant_uuid", UUID.class)).isNull(); + assertThat(firstMembershipAfter.get("tenant_provenance_kind", String.class)) + .isEqualTo("UNBRIDGED_RETAINED"); + assertThat(firstMembershipAfter.get("tenant_source_operation_id", UUID.class)).isNull(); + assertThat(firstMembershipAfter.get("tenant_provenance_digest", String.class)).isNull(); + Record secondMembershipAfter = + Objects.requireNonNull( + dsl.resultQuery(membershipTenantIdentityQuery, secondAccountId).fetchOne()); + assertThat(secondMembershipAfter.get("tenant_uuid", UUID.class)).isNull(); + assertThat(secondMembershipAfter.get("tenant_provenance_kind", String.class)) + .isEqualTo("UNBRIDGED_RETAINED"); + assertThat(secondMembershipAfter.get("tenant_source_operation_id", UUID.class)).isNull(); + assertThat(secondMembershipAfter.get("tenant_provenance_digest", String.class)).isNull(); assertThat( jsonRow( "SELECT " diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipCanonicalIdentityIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipCanonicalIdentityIntegrationTest.java new file mode 100644 index 0000000000..4fb5e7ab3d --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipCanonicalIdentityIntegrationTest.java @@ -0,0 +1,530 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.ApprovedLegacyTenantAssociationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.repository.LegacyTenantSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof of the shared numeric-history/canonical-UUID membership storage boundary. + * + *

Owner source rows are installed locally to isolate persistence behavior; this is not proof of + * authenticated remote evidence, JOIN authorization, or membership activation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountTenantMembershipCanonicalIdentityIntegrationTest { + private static final String TEST_NAMESPACE = "account-service"; + private static final long RETAINED_TENANT_ID = 700L; + private static final String RETAINED_MANIFEST_DIGEST = "sha256:" + "b".repeat(64); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void migrationPreservesRetainedMembershipAndCanonicalRowsUseExactUuidAndSourceEvidence() { + Fixture fixture = fixture(); + SeededRetainedMembership retained = seedRetainedMembership(fixture.setupDsl()); + assertPersistedRoleHistory(fixture.setupDsl(), retained.membershipId()); + String retainedDigest = + new LegacyTenantSourceEvidence(fixture.setupDsl()).digest(RETAINED_TENANT_ID); + UUID retainedTenantUuid = UUID.randomUUID(); + UUID retainedOperationId = UUID.randomUUID(); + insertApprovedRetainedAssociation( + fixture.setupDsl(), retainedTenantUuid, retainedOperationId, retainedDigest); + + flyway(fixture.dataSource(), fixture.schema(), "45").migrate(); + RepositoryFixture repositories = repositories(fixture); + assertPersistedRoleHistory(fixture.setupDsl(), retained.membershipId()); + String identityConstraint = + fixture + .setupDsl() + .resultQuery( + "SELECT pg_get_constraintdef(oid) FROM pg_constraint " + + "WHERE conname = 'account_tenant_membership_tenant_identity_check'") + .fetchOne(0, String.class); + assertThat(identityConstraint) + .contains( + "tenant_id IS NOT NULL", + "tenant_uuid IS NOT NULL", + "tenant_provenance_digest IS NOT NULL"); + + AccountTenantMembership beforeBinding = + repositories + .memberships() + .findByAccountIdAndTenantId(retained.accountId(), RETAINED_TENANT_ID) + .orElseThrow(); + assertThat(beforeBinding.getId()).isEqualTo(retained.membershipId()); + assertThat(beforeBinding.getTenantId()).isEqualTo(RETAINED_TENANT_ID); + assertThat(beforeBinding.getTenantUuid()).isNull(); + assertThat(beforeBinding.getTenantProvenanceKind()).isEqualTo("UNBRIDGED_RETAINED"); + assertThat(beforeBinding.getLifecycleState()).isEqualTo("LEGACY_UNVERIFIED"); + assertThat(beforeBinding.getMembershipVersion()).isEqualTo(1L); + assertThat(beforeBinding.getMembershipAuthorityGeneration()).isEqualTo(1L); + assertThat(beforeBinding.getAuthorityProvenance()).isEqualTo("LEGACY_UNVERIFIED"); + assertThat(beforeBinding.isGameplayAdmissionAllowed()).isFalse(); + var retainedNumericRoleHistory = + fixture + .transaction() + .execute( + status -> + repositories + .roles() + .findForUpdate( + retained.accountId(), RETAINED_TENANT_ID, retained.membershipId(), 1L)) + .orElseThrow(); + assertThat(retainedNumericRoleHistory.tenantId()).isEqualTo(RETAINED_TENANT_ID); + assertThat(retainedNumericRoleHistory.tenantUuid()).isNull(); + assertThat(retainedNumericRoleHistory.roles()).containsExactly("legacy_observer"); + + VerifiedTenantProvenance retainedProvenance = + new VerifiedTenantProvenance( + RETAINED_TENANT_ID, + TenantProvenanceKind.APPROVED_RETAINED, + retainedOperationId, + RETAINED_MANIFEST_DIGEST); + AccountTenantMembership retainedReadback = + fixture + .transaction() + .execute( + status -> + repositories + .memberships() + .saveCanonical( + beforeBinding, + retained.accountUuid(), + retainedTenantUuid, + retainedProvenance)); + assertPersistedRoleHistory(fixture.setupDsl(), retained.membershipId()); + assertThat(retainedReadback).isNotNull(); + assertThat(retainedReadback.getId()).isEqualTo(retained.membershipId()); + assertThat(retainedReadback.getTenantId()).isEqualTo(RETAINED_TENANT_ID); + assertThat(retainedReadback.getTenantUuid()).isEqualTo(retainedTenantUuid); + assertThat(retainedReadback.getTenantProvenanceKind()).isEqualTo("APPROVED_RETAINED"); + assertThat(retainedReadback.getTenantSourceOperationId()).isEqualTo(retainedOperationId); + assertThat(retainedReadback.getTenantProvenanceDigest()).isEqualTo(RETAINED_MANIFEST_DIGEST); + assertThat(retainedReadback.getLifecycleState()).isEqualTo("LEGACY_UNVERIFIED"); + assertThat(retainedReadback.getMembershipVersion()).isEqualTo(1L); + assertThat(retainedReadback.getMembershipAuthorityGeneration()).isEqualTo(1L); + assertThat(retainedReadback.getAuthorityProvenance()).isEqualTo("LEGACY_UNVERIFIED"); + assertThat(retainedReadback.isGameplayAdmissionAllowed()).isFalse(); + + AccountTenantMembership retainedBaseSelectReadback = + repositories + .memberships() + .findByAccountIdAndTenantId(retained.accountId(), RETAINED_TENANT_ID) + .orElseThrow(); + assertThat(retainedBaseSelectReadback.getTenantUuid()).isEqualTo(retainedTenantUuid); + assertThat(retainedBaseSelectReadback.getTenantProvenanceKind()).isEqualTo("APPROVED_RETAINED"); + assertThat(retainedBaseSelectReadback.getTenantSourceOperationId()) + .isEqualTo(retainedOperationId); + assertThat(retainedBaseSelectReadback.getTenantProvenanceDigest()) + .isEqualTo(RETAINED_MANIFEST_DIGEST); + + var retainedCanonicalRoleHistory = + fixture + .transaction() + .execute( + status -> + repositories + .roles() + .findForCanonicalUpdate( + retained.accountUuid(), + retainedTenantUuid, + retainedProvenance, + retained.membershipId(), + 1L)) + .orElseThrow(); + assertThat(retainedCanonicalRoleHistory.membershipId()).isEqualTo(retained.membershipId()); + assertThat(retainedCanonicalRoleHistory.snapshotVersion()).isEqualTo(1L); + assertThat(retainedCanonicalRoleHistory.tenantUuid()).isEqualTo(retainedTenantUuid); + assertThat(retainedCanonicalRoleHistory.tenantProvenance()).isEqualTo(retainedProvenance); + assertThat(retainedCanonicalRoleHistory.roles()).containsExactly("legacy_observer"); + + UUID freshTenantUuid = UUID.randomUUID(); + FreshTenantCreationEvidence freshEvidence = freshTenantEvidence(freshTenantUuid); + fixture + .transaction() + .executeWithoutResult( + status -> repositories.freshAssociations().importVerified(freshEvidence)); + VerifiedTenantProvenance freshProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + freshEvidence.operationId(), + freshEvidence.evidenceDigest()); + AccountTenantMembership freshMembership = new AccountTenantMembership(); + Account account = new Account(); + account.setId(retained.accountId()); + freshMembership.setAccount(account); + freshMembership.setGameplayAdmissionAllowed(false); + freshMembership.setLifecycleState("LEGACY_UNVERIFIED"); + freshMembership.setMembershipVersion(1L); + freshMembership.setMembershipAuthorityGeneration(1L); + freshMembership.setAuthorityProvenance("LEGACY_UNVERIFIED"); + AccountTenantMembership freshReadback = + fixture + .transaction() + .execute( + status -> + repositories + .memberships() + .saveCanonical( + freshMembership, + retained.accountUuid(), + freshTenantUuid, + freshProvenance)); + + assertThat(freshReadback).isNotNull(); + assertThat(freshReadback.getTenantId()).isNull(); + assertThat(freshReadback.getTenantUuid()).isEqualTo(freshTenantUuid); + assertThat(freshReadback.getTenantProvenanceKind()).isEqualTo("FRESH_GAME_DESIGN"); + assertThat(freshReadback.getTenantSourceOperationId()).isEqualTo(freshEvidence.operationId()); + assertThat(freshReadback.getTenantProvenanceDigest()).isEqualTo(freshEvidence.evidenceDigest()); + + var replacedRoles = + fixture + .transaction() + .execute( + status -> + repositories + .roles() + .replaceCanonical( + freshReadback, + retained.accountUuid(), + freshTenantUuid, + freshProvenance, + 1L, + List.of("observer"))); + assertThat(replacedRoles).isNotNull(); + assertThat(replacedRoles.accountUuid()).isEqualTo(retained.accountUuid()); + assertThat(replacedRoles.tenantUuid()).isEqualTo(freshTenantUuid); + assertThat(replacedRoles.tenantId()).isNull(); + assertThat(replacedRoles.tenantProvenance()).isEqualTo(freshProvenance); + assertThat(replacedRoles.roles()).containsExactly("observer"); + Optional freshRoleReadback = + fixture + .transaction() + .execute( + status -> + repositories + .roles() + .findForCanonicalUpdate( + retained.accountUuid(), + freshTenantUuid, + freshProvenance, + freshReadback.getId(), + 1L)); + assertThat(freshRoleReadback).contains(replacedRoles); + + assertThat( + repositories + .memberships() + .findByAccountIdAndTenantId(retained.accountId(), freshEvidence.sourceGameRowId())) + .isEmpty(); + assertThat(repositories.memberships().findByAccountId(retained.accountId())) + .extracting(AccountTenantMembership::getId) + .containsExactly(retained.membershipId()); + assertThatThrownBy(() -> repositories.memberships().save(freshReadback)) + .isInstanceOf(IllegalArgumentException.class); + + assertIdentityInsertRejected( + fixture.setupDsl(), + retained.accountId(), + freshTenantUuid, + freshEvidence.operationId(), + freshEvidence.evidenceDigest(), + "FRESH_GAME_DESIGN", + 702L); + assertIdentityInsertRejected( + fixture.setupDsl(), + retained.accountId(), + freshTenantUuid, + freshEvidence.operationId(), + null, + "FRESH_GAME_DESIGN", + null); + assertIdentityInsertRejected( + fixture.setupDsl(), + retained.accountId(), + null, + freshEvidence.operationId(), + freshEvidence.evidenceDigest(), + "FRESH_GAME_DESIGN", + null); + assertIdentityInsertRejected( + fixture.setupDsl(), + retained.accountId(), + new UUID(0L, 0L), + freshEvidence.operationId(), + freshEvidence.evidenceDigest(), + "FRESH_GAME_DESIGN", + null); + assertIdentityInsertRejected( + fixture.setupDsl(), + retained.accountId(), + retainedTenantUuid, + retainedOperationId, + RETAINED_MANIFEST_DIGEST, + "APPROVED_RETAINED", + null); + assertIdentityInsertRejected( + fixture.setupDsl(), retained.accountId(), null, null, null, "UNRECOGNIZED", 703L); + } + + private static Fixture fixture() { + String schema = "membership_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + flyway(dataSource, schema, "44").migrate(); + + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + return new Fixture(schema, dataSource, setupDsl, transactionDsl, transaction); + } + + private static Flyway flyway( + DriverManagerDataSource dataSource, String schema, String targetVersion) { + return Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target(targetVersion) + .load(); + } + + private static SeededRetainedMembership seedRetainedMembership(DSLContext dsl) { + String suffix = UUID.randomUUID().toString().replace("-", ""); + Record account = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash, tenant_id) " + + "VALUES (?, ?, ?, ?) RETURNING id, account_uuid", + "mi-" + suffix, + "membership-identity-" + suffix + "@example.test", + "opaque-test-hash", + RETAINED_TENANT_ID), + "account insert must return its persisted identity row"); + long accountId = account.get("id", Long.class); + UUID accountUuid = account.get("account_uuid", UUID.class); + Long membershipId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED') " + + "RETURNING id", + accountId, + RETAINED_TENANT_ID) + .fetchOne(0, Long.class), + "membership insert must return its persisted id"); + dsl.execute( + "INSERT INTO account_legacy_tenant_sources " + + "(account_id, legacy_tenant_id, matching_membership_id, " + + "matching_membership_admission_allowed, profile_tenant_count, " + + "matching_profile_count, disposition) " + + "VALUES (?, ?, ?, FALSE, 0, 0, 'UNVERIFIED')", + accountId, + RETAINED_TENANT_ID, + membershipId); + dsl.execute( + "INSERT INTO account_legacy_membership_sources " + + "(membership_id, account_id, tenant_id, original_gameplay_admission_allowed, " + + "matches_account_legacy_tenant, disposition) " + + "VALUES (?, ?, ?, FALSE, TRUE, 'UNVERIFIED')", + membershipId, + accountId, + RETAINED_TENANT_ID); + dsl.execute( + "INSERT INTO account_tenant_membership_role_snapshots (membership_id, snapshot_version) " + + "VALUES (?, 1)", + membershipId); + dsl.execute( + "INSERT INTO account_tenant_membership_role_snapshot_roles " + + "(membership_id, snapshot_version, role_identifier) VALUES (?, 1, 'legacy_observer')", + membershipId); + return new SeededRetainedMembership(accountId, accountUuid, membershipId); + } + + private static void insertApprovedRetainedAssociation( + DSLContext dsl, UUID canonicalTenantUuid, UUID operationId, String sourceDigest) { + dsl.execute( + "INSERT INTO account_approved_legacy_tenant_associations " + + "(legacy_tenant_id, canonical_tenant_id, source_legacy_game_tenant_id, " + + "source_game_row_id, account_evidence_digest, operation_id, manifest_digest, " + + "manifest_signature, target_namespace, signer_key_id, approved_by, " + + "approval_reference, signed_at, operation_entry_count, manifest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1)", + RETAINED_TENANT_ID, + canonicalTenantUuid, + "legacy-game-tenant-700", + RETAINED_TENANT_ID, + sourceDigest, + operationId, + RETAINED_MANIFEST_DIGEST, + Base64.getEncoder().encodeToString(new byte[64]), + TEST_NAMESPACE, + "fixture-signing-key", + "fixture-operator", + "membership-identity-fixture", + "2026-10-03T00:00:00Z"); + } + + private static RepositoryFixture repositories(Fixture fixture) { + AccountRepository accounts = new AccountRepository(fixture.transactionDsl()); + LegacyTenantSourceEvidence sourceEvidence = + new LegacyTenantSourceEvidence(fixture.transactionDsl()); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(fixture.transactionDsl()); + ApprovedLegacyTenantAssociationRepository approved = + new ApprovedLegacyTenantAssociationRepository( + fixture.transactionDsl(), sourceEvidence, TEST_NAMESPACE, generations); + AccountTenantIdentityResolver resolver = + new AccountTenantIdentityResolver(approved, sourceEvidence, TEST_NAMESPACE); + FreshTenantIdentityAssociationRepository fresh = + new FreshTenantIdentityAssociationRepository(fixture.transactionDsl(), TEST_NAMESPACE); + return new RepositoryFixture( + new AccountTenantMembershipRepository(fixture.transactionDsl(), accounts, resolver, fresh), + new AccountTenantMembershipRoleSnapshotRepository(fixture.transactionDsl()), + fresh); + } + + private static FreshTenantCreationEvidence freshTenantEvidence(UUID canonicalTenantUuid) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceTenantKey = "f-" + UUID.randomUUID().toString().replace("-", ""); + String requestDigest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, requestId, sourceTenantKey, "Fixture tenant", null); + long sourceGameRowId = 701L; + String sourceKind = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + canonicalTenantUuid, + sourceGameRowId, + sourceTenantKey, + sourceKind, + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + canonicalTenantUuid, + sourceGameRowId, + sourceTenantKey, + sourceKind)); + } + + private static void assertIdentityInsertRejected( + DSLContext dsl, + long accountId, + UUID tenantUuid, + UUID operationId, + String digest, + String kind, + Long tenantId) { + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, tenant_uuid, tenant_provenance_kind, " + + "tenant_source_operation_id, tenant_provenance_digest, " + + "gameplay_admission_allowed, lifecycle_state, membership_version, " + + "membership_authority_generation, authority_provenance) " + + "VALUES (?, ?, ?, ?, ?, ?, FALSE, 'LEGACY_UNVERIFIED', 1, 1, " + + "'LEGACY_UNVERIFIED')", + accountId, + tenantId, + tenantUuid, + kind, + operationId, + digest)) + .isInstanceOf(DataAccessException.class); + } + + private static void assertPersistedRoleHistory(DSLContext dsl, long membershipId) { + Record header = + dsl.fetchOne( + "SELECT membership_id, snapshot_version " + + "FROM account_tenant_membership_role_snapshots WHERE membership_id = ?", + membershipId); + assertThat(header).isNotNull(); + assertThat(header.get("membership_id", Long.class)).isEqualTo(membershipId); + assertThat(header.get("snapshot_version", Long.class)).isEqualTo(1L); + + List roleBytes = + dsl.fetch( + "SELECT convert_to(role_identifier, 'UTF8') AS role_identifier_bytes " + + "FROM account_tenant_membership_role_snapshot_roles " + + "WHERE membership_id = ? AND snapshot_version = 1 " + + "ORDER BY convert_to(role_identifier, 'UTF8')", + membershipId) + .map(row -> row.get("role_identifier_bytes", byte[].class)); + assertThat(roleBytes).hasSize(1); + assertThat(roleBytes.get(0)) + .containsExactly("legacy_observer".getBytes(StandardCharsets.UTF_8)); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext setupDsl, + DSLContext transactionDsl, + TransactionTemplate transaction) {} + + private record SeededRetainedMembership(long accountId, UUID accountUuid, long membershipId) {} + + private record RepositoryFixture( + AccountTenantMembershipRepository memberships, + AccountTenantMembershipRoleSnapshotRepository roles, + FreshTenantIdentityAssociationRepository freshAssociations) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java index 0a9a029857..41da6e3b37 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java @@ -4,7 +4,14 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import org.junit.jupiter.api.Test; class AccountJoinDigestTest { @@ -62,6 +69,128 @@ void canonicalSerializationRejectsAmbiguousValues() { () -> AccountJoinDigest.request(scope("scope-token", "production"), "caller", true, null)); } + @Test + void v2ScopeAndIntentMatchIndependentGoldenVectorsForAsciiAndUtf8Bindings() { + CanonicalJoinScopeV2 scope = canonicalScope(); + + assertEquals( + "sha256:f1a0f168078ccedfba6c418648e1ff9d7dcf80d7df8a87016a81e0ccdb9ec312", + AccountJoinDigest.scopeV2(scope)); + assertEquals( + "sha256:f1a0f168078ccedfba6c418648e1ff9d7dcf80d7df8a87016a81e0ccdb9ec312", + referenceDigest("account-join-scope/v2", "PUBLIC_PRODUCTION", List.of(), scope, List.of())); + assertEquals( + "sha256:8e550967de5a3b9e4db453fda8b8ae8f9dcf0b82bfe2d747e7513a5435554b97", + AccountJoinDigest.intentV2("request-42", scope, "caller-binding-42")); + assertEquals( + "sha256:8e550967de5a3b9e4db453fda8b8ae8f9dcf0b82bfe2d747e7513a5435554b97", + referenceDigest( + "account-join-intent/v2", + "JOIN", + List.of("request-42", "caller-binding-42"), + scope, + List.of())); + + assertEquals( + "sha256:8f3d27ab24423eb49e8f7b7f85110457f10a470003a1a7dde514b27b88deb606", + AccountJoinDigest.intentV2("request-42", scope, "bootstrap-jti-α")); + assertEquals( + "sha256:8f3d27ab24423eb49e8f7b7f85110457f10a470003a1a7dde514b27b88deb606", + referenceDigest( + "account-join-intent/v2", + "JOIN", + List.of("request-42", "bootstrap-jti-α"), + scope, + List.of())); + } + + @Test + void v2RequestMatchesLargeBigintPolicyVectorAndPolicyChangesChangeDigest() { + CanonicalJoinScopeV2 scope = canonicalScope(); + String original = + AccountJoinDigest.requestV2( + scope, "bootstrap-jti-α", EntitlementAvailabilityV2.AVAILABLE, true, 9L); + + assertEquals( + "sha256:90dd727af35a10f3c0532383cec9d4813654fd4b903bc551eb99af5ffbe8614f", original); + assertEquals( + "sha256:90dd727af35a10f3c0532383cec9d4813654fd4b903bc551eb99af5ffbe8614f", + referenceDigest( + "account-join-request/v2", + "JOIN", + List.of("bootstrap-jti-α"), + scope, + List.of("AVAILABLE", "true", "9"))); + assertNotEquals( + original, + AccountJoinDigest.requestV2( + scope, "bootstrap-jti-α", EntitlementAvailabilityV2.AVAILABLE, false, 9L)); + assertNotEquals( + original, + AccountJoinDigest.requestV2( + scope, "bootstrap-jti-α", EntitlementAvailabilityV2.AVAILABLE, true, 10L)); + } + + @Test + void everyV2ScopeFieldChangesScopeIntentAndRequestDigests() { + CanonicalJoinScopeV2 scope = canonicalScope(); + String scopeDigest = AccountJoinDigest.scopeV2(scope); + String intentDigest = AccountJoinDigest.intentV2("request-42", scope, "caller-binding-42"); + String requestDigest = + AccountJoinDigest.requestV2( + scope, "caller-binding-42", EntitlementAvailabilityV2.AVAILABLE, true, 9L); + + for (CanonicalJoinScopeV2 changed : everyScopeFieldChanged(scope)) { + assertNotEquals(scopeDigest, AccountJoinDigest.scopeV2(changed)); + assertNotEquals( + intentDigest, AccountJoinDigest.intentV2("request-42", changed, "caller-binding-42")); + assertNotEquals( + requestDigest, + AccountJoinDigest.requestV2( + changed, "caller-binding-42", EntitlementAvailabilityV2.AVAILABLE, true, 9L)); + } + assertNotEquals( + intentDigest, AccountJoinDigest.intentV2("request-43", scope, "caller-binding-42")); + assertNotEquals( + intentDigest, AccountJoinDigest.intentV2("request-42", scope, "caller-binding-43")); + assertNotEquals( + requestDigest, + AccountJoinDigest.requestV2( + scope, "caller-binding-43", EntitlementAvailabilityV2.AVAILABLE, true, 9L)); + } + + @Test + void v2RequestRejectsUnavailableMissingAndInvalidPolicyEvidence() { + CanonicalJoinScopeV2 scope = canonicalScope(); + + assertThrows( + IllegalArgumentException.class, + () -> + AccountJoinDigest.requestV2( + scope, "caller", EntitlementAvailabilityV2.UNAVAILABLE, true, 9L)); + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.requestV2(scope, "caller", null, true, 9L)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountJoinDigest.requestV2( + scope, "caller", EntitlementAvailabilityV2.AVAILABLE, null, 9L)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountJoinDigest.requestV2( + scope, "caller", EntitlementAvailabilityV2.AVAILABLE, true, null)); + assertThrows( + IllegalArgumentException.class, + () -> + AccountJoinDigest.requestV2( + scope, "caller", EntitlementAvailabilityV2.AVAILABLE, true, 0L)); + assertThrows( + IllegalArgumentException.class, + () -> AccountJoinDigest.intentV2("request", scope, "\uD800")); + } + private static VerifiedJoinScope withGameInstance(VerifiedJoinScope scope, long gameInstanceId) { return new VerifiedJoinScope( scope.connectScopeId(), @@ -115,4 +244,278 @@ private static VerifiedJoinScope scope(String connectScopeId, String realmSlug) "2026-09-24T10:02:00Z", "unused-by-preimage"); } + + private static CanonicalJoinScopeV2 canonicalScope() { + return new CanonicalJoinScopeV2( + "connect-scope-42", + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "acme-worlds", + "demo", + "main", + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "SHARED", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + 9_007_199_254_740_993L, + Long.MAX_VALUE, + "2026-10-03T01:02:03.120Z", + "2026-10-03T01:04:03Z"); + } + + private static List everyScopeFieldChanged(CanonicalJoinScopeV2 scope) { + return List.of( + new CanonicalJoinScopeV2( + "connect-scope-43", + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + "other-tenant", + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + "other-world", + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + "other-realm", + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + "ISOLATED", + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision() - 1L, + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion() - 1L, + scope.evaluatedAt(), + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + "2026-10-03T01:02:03.12Z", + scope.connectScopeExpiresAt()), + new CanonicalJoinScopeV2( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + "2026-10-03T01:04:04Z")); + } + + private static String referenceDigest( + String domain, + String operationKind, + List leadingValues, + CanonicalJoinScopeV2 scope, + List trailingValues) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + referenceSegment(preimage, domain); + referenceSegment(preimage, "2"); + referenceSegment(preimage, operationKind); + leadingValues.forEach(value -> referenceSegment(preimage, value)); + referenceSegment(preimage, scope.connectScopeId()); + referenceSegment(preimage, scope.accountId().toString()); + referenceSegment(preimage, scope.tenantId().toString()); + referenceSegment(preimage, scope.realmId().toString()); + referenceSegment(preimage, scope.tenantSlug()); + referenceSegment(preimage, scope.worldSlug()); + referenceSegment(preimage, scope.realmSlug()); + referenceSegment(preimage, scope.playableStateNamespaceId().toString()); + referenceSegment(preimage, scope.playableStateScope()); + referenceSegment(preimage, scope.gameInstanceId().toString()); + referenceSegment(preimage, Long.toString(scope.catalogRevision())); + referenceSegment(preimage, Long.toString(scope.pointerVersion())); + referenceSegment(preimage, scope.evaluatedAt()); + referenceSegment(preimage, scope.connectScopeExpiresAt()); + trailingValues.forEach(value -> referenceSegment(preimage, value)); + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } + + private static void referenceSegment(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); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2Test.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2Test.java new file mode 100644 index 0000000000..67e5fcf49e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/CanonicalJoinScopeV2Test.java @@ -0,0 +1,377 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.lang.reflect.RecordComponent; +import java.time.Instant; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import org.junit.jupiter.api.Test; + +class CanonicalJoinScopeV2Test { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @Test + void exposesOrderedUuidTypedIdentityAndNoPersistedDigestField() { + RecordComponent[] components = CanonicalJoinScopeV2.class.getRecordComponents(); + + assertArrayEquals( + new String[] { + "connectScopeId", + "accountId", + "tenantId", + "realmId", + "tenantSlug", + "worldSlug", + "realmSlug", + "playableStateNamespaceId", + "playableStateScope", + "gameInstanceId", + "catalogRevision", + "pointerVersion", + "evaluatedAt", + "connectScopeExpiresAt" + }, + Arrays.stream(components).map(RecordComponent::getName).toArray(String[]::new)); + + assertEquals(UUID.class, componentType(components, "accountId")); + assertEquals(UUID.class, componentType(components, "tenantId")); + assertEquals(UUID.class, componentType(components, "realmId")); + assertEquals(UUID.class, componentType(components, "playableStateNamespaceId")); + assertEquals(UUID.class, componentType(components, "gameInstanceId")); + } + + @Test + void rejectsNilUuidIdentitiesAndNonPositiveBigintCounters() { + CanonicalJoinScopeV2 scope = scope(); + + assertThrows( + IllegalArgumentException.class, + () -> + build( + scope.connectScopeId(), + NIL_UUID, + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt())); + assertThrows( + IllegalArgumentException.class, + () -> + build( + scope.connectScopeId(), + scope.accountId(), + NIL_UUID, + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt())); + assertThrows( + IllegalArgumentException.class, + () -> + build( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + NIL_UUID, + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt())); + assertThrows( + IllegalArgumentException.class, + () -> + build( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + NIL_UUID, + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt())); + assertThrows( + IllegalArgumentException.class, + () -> + build( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + NIL_UUID, + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt())); + + assertThrows(IllegalArgumentException.class, () -> withCounters(scope, 0L, 1L)); + assertThrows(IllegalArgumentException.class, () -> withCounters(scope, 1L, 0L)); + assertThrows(IllegalArgumentException.class, () -> withCounters(scope, -1L, 1L)); + assertThrows(IllegalArgumentException.class, () -> withCounters(scope, 1L, -1L)); + } + + @Test + void preservesExactCanonicalSelectorAndUtcTimestampBytes() { + CanonicalJoinScopeV2 exact = scope(); + CanonicalJoinScopeV2 sameInstantDifferentTimestampBytes = + withEvaluatedAt(exact, "2026-10-03T01:02:03.12Z"); + + assertEquals("acme-worlds", exact.tenantSlug()); + assertEquals("demo", exact.worldSlug()); + assertEquals("main", exact.realmSlug()); + assertEquals("2026-10-03T01:02:03.120Z", exact.evaluatedAt()); + assertEquals( + Instant.parse(exact.evaluatedAt()), + Instant.parse(sameInstantDifferentTimestampBytes.evaluatedAt())); + assertEquals("2026-10-03T01:02:03.12Z", sameInstantDifferentTimestampBytes.evaluatedAt()); + assertNotEquals( + AccountJoinDigest.scopeV2(exact), + AccountJoinDigest.scopeV2(sameInstantDifferentTimestampBytes)); + } + + @Test + void preservesExactSelectorBytesAndRejectsMalformedOrNonUtcTimestamps() { + CanonicalJoinScopeV2 scope = scope(); + CanonicalJoinScopeV2 exactSelectorBytes = + build( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + "Acme-worlds", + "demo_world", + "máin", + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()); + + assertEquals("Acme-worlds", exactSelectorBytes.tenantSlug()); + assertEquals("demo_world", exactSelectorBytes.worldSlug()); + assertEquals("máin", exactSelectorBytes.realmSlug()); + assertNotEquals( + AccountJoinDigest.scopeV2(scope), AccountJoinDigest.scopeV2(exactSelectorBytes)); + assertThrows(IllegalArgumentException.class, () -> withPlayableStateScope(scope, "shared")); + assertThrows( + IllegalArgumentException.class, () -> withEvaluatedAt(scope, "2026-10-03T01:02:03+00:00")); + assertThrows( + IllegalArgumentException.class, () -> withEvaluatedAt(scope, "2026-10-03T01:02:03z")); + assertThrows( + IllegalArgumentException.class, () -> withEvaluatedAt(scope, "2026-02-30T01:02:03Z")); + assertThrows( + IllegalArgumentException.class, () -> withEvaluatedAt(scope, "2026-10-03T24:02:03Z")); + assertThrows(IllegalArgumentException.class, () -> withExpiry(scope, "2026-10-03T01:04:03")); + assertThrows(IllegalArgumentException.class, () -> withConnectScopeId(scope, "\uD800")); + assertThrows(IllegalArgumentException.class, () -> withRealmSlug(scope, "\uD800")); + } + + private static Class componentType(RecordComponent[] components, String name) { + return Arrays.stream(components) + .filter(component -> component.getName().equals(name)) + .findFirst() + .orElseThrow() + .getType(); + } + + private static CanonicalJoinScopeV2 scope() { + return build( + "connect-scope-42", + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "acme-worlds", + "demo", + "main", + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "SHARED", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + 9_007_199_254_740_993L, + Long.MAX_VALUE, + "2026-10-03T01:02:03.120Z", + "2026-10-03T01:04:03Z"); + } + + private static CanonicalJoinScopeV2 build( + String connectScopeId, + UUID accountId, + UUID tenantId, + UUID realmId, + String tenantSlug, + String worldSlug, + String realmSlug, + UUID playableStateNamespaceId, + String playableStateScope, + UUID gameInstanceId, + long catalogRevision, + long pointerVersion, + String evaluatedAt, + String connectScopeExpiresAt) { + return new CanonicalJoinScopeV2( + connectScopeId, + accountId, + tenantId, + realmId, + tenantSlug, + worldSlug, + realmSlug, + playableStateNamespaceId, + playableStateScope, + gameInstanceId, + catalogRevision, + pointerVersion, + evaluatedAt, + connectScopeExpiresAt); + } + + private static CanonicalJoinScopeV2 withCounters( + CanonicalJoinScopeV2 scope, long catalogRevision, long pointerVersion) { + return build( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + catalogRevision, + pointerVersion, + scope.evaluatedAt(), + scope.connectScopeExpiresAt()); + } + + private static CanonicalJoinScopeV2 withConnectScopeId( + CanonicalJoinScopeV2 scope, String connectScopeId) { + return build( + connectScopeId, + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()); + } + + private static CanonicalJoinScopeV2 withRealmSlug(CanonicalJoinScopeV2 scope, String realmSlug) { + return build( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + realmSlug, + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()); + } + + private static CanonicalJoinScopeV2 withPlayableStateScope( + CanonicalJoinScopeV2 scope, String playableStateScope) { + return build( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + playableStateScope, + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt()); + } + + private static CanonicalJoinScopeV2 withEvaluatedAt( + CanonicalJoinScopeV2 scope, String evaluatedAt) { + return build( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + evaluatedAt, + scope.connectScopeExpiresAt()); + } + + private static CanonicalJoinScopeV2 withExpiry(CanonicalJoinScopeV2 scope, String expiresAt) { + return build( + scope.connectScopeId(), + scope.accountId(), + scope.tenantId(), + scope.realmId(), + scope.tenantSlug(), + scope.worldSlug(), + scope.realmSlug(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + scope.gameInstanceId(), + scope.catalogRevision(), + scope.pointerVersion(), + scope.evaluatedAt(), + expiresAt); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepositoryTest.java index c61cbbabae..518b46b7ba 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepositoryTest.java @@ -4,6 +4,12 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -71,6 +77,16 @@ void emptyRoleSetIsAnAuthoritativeSnapshotOnlyWhenVersionedAndPresent() { @Test void persistenceMethodsRequireTheCallingJoinTransaction() throws ReflectiveOperationException { + assertMandatory( + AccountTenantMembershipRepository.class.getMethod( + "findCanonicalMembershipForUpdate", UUID.class, UUID.class)); + assertMandatory( + AccountTenantMembershipRepository.class.getMethod( + "saveCanonical", + AccountTenantMembership.class, + UUID.class, + UUID.class, + VerifiedTenantProvenance.class)); assertMandatory( AccountTenantMembershipRoleSnapshotRepository.class.getMethod( "findForUpdate", long.class, long.class, long.class, long.class)); @@ -80,6 +96,73 @@ void persistenceMethodsRequireTheCallingJoinTransaction() throws ReflectiveOpera net.firedevops.firemud.accountservice.entity.AccountTenantMembership.class, long.class, java.util.Collection.class)); + assertMandatory( + AccountTenantMembershipRoleSnapshotRepository.class.getMethod( + "findForCanonicalUpdate", + UUID.class, + UUID.class, + VerifiedTenantProvenance.class, + long.class, + long.class)); + assertMandatory( + AccountTenantMembershipRoleSnapshotRepository.class.getMethod( + "replaceCanonical", + AccountTenantMembership.class, + UUID.class, + UUID.class, + VerifiedTenantProvenance.class, + long.class, + java.util.Collection.class)); + } + + @Test + void canonicalRoleSnapshotRetainsFreshUuidAndFullSourceWithoutNumericAlias() { + UUID accountUuid = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID tenantUuid = UUID.fromString("22222222-2222-4222-8222-222222222222"); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "sha256:" + "a".repeat(64)); + + AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot snapshot = + new AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot( + 11L, null, 701L, 1L, List.of("player"), accountUuid, tenantUuid, provenance); + + assertThat(snapshot.accountUuid()).isEqualTo(accountUuid); + assertThat(snapshot.tenantUuid()).isEqualTo(tenantUuid); + assertThat(snapshot.tenantId()).isNull(); + assertThat(snapshot.tenantProvenance()).isEqualTo(provenance); + assertThatThrownBy( + () -> + new AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot( + 11L, 7L, 701L, 1L, List.of("player"), accountUuid, tenantUuid, provenance)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void canonicalMembershipAndRoleMethodsRequireAnActiveOwnerTransactionWithoutSpringProxy() { + UUID accountUuid = UUID.randomUUID(); + UUID tenantUuid = UUID.randomUUID(); + AccountTenantMembershipRepository memberships = + new AccountTenantMembershipRepository(DSL.using(SQLDialect.POSTGRES), null, null, null); + AccountTenantMembershipRoleSnapshotRepository roles = + new AccountTenantMembershipRoleSnapshotRepository(DSL.using(SQLDialect.POSTGRES)); + + assertThatThrownBy(() -> memberships.findCanonicalMembershipForUpdate(accountUuid, tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThatThrownBy(() -> memberships.saveCanonical(null, accountUuid, tenantUuid, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThatThrownBy(() -> roles.findForCanonicalUpdate(accountUuid, tenantUuid, null, 1L, 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + assertThatThrownBy( + () -> roles.replaceCanonical(null, accountUuid, tenantUuid, null, 1L, List.of())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); } private void assertMandatory(java.lang.reflect.Method method) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcServiceTest.java index d2e0d73468..92ada5de23 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityGrpcServiceTest.java @@ -2,7 +2,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -10,18 +12,31 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AcknowledgeIssuerProjectionForRuntimeRequest; +import net.firedevops.firemud.account.v1.AcknowledgeIssuerProjectionForRuntimeResponse; +import net.firedevops.firemud.account.v1.CaptureIssuerProjectionForRuntimeRequest; +import net.firedevops.firemud.account.v1.CaptureIssuerProjectionForRuntimeResponse; import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeRequest; import net.firedevops.firemud.account.v1.ReadIssuerAuthorityForRuntimeResponse; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionAcknowledgmentRepository.Acknowledgment; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository.Receipt; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityGrpcService; +import net.firedevops.firemud.accountservice.service.AccountIssuerProjectionAcknowledgmentService; +import net.firedevops.firemud.accountservice.service.AccountIssuerProjectionReconciliationService; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.account.authority.IssuerProjectionInstallationAcknowledgmentDigestV1; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.junit.jupiter.api.Test; import org.springframework.dao.TransientDataAccessResourceException; @@ -30,20 +45,45 @@ class AccountIssuerAuthorityGrpcServiceTest { private static final String ISSUER_ID = "https://account.example.test/issuer"; private static final String SOURCE_SCOPE = "issuer/" + ISSUER_ID; private static final String STREAM_KEY = "account:auth-authority:v1:" + SOURCE_SCOPE; + private static final String PROJECTION_KEY = + "session:game:auth:issuer-generation:v1:" + ISSUER_ID; 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 REQUEST_ID = "f50e8400-e29b-41d4-a716-446655440000"; + private static final UUID OPERATION_ID = UUID.fromString("91b0eb2d-f7b1-4d88-8db4-2b81cacfc96a"); + private static final UUID ACKNOWLEDGMENT_ID = + UUID.fromString("f50e8400-e29b-41d4-a716-446655440001"); private static final GrpcPeerIdentity GAME_SESSION_PEER = new GrpcPeerIdentity(GAME_SESSION_URI, NAMESPACE, "game-session-service"); @Test void constructorRequiresProducerAndValidWorkloadNamespace() { - assertThatThrownBy(() -> new AccountIssuerAuthorityGrpcService(null, NAMESPACE)) + assertThatThrownBy( + () -> + new AccountIssuerAuthorityGrpcService( + null, mockCaptureService(), mockAcknowledgmentService(), NAMESPACE)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("producer"); assertThatThrownBy( - () -> new AccountIssuerAuthorityGrpcService(mockProducer(), "Invalid_Namespace")) + () -> + new AccountIssuerAuthorityGrpcService( + mockProducer(), null, mockAcknowledgmentService(), NAMESPACE)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("reconciliation service"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityGrpcService( + mockProducer(), mockCaptureService(), null, NAMESPACE)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("acknowledgment service"); + assertThatThrownBy( + () -> + new AccountIssuerAuthorityGrpcService( + mockProducer(), + mockCaptureService(), + mockAcknowledgmentService(), + "Invalid_Namespace")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("namespace"); } @@ -257,15 +297,434 @@ void exactConfiguredIssuerRejectionIsInvalidArgument() { assertFailure(outcome, Status.Code.INVALID_ARGUMENT); } + @Test + void captureReturnsCompletePristineReceiptWithoutChangingSourceReadback() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerProjectionReconciliationService captureService = mockCaptureService(); + Receipt receipt = receipt(OPERATION_ID, REQUEST_ID, GAME_SESSION_URI, baseline()); + when(captureService.capture(ISSUER_ID, GAME_SESSION_URI, UUID.fromString(REQUEST_ID))) + .thenReturn(receipt); + AccountIssuerAuthorityGrpcService service = newService(producer, captureService); + + Outcome outcome = + invokeCapture(service, validCaptureRequest(), GAME_SESSION_PEER); + + CaptureIssuerProjectionForRuntimeResponse response = assertSuccess(outcome); + assertThat(response.getSchemaVersion()).isEqualTo("account-auth-issuer-projection-capture/v1"); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getRequestId()).isEqualTo(REQUEST_ID); + assertThat(response.getIssuerId()).isEqualTo(ISSUER_ID); + assertThat(response.getCallerWorkloadIdentity()).isEqualTo(GAME_SESSION_URI); + assertThat(response.getProjectionKey()).isEqualTo(PROJECTION_KEY); + assertThat(response.getRequestDigestVersion()).isEqualTo(1); + assertThat(response.getRequestDigest()).isEqualTo(receipt.requestDigest()); + assertThat(response.hasCapturedSourceSnapshot()).isTrue(); + assertThat(response.getCapturedSourceSnapshot().getIssuerId()).isEqualTo(ISSUER_ID); + assertThat(response.getCapturedSourceSnapshot().getIssuerAuthGeneration()).isEqualTo("1"); + assertThat(response.getCapturedSourceSnapshot().getSourceVersion()).isEqualTo("1"); + assertThat(response.getCapturedSourceSnapshot().getOutboxSequence()).isEqualTo("0"); + assertThat(response.getCapturedSourceSnapshot().hasLatestEventCanonicalJson()).isFalse(); + verify(captureService, org.mockito.Mockito.times(1)) + .capture(ISSUER_ID, GAME_SESSION_URI, UUID.fromString(REQUEST_ID)); + verifyNoInteractions(producer); + } + + @Test + void capturePreservesIndependentPositiveCountersAndCompleteCanonicalEvent() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerProjectionReconciliationService captureService = mockCaptureService(); + IssuerGenerationAuthorityEvent capturedEvent = + event("f50e8400-e29b-41d4-a716-446655440001", 3L, 8L, 13L); + IssuerAuthoritySnapshot captured = newSnapshot(8L, 13L, 3L, Optional.of(capturedEvent)); + Receipt receipt = receipt(OPERATION_ID, REQUEST_ID, GAME_SESSION_URI, captured); + when(captureService.capture(ISSUER_ID, GAME_SESSION_URI, UUID.fromString(REQUEST_ID))) + .thenReturn(receipt); + AccountIssuerAuthorityGrpcService service = newService(producer, captureService); + + Outcome outcome = + invokeCapture(service, validCaptureRequest(), GAME_SESSION_PEER); + + CaptureIssuerProjectionForRuntimeResponse response = assertSuccess(outcome); + assertThat(response.getCapturedSourceSnapshot().getIssuerAuthGeneration()).isEqualTo("8"); + assertThat(response.getCapturedSourceSnapshot().getSourceVersion()).isEqualTo("13"); + assertThat(response.getCapturedSourceSnapshot().getOutboxSequence()).isEqualTo("3"); + assertThat(response.getCapturedSourceSnapshot().getLatestEventCanonicalJson()) + .isEqualTo(capturedEvent.canonicalJson()); + verify(captureService, org.mockito.Mockito.times(1)) + .capture(ISSUER_ID, GAME_SESSION_URI, UUID.fromString(REQUEST_ID)); + verifyNoInteractions(producer); + } + + @Test + void exactHistoricalRetryReturnsTheOriginalCaptureReceiptSnapshot() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerProjectionReconciliationService captureService = mockCaptureService(); + IssuerGenerationAuthorityEvent oldEvent = + event("f50e8400-e29b-41d4-a716-446655440001", 1L, 2L, 5L); + IssuerAuthoritySnapshot historical = newSnapshot(2L, 5L, 1L, Optional.of(oldEvent)); + UUID originalOperationId = UUID.fromString("21b0eb2d-f7b1-4d88-8db4-2b81cacfc96a"); + Receipt original = receipt(originalOperationId, REQUEST_ID, GAME_SESSION_URI, historical); + when(captureService.capture(ISSUER_ID, GAME_SESSION_URI, UUID.fromString(REQUEST_ID))) + .thenReturn(original); + AccountIssuerAuthorityGrpcService service = newService(producer, captureService); + + Outcome outcome = + invokeCapture(service, validCaptureRequest(), GAME_SESSION_PEER); + + CaptureIssuerProjectionForRuntimeResponse response = assertSuccess(outcome); + assertThat(response.getOperationId()).isEqualTo(originalOperationId.toString()); + assertThat(response.getCapturedSourceSnapshot().getIssuerAuthGeneration()).isEqualTo("2"); + assertThat(response.getCapturedSourceSnapshot().getSourceVersion()).isEqualTo("5"); + assertThat(response.getCapturedSourceSnapshot().getOutboxSequence()).isEqualTo("1"); + assertThat(response.getCapturedSourceSnapshot().getLatestEventCanonicalJson()) + .isEqualTo(oldEvent.canonicalJson()); + verify(captureService, org.mockito.Mockito.times(1)) + .capture(ISSUER_ID, GAME_SESSION_URI, UUID.fromString(REQUEST_ID)); + verifyNoInteractions(producer); + } + + @Test + void captureRejectsWrongOrMissingPeerBeforeParsingOrOwnerInteraction() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerProjectionReconciliationService captureService = mockCaptureService(); + AccountIssuerAuthorityGrpcService service = newService(producer, captureService); + CaptureIssuerProjectionForRuntimeRequest malformed = + CaptureIssuerProjectionForRuntimeRequest.newBuilder().setIssuerId(" ").build(); + + Outcome wrongPeer = + invokeCapture( + service, + malformed, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", + NAMESPACE, + "account-service")); + Outcome missingPeer = + invokeWithoutPeerCapture(service, malformed); + + assertFailure(wrongPeer, Status.Code.PERMISSION_DENIED); + assertFailure(missingPeer, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(producer, captureService); + } + + @Test + void captureRejectsUnknownFieldsAndMalformedRequestIdsBeforeCallingCaptureService() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerProjectionReconciliationService captureService = mockCaptureService(); + AccountIssuerAuthorityGrpcService service = newService(producer, captureService); + CaptureIssuerProjectionForRuntimeRequest valid = validCaptureRequest(); + List invalidRequests = + List.of( + valid.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1L) + .build()) + .build()) + .build(), + valid.toBuilder().setRequestId("F50E8400-E29B-41D4-A716-446655440000").build(), + valid.toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + valid.toBuilder().setRequestId("f50e8400-e29b-41d4-a716-446655440000 ").build()); + + for (CaptureIssuerProjectionForRuntimeRequest invalidRequest : invalidRequests) { + assertFailure( + invokeCapture(service, invalidRequest, GAME_SESSION_PEER), Status.Code.INVALID_ARGUMENT); + } + + verifyNoInteractions(producer, captureService); + } + + @Test + void captureRejectsCrossBoundAndContradictoryReceiptsWithoutPartialResponse() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerProjectionReconciliationService crossBoundCaptureService = mockCaptureService(); + Receipt crossBound = + receipt( + OPERATION_ID, + REQUEST_ID, + "spiffe://firemud/ns/other-unit/sa/game-session-service", + baseline()); + when(crossBoundCaptureService.capture(ISSUER_ID, GAME_SESSION_URI, UUID.fromString(REQUEST_ID))) + .thenReturn(crossBound); + AccountIssuerAuthorityGrpcService crossBoundService = + newService(producer, crossBoundCaptureService); + + Outcome crossBoundOutcome = + invokeCapture(crossBoundService, validCaptureRequest(), GAME_SESSION_PEER); + + assertFailure(crossBoundOutcome, Status.Code.FAILED_PRECONDITION); + + AccountIssuerProjectionReconciliationService contradictoryCaptureService = mockCaptureService(); + Receipt contradictory = spy(receipt(OPERATION_ID, REQUEST_ID, GAME_SESSION_URI, baseline())); + IssuerAuthoritySnapshot contradictorySnapshot = mock(IssuerAuthoritySnapshot.class); + when(contradictorySnapshot.issuerId()).thenReturn(ISSUER_ID); + when(contradictorySnapshot.issuerAuthGeneration()).thenReturn(2L); + when(contradictorySnapshot.sourceVersion()).thenReturn(2L); + when(contradictorySnapshot.outboxStreamKey()).thenReturn(STREAM_KEY); + when(contradictorySnapshot.outboxSequence()).thenReturn(0L); + when(contradictorySnapshot.latestEvent()).thenReturn(Optional.empty()); + // Both production constructors reject this inconsistent checkpoint. Mock it only to exercise + // transport defense against untrusted collaborator output, not a migrated SQL row. + doReturn(contradictorySnapshot).when(contradictory).capturedSource(); + when(contradictoryCaptureService.capture( + ISSUER_ID, GAME_SESSION_URI, UUID.fromString(REQUEST_ID))) + .thenReturn(contradictory); + AccountIssuerAuthorityGrpcService contradictoryService = + newService(producer, contradictoryCaptureService); + + Outcome contradictoryOutcome = + invokeCapture(contradictoryService, validCaptureRequest(), GAME_SESSION_PEER); + + assertFailure(contradictoryOutcome, Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(producer); + } + + @Test + void captureMapsExactIssuerConflictReceiptConflictAndTransientFailureToBoundedStatuses() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerProjectionReconciliationService mismatchService = mockCaptureService(); + String otherIssuer = "https://other.example.test/issuer"; + when(mismatchService.capture(otherIssuer, GAME_SESSION_URI, UUID.fromString(REQUEST_ID))) + .thenThrow(new AccountIssuerAuthorityEventProducer.IssuerMismatchException()); + AccountIssuerAuthorityGrpcService mismatchGrpcService = newService(producer, mismatchService); + CaptureIssuerProjectionForRuntimeRequest wrongIssuerRequest = + validCaptureRequest().toBuilder().setIssuerId(otherIssuer).build(); + assertFailure( + invokeCapture(mismatchGrpcService, wrongIssuerRequest, GAME_SESSION_PEER), + Status.Code.INVALID_ARGUMENT); + + AccountIssuerProjectionReconciliationService conflictService = mockCaptureService(); + when(conflictService.capture(ISSUER_ID, GAME_SESSION_URI, UUID.fromString(REQUEST_ID))) + .thenThrow( + new AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException( + "private conflict detail")); + Outcome conflict = + invokeCapture( + newService(producer, conflictService), validCaptureRequest(), GAME_SESSION_PEER); + assertFailure(conflict, Status.Code.ALREADY_EXISTS); + assertThat(conflict.error().getDescription()).doesNotContain("private conflict detail"); + + AccountIssuerProjectionReconciliationService transientService = mockCaptureService(); + when(transientService.capture(ISSUER_ID, GAME_SESSION_URI, UUID.fromString(REQUEST_ID))) + .thenThrow(new TransientDataAccessResourceException("database detail")); + Outcome unavailable = + invokeCapture( + newService(producer, transientService), validCaptureRequest(), GAME_SESSION_PEER); + assertFailure(unavailable, Status.Code.UNAVAILABLE); + assertThat(unavailable.error().getDescription()).doesNotContain("database detail"); + verifyNoInteractions(producer); + } + + @Test + void acknowledgmentRequiresExactCertificatePeerBeforeParsingOrOwnerAccess() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerProjectionReconciliationService captureService = mockCaptureService(); + AccountIssuerProjectionAcknowledgmentService acknowledgmentService = + mockAcknowledgmentService(); + AccountIssuerAuthorityGrpcService service = + newService(producer, captureService, acknowledgmentService); + AcknowledgeIssuerProjectionForRuntimeRequest malformed = + AcknowledgeIssuerProjectionForRuntimeRequest.newBuilder().setIssuerId(" ").build(); + + Outcome wrongPeer = + invokeAcknowledgment( + service, + malformed, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", + NAMESPACE, + "account-service")); + Outcome missingPeer = + invokeAcknowledgmentWithoutPeer(service, malformed); + + assertFailure(wrongPeer, Status.Code.PERMISSION_DENIED); + assertFailure(missingPeer, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(producer, captureService, acknowledgmentService); + } + + @Test + void acknowledgmentRejectsUnknownFieldsAndMalformedBindingsBeforeOwnerAccess() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerProjectionReconciliationService captureService = mockCaptureService(); + AccountIssuerProjectionAcknowledgmentService acknowledgmentService = + mockAcknowledgmentService(); + AccountIssuerAuthorityGrpcService service = + newService(producer, captureService, acknowledgmentService); + AcknowledgeIssuerProjectionForRuntimeRequest valid = validAcknowledgmentRequest(); + List invalidRequests = + List.of( + valid.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1L) + .build()) + .build()) + .build(), + valid.toBuilder().setCaptureOperationId("91B0EB2D-F7B1-4D88-8DB4-2B81CACFC96A").build(), + valid.toBuilder().setCaptureOperationId("00000000-0000-0000-0000-000000000000").build(), + valid.toBuilder().setCaptureRequestId("f50e8400-e29b-41d4-a716-446655440000 ").build(), + valid.toBuilder().setCaptureRequestDigestVersion(2).build(), + valid.toBuilder().setCaptureRequestDigest("A".repeat(64)).build(), + valid.toBuilder().setProjectionKey(PROJECTION_KEY + ":other").build(), + valid.toBuilder().setInstalledProjectionJson("{").build(), + valid.toBuilder().setInstalledProjectionJson("[]").build(), + valid.toBuilder() + .setInstalledProjectionJson( + projectionJson().replace("lastAppliedIssuerGeneration", "unexpected")) + .build()); + + for (AcknowledgeIssuerProjectionForRuntimeRequest invalidRequest : invalidRequests) { + assertFailure( + invokeAcknowledgment(service, invalidRequest, GAME_SESSION_PEER), + Status.Code.INVALID_ARGUMENT); + } + + verifyNoInteractions(producer, captureService, acknowledgmentService); + } + + @Test + void acknowledgmentReturnsTheCompleteOwnerResultAfterExactBindingValidation() { + AccountIssuerAuthorityEventProducer producer = mockProducer(); + AccountIssuerProjectionReconciliationService captureService = mockCaptureService(); + AccountIssuerProjectionAcknowledgmentService acknowledgmentService = + mockAcknowledgmentService(); + AcknowledgeIssuerProjectionForRuntimeRequest request = validAcknowledgmentRequest(); + Acknowledgment original = validAcknowledgment(); + when(acknowledgmentService.acknowledge( + ISSUER_ID, + GAME_SESSION_URI, + OPERATION_ID, + UUID.fromString(REQUEST_ID), + 1, + captureDigest(), + projectionJson())) + .thenReturn(original); + AccountIssuerAuthorityGrpcService service = + newService(producer, captureService, acknowledgmentService); + + Outcome outcome = + invokeAcknowledgment(service, request, GAME_SESSION_PEER); + + AcknowledgeIssuerProjectionForRuntimeResponse response = assertSuccess(outcome); + assertThat(response.getSchemaVersion()) + .isEqualTo("account-auth-issuer-projection-installation-ack/v1"); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getAcknowledgmentId()).isEqualTo(ACKNOWLEDGMENT_ID.toString()); + assertThat(response.getIssuerId()).isEqualTo(ISSUER_ID); + assertThat(response.getCallerWorkloadIdentity()).isEqualTo(GAME_SESSION_URI); + assertThat(response.getProjectionKey()).isEqualTo(PROJECTION_KEY); + assertThat(response.getCaptureOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getCaptureRequestId()).isEqualTo(REQUEST_ID); + assertThat(response.getCaptureRequestDigestVersion()).isEqualTo(1); + assertThat(response.getCaptureRequestDigest()).isEqualTo(captureDigest()); + assertThat(response.getRequestDigestVersion()).isEqualTo(1); + assertThat(response.getRequestDigest()).isEqualTo(original.requestDigest()); + assertThat(response.getInstalledProjectionJson()).isEqualTo(projectionJson()); + assertThat(response.getInstalledProjectionSha256()) + .isEqualTo(java.util.HexFormat.of().formatHex(original.installedProjectionSha256())); + verify(acknowledgmentService) + .acknowledge( + ISSUER_ID, + GAME_SESSION_URI, + OPERATION_ID, + UUID.fromString(REQUEST_ID), + 1, + captureDigest(), + projectionJson()); + verifyNoInteractions(producer, captureService); + } + + @Test + void acknowledgmentMapsConflictInvalidAuthenticationStaleAndTransientFailures() { + assertAcknowledgmentFailure( + new AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException( + "private conflict detail"), + Status.Code.ALREADY_EXISTS); + assertAcknowledgmentFailure( + new IllegalArgumentException("private malformed detail"), Status.Code.INVALID_ARGUMENT); + assertAcknowledgmentFailure( + new SecurityException("private identity detail"), Status.Code.PERMISSION_DENIED); + assertAcknowledgmentFailure( + new IllegalStateException( + "First issuer installation acknowledgment requires the captured source to remain current"), + Status.Code.FAILED_PRECONDITION); + assertAcknowledgmentFailure( + new TransientDataAccessResourceException("database detail"), Status.Code.UNAVAILABLE); + + AccountIssuerProjectionAcknowledgmentService unavailableEvidence = mockAcknowledgmentService(); + when(unavailableEvidence.acknowledge( + ISSUER_ID, + GAME_SESSION_URI, + OPERATION_ID, + UUID.fromString(REQUEST_ID), + 1, + captureDigest(), + projectionJson())) + .thenThrow(new IllegalStateException("Post-commit acknowledgment readback is missing")); + Outcome unavailable = + invokeAcknowledgment( + newService(mockProducer(), mockCaptureService(), unavailableEvidence), + validAcknowledgmentRequest(), + GAME_SESSION_PEER); + assertFailure(unavailable, Status.Code.FAILED_PRECONDITION); + assertThat(unavailable.error().getDescription()).doesNotContain("readback is missing"); + + AccountIssuerProjectionAcknowledgmentService invalidResult = mockAcknowledgmentService(); + when(invalidResult.acknowledge( + ISSUER_ID, + GAME_SESSION_URI, + OPERATION_ID, + UUID.fromString(REQUEST_ID), + 1, + captureDigest(), + projectionJson())) + .thenReturn(null); + Outcome contradictory = + invokeAcknowledgment( + newService(mockProducer(), mockCaptureService(), invalidResult), + validAcknowledgmentRequest(), + GAME_SESSION_PEER); + assertFailure(contradictory, Status.Code.DATA_LOSS); + } + private static AccountIssuerAuthorityGrpcService newService( AccountIssuerAuthorityEventProducer producer) { - return new AccountIssuerAuthorityGrpcService(producer, NAMESPACE); + return newService(producer, mockCaptureService(), mockAcknowledgmentService()); + } + + private static AccountIssuerAuthorityGrpcService newService( + AccountIssuerAuthorityEventProducer producer, + AccountIssuerProjectionReconciliationService captureService) { + return newService(producer, captureService, mockAcknowledgmentService()); + } + + private static AccountIssuerAuthorityGrpcService newService( + AccountIssuerAuthorityEventProducer producer, + AccountIssuerProjectionReconciliationService captureService, + AccountIssuerProjectionAcknowledgmentService acknowledgmentService) { + return new AccountIssuerAuthorityGrpcService( + producer, captureService, acknowledgmentService, NAMESPACE); } private static AccountIssuerAuthorityEventProducer mockProducer() { return mock(AccountIssuerAuthorityEventProducer.class); } + private static AccountIssuerProjectionReconciliationService mockCaptureService() { + return mock(AccountIssuerProjectionReconciliationService.class); + } + + private static AccountIssuerProjectionAcknowledgmentService mockAcknowledgmentService() { + return mock(AccountIssuerProjectionAcknowledgmentService.class); + } + private static ReadIssuerAuthorityForRuntimeRequest validRequest() { return ReadIssuerAuthorityForRuntimeRequest.newBuilder() .setIssuerId(ISSUER_ID) @@ -273,6 +732,122 @@ private static ReadIssuerAuthorityForRuntimeRequest validRequest() { .build(); } + private static CaptureIssuerProjectionForRuntimeRequest validCaptureRequest() { + return CaptureIssuerProjectionForRuntimeRequest.newBuilder() + .setIssuerId(ISSUER_ID) + .setRequestId(REQUEST_ID) + .build(); + } + + private static AcknowledgeIssuerProjectionForRuntimeRequest validAcknowledgmentRequest() { + return AcknowledgeIssuerProjectionForRuntimeRequest.newBuilder() + .setIssuerId(ISSUER_ID) + .setCaptureOperationId(OPERATION_ID.toString()) + .setCaptureRequestId(REQUEST_ID) + .setCaptureRequestDigestVersion(1) + .setCaptureRequestDigest(captureDigest()) + .setProjectionKey(PROJECTION_KEY) + .setInstalledProjectionJson(projectionJson()) + .build(); + } + + private static Acknowledgment validAcknowledgment() { + byte[] projectionBytes = projectionJson().getBytes(StandardCharsets.UTF_8); + String acknowledgmentDigest = + IssuerProjectionInstallationAcknowledgmentDigestV1.digest( + ISSUER_ID, + GAME_SESSION_URI, + PROJECTION_KEY, + OPERATION_ID, + UUID.fromString(REQUEST_ID), + 1, + captureDigest(), + projectionJson()); + return new Acknowledgment( + ACKNOWLEDGMENT_ID, + OPERATION_ID, + UUID.fromString(REQUEST_ID), + ISSUER_ID, + GAME_SESSION_URI, + PROJECTION_KEY, + 1, + captureDigest(), + 1, + acknowledgmentDigest, + projectionBytes, + sha256(projectionBytes)); + } + + private static String projectionJson() { + return "{\"schemaVersion\":\"game-session-auth-issuer-projection/v1\"," + + "\"issuerId\":\"" + + ISSUER_ID + + "\"," + + "\"lastAppliedIssuerGeneration\":\"1\"," + + "\"lastAppliedSourceOutboxSequence\":\"0\"," + + "\"outboxStreamKey\":\"" + + STREAM_KEY + + "\"," + + "\"appliedAt\":\"2026-10-03T00:00:00Z\"," + + "\"appliedSourceEvidence\":{}}"; + } + + private static String captureDigest() { + return Receipt.requestDigestFor( + ISSUER_ID, GAME_SESSION_URI, PROJECTION_KEY, UUID.fromString(REQUEST_ID)); + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static void assertAcknowledgmentFailure( + RuntimeException failure, Status.Code expectedCode) { + AccountIssuerProjectionAcknowledgmentService acknowledgmentService = + mockAcknowledgmentService(); + when(acknowledgmentService.acknowledge( + ISSUER_ID, + GAME_SESSION_URI, + OPERATION_ID, + UUID.fromString(REQUEST_ID), + 1, + captureDigest(), + projectionJson())) + .thenThrow(failure); + Outcome outcome = + invokeAcknowledgment( + newService(mockProducer(), mockCaptureService(), acknowledgmentService), + validAcknowledgmentRequest(), + GAME_SESSION_PEER); + assertFailure(outcome, expectedCode); + assertThat(outcome.error().getDescription()).doesNotContain(failure.getMessage()); + } + + private static IssuerAuthoritySnapshot baseline() { + return newSnapshot(1L, 1L, 0L, Optional.empty()); + } + + private static Receipt receipt( + UUID operationId, + String requestId, + String callerIdentity, + IssuerAuthoritySnapshot capturedSource) { + UUID stableRequestId = UUID.fromString(requestId); + return new Receipt( + operationId, + stableRequestId, + ISSUER_ID, + callerIdentity, + PROJECTION_KEY, + 1, + Receipt.requestDigestFor(ISSUER_ID, callerIdentity, PROJECTION_KEY, stableRequestId), + capturedSource); + } + private static IssuerAuthoritySnapshot newSnapshot( long generation, long sourceVersion, @@ -282,6 +857,56 @@ private static IssuerAuthoritySnapshot newSnapshot( ISSUER_ID, generation, sourceVersion, STREAM_KEY, sequence, latestEvent); } + private static Outcome invokeCapture( + AccountIssuerAuthorityGrpcService service, + CaptureIssuerProjectionForRuntimeRequest request, + GrpcPeerIdentity peerIdentity) { + Context peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peerIdentity); + Context previous = peerContext.attach(); + try { + RecordingObserver observer = + new RecordingObserver<>(); + service.captureIssuerProjectionForRuntime(request, observer); + return observer.outcome(); + } finally { + peerContext.detach(previous); + } + } + + private static Outcome invokeWithoutPeerCapture( + AccountIssuerAuthorityGrpcService service, CaptureIssuerProjectionForRuntimeRequest request) { + RecordingObserver observer = + new RecordingObserver<>(); + service.captureIssuerProjectionForRuntime(request, observer); + return observer.outcome(); + } + + private static Outcome invokeAcknowledgment( + AccountIssuerAuthorityGrpcService service, + AcknowledgeIssuerProjectionForRuntimeRequest request, + GrpcPeerIdentity peerIdentity) { + Context peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peerIdentity); + Context previous = peerContext.attach(); + try { + RecordingObserver observer = + new RecordingObserver<>(); + service.acknowledgeIssuerProjectionForRuntime(request, observer); + return observer.outcome(); + } finally { + peerContext.detach(previous); + } + } + + private static Outcome + invokeAcknowledgmentWithoutPeer( + AccountIssuerAuthorityGrpcService service, + AcknowledgeIssuerProjectionForRuntimeRequest request) { + RecordingObserver observer = + new RecordingObserver<>(); + service.acknowledgeIssuerProjectionForRuntime(request, observer); + return observer.outcome(); + } + private static IssuerGenerationAuthorityEvent event( String eventRequestId, long sequence, long generation, long sourceVersion) { return IssuerGenerationAuthorityEventV1Codec.seal( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionAcknowledgmentServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionAcknowledgmentServiceTest.java new file mode 100644 index 0000000000..c20a965f96 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionAcknowledgmentServiceTest.java @@ -0,0 +1,521 @@ +package 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.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReentrantLock; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionAcknowledgmentRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionAcknowledgmentRepository.Acknowledgment; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository.Receipt; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +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 AccountIssuerProjectionAcknowledgmentServiceTest { + private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String GAME_SESSION_ID = + "spiffe://firemud/ns/account-unit/sa/game-session-service"; + private static final String OTHER_GAME_SESSION_ID = + "spiffe://firemud/ns/other-unit/sa/game-session-service"; + private static final String STREAM_KEY = "account:auth-authority:v1:issuer/" + ISSUER_ID; + private static final String PROJECTION_KEY = + "session:game:auth:issuer-generation:v1:" + ISSUER_ID; + private static final UUID REQUEST_ID = UUID.fromString("a3a69671-8149-4d97-86f8-25a2582fdd68"); + private static final UUID OPERATION_ID = UUID.fromString("91b0eb2d-f7b1-4d88-8db4-2b81cacfc96a"); + private static final UUID OTHER_OPERATION_ID = + UUID.fromString("a3d2fe11-23ac-40b7-8e85-26dd9e9b9a23"); + private static final String APPLIED_AT = "2026-10-03T00:00:00Z"; + + @Test + void persistsOnlyAfterOwnerTransactionReadbackAndSeparateFencedDurableReadback() { + Fixture fixture = fixture(baseline(), capture(OPERATION_ID, REQUEST_ID, baseline())); + AtomicReference stored = fixture.store(); + + Acknowledgment result = fixture.acknowledge(baseline(), APPLIED_AT); + + assertThat(result.acknowledgmentId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(result.captureOperationId()).isEqualTo(OPERATION_ID); + assertThat(result.captureRequestId()).isEqualTo(REQUEST_ID); + assertThat(result.installedProjectionUtf8()) + .containsExactly(projectionJson(baseline(), APPLIED_AT).getBytes(StandardCharsets.UTF_8)); + assertThat(stored.get().acknowledgmentId()).isEqualTo(result.acknowledgmentId()); + verify(fixture.transactions(), times(2)).getTransaction(any(TransactionDefinition.class)); + verify(fixture.transactions(), times(2)).commit(any()); + verify(fixture.repository(), times(1)).insert(any(Acknowledgment.class)); + verify(fixture.repository(), times(3)).findByCaptureOperationId(OPERATION_ID); + verify(fixture.source(), times(2)).readCurrentForProjectionReconciliation(ISSUER_ID); + verify(fixture.source(), never()).advance(any(), any(), anyLong(), anyLong()); + } + + @Test + void exactRetryReturnsOriginalAcknowledgmentAfterSourceAdvance() { + IssuerGenerationAuthorityEvent capturedEvent = event(REQUEST_ID, 1L, 2L, 2L); + IssuerAuthoritySnapshot captured = snapshot(2L, 2L, 1L, capturedEvent); + IssuerGenerationAuthorityEvent laterEvent = event(UUID.randomUUID(), 2L, 3L, 3L); + IssuerAuthoritySnapshot later = snapshot(3L, 3L, 2L, laterEvent); + Fixture fixture = fixture(captured, capture(OPERATION_ID, REQUEST_ID, captured)); + AtomicReference stored = fixture.store(); + + Acknowledgment original = fixture.acknowledge(captured, APPLIED_AT); + when(fixture.source().readCurrentForProjectionReconciliation(ISSUER_ID)) + .thenReturn(later, later); + when(fixture.source().readCommittedEventForProjectionReconciliation(ISSUER_ID, 1L)) + .thenReturn( + new IssuerAuthorityEventReadback(later, capturedEvent), + new IssuerAuthorityEventReadback(later, capturedEvent)); + + Acknowledgment recovered = fixture.acknowledge(captured, APPLIED_AT); + + assertThat(recovered.acknowledgmentId()).isEqualTo(original.acknowledgmentId()); + assertThat(recovered.installedProjectionUtf8()).isEqualTo(original.installedProjectionUtf8()); + assertThat(stored.get().acknowledgmentId()).isEqualTo(original.acknowledgmentId()); + verify(fixture.repository(), times(1)).insert(any(Acknowledgment.class)); + verify(fixture.source(), times(2)).readCommittedEventForProjectionReconciliation(ISSUER_ID, 1L); + } + + @Test + void concurrentExactRetriesSerializeOnOwnerTransactionAndReuseOneAcknowledgment() + throws Exception { + // This transaction-manager lock models the Account issuer fence. Real PostgreSQL concurrency + // proof remains a separate integration obligation. + IssuerAuthoritySnapshot captured = baseline(); + Fixture fixture = fixture(captured, capture(OPERATION_ID, REQUEST_ID, captured)); + ExecutorService attempts = Executors.newFixedThreadPool(2); + try { + var first = attempts.submit(() -> fixture.acknowledge(captured, APPLIED_AT)); + var second = attempts.submit(() -> fixture.acknowledge(captured, APPLIED_AT)); + + Acknowledgment firstResult = first.get(30, TimeUnit.SECONDS); + Acknowledgment secondResult = second.get(30, TimeUnit.SECONDS); + + assertThat(firstResult.acknowledgmentId()).isEqualTo(secondResult.acknowledgmentId()); + assertThat(fixture.store().get().acknowledgmentId()) + .isEqualTo(firstResult.acknowledgmentId()); + verify(fixture.repository(), times(1)).insert(any(Acknowledgment.class)); + } finally { + attempts.shutdownNow(); + } + } + + @Test + void changedProjectionBytesConflictWithoutReplacingCommittedAcknowledgment() { + IssuerAuthoritySnapshot captured = baseline(); + Fixture fixture = fixture(captured, capture(OPERATION_ID, REQUEST_ID, captured)); + fixture.acknowledge(captured, APPLIED_AT); + + assertThatThrownBy(() -> fixture.acknowledge(captured, APPLIED_AT + " ")) + .isInstanceOf( + AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException.class) + .hasMessageContaining("changed projection bytes"); + + verify(fixture.repository(), times(1)).insert(any(Acknowledgment.class)); + } + + @Test + void changedCaptureOperationAndDigestConflictBeforeInsert() { + IssuerAuthoritySnapshot captured = baseline(); + Fixture fixture = fixture(captured, capture(OPERATION_ID, REQUEST_ID, captured)); + + assertThatThrownBy( + () -> + fixture + .service() + .acknowledge( + ISSUER_ID, + GAME_SESSION_ID, + OTHER_OPERATION_ID, + REQUEST_ID, + 1, + Receipt.requestDigestFor( + ISSUER_ID, GAME_SESSION_ID, PROJECTION_KEY, REQUEST_ID), + projectionJson(captured, APPLIED_AT))) + .isInstanceOf( + AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException.class) + .hasMessageContaining("original capture binding"); + + verify(fixture.repository(), never()).insert(any(Acknowledgment.class)); + + Fixture changedDigest = fixture(captured, capture(OPERATION_ID, REQUEST_ID, captured)); + assertThatThrownBy( + () -> + changedDigest + .service() + .acknowledge( + ISSUER_ID, + GAME_SESSION_ID, + OPERATION_ID, + REQUEST_ID, + 1, + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + projectionJson(captured, APPLIED_AT))) + .isInstanceOf( + AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException.class) + .hasMessageContaining("original capture binding"); + verify(changedDigest.repository(), never()).insert(any(Acknowledgment.class)); + } + + @Test + void rejectsWrongCallerAndMissingCaptureBeforeAcknowledgmentInsert() { + Fixture wrongCaller = fixture(baseline(), capture(OPERATION_ID, REQUEST_ID, baseline())); + assertThatThrownBy( + () -> + wrongCaller + .service() + .acknowledge( + ISSUER_ID, + OTHER_GAME_SESSION_ID, + OPERATION_ID, + REQUEST_ID, + 1, + captureDigest(), + projectionJson(baseline(), APPLIED_AT))) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("exact authenticated Game Session"); + verifyNoInteractions( + wrongCaller.source(), wrongCaller.captureRepository(), wrongCaller.repository()); + + Fixture missingCapture = fixture(baseline(), null); + when(missingCapture.captureRepository().findByIssuerAndRequestId(ISSUER_ID, REQUEST_ID)) + .thenReturn(Optional.empty()); + assertThatThrownBy(() -> missingCapture.acknowledge(baseline(), APPLIED_AT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("missing capture"); + verify(missingCapture.repository(), never()).insert(any(Acknowledgment.class)); + } + + @Test + void staleFirstAcknowledgmentAndCompleteProjectionMismatchFailBeforeInsert() { + IssuerAuthoritySnapshot captured = baseline(); + IssuerGenerationAuthorityEvent advancedEvent = event(UUID.randomUUID(), 1L, 2L, 2L); + IssuerAuthoritySnapshot advanced = snapshot(2L, 2L, 1L, advancedEvent); + Fixture stale = fixture(advanced, capture(OPERATION_ID, REQUEST_ID, captured)); + assertThatThrownBy(() -> stale.acknowledge(captured, APPLIED_AT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires the captured source to remain current"); + verify(stale.repository(), never()).insert(any(Acknowledgment.class)); + + IssuerGenerationAuthorityEvent capturedEvent = event(REQUEST_ID, 1L, 2L, 2L); + IssuerAuthoritySnapshot positive = snapshot(2L, 2L, 1L, capturedEvent); + IssuerGenerationAuthorityEvent otherEvent = event(UUID.randomUUID(), 2L, 3L, 3L); + IssuerAuthoritySnapshot differentCheckpoint = snapshot(3L, 3L, 2L, otherEvent); + Fixture mismatch = fixture(positive, capture(OPERATION_ID, REQUEST_ID, positive)); + assertThatThrownBy(() -> mismatch.acknowledge(differentCheckpoint, APPLIED_AT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not exactly match the captured checkpoint"); + verify(mismatch.repository(), never()).insert(any(Acknowledgment.class)); + } + + @Test + void refusesAmbientTransactionBeforeReadingSourceOrAcknowledgment() { + Fixture fixture = fixture(baseline(), capture(OPERATION_ID, REQUEST_ID, baseline())); + boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> fixture.acknowledge(baseline(), APPLIED_AT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient transaction"); + verifyNoInteractions(fixture.source(), fixture.captureRepository(), fixture.repository()); + verifyNoInteractions(fixture.transactions()); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(wasActive); + } + } + + @Test + void requestDigestUsesTheExactTenUtf8FramedSegmentsAndProjectionBytes() throws Exception { + String projection = projectionJson(baseline(), "2026-10-03T00:00:00Z-ä"); + String digest = + Acknowledgment.requestDigestFor( + ISSUER_ID, + "spiffe://firemud/ns/ä/sa/game-session-service", + PROJECTION_KEY, + OPERATION_ID, + REQUEST_ID, + 1, + captureDigest(), + projection); + + assertThat(digest) + .isEqualTo( + independentDigest( + "issuer-projection-installation-ack/v1", + "ISSUER_PROJECTION_INSTALLATION_ACK", + ISSUER_ID, + "spiffe://firemud/ns/ä/sa/game-session-service", + PROJECTION_KEY, + OPERATION_ID.toString(), + REQUEST_ID.toString(), + "1", + captureDigest(), + projection)); + assertThat(digest) + .isNotEqualTo( + Acknowledgment.requestDigestFor( + ISSUER_ID, + "spiffe://firemud/ns/ä/sa/game-session-service", + PROJECTION_KEY, + OPERATION_ID, + REQUEST_ID, + 1, + captureDigest(), + projection + " ")); + } + + @Test + void repositoryRejectsMissingDslBeforeReadOrInsertSqlAccess() { + AccountIssuerProjectionAcknowledgmentRepository repository = + new AccountIssuerProjectionAcknowledgmentRepository(null); + boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> repository.findByCaptureOperationId(OPERATION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires a DSLContext"); + assertThatThrownBy(() -> repository.insert(validAcknowledgment(baseline()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires a DSLContext"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(wasActive); + } + } + + private static Fixture fixture(IssuerAuthoritySnapshot current, Receipt capture) { + AccountIssuerAuthorityEventProducer source = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationRepository captureRepository = + mock(AccountIssuerProjectionReconciliationRepository.class); + AccountIssuerProjectionAcknowledgmentRepository repository = + mock(AccountIssuerProjectionAcknowledgmentRepository.class); + PlatformTransactionManager transactions = transactionManager(); + when(source.readCurrentForProjectionReconciliation(ISSUER_ID)) + .thenAnswer(invocation -> current); + when(captureRepository.findByIssuerAndRequestId(ISSUER_ID, REQUEST_ID)) + .thenReturn(Optional.ofNullable(capture)); + AtomicReference stored = new AtomicReference<>(); + when(repository.findByCaptureOperationId(OPERATION_ID)) + .thenAnswer(invocation -> Optional.ofNullable(stored.get())); + when(repository.insert(any(Acknowledgment.class))) + .thenAnswer( + invocation -> { + Acknowledgment candidate = invocation.getArgument(0); + stored.set(candidate); + return candidate; + }); + AccountIssuerProjectionReconciliationService captureService = + new AccountIssuerProjectionReconciliationService( + ISSUER_ID, GAME_SESSION_ID, source, captureRepository, transactions); + AccountIssuerProjectionAcknowledgmentService service = + new AccountIssuerProjectionAcknowledgmentService( + ISSUER_ID, GAME_SESSION_ID, captureService, repository, transactions); + return new Fixture(service, source, captureRepository, repository, transactions, stored); + } + + private static PlatformTransactionManager transactionManager() { + PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + ReentrantLock transactionLock = new ReentrantLock(); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer( + invocation -> { + transactionLock.lock(); + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + }); + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(false); + transactionLock.unlock(); + return null; + }) + .when(transactions) + .commit(any()); + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(false); + transactionLock.unlock(); + return null; + }) + .when(transactions) + .rollback(any()); + return transactions; + } + + private static Acknowledgment validAcknowledgment(IssuerAuthoritySnapshot captured) { + byte[] projection = projectionJson(captured, APPLIED_AT).getBytes(StandardCharsets.UTF_8); + String requestDigest = + Acknowledgment.requestDigestFor( + ISSUER_ID, + GAME_SESSION_ID, + PROJECTION_KEY, + OPERATION_ID, + REQUEST_ID, + 1, + captureDigest(), + projectionJson(captured, APPLIED_AT)); + return new Acknowledgment( + OTHER_OPERATION_ID, + OPERATION_ID, + REQUEST_ID, + ISSUER_ID, + GAME_SESSION_ID, + PROJECTION_KEY, + 1, + captureDigest(), + 1, + requestDigest, + projection, + sha256(projection)); + } + + private static Receipt capture( + UUID operationId, UUID requestId, IssuerAuthoritySnapshot captured) { + return new Receipt( + operationId, + requestId, + ISSUER_ID, + GAME_SESSION_ID, + PROJECTION_KEY, + 1, + Receipt.requestDigestFor(ISSUER_ID, GAME_SESSION_ID, PROJECTION_KEY, requestId), + captured); + } + + private static String captureDigest() { + return Receipt.requestDigestFor(ISSUER_ID, GAME_SESSION_ID, PROJECTION_KEY, REQUEST_ID); + } + + private static IssuerAuthoritySnapshot baseline() { + return new IssuerAuthoritySnapshot(ISSUER_ID, 1L, 1L, STREAM_KEY, 0L, Optional.empty()); + } + + private static IssuerAuthoritySnapshot snapshot( + long generation, long sourceVersion, long sequence, IssuerGenerationAuthorityEvent event) { + return new IssuerAuthoritySnapshot( + ISSUER_ID, generation, sourceVersion, STREAM_KEY, sequence, Optional.of(event)); + } + + private static IssuerGenerationAuthorityEvent event( + UUID requestId, long sequence, long generation, long sourceVersion) { + String request = requestId.toString(); + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + "account-issuer-authority-event-v1:" + request, + "requestId", + request, + "issuerId", + ISSUER_ID, + "sourceScope", + "issuer/" + ISSUER_ID, + "outboxStreamKey", + STREAM_KEY, + "outboxSequence", + Long.toString(sequence), + "issuerAuthGeneration", + Long.toString(generation), + "sourceVersion", + Long.toString(sourceVersion))); + } + + private static String projectionJson(IssuerAuthoritySnapshot source, String appliedAt) { + Map projection = new LinkedHashMap<>(); + projection.put("schemaVersion", "game-session-auth-issuer-projection/v1"); + projection.put("issuerId", source.issuerId()); + projection.put("lastAppliedIssuerGeneration", Long.toString(source.issuerAuthGeneration())); + projection.put("lastAppliedSourceOutboxSequence", Long.toString(source.outboxSequence())); + projection.put("outboxStreamKey", source.outboxStreamKey()); + if (source.latestEvent().isPresent()) { + IssuerGenerationAuthorityEvent event = source.latestEvent().orElseThrow(); + projection.put("lastAppliedSourceEventId", event.eventId()); + projection.put("lastAppliedSourceEventDigest", event.eventDigest()); + projection.put( + "appliedSourceEvidence", + Map.of(Long.toString(source.outboxSequence()), event.canonicalJson())); + } else { + projection.put("appliedSourceEvidence", Map.of()); + } + projection.put("appliedAt", appliedAt); + return writeJson(projection); + } + + private static String writeJson(Map value) { + try { + return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(value); + } catch (com.fasterxml.jackson.core.JsonProcessingException failure) { + throw new IllegalStateException( + "Issuer projection test fixture could not be serialized", failure); + } + } + + private static String independentDigest(String... fields) throws Exception { + ByteArrayOutputStream framed = new ByteArrayOutputStream(); + for (String field : fields) { + byte[] encoded = field.getBytes(StandardCharsets.UTF_8); + framed.write(Integer.toString(encoded.length).getBytes(StandardCharsets.US_ASCII)); + framed.write(':'); + framed.write(encoded); + } + return java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(framed.toByteArray())); + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private record Fixture( + AccountIssuerProjectionAcknowledgmentService service, + AccountIssuerAuthorityEventProducer source, + AccountIssuerProjectionReconciliationRepository captureRepository, + AccountIssuerProjectionAcknowledgmentRepository repository, + PlatformTransactionManager transactions, + AtomicReference stored) { + private Acknowledgment acknowledge(IssuerAuthoritySnapshot captured, String appliedAt) { + return service.acknowledge( + ISSUER_ID, + GAME_SESSION_ID, + OPERATION_ID, + REQUEST_ID, + 1, + captureDigest(), + projectionJson(captured, appliedAt)); + } + + private AtomicReference store() { + return stored; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionReconciliationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionReconciliationServiceTest.java new file mode 100644 index 0000000000..c05de60e5d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerProjectionReconciliationServiceTest.java @@ -0,0 +1,341 @@ +package 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.Mockito.doNothing; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository.Receipt; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +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 AccountIssuerProjectionReconciliationServiceTest { + private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String OTHER_ISSUER_ID = "https://other.example.test/issuer"; + private static final String GAME_SESSION_ID = + "spiffe://firemud/ns/account-unit/sa/game-session-service"; + private static final String OTHER_GAME_SESSION_ID = + "spiffe://firemud/ns/other-unit/sa/game-session-service"; + private static final String STREAM_KEY = "account:auth-authority:v1:issuer/" + ISSUER_ID; + private static final String PROJECTION_KEY = + "session:game:auth:issuer-generation:v1:" + ISSUER_ID; + private static final UUID REQUEST_ID = UUID.fromString("a3a69671-8149-4d97-86f8-25a2582fdd68"); + private static final UUID OPERATION_ID = UUID.fromString("91b0eb2d-f7b1-4d88-8db4-2b81cacfc96a"); + + @Test + void capturesPristineBaselineAndReturnsOnlyAfterSeparateExactPostCommitReadback() { + AccountIssuerAuthorityEventProducer source = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationRepository repository = + mock(AccountIssuerProjectionReconciliationRepository.class); + PlatformTransactionManager transactions = transactionManager(); + IssuerAuthoritySnapshot baseline = baseline(); + AtomicReference stored = new AtomicReference<>(); + when(source.readCurrentForProjectionReconciliation(ISSUER_ID)).thenReturn(baseline, baseline); + when(repository.findByIssuerAndRequestId(ISSUER_ID, REQUEST_ID)) + .thenAnswer(invocation -> Optional.ofNullable(stored.get())); + when(repository.insert(any(Receipt.class))) + .thenAnswer( + invocation -> { + Receipt candidate = invocation.getArgument(0); + stored.set(candidate); + return candidate; + }); + + Receipt receipt = + service(source, repository, transactions).capture(ISSUER_ID, GAME_SESSION_ID, REQUEST_ID); + + assertThat(receipt.operationId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(receipt.requestId()).isEqualTo(REQUEST_ID); + assertThat(receipt.issuerId()).isEqualTo(ISSUER_ID); + assertThat(receipt.callerWorkloadIdentity()).isEqualTo(GAME_SESSION_ID); + assertThat(receipt.projectionKey()).isEqualTo(PROJECTION_KEY); + assertThat(receipt.requestDigestVersion()).isEqualTo(1); + assertThat(receipt.requestDigest()).matches("[0-9a-f]{64}"); + assertThat(receipt.capturedSource()).isEqualTo(baseline); + verify(transactions, times(2)).getTransaction(any(TransactionDefinition.class)); + verify(transactions, times(2)).commit(any()); + verify(repository, times(1)).insert(any(Receipt.class)); + verify(source, times(2)).readCurrentForProjectionReconciliation(ISSUER_ID); + verify(source, never()).advance(anyString(), any(), anyLong(), anyLong()); + var order = inOrder(source, repository); + order.verify(source).readCurrentForProjectionReconciliation(ISSUER_ID); + order.verify(repository).findByIssuerAndRequestId(ISSUER_ID, REQUEST_ID); + } + + @Test + void exactRetryReturnsOriginalPositiveSnapshotAfterSourceHasAdvanced() { + AccountIssuerAuthorityEventProducer source = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationRepository repository = + mock(AccountIssuerProjectionReconciliationRepository.class); + PlatformTransactionManager transactions = transactionManager(); + IssuerGenerationAuthorityEvent capturedEvent = event(REQUEST_ID, 1L, 2L, 2L); + IssuerAuthoritySnapshot captured = + new IssuerAuthoritySnapshot(ISSUER_ID, 2L, 2L, STREAM_KEY, 1L, Optional.of(capturedEvent)); + IssuerGenerationAuthorityEvent laterEvent = event(UUID.randomUUID(), 2L, 3L, 3L); + IssuerAuthoritySnapshot current = + new IssuerAuthoritySnapshot(ISSUER_ID, 3L, 3L, STREAM_KEY, 2L, Optional.of(laterEvent)); + Receipt original = receipt(OPERATION_ID, REQUEST_ID, GAME_SESSION_ID, captured); + when(source.readCurrentForProjectionReconciliation(ISSUER_ID)).thenReturn(current, current); + when(source.readCommittedEventForProjectionReconciliation(ISSUER_ID, 1L)) + .thenReturn( + new IssuerAuthorityEventReadback(current, capturedEvent), + new IssuerAuthorityEventReadback(current, capturedEvent)); + when(repository.findByIssuerAndRequestId(ISSUER_ID, REQUEST_ID)) + .thenReturn(Optional.of(original), Optional.of(original)); + + Receipt recovered = + service(source, repository, transactions).capture(ISSUER_ID, GAME_SESSION_ID, REQUEST_ID); + + assertThat(recovered.operationId()).isEqualTo(OPERATION_ID); + assertThat(recovered.capturedSource()).isEqualTo(captured); + verify(repository, never()).insert(any(Receipt.class)); + verify(source, times(2)).readCurrentForProjectionReconciliation(ISSUER_ID); + verify(source, times(2)).readCommittedEventForProjectionReconciliation(ISSUER_ID, 1L); + verify(source, never()).advance(anyString(), any(), anyLong(), anyLong()); + } + + @Test + void changedOriginalCallerBindingConflictsWithoutReceiptReplacementOrSourceMutation() { + AccountIssuerAuthorityEventProducer source = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationRepository repository = + mock(AccountIssuerProjectionReconciliationRepository.class); + PlatformTransactionManager transactions = transactionManager(); + IssuerAuthoritySnapshot current = baseline(); + Receipt prior = receipt(OPERATION_ID, REQUEST_ID, OTHER_GAME_SESSION_ID, current); + when(source.readCurrentForProjectionReconciliation(ISSUER_ID)).thenReturn(current); + when(repository.findByIssuerAndRequestId(ISSUER_ID, REQUEST_ID)).thenReturn(Optional.of(prior)); + + assertThatThrownBy( + () -> + service(source, repository, transactions) + .capture(ISSUER_ID, GAME_SESSION_ID, REQUEST_ID)) + .isInstanceOf( + AccountIssuerProjectionReconciliationRepository.IdempotencyConflictException.class) + .hasMessageContaining("changed caller or projection bindings"); + + verify(repository, never()).insert(any(Receipt.class)); + verify(source, never()).readCommittedEventForProjectionReconciliation(anyString(), anyLong()); + verify(source, never()).advance(anyString(), any(), anyLong(), anyLong()); + verify(transactions, never()).commit(any()); + verify(transactions, times(1)).rollback(any()); + } + + @Test + void nilRequestWrongIssuerAndWrongCallerFailBeforeTransactionsOrOwnerAccess() { + AccountIssuerAuthorityEventProducer source = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationRepository repository = + mock(AccountIssuerProjectionReconciliationRepository.class); + PlatformTransactionManager transactions = transactionManager(); + AccountIssuerProjectionReconciliationService service = + service(source, repository, transactions); + + assertThatThrownBy(() -> service.capture(ISSUER_ID, GAME_SESSION_ID, new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + assertThatThrownBy(() -> service.capture(OTHER_ISSUER_ID, GAME_SESSION_ID, REQUEST_ID)) + .isInstanceOf(AccountIssuerAuthorityEventProducer.IssuerMismatchException.class); + assertThatThrownBy(() -> service.capture(ISSUER_ID, OTHER_GAME_SESSION_ID, REQUEST_ID)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("exact authenticated Game Session"); + + verifyNoInteractions(source, repository, transactions); + } + + @Test + void missingPostCommitReceiptReadbackFailsClosedAfterInsert() { + AccountIssuerAuthorityEventProducer source = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationRepository repository = + mock(AccountIssuerProjectionReconciliationRepository.class); + PlatformTransactionManager transactions = transactionManager(); + IssuerAuthoritySnapshot baseline = baseline(); + AtomicReference stored = new AtomicReference<>(); + AtomicInteger lookup = new AtomicInteger(); + when(source.readCurrentForProjectionReconciliation(ISSUER_ID)).thenReturn(baseline, baseline); + when(repository.findByIssuerAndRequestId(ISSUER_ID, REQUEST_ID)) + .thenAnswer( + invocation -> + lookup.incrementAndGet() < 3 + ? Optional.ofNullable(stored.get()) + : Optional.empty()); + when(repository.insert(any(Receipt.class))) + .thenAnswer( + invocation -> { + Receipt candidate = invocation.getArgument(0); + stored.set(candidate); + return candidate; + }); + + assertThatThrownBy( + () -> + service(source, repository, transactions) + .capture(ISSUER_ID, GAME_SESSION_ID, REQUEST_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Post-commit issuer reconciliation receipt readback is missing"); + + verify(repository, times(1)).insert(any(Receipt.class)); + verify(transactions, times(1)).commit(any()); + verify(transactions, times(1)).rollback(any()); + } + + @Test + void ambientTransactionIsRefusedBeforeSourceOrReceiptAccess() { + AccountIssuerAuthorityEventProducer source = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationRepository repository = + mock(AccountIssuerProjectionReconciliationRepository.class); + PlatformTransactionManager transactions = transactionManager(); + boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + service(source, repository, transactions) + .capture(ISSUER_ID, GAME_SESSION_ID, REQUEST_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient transaction"); + verifyNoInteractions(source, repository, transactions); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(wasActive); + } + } + + @Test + void repositoryRejectsMissingDslBeforeBothReadAndInsertSqlAccess() { + AccountIssuerProjectionReconciliationRepository repository = + new AccountIssuerProjectionReconciliationRepository(null); + Receipt validReceipt = receipt(OPERATION_ID, REQUEST_ID, GAME_SESSION_ID, baseline()); + boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> repository.findByIssuerAndRequestId(ISSUER_ID, REQUEST_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires a DSLContext"); + assertThatThrownBy(() -> repository.insert(validReceipt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires a DSLContext"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(wasActive); + } + } + + @Test + void requestDigestUsesTheFixedVersionedSixFieldUtf8ByteFraming() throws Exception { + assertThat(Receipt.requestDigestFor(ISSUER_ID, GAME_SESSION_ID, PROJECTION_KEY, REQUEST_ID)) + .isEqualTo("240027543295dc990703ec833578b423f1cdc51e91333d8b58c91d6c5f571d15"); + + String unicodeCaller = "spiffe://firemud/ns/ä/sa/game-session-service"; + String digest = Receipt.requestDigestFor(ISSUER_ID, unicodeCaller, PROJECTION_KEY, REQUEST_ID); + String expected = + independentDigest( + "issuer-projection-reconciliation-request/v1", + "ISSUER_PROJECTION_SNAPSHOT_CAPTURE", + ISSUER_ID, + unicodeCaller, + PROJECTION_KEY, + REQUEST_ID.toString()); + + assertThat(digest).isEqualTo(expected); + assertThat(digest) + .isNotEqualTo( + Receipt.requestDigestFor(ISSUER_ID, GAME_SESSION_ID, PROJECTION_KEY, REQUEST_ID)); + } + + private static String independentDigest(String... fields) throws Exception { + java.io.ByteArrayOutputStream framed = new java.io.ByteArrayOutputStream(); + for (String field : fields) { + byte[] encoded = field.getBytes(StandardCharsets.UTF_8); + framed.write(Integer.toString(encoded.length).getBytes(StandardCharsets.US_ASCII)); + framed.write(':'); + framed.write(encoded); + } + return java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(framed.toByteArray())); + } + + private static IssuerAuthoritySnapshot baseline() { + return new IssuerAuthoritySnapshot(ISSUER_ID, 1L, 1L, STREAM_KEY, 0L, Optional.empty()); + } + + private static IssuerGenerationAuthorityEvent event( + UUID requestId, long sequence, long generation, long sourceVersion) { + String request = requestId.toString(); + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + "account-issuer-authority-event-v1:" + request, + "requestId", + request, + "issuerId", + ISSUER_ID, + "sourceScope", + "issuer/" + ISSUER_ID, + "outboxStreamKey", + STREAM_KEY, + "outboxSequence", + Long.toString(sequence), + "issuerAuthGeneration", + Long.toString(generation), + "sourceVersion", + Long.toString(sourceVersion))); + } + + private static Receipt receipt( + UUID operationId, + UUID requestId, + String callerIdentity, + IssuerAuthoritySnapshot capturedSource) { + return new Receipt( + operationId, + requestId, + ISSUER_ID, + callerIdentity, + PROJECTION_KEY, + 1, + Receipt.requestDigestFor(ISSUER_ID, callerIdentity, PROJECTION_KEY, requestId), + capturedSource); + } + + private static AccountIssuerProjectionReconciliationService service( + AccountIssuerAuthorityEventProducer source, + AccountIssuerProjectionReconciliationRepository repository, + PlatformTransactionManager transactions) { + return new AccountIssuerProjectionReconciliationService( + ISSUER_ID, GAME_SESSION_ID, source, repository, transactions); + } + + private static PlatformTransactionManager transactionManager() { + PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(invocation -> new SimpleTransactionStatus()); + doNothing().when(transactions).commit(any()); + doNothing().when(transactions).rollback(any()); + return transactions; + } +} 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 90e1c8b826..66f4a71ec8 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 @@ -202,4 +202,59 @@ void existingPositiveSnapshotRequiresOwnerTransactionBeforeIdentityReads() { membershipRepository, roleSnapshotRepository); } + + @Test + void existingRuntimeSnapshotRequiresOwnerTransactionBeforeIdentityReads() { + AccountJoinOperationRepository joinOperationRepository = + mock(AccountJoinOperationRepository.class); + AccountMembershipPairAuthorityRepository pairAuthorityRepository = + mock(AccountMembershipPairAuthorityRepository.class); + AccountRepository accountRepository = mock(AccountRepository.class); + AccountTenantIdentityResolver tenantIdentityResolver = + mock(AccountTenantIdentityResolver.class); + FreshTenantIdentityAssociationRepository freshAssociationRepository = + mock(FreshTenantIdentityAssociationRepository.class); + AccountAuthorityGenerationRepository authorityGenerationRepository = + mock(AccountAuthorityGenerationRepository.class); + AccountAuthorityOutboxRepository authorityOutboxRepository = + mock(AccountAuthorityOutboxRepository.class); + AccountMembershipTransitionReceiptRepository transitionReceiptRepository = + mock(AccountMembershipTransitionReceiptRepository.class); + AccountTenantMembershipRepository membershipRepository = + mock(AccountTenantMembershipRepository.class); + AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + AccountMembershipAuthorityEventProducer producer = + new AccountMembershipAuthorityEventProducer( + joinOperationRepository, + pairAuthorityRepository, + accountRepository, + tenantIdentityResolver, + freshAssociationRepository, + authorityGenerationRepository, + authorityOutboxRepository, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), + transitionReceiptRepository, + membershipRepository, + roleSnapshotRepository); + + assertThatThrownBy( + () -> + producer.readExistingRuntimeMembershipSnapshot( + UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + verifyNoInteractions( + joinOperationRepository, + pairAuthorityRepository, + accountRepository, + tenantIdentityResolver, + freshAssociationRepository, + authorityGenerationRepository, + authorityOutboxRepository, + transitionReceiptRepository, + membershipRepository, + roleSnapshotRepository); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipSourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipSourceReaderTest.java new file mode 100644 index 0000000000..29d77e9fee --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipSourceReaderTest.java @@ -0,0 +1,287 @@ +package 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.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto.MembershipBaseline; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import 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.TransactionSynchronizationManager; + +class AccountMembershipSourceReaderTest { + private static final UUID ACCOUNT_ID = UUID.fromString("6d39b28e-3ef4-44a7-8479-19672a9663c4"); + private static final UUID TENANT_ID = UUID.fromString("a039b28e-3ef4-44a7-8479-19672a9663c4"); + + @Test + void readsStrictMembershipSnapshotAndIndependentSourceCountersInOwnedTransaction() { + AccountMembershipAuthorityEventProducer membershipProducer = + mock(AccountMembershipAuthorityEventProducer.class); + AccountAuthorityGenerationRepository generationRepository = + mock(AccountAuthorityGenerationRepository.class); + PlatformTransactionManager transactionManager = transactionManager(); + RuntimeMembershipSnapshotDto membership = membershipSnapshot(ACCOUNT_ID, TENANT_ID, "8", "3"); + ScopeState sourceState = + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), + 3L, + 9L, + new IssuanceFence(ACCOUNT_ID, 2L, 11L)); + when(membershipProducer.readExistingRuntimeMembershipSnapshot(ACCOUNT_ID, TENANT_ID)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return membership; + }); + when(generationRepository.read(AuthorityScope.membership(ACCOUNT_ID, TENANT_ID))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return sourceState; + }); + + AccountMembershipSourceReader reader = + new AccountMembershipSourceReader( + membershipProducer, generationRepository, transactionManager); + + AccountMembershipSourceReader.MembershipSourceSnapshot result = + reader.readCurrent(ACCOUNT_ID, TENANT_ID); + + assertThat(result.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(result.tenantId()).isEqualTo(TENANT_ID); + assertThat(result.snapshot()).isSameAs(membership); + assertThat(result.snapshot().membershipBaseline().membershipVersion()) + .isEqualTo(Map.of(TENANT_ID.toString(), "8")); + assertThat(result.sourceState().generation()).isEqualTo(3L); + assertThat(result.sourceState().sourceVersion()).isEqualTo(9L); + assertThat(result.sourceState().issuanceFence().sourceVersion()).isEqualTo(11L); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + verify(membershipProducer).readExistingRuntimeMembershipSnapshot(ACCOUNT_ID, TENANT_ID); + verify(generationRepository).read(AuthorityScope.membership(ACCOUNT_ID, TENANT_ID)); + } + + @Test + void rejectsAmbientTransactionBeforeCallingOwnerCollaborators() { + AccountMembershipAuthorityEventProducer membershipProducer = + mock(AccountMembershipAuthorityEventProducer.class); + AccountAuthorityGenerationRepository generationRepository = + mock(AccountAuthorityGenerationRepository.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + AccountMembershipSourceReader reader = + new AccountMembershipSourceReader( + membershipProducer, generationRepository, transactionManager); + boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + try { + assertThatThrownBy(() -> reader.readCurrent(ACCOUNT_ID, TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot join an ambient transaction"); + verifyNoInteractions(membershipProducer, generationRepository, transactionManager); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previouslyActive); + } + } + + @Test + void rejectsNilIdentityBeforeOpeningTransactionOrReadingSource() { + AccountMembershipAuthorityEventProducer membershipProducer = + mock(AccountMembershipAuthorityEventProducer.class); + AccountAuthorityGenerationRepository generationRepository = + mock(AccountAuthorityGenerationRepository.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + AccountMembershipSourceReader reader = + new AccountMembershipSourceReader( + membershipProducer, generationRepository, transactionManager); + + assertThatThrownBy(() -> reader.readCurrent(new UUID(0L, 0L), TENANT_ID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + verifyNoInteractions(membershipProducer, generationRepository, transactionManager); + } + + @Test + void rejectsSourceStateForDifferentAccountTenantPair() { + RuntimeMembershipSnapshotDto membership = membershipSnapshot(ACCOUNT_ID, TENANT_ID, "8", "3"); + ScopeState sourceState = + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, UUID.randomUUID()), + 3L, + 9L, + new IssuanceFence(ACCOUNT_ID, 2L, 11L)); + + assertThatThrownBy( + () -> + new AccountMembershipSourceReader.MembershipSourceSnapshot( + ACCOUNT_ID, TENANT_ID, membership, sourceState)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact scope"); + } + + @Test + void rejectsMembershipGenerationThatDiffersFromTheOneTenantSnapshot() { + RuntimeMembershipSnapshotDto membership = membershipSnapshot(ACCOUNT_ID, TENANT_ID, "8", "4"); + ScopeState sourceState = + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), + 3L, + 9L, + new IssuanceFence(ACCOUNT_ID, 2L, 11L)); + + assertThatThrownBy( + () -> + new AccountMembershipSourceReader.MembershipSourceSnapshot( + ACCOUNT_ID, TENANT_ID, membership, sourceState)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("version map or generation"); + } + + @Test + void rejectsSnapshotWithAnotherCanonicalIdentityOrMembershipVersionKey() { + RuntimeMembershipSnapshotDto wrongIdentity = + membershipSnapshot(UUID.randomUUID(), TENANT_ID, "8", "3"); + ScopeState sourceState = + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), + 3L, + 9L, + new IssuanceFence(ACCOUNT_ID, 2L, 11L)); + + assertThatThrownBy( + () -> + new AccountMembershipSourceReader.MembershipSourceSnapshot( + ACCOUNT_ID, TENANT_ID, wrongIdentity, sourceState)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact Account/tenant source scope"); + + RuntimeMembershipSnapshotDto wrongVersionKey = mock(RuntimeMembershipSnapshotDto.class); + when(wrongVersionKey.accountUuid()).thenReturn(ACCOUNT_ID.toString()); + when(wrongVersionKey.tenantUuid()).thenReturn(TENANT_ID.toString()); + when(wrongVersionKey.requestAccountUuid()).thenReturn(ACCOUNT_ID.toString()); + when(wrongVersionKey.requestTenantUuid()).thenReturn(TENANT_ID.toString()); + when(wrongVersionKey.issuanceFence()).thenReturn("2"); + when(wrongVersionKey.membershipBaseline()) + .thenReturn( + new MembershipBaseline("ACTIVE", Map.of(UUID.randomUUID().toString(), "8"), "3")); + + assertThatThrownBy( + () -> + new AccountMembershipSourceReader.MembershipSourceSnapshot( + ACCOUNT_ID, TENANT_ID, wrongVersionKey, sourceState)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("version map or generation"); + } + + @Test + void rejectsIssuanceFenceFromAnotherAccountOrSnapshotFenceValue() { + RuntimeMembershipSnapshotDto membership = membershipSnapshot(ACCOUNT_ID, TENANT_ID, "8", "3"); + ScopeState wrongAccountFence = + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), + 3L, + 9L, + new IssuanceFence(UUID.randomUUID(), 2L, 11L)); + + assertThatThrownBy( + () -> + new AccountMembershipSourceReader.MembershipSourceSnapshot( + ACCOUNT_ID, TENANT_ID, membership, wrongAccountFence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("issuance fence"); + + RuntimeMembershipSnapshotDto wrongFenceValue = mock(RuntimeMembershipSnapshotDto.class); + when(wrongFenceValue.accountUuid()).thenReturn(ACCOUNT_ID.toString()); + when(wrongFenceValue.tenantUuid()).thenReturn(TENANT_ID.toString()); + when(wrongFenceValue.requestAccountUuid()).thenReturn(ACCOUNT_ID.toString()); + when(wrongFenceValue.requestTenantUuid()).thenReturn(TENANT_ID.toString()); + when(wrongFenceValue.issuanceFence()).thenReturn("3"); + when(wrongFenceValue.membershipBaseline()) + .thenReturn(new MembershipBaseline("ACTIVE", Map.of(TENANT_ID.toString(), "8"), "3")); + ScopeState matchingScope = + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), + 3L, + 9L, + new IssuanceFence(ACCOUNT_ID, 2L, 11L)); + + assertThatThrownBy( + () -> + new AccountMembershipSourceReader.MembershipSourceSnapshot( + ACCOUNT_ID, TENANT_ID, wrongFenceValue, matchingScope)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("issuance fence"); + } + + @Test + void rejectsMissingAccountIssuanceFence() { + RuntimeMembershipSnapshotDto membership = membershipSnapshot(ACCOUNT_ID, TENANT_ID, "8", "3"); + ScopeState sourceState = + new ScopeState(AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), 3L, 9L, null); + + assertThatThrownBy( + () -> + new AccountMembershipSourceReader.MembershipSourceSnapshot( + ACCOUNT_ID, TENANT_ID, membership, sourceState)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account issuance fence"); + } + + private static RuntimeMembershipSnapshotDto membershipSnapshot( + UUID accountId, UUID tenantId, String membershipVersion, String membershipGeneration) { + RuntimeMembershipSnapshotDto snapshot = mock(RuntimeMembershipSnapshotDto.class); + when(snapshot.accountUuid()).thenReturn(accountId.toString()); + when(snapshot.tenantUuid()).thenReturn(tenantId.toString()); + when(snapshot.requestAccountUuid()).thenReturn(accountId.toString()); + when(snapshot.requestTenantUuid()).thenReturn(tenantId.toString()); + when(snapshot.issuanceFence()).thenReturn("2"); + when(snapshot.membershipBaseline()) + .thenReturn( + new MembershipBaseline( + "ACTIVE", Map.of(tenantId.toString(), membershipVersion), membershipGeneration)); + return snapshot; + } + + private static PlatformTransactionManager transactionManager() { + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + TransactionStatus transactionStatus = mock(TransactionStatus.class); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenAnswer( + invocation -> { + TransactionDefinition definition = invocation.getArgument(0); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + TransactionSynchronizationManager.setActualTransactionActive(true); + return transactionStatus; + }); + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(false); + return null; + }) + .when(transactionManager) + .commit(transactionStatus); + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(false); + return null; + }) + .when(transactionManager) + .rollback(transactionStatus); + return transactionManager; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/MembershipGenerationProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/MembershipGenerationProjectionTest.java new file mode 100644 index 0000000000..b00b3ff5a2 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/MembershipGenerationProjectionTest.java @@ -0,0 +1,417 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.math.BigInteger; +import java.time.Instant; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto.MembershipBaseline; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisContract; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountMembershipSourceReader.MembershipSourceSnapshot; +import net.firedevops.firemud.accountservice.service.MembershipGenerationProjection; +import net.firedevops.firemud.accountservice.service.MembershipGenerationProjectionRedisContract; +import net.firedevops.firemud.accountservice.service.TenantGenerationProjectionRedisContract; +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 org.junit.jupiter.api.Test; + +class MembershipGenerationProjectionTest { + private static final UUID ACCOUNT_ID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + private static final UUID TENANT_ID = UUID.fromString("10000000-0000-0000-0000-000000000001"); + private static final String ACCOUNT_TEXT = ACCOUNT_ID.toString(); + private static final String TENANT_TEXT = TENANT_ID.toString(); + private static final String KEY = + "session:auth:generation:membership:" + ACCOUNT_TEXT + ":" + TENANT_TEXT; + private static final String STREAM_KEY = + "account:auth-authority:v1:membership/" + ACCOUNT_TEXT + "/" + TENANT_TEXT; + + @Test + void emitsExactExistingSequenceZeroBaselineAndNoEventMirror() { + MembershipGenerationProjection projection = + MembershipGenerationProjection.fromSource(baselineSource(1L, 1L)); + + assertThat(projection.key()).isEqualTo(KEY); + assertThat(projection.toJson()) + .isEqualTo( + "{\"schemaVersion\":\"account-auth-membership-generation-projection/v1\"," + + "\"accountId\":\"" + + ACCOUNT_TEXT + + "\",\"tenantId\":\"" + + TENANT_TEXT + + "\",\"membershipAuthorityGeneration\":\"1\",\"sourceVersion\":\"1\"," + + "\"membershipVersion\":{\"" + + TENANT_TEXT + + "\":\"1\"},\"outboxStreamKey\":\"" + + STREAM_KEY + + "\",\"outboxSequence\":\"0\"}"); + assertThat(MembershipGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + assertThat(projection.toJson()).doesNotContain("sourceEvent"); + } + + @Test + void registersOnlyTheExactMembershipPairPrefixOnTheExistingCasScript() { + var descriptor = MembershipGenerationProjectionRedisContract.descriptor(); + + assertThat(descriptor.scriptId()).isEqualTo("account.membership-generation-projection.v1"); + assertThat(descriptor.resourcePath()) + .isEqualTo(AccountGenerationProjectionRedisContract.RESOURCE_PATH); + assertThat(descriptor.sha256()) + .isEqualTo(AccountGenerationProjectionRedisContract.descriptor().sha256()) + .isEqualTo(TenantGenerationProjectionRedisContract.descriptor().sha256()); + assertThat(descriptor.owner()).isEqualTo("account-service"); + assertThat(descriptor.principal()).isEqualTo("account_coord_app"); + assertThat(descriptor.keys()).hasSize(1); + assertThat(descriptor.keys().getFirst().ownedPrefix()) + .isEqualTo(MembershipGenerationProjection.KEY_PREFIX) + .isNotEqualTo(AccountGenerationProjectionRedisContract.KEY_PREFIX) + .isNotEqualTo(TenantGenerationProjectionRedisContract.KEY_PREFIX); + assertThat(descriptor.keys().getFirst().hashTagDeclaration().name()).isEqualTo("NOT_REQUIRED"); + } + + @Test + void storesWholeCanonicalMembershipEventAsStringWithIndependentCounters() throws Exception { + MembershipEvent event = membershipEvent("1", "2", "1"); + MembershipGenerationProjection projection = + MembershipGenerationProjection.fromSource(positiveSource(1L, 1L, 2L, 1L, event)); + MembershipGenerationProjection parsed = + MembershipGenerationProjection.parse(projection.toJson()); + + assertThat(parsed).isEqualTo(projection); + assertThat(parsed.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(parsed.sourceVersion()).isEqualTo("1"); + assertThat(parsed.membershipVersion()).isEqualTo(Map.of(TENANT_TEXT, "2")); + assertThat(parsed.outboxSequence()).isEqualTo("1"); + assertThat(parsed.sourceEvent()).contains(event.canonicalJson()); + assertThat(parsed.toJson()).contains("\"sourceEvent\":\"{"); + JsonNode projectionJson = new ObjectMapper().readTree(parsed.toJson()); + Set projectionFields = new HashSet<>(); + projectionJson.fieldNames().forEachRemaining(projectionFields::add); + assertThat(projectionFields) + .containsExactlyInAnyOrder( + "schemaVersion", + "accountId", + "tenantId", + "membershipAuthorityGeneration", + "sourceVersion", + "membershipVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent"); + assertThat(projectionJson.get("sourceEvent").isTextual()).isTrue(); + assertThat( + MembershipAuthorityEventV1Codec.verify(parsed.sourceEvent().orElseThrow()) + .canonicalJson()) + .isEqualTo(event.canonicalJson()); + } + + @Test + void preservesIndependentGenerationVersionAndSequenceAxesWithoutTenantArithmetic() { + MembershipEvent event = membershipEvent("9", "14", "6"); + MembershipGenerationProjection projection = + MembershipGenerationProjection.fromSource(positiveSource(9L, 31L, 14L, 6L, event)); + + assertThat(projection.generationValue()).isEqualTo(BigInteger.valueOf(9L)); + assertThat(projection.sourceVersionValue()).isEqualTo(BigInteger.valueOf(31L)); + assertThat(projection.membershipVersionValue()).isEqualTo(BigInteger.valueOf(14L)); + assertThat(projection.outboxSequenceValue()).isEqualTo(BigInteger.valueOf(6L)); + assertThat(MembershipGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + } + + @Test + void acceptsCanonicalCountersBeyondLongRange() { + String large = "922337203685477580812345678901234567890"; + MembershipEvent event = membershipEvent("9", "2", "6"); + MembershipGenerationProjection projection = + new MembershipGenerationProjection( + ACCOUNT_TEXT, + TENANT_TEXT, + "9", + large, + Map.of(TENANT_TEXT, "2"), + STREAM_KEY, + "6", + Optional.of(event.canonicalJson())); + + assertThat(projection.sourceVersionValue()).isEqualTo(new BigInteger(large)); + assertThat(MembershipGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + } + + @Test + void closesProjectionAndRejectsMalformedMapCountersAndJson() { + String baseline = MembershipGenerationProjection.fromSource(baselineSource(1L, 1L)).toJson(); + String duplicateAccount = + baseline.replace( + "\"accountId\":\"" + ACCOUNT_TEXT + "\"", + "\"accountId\":\"" + ACCOUNT_TEXT + "\",\"accountId\":\"" + ACCOUNT_TEXT + "\""); + String unknown = baseline.substring(0, baseline.length() - 1) + ",\"issuanceFence\":\"1\"}"; + String nullEvent = baseline.substring(0, baseline.length() - 1) + ",\"sourceEvent\":null}"; + String badSequence = baseline.replace("\"outboxSequence\":\"0\"", "\"outboxSequence\":\"00\""); + String wrongMapKey = + baseline.replace(TENANT_TEXT + "\":\"1", "10000000-0000-0000-0000-000000000002\":\"1"); + String trailing = baseline + " {}"; + + assertThatThrownBy(() -> MembershipGenerationProjection.parse(duplicateAccount)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> MembershipGenerationProjection.parse(unknown)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> MembershipGenerationProjection.parse(nullEvent)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> MembershipGenerationProjection.parse(badSequence)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> MembershipGenerationProjection.parse(wrongMapKey)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> MembershipGenerationProjection.parse(trailing)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new MembershipGenerationProjection( + ACCOUNT_TEXT, + TENANT_TEXT, + "1", + "1", + Map.of(TENANT_TEXT, "1", ACCOUNT_TEXT, "2"), + STREAM_KEY, + "0", + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresSequenceZeroToBeTheOriginalProvedBaseline() { + assertThatThrownBy( + () -> + new MembershipGenerationProjection( + ACCOUNT_TEXT, + TENANT_TEXT, + "2", + "1", + Map.of(TENANT_TEXT, "1"), + STREAM_KEY, + "0", + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence zero"); + assertThatThrownBy( + () -> + new MembershipGenerationProjection( + ACCOUNT_TEXT, + TENANT_TEXT, + "1", + "2", + Map.of(TENANT_TEXT, "1"), + STREAM_KEY, + "0", + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence zero"); + assertThatThrownBy( + () -> + new MembershipGenerationProjection( + ACCOUNT_TEXT, + TENANT_TEXT, + "1", + "1", + Map.of(TENANT_TEXT, "2"), + STREAM_KEY, + "0", + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence zero"); + } + + @Test + void rejectsEventIdentityCheckpointGenerationAndVersionDisagreement() { + String valid = membershipEvent("1", "2", "1").canonicalJson(); + String changedDigest = valid.replace("\"outboxSequence\":\"1\"", "\"outboxSequence\":\"2\""); + assertThatThrownBy( + () -> + new MembershipGenerationProjection( + ACCOUNT_TEXT, + TENANT_TEXT, + "1", + "13", + Map.of(TENANT_TEXT, "2"), + STREAM_KEY, + "1", + Optional.of(changedDigest))) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new MembershipGenerationProjection( + ACCOUNT_TEXT, + TENANT_TEXT, + "2", + "13", + Map.of(TENANT_TEXT, "2"), + STREAM_KEY, + "1", + Optional.of(valid))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("checkpoint"); + assertThatThrownBy( + () -> + new MembershipGenerationProjection( + ACCOUNT_TEXT, + TENANT_TEXT, + "1", + "13", + Map.of(TENANT_TEXT, "3"), + STREAM_KEY, + "1", + Optional.of(valid))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("checkpoint"); + assertThatThrownBy( + () -> + new MembershipGenerationProjection( + "00000000-0000-0000-0000-000000000000", + TENANT_TEXT, + "1", + "1", + Map.of(TENANT_TEXT, "1"), + STREAM_KEY, + "0", + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static MembershipSourceSnapshot baselineSource(long generation, long sourceVersion) { + RuntimeMembershipSnapshotDto snapshot = + new RuntimeMembershipSnapshotDto( + ACCOUNT_TEXT, + TENANT_TEXT, + ACCOUNT_TEXT, + TENANT_TEXT, + false, + false, + new MembershipBaseline("MISSING", Map.of(TENANT_TEXT, "1"), "1"), + List.of(), + tuple("1"), + "1", + Instant.parse("2026-10-01T00:00:00Z"), + List.of( + new OutboxCheckpointEntry("account:auth-authority:v1:account/" + ACCOUNT_TEXT, "0"), + new OutboxCheckpointEntry( + "account:auth-authority:v1:issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + "0"), + new OutboxCheckpointEntry(STREAM_KEY, "0"), + new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + TENANT_TEXT, "0")), + List.of(), + null); + return source(snapshot, generation, sourceVersion, 1L); + } + + private static MembershipSourceSnapshot positiveSource( + long generation, + long sourceVersion, + long membershipVersion, + long sequence, + MembershipEvent event) { + String generationText = Long.toString(generation); + String versionText = Long.toString(membershipVersion); + String sequenceText = Long.toString(sequence); + String stream = event.outboxStreamKey(); + RuntimeMembershipSnapshotDto snapshot = + new RuntimeMembershipSnapshotDto( + ACCOUNT_TEXT, + TENANT_TEXT, + ACCOUNT_TEXT, + TENANT_TEXT, + true, + true, + new MembershipBaseline("ACTIVE", Map.of(TENANT_TEXT, versionText), generationText), + List.of("player"), + tuple(generationText), + event.issuanceFence(), + Instant.parse("2026-10-01T00:00:00Z"), + List.of( + new OutboxCheckpointEntry("account:auth-authority:v1:account/" + ACCOUNT_TEXT, "0"), + new OutboxCheckpointEntry( + "account:auth-authority:v1:issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + "0"), + new OutboxCheckpointEntry(stream, sequenceText), + new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + TENANT_TEXT, "0")), + List.of( + new OutboxSourceEvidence( + stream, + sequenceText, + event.eventId(), + event.eventDigest(), + event.canonicalJson())), + event); + return source(snapshot, generation, sourceVersion, Long.parseLong(event.issuanceFence())); + } + + private static MembershipSourceSnapshot source( + RuntimeMembershipSnapshotDto snapshot, long generation, long sourceVersion, long fenceValue) { + return new MembershipSourceSnapshot( + ACCOUNT_ID, + TENANT_ID, + snapshot, + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), + generation, + sourceVersion, + new IssuanceFence(ACCOUNT_ID, fenceValue, 1L))); + } + + private static AuthorityTuple tuple(String membershipGeneration) { + return new AuthorityTuple( + "1", + "1", + Map.of(TENANT_TEXT, "1"), + Map.of(TENANT_TEXT, membershipGeneration), + List.of(), + Optional.empty(), + Optional.empty()); + } + + private static MembershipEvent membershipEvent( + String generation, String membershipVersion, String sequence) { + String eventId = "04ef66b4-c0ad-3d5b-b3b2-0e8510e72002"; + return MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", eventId), + Map.entry("requestId", "join-request-1"), + Map.entry("outboxStreamKey", STREAM_KEY), + Map.entry("outboxSequence", sequence), + Map.entry("sourceScope", "membership/" + ACCOUNT_TEXT + "/" + TENANT_TEXT), + Map.entry("accountId", ACCOUNT_TEXT), + Map.entry("tenantId", TENANT_TEXT), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(TENANT_TEXT, membershipVersion)), + Map.entry("membershipAuthorityGeneration", generation), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(TENANT_TEXT, "1"), + "membershipAuthorityGeneration", Map.of(TENANT_TEXT, generation), + "privateRealmGrantVersions", List.of())), + Map.entry("issuanceFence", "1"), + Map.entry("roles", List.of("player")), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisMembershipGenerationProjectionStoreTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisMembershipGenerationProjectionStoreTest.java new file mode 100644 index 0000000000..9dbcfda8fe --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisMembershipGenerationProjectionStoreTest.java @@ -0,0 +1,558 @@ +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.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto; +import net.firedevops.firemud.accountservice.dto.RuntimeMembershipSnapshotDto.MembershipBaseline; +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.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountMembershipSourceReader; +import net.firedevops.firemud.accountservice.service.AccountMembershipSourceReader.MembershipSourceSnapshot; +import net.firedevops.firemud.accountservice.service.MembershipGenerationProjection; +import net.firedevops.firemud.accountservice.service.RedisMembershipGenerationProjectionStore; +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 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 RedisMembershipGenerationProjectionStoreTest { + private static final String PASSWORD = "coordination-secret"; + private static final UUID ACCOUNT_ID = UUID.fromString("c980fa44-619e-4ca4-8ad6-75b0538a66a3"); + private static final UUID TENANT_ID = UUID.fromString("10000000-0000-0000-0000-000000000001"); + private static final String ACCOUNT_TEXT = ACCOUNT_ID.toString(); + private static final String TENANT_TEXT = TENANT_ID.toString(); + private static final String KEY = + "session:auth:generation:membership:" + ACCOUNT_TEXT + ":" + TENANT_TEXT; + private static final String STREAM_KEY = + "account:auth-authority:v1:membership/" + ACCOUNT_TEXT + "/" + TENANT_TEXT; + + @Test + void requiresAccountCoordinationPrincipalAndDistinctCacheEndpoint() { + assertThatThrownBy( + () -> + new RedisMembershipGenerationProjectionStore.CoordinationEndpoint( + "coordination.internal", 6379, "gamesession_coord_app", PASSWORD)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("account_coord_app"); + assertThatThrownBy( + () -> + new RedisMembershipGenerationProjectionStore.CoordinationEndpoint( + "coordination.internal", 6379, "account_coord_app", " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("credential"); + + var coordination = coordination("coordination.internal", 6379); + var cache = + new RedisMembershipGenerationProjectionStore.CacheRateLimitEndpoint( + "COORDINATION.INTERNAL.", 6379); + assertThatThrownBy( + () -> newStore(mock(AccountMembershipSourceReader.class), coordination, cache)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("endpoints must be distinct"); + assertThat(coordination.toString()).contains("password=").doesNotContain(PASSWORD); + } + + @Test + void requiresExplicitInitializationAndDoesNotAcceptAmbientRedisTemplate() { + AccountMembershipSourceReader reader = mock(AccountMembershipSourceReader.class); + RedisMembershipGenerationProjectionStore store = + newStore(reader, coordination("coord.internal", 6379), cache()); + + assertThatThrownBy(() -> store.refreshCurrent(ACCOUNT_ID, TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("explicit init()"); + boolean acceptsAmbientTemplate = + java.util.Arrays.stream(RedisMembershipGenerationProjectionStore.class.getConstructors()) + .anyMatch( + constructor -> + java.util.Arrays.stream(constructor.getParameterTypes()) + .anyMatch(StringRedisTemplate.class::isAssignableFrom)); + assertThat(acceptsAmbientTemplate).isFalse(); + store.close(); + assertThatThrownBy(store::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + verify(reader, times(0)).readCurrent(any(), any()); + } + + @Test + void rebuildsOnlyTheExistingBaselineThenVerifiesExactBytesAndSource() throws Exception { + MembershipSourceSnapshot baseline = baselineSource(1L, 1L); + Harness harness = harness(new FakeRedis(), baseline, baseline); + + RedisMembershipGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID, TENANT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisMembershipGenerationProjectionStore.Outcome.APPLIED); + assertThat(result.snapshot()).isPresent(); + assertThat(result.snapshot().orElseThrow().key()).isEqualTo(KEY); + assertThat(MembershipGenerationProjection.parse(result.snapshot().orElseThrow().json())) + .isEqualTo(MembershipGenerationProjection.fromSource(baseline)); + assertThat(harness.redis().bytes) + .isEqualTo(result.snapshot().orElseThrow().json().getBytes(StandardCharsets.UTF_8)); + assertThat(harness.redis().lastMode).isEqualTo("ABSENT"); + assertThat(harness.redis().ttlMillis).isEqualTo(-1L); + verify(harness.reader(), times(2)).readCurrent(ACCOUNT_ID, TENANT_ID); + harness.store().close(); + } + + @Test + void appliesPositiveFirstJoinWithIndependentSourceVersionAndNoEventMirror() throws Exception { + MembershipSourceSnapshot joined = + positiveSource(1L, 5L, 2L, 1L, membershipEvent("1", "2", "1", "join-a")); + Harness harness = harness(new FakeRedis(), joined, joined); + + RedisMembershipGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID, TENANT_ID); + MembershipGenerationProjection projection = + MembershipGenerationProjection.parse(result.snapshot().orElseThrow().json()); + + assertThat(result.outcome()) + .isEqualTo(RedisMembershipGenerationProjectionStore.Outcome.APPLIED); + assertThat(projection.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(projection.sourceVersion()).isEqualTo("5"); + assertThat(projection.membershipVersion()).isEqualTo(Map.of(TENANT_TEXT, "2")); + assertThat(projection.outboxSequence()).isEqualTo("1"); + assertThat(projection.sourceEvent()).contains(joined.snapshot().sourceEvent().canonicalJson()); + assertThat(harness.redis().scriptCalls).isEqualTo(1); + harness.store().close(); + } + + @Test + void exactSourceReplayUsesOneNonMutatingCasAndFreshSourceRead() throws Exception { + MembershipSourceSnapshot source = baselineSource(1L, 1L); + MembershipGenerationProjection projection = MembershipGenerationProjection.fromSource(source); + FakeRedis redis = new FakeRedis(projection.toJson().getBytes(StandardCharsets.UTF_8)); + Harness harness = harness(redis, source, source); + + RedisMembershipGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID, TENANT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisMembershipGenerationProjectionStore.Outcome.REPLAYED); + assertThat(redis.lastMode).isEqualTo("VERIFY"); + assertThat(redis.scriptCalls).isEqualTo(1); + verify(harness.reader(), times(2)).readCurrent(ACCOUNT_ID, TENANT_ID); + harness.store().close(); + } + + @Test + void sourceAdvanceAfterExactRedisReadbackReturnsSourceChangedWithoutRetry() throws Exception { + MembershipSourceSnapshot baseline = baselineSource(1L, 1L); + MembershipSourceSnapshot joined = + positiveSource(1L, 2L, 2L, 1L, membershipEvent("1", "2", "1", "join-a")); + FakeRedis redis = new FakeRedis(); + Harness harness = harness(redis, baseline, joined); + + RedisMembershipGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID, TENANT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisMembershipGenerationProjectionStore.Outcome.SOURCE_CHANGED); + assertThat(result.snapshot()).isPresent(); + assertThat(redis.scriptCalls).isEqualTo(1); + assertThat(redis.bytes) + .isEqualTo( + MembershipGenerationProjection.fromSource(baseline) + .toJson() + .getBytes(StandardCharsets.UTF_8)); + verify(harness.reader(), times(2)).readCurrent(ACCOUNT_ID, TENANT_ID); + harness.store().close(); + } + + @Test + void newerValidRedisReadbackAfterCasIsReturnedAsStaleWithoutRetry() throws Exception { + MembershipSourceSnapshot baseline = baselineSource(1L, 1L); + MembershipSourceSnapshot candidateSource = + positiveSource(1L, 1L, 2L, 1L, membershipEvent("1", "2", "1", "join-a")); + MembershipSourceSnapshot laterSource = + positiveSource(2L, 2L, 3L, 2L, membershipEvent("2", "3", "2", "join-b")); + MembershipGenerationProjection laterProjection = + MembershipGenerationProjection.fromSource(laterSource); + FakeRedis redis = + new FakeRedis( + MembershipGenerationProjection.fromSource(baseline) + .toJson() + .getBytes(StandardCharsets.UTF_8)); + redis.afterWriteBytes = laterProjection.toJson().getBytes(StandardCharsets.UTF_8); + Harness harness = harness(redis, candidateSource); + + RedisMembershipGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID, TENANT_ID); + + assertThat(result.outcome()).isEqualTo(RedisMembershipGenerationProjectionStore.Outcome.STALE); + assertThat(result.detail()).contains("REDIS_READBACK_CHANGED"); + assertThat(result.snapshot()) + .contains( + new RedisMembershipGenerationProjectionStore.ProjectionSnapshot( + KEY, laterProjection.toJson())); + assertThat(redis.bytes).isEqualTo(laterProjection.toJson().getBytes(StandardCharsets.UTF_8)); + assertThat(redis.scriptCalls).isEqualTo(1); + verify(harness.reader(), times(1)).readCurrent(ACCOUNT_ID, TENANT_ID); + harness.store().close(); + } + + @Test + void aheadProjectionAndSameCheckpointConflictAreNotOverwritten() throws Exception { + MembershipSourceSnapshot baseline = baselineSource(1L, 1L); + MembershipGenerationProjection ahead = + MembershipGenerationProjection.fromSource( + positiveSource(2L, 3L, 2L, 1L, membershipEvent("2", "2", "1", "join-a"))); + FakeRedis aheadRedis = new FakeRedis(ahead.toJson().getBytes(StandardCharsets.UTF_8)); + Harness aheadHarness = harness(aheadRedis, baseline); + + RedisMembershipGenerationProjectionStore.ApplyResult aheadResult = + aheadHarness.store().refreshCurrent(ACCOUNT_ID, TENANT_ID); + + assertThat(aheadResult.outcome()) + .isEqualTo(RedisMembershipGenerationProjectionStore.Outcome.STALE_SOURCE); + assertThat(aheadRedis.scriptCalls).isZero(); + aheadHarness.store().close(); + + MembershipSourceSnapshot first = + positiveSource(1L, 2L, 2L, 1L, membershipEvent("1", "2", "1", "join-a")); + MembershipSourceSnapshot conflict = + positiveSource(1L, 2L, 2L, 1L, membershipEvent("1", "2", "1", "join-b")); + MembershipGenerationProjection stored = MembershipGenerationProjection.fromSource(first); + FakeRedis conflictRedis = new FakeRedis(stored.toJson().getBytes(StandardCharsets.UTF_8)); + Harness conflictHarness = harness(conflictRedis, conflict); + + RedisMembershipGenerationProjectionStore.ApplyResult conflictResult = + conflictHarness.store().refreshCurrent(ACCOUNT_ID, TENANT_ID); + + assertThat(conflictResult.outcome()) + .isEqualTo(RedisMembershipGenerationProjectionStore.Outcome.QUARANTINED); + assertThat(conflictResult.detail()).contains("SAME_CHECKPOINT_DISAGREEMENT"); + assertThat(conflictRedis.scriptCalls).isZero(); + conflictHarness.store().close(); + } + + @Test + void ttlAndMalformedRedisStateAreQuarantinedWithoutCas() throws Exception { + MembershipSourceSnapshot source = baselineSource(1L, 1L); + MembershipGenerationProjection projection = MembershipGenerationProjection.fromSource(source); + FakeRedis ttlRedis = new FakeRedis(projection.toJson().getBytes(StandardCharsets.UTF_8)); + ttlRedis.ttlMillis = 10_000L; + Harness ttlHarness = harness(ttlRedis, source); + + RedisMembershipGenerationProjectionStore.ApplyResult ttlResult = + ttlHarness.store().refreshCurrent(ACCOUNT_ID, TENANT_ID); + + assertThat(ttlResult.outcome()) + .isEqualTo(RedisMembershipGenerationProjectionStore.Outcome.QUARANTINED); + assertThat(ttlResult.detail()).contains("TTL_PRESENT"); + assertThat(ttlRedis.scriptCalls).isZero(); + ttlHarness.store().close(); + + FakeRedis malformedRedis = new FakeRedis("{\"unknown\":true}".getBytes(StandardCharsets.UTF_8)); + Harness malformedHarness = harness(malformedRedis, source); + + RedisMembershipGenerationProjectionStore.ApplyResult malformedResult = + malformedHarness.store().refreshCurrent(ACCOUNT_ID, TENANT_ID); + + assertThat(malformedResult.outcome()) + .isEqualTo(RedisMembershipGenerationProjectionStore.Outcome.QUARANTINED); + assertThat(malformedResult.detail()).contains("MALFORMED_STORED_PROJECTION"); + assertThat(malformedRedis.scriptCalls).isZero(); + malformedHarness.store().close(); + } + + @Test + void casStalenessDoesNotTriggerASecondAttempt() throws Exception { + MembershipSourceSnapshot baseline = baselineSource(1L, 1L); + FakeRedis redis = new FakeRedis(); + redis.forcedScriptResult = "STALE"; + Harness harness = harness(redis, baseline); + + RedisMembershipGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(ACCOUNT_ID, TENANT_ID); + + assertThat(result.outcome()).isEqualTo(RedisMembershipGenerationProjectionStore.Outcome.STALE); + assertThat(redis.scriptCalls).isEqualTo(1); + verify(harness.reader(), times(1)).readCurrent(ACCOUNT_ID, TENANT_ID); + harness.store().close(); + } + + @Test + void redisFailureRemainsVisible() throws Exception { + MembershipSourceSnapshot source = baselineSource(1L, 1L); + FakeRedis redis = new FakeRedis(); + redis.readFailure = new DataAccessResourceFailureException("Coordination Redis unavailable"); + Harness harness = harness(redis, source); + + assertThatThrownBy(() -> harness.store().refreshCurrent(ACCOUNT_ID, TENANT_ID)) + .isSameAs(redis.readFailure); + harness.store().close(); + } + + private static Harness harness(FakeRedis redis, MembershipSourceSnapshot... sources) + throws Exception { + AccountMembershipSourceReader reader = mock(AccountMembershipSourceReader.class); + AtomicInteger sourceIndex = new AtomicInteger(); + doAnswer(ignored -> sources[Math.min(sourceIndex.getAndIncrement(), sources.length - 1)]) + .when(reader) + .readCurrent(ACCOUNT_ID, TENANT_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)); + + RedisMembershipGenerationProjectionStore store = + newStore(reader, coordination("coordination.internal", 6379), cache()); + Field templateField = + RedisMembershipGenerationProjectionStore.class.getDeclaredField("redisTemplate"); + templateField.setAccessible(true); + templateField.set(store, template); + return new Harness(store, reader, redis); + } + + private static RedisMembershipGenerationProjectionStore newStore( + AccountMembershipSourceReader reader, + RedisMembershipGenerationProjectionStore.CoordinationEndpoint coordination, + RedisMembershipGenerationProjectionStore.CacheRateLimitEndpoint cache) { + return new RedisMembershipGenerationProjectionStore(reader, coordination, cache); + } + + private static RedisMembershipGenerationProjectionStore.CoordinationEndpoint coordination( + String host, int port) { + return new RedisMembershipGenerationProjectionStore.CoordinationEndpoint( + host, port, "account_coord_app", PASSWORD); + } + + private static RedisMembershipGenerationProjectionStore.CacheRateLimitEndpoint cache() { + return new RedisMembershipGenerationProjectionStore.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 MembershipSourceSnapshot baselineSource(long generation, long sourceVersion) { + RuntimeMembershipSnapshotDto snapshot = + new RuntimeMembershipSnapshotDto( + ACCOUNT_TEXT, + TENANT_TEXT, + ACCOUNT_TEXT, + TENANT_TEXT, + false, + false, + new MembershipBaseline("MISSING", Map.of(TENANT_TEXT, "1"), "1"), + List.of(), + tuple("1"), + "1", + Instant.parse("2026-10-01T00:00:00Z"), + checkpoints("0"), + List.of(), + null); + return source(snapshot, generation, sourceVersion, 1L); + } + + private static MembershipSourceSnapshot positiveSource( + long generation, + long sourceVersion, + long membershipVersion, + long sequence, + MembershipEvent event) { + String generationText = Long.toString(generation); + String versionText = Long.toString(membershipVersion); + String sequenceText = Long.toString(sequence); + RuntimeMembershipSnapshotDto snapshot = + new RuntimeMembershipSnapshotDto( + ACCOUNT_TEXT, + TENANT_TEXT, + ACCOUNT_TEXT, + TENANT_TEXT, + true, + true, + new MembershipBaseline("ACTIVE", Map.of(TENANT_TEXT, versionText), generationText), + List.of("player"), + tuple(generationText), + event.issuanceFence(), + Instant.parse("2026-10-01T00:00:00Z"), + checkpoints(sequenceText), + List.of( + new OutboxSourceEvidence( + STREAM_KEY, + sequenceText, + event.eventId(), + event.eventDigest(), + event.canonicalJson())), + event); + return source(snapshot, generation, sourceVersion, Long.parseLong(event.issuanceFence())); + } + + private static List checkpoints(String membershipSequence) { + return List.of( + new OutboxCheckpointEntry("account:auth-authority:v1:account/" + ACCOUNT_TEXT, "0"), + new OutboxCheckpointEntry( + "account:auth-authority:v1:issuer/" + AccountServiceImpl.ACCOUNT_JWT_ISSUER, "0"), + new OutboxCheckpointEntry(STREAM_KEY, membershipSequence), + new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + TENANT_TEXT, "0")); + } + + private static MembershipSourceSnapshot source( + RuntimeMembershipSnapshotDto snapshot, long generation, long sourceVersion, long fenceValue) { + return new MembershipSourceSnapshot( + ACCOUNT_ID, + TENANT_ID, + snapshot, + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), + generation, + sourceVersion, + new IssuanceFence(ACCOUNT_ID, fenceValue, 1L))); + } + + private static AuthorityTuple tuple(String membershipGeneration) { + return new AuthorityTuple( + "1", + "1", + Map.of(TENANT_TEXT, "1"), + Map.of(TENANT_TEXT, membershipGeneration), + List.of(), + Optional.empty(), + Optional.empty()); + } + + private static MembershipEvent membershipEvent( + String generation, String membershipVersion, String sequence, String requestId) { + return MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "event-" + requestId), + Map.entry("requestId", requestId), + Map.entry("outboxStreamKey", STREAM_KEY), + Map.entry("outboxSequence", sequence), + Map.entry("sourceScope", "membership/" + ACCOUNT_TEXT + "/" + TENANT_TEXT), + Map.entry("accountId", ACCOUNT_TEXT), + Map.entry("tenantId", TENANT_TEXT), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(TENANT_TEXT, membershipVersion)), + Map.entry("membershipAuthorityGeneration", generation), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(TENANT_TEXT, "1"), + "membershipAuthorityGeneration", Map.of(TENANT_TEXT, generation), + "privateRealmGrantVersions", List.of())), + Map.entry("issuanceFence", "1"), + Map.entry("roles", List.of("player")), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false))); + } + + private record Harness( + RedisMembershipGenerationProjectionStore store, + AccountMembershipSourceReader 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/RedisTenantGenerationProjectionStoreTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisTenantGenerationProjectionStoreTest.java new file mode 100644 index 0000000000..fa6133f144 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/RedisTenantGenerationProjectionStoreTest.java @@ -0,0 +1,489 @@ +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.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.service.AccountTenantAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot; +import net.firedevops.firemud.accountservice.service.RedisTenantGenerationProjectionStore; +import net.firedevops.firemud.accountservice.service.TenantGenerationProjection; +import net.firedevops.firemud.accountservice.service.TenantGenerationProjectionRedisContract; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent; +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 RedisTenantGenerationProjectionStoreTest { + private static final String PASSWORD = "coordination-secret"; + private static final UUID TENANT_ID = UUID.fromString("10000000-0000-0000-0000-000000000001"); + private static final String TENANT_TEXT = TENANT_ID.toString(); + private static final String KEY = "session:auth:generation:tenant:" + TENANT_TEXT; + private static final String STREAM_KEY = "account:auth-authority:v1:tenant/" + TENANT_TEXT; + + @Test + void requiresAccountCoordinationPrincipalAndSeparateCacheEndpoint() { + assertThatThrownBy( + () -> + new RedisTenantGenerationProjectionStore.CoordinationEndpoint( + "coordination.internal", 6379, "gamesession_coord_app", PASSWORD)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("account_coord_app"); + assertThatThrownBy( + () -> + new RedisTenantGenerationProjectionStore.CoordinationEndpoint( + "coordination.internal", 6379, "account_coord_app", " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("credential"); + + var coordination = coordination("coordination.internal", 6379); + var cache = + new RedisTenantGenerationProjectionStore.CacheRateLimitEndpoint( + "COORDINATION.INTERNAL.", 6379); + assertThatThrownBy( + () -> newStore(mock(AccountTenantAuthorityEventProducer.class), coordination, cache)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("endpoints must be distinct"); + assertThat(coordination.toString()).contains("password=").doesNotContain(PASSWORD); + } + + @Test + void constructorRequiresExplicitInitAndDoesNotAcceptAmbientRedisTemplate() { + RedisTenantGenerationProjectionStore store = + newStore( + mock(AccountTenantAuthorityEventProducer.class), + coordination("coord.internal", 6379), + cache()); + + assertThatThrownBy(() -> store.refreshCurrent(TENANT_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("explicit init()"); + boolean acceptsAmbientTemplate = + java.util.Arrays.stream(RedisTenantGenerationProjectionStore.class.getConstructors()) + .anyMatch( + constructor -> + java.util.Arrays.stream(constructor.getParameterTypes()) + .anyMatch(StringRedisTemplate.class::isAssignableFrom)); + assertThat(acceptsAmbientTemplate).isFalse(); + store.close(); + } + + @Test + void installsProvedOriginalBaselineAndRequiresSourceReadbackAfterExactRedisBytes() + throws Exception { + TenantAuthoritySnapshot baseline = source(1L, 1L, 0L, null); + Harness harness = harness(new FakeRedis(), baseline, baseline); + + RedisTenantGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(TENANT_ID); + + assertThat(result.outcome()).isEqualTo(RedisTenantGenerationProjectionStore.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.source(), times(2)).readCurrent(TENANT_ID); + harness.store().close(); + } + + @Test + void exactSnapshotUsesRegisteredNonMutatingVerificationAndReturnsReplay() throws Exception { + TenantAuthoritySnapshot baseline = source(1L, 1L, 0L, null); + TenantGenerationProjection projection = TenantGenerationProjection.fromSource(baseline); + FakeRedis redis = new FakeRedis(projection.toJson().getBytes(StandardCharsets.UTF_8)); + Harness harness = harness(redis, baseline, baseline); + + RedisTenantGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(TENANT_ID); + + assertThat(result.outcome()).isEqualTo(RedisTenantGenerationProjectionStore.Outcome.REPLAYED); + assertThat(redis.lastMode).isEqualTo("VERIFY"); + assertThat(redis.scriptCalls).isEqualTo(1); + assertThat(redis.commandOrder).containsExactly("SCRIPT LOAD", "EVALSHA"); + assertThat(redis.loadedScriptSha256) + .isEqualTo(TenantGenerationProjectionRedisContract.descriptor().sha256()); + assertThat(redis.loadedScriptSha1).isEqualTo(redis.evalShaArgument); + verify(harness.source(), times(2)).readCurrent(TENANT_ID); + harness.store().close(); + } + + @Test + void ttlBearingProjectionIsQuarantinedWithoutMutation() throws Exception { + TenantAuthoritySnapshot baseline = source(1L, 1L, 0L, null); + TenantGenerationProjection projection = TenantGenerationProjection.fromSource(baseline); + FakeRedis redis = new FakeRedis(projection.toJson().getBytes(StandardCharsets.UTF_8)); + redis.ttlMillis = 10_000L; + Harness harness = harness(redis, baseline); + + RedisTenantGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(TENANT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisTenantGenerationProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains("TTL_PRESENT"); + assertThat(redis.scriptCalls).isZero(); + verify(harness.source(), times(1)).readCurrent(TENANT_ID); + harness.store().close(); + } + + @Test + void sourceRegressionNeverOverwritesAnExistingHigherProjection() throws Exception { + TenantAuthoritySnapshot baseline = source(1L, 1L, 0L, null); + TenantGenerationProjection newer = + TenantGenerationProjection.fromSource(source(3L, 3L, 2L, tenantEvent("3", "3", "2"))); + FakeRedis redis = new FakeRedis(newer.toJson().getBytes(StandardCharsets.UTF_8)); + Harness harness = harness(redis, baseline); + + RedisTenantGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(TENANT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisTenantGenerationProjectionStore.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 sameCheckpointDisagreementFailsClosedWithoutCallingRedisCas() throws Exception { + TenantGenerationProjection stored = + TenantGenerationProjection.fromSource( + source(2L, 2L, 1L, tenantEvent("2", "2", "1", "11111111-1111-4111-8111-111111111111"))); + TenantAuthoritySnapshot conflicting = + source(2L, 2L, 1L, tenantEvent("2", "2", "1", "22222222-2222-4222-8222-222222222222")); + FakeRedis redis = new FakeRedis(stored.toJson().getBytes(StandardCharsets.UTF_8)); + Harness harness = harness(redis, conflicting); + + RedisTenantGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(TENANT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisTenantGenerationProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains("SAME_CHECKPOINT_DISAGREEMENT"); + assertThat(redis.scriptCalls).isZero(); + harness.store().close(); + } + + @Test + void staleCasReturnsWithoutBlindRetry() throws Exception { + TenantAuthoritySnapshot baseline = source(1L, 1L, 0L, null); + TenantAuthoritySnapshot advanced = source(2L, 2L, 1L, tenantEvent("2", "2", "1")); + FakeRedis redis = + new FakeRedis( + TenantGenerationProjection.fromSource(baseline) + .toJson() + .getBytes(StandardCharsets.UTF_8)); + redis.forcedScriptResult = "STALE"; + Harness harness = harness(redis, advanced); + + RedisTenantGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(TENANT_ID); + + assertThat(result.outcome()).isEqualTo(RedisTenantGenerationProjectionStore.Outcome.STALE); + assertThat(redis.scriptCalls).isEqualTo(1); + verify(harness.source(), times(1)).readCurrent(TENANT_ID); + harness.store().close(); + } + + @Test + void changedRedisReadbackCannotReturnSuccess() throws Exception { + TenantAuthoritySnapshot baseline = source(1L, 1L, 0L, null); + TenantAuthoritySnapshot candidateSource = source(2L, 2L, 1L, tenantEvent("2", "2", "1")); + TenantGenerationProjection newer = + TenantGenerationProjection.fromSource( + source(3L, 3L, 2L, tenantEvent("3", "3", "2", "33333333-3333-4333-8333-333333333333"))); + FakeRedis redis = + new FakeRedis( + TenantGenerationProjection.fromSource(baseline) + .toJson() + .getBytes(StandardCharsets.UTF_8)); + redis.afterWriteBytes = newer.toJson().getBytes(StandardCharsets.UTF_8); + Harness harness = harness(redis, candidateSource); + + RedisTenantGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(TENANT_ID); + + assertThat(result.outcome()).isEqualTo(RedisTenantGenerationProjectionStore.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.source(), times(1)).readCurrent(TENANT_ID); + harness.store().close(); + } + + @Test + void sourceAdvanceAfterSuccessfulRedisReadbackReturnsSourceChanged() throws Exception { + TenantAuthoritySnapshot baseline = source(1L, 1L, 0L, null); + TenantAuthoritySnapshot advanced = source(2L, 2L, 1L, tenantEvent("2", "2", "1")); + FakeRedis redis = new FakeRedis(); + Harness harness = harness(redis, baseline, advanced); + + RedisTenantGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(TENANT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisTenantGenerationProjectionStore.Outcome.SOURCE_CHANGED); + assertThat(result.snapshot()).isPresent(); + assertThat(result.snapshot().orElseThrow().json()) + .isEqualTo(TenantGenerationProjection.fromSource(baseline).toJson()); + assertThat(redis.bytes) + .isEqualTo( + TenantGenerationProjection.fromSource(baseline) + .toJson() + .getBytes(StandardCharsets.UTF_8)); + assertThat(redis.scriptCalls).isEqualTo(1); + verify(harness.source(), times(2)).readCurrent(TENANT_ID); + harness.store().close(); + } + + @Test + void malformedStoredProjectionIsQuarantined() throws Exception { + TenantAuthoritySnapshot baseline = source(1L, 1L, 0L, null); + FakeRedis redis = new FakeRedis("{\"unknown\":true}".getBytes(StandardCharsets.UTF_8)); + Harness harness = harness(redis, baseline); + + RedisTenantGenerationProjectionStore.ApplyResult result = + harness.store().refreshCurrent(TENANT_ID); + + assertThat(result.outcome()) + .isEqualTo(RedisTenantGenerationProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains("MALFORMED_STORED_PROJECTION"); + assertThat(redis.scriptCalls).isZero(); + harness.store().close(); + } + + @Test + void noscriptFailurePropagatesAfterOneLoadAndOneEvalShaWithoutFallback() throws Exception { + TenantAuthoritySnapshot baseline = source(1L, 1L, 0L, null); + FakeRedis redis = new FakeRedis(); + redis.evalFailure = new DataAccessResourceFailureException("NOSCRIPT missing script"); + Harness harness = harness(redis, baseline); + + assertThatThrownBy(() -> harness.store().refreshCurrent(TENANT_ID)).isSameAs(redis.evalFailure); + assertThat(redis.scriptLoads).isEqualTo(1); + assertThat(redis.scriptCalls).isEqualTo(1); + assertThat(redis.commandOrder).containsExactly("SCRIPT LOAD", "EVALSHA"); + assertThat( + org.mockito.Mockito.mockingDetails(redis.scriptingCommands).getInvocations().stream() + .anyMatch(invocation -> invocation.getMethod().getName().equals("eval"))) + .isFalse(); + harness.store().close(); + } + + @Test + void redisConnectionFailureRemainsVisibleToCaller() throws Exception { + TenantAuthoritySnapshot baseline = source(1L, 1L, 0L, null); + FakeRedis redis = new FakeRedis(); + redis.readFailure = new DataAccessResourceFailureException("Coordination Redis unavailable"); + Harness harness = harness(redis, baseline); + + assertThatThrownBy(() -> harness.store().refreshCurrent(TENANT_ID)).isSameAs(redis.readFailure); + harness.store().close(); + } + + private static Harness harness(FakeRedis redis, TenantAuthoritySnapshot... sources) + throws Exception { + AccountTenantAuthorityEventProducer source = mock(AccountTenantAuthorityEventProducer.class); + AtomicInteger sourceIndex = new AtomicInteger(); + doAnswer(ignored -> sources[Math.min(sourceIndex.getAndIncrement(), sources.length - 1)]) + .when(source) + .readCurrent(TENANT_ID); + + RedisConnection connection = mock(RedisConnection.class); + RedisStringCommands stringCommands = mock(RedisStringCommands.class); + RedisKeyCommands keyCommands = mock(RedisKeyCommands.class); + RedisScriptingCommands scriptingCommands = mock(RedisScriptingCommands.class); + redis.scriptingCommands = scriptingCommands; + 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 -> { + byte[] script = invocation.getArgument(0); + redis.scriptLoads++; + redis.commandOrder.add("SCRIPT LOAD"); + redis.loadedScriptSha1 = sha1(script); + redis.loadedScriptSha256 = sha256(script); + return redis.loadedScriptSha1; + }); + + 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++; + redis.commandOrder.add("EVALSHA"); + redis.evalShaArgument = invocation.getArgument(0); + if (redis.evalFailure != null) { + throw redis.evalFailure; + } + 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)); + + RedisTenantGenerationProjectionStore store = + newStore( + source, + coordination("coordination.internal", 6379), + new RedisTenantGenerationProjectionStore.CacheRateLimitEndpoint( + "cache.internal", 6380)); + Field templateField = + RedisTenantGenerationProjectionStore.class.getDeclaredField("redisTemplate"); + templateField.setAccessible(true); + templateField.set(store, template); + return new Harness(store, source, redis); + } + + private static RedisTenantGenerationProjectionStore newStore( + AccountTenantAuthorityEventProducer source, + RedisTenantGenerationProjectionStore.CoordinationEndpoint coordination, + RedisTenantGenerationProjectionStore.CacheRateLimitEndpoint cache) { + return new RedisTenantGenerationProjectionStore(source, coordination, cache); + } + + private static RedisTenantGenerationProjectionStore.CoordinationEndpoint coordination( + String host, int port) { + return new RedisTenantGenerationProjectionStore.CoordinationEndpoint( + host, port, "account_coord_app", PASSWORD); + } + + private static RedisTenantGenerationProjectionStore.CacheRateLimitEndpoint cache() { + return new RedisTenantGenerationProjectionStore.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 String sha256(byte[] script) throws NoSuchAlgorithmException { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(script)); + } + + private static TenantAuthoritySnapshot source( + long generation, long sourceVersion, long sequence, TenantGenerationAuthorityEvent event) { + return new TenantAuthoritySnapshot( + TENANT_ID, generation, sourceVersion, STREAM_KEY, sequence, Optional.ofNullable(event)); + } + + private static TenantGenerationAuthorityEvent tenantEvent( + String generation, String sourceVersion, String sequence) { + return tenantEvent(generation, sourceVersion, sequence, "11111111-1111-4111-8111-111111111111"); + } + + private static TenantGenerationAuthorityEvent tenantEvent( + String generation, String sourceVersion, String sequence, String requestId) { + var evidence = + TenantGenerationAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", TenantGenerationAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", TenantGenerationAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId), + Map.entry("tenantId", TENANT_TEXT), + Map.entry("sourceScope", "tenant/" + TENANT_TEXT), + Map.entry("outboxStreamKey", STREAM_KEY), + Map.entry("outboxSequence", sequence), + Map.entry("tenantAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion))); + return evidence; + } + + private record Harness( + RedisTenantGenerationProjectionStore store, + AccountTenantAuthorityEventProducer source, + FakeRedis redis) {} + + private static final class FakeRedis { + private byte[] bytes; + private long ttlMillis = -1L; + private String forcedScriptResult; + private byte[] afterWriteBytes; + private RuntimeException readFailure; + private RuntimeException evalFailure; + private int scriptLoads; + private int scriptCalls; + private String lastMode; + private String loadedScriptSha1; + private String loadedScriptSha256; + private String evalShaArgument; + private RedisScriptingCommands scriptingCommands; + private final List commandOrder = new ArrayList<>(); + + 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/TenantGenerationProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/TenantGenerationProjectionTest.java new file mode 100644 index 0000000000..9c1337c922 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/TenantGenerationProjectionTest.java @@ -0,0 +1,175 @@ +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.service.AccountTenantAuthorityEventProducer.TenantAuthoritySnapshot; +import net.firedevops.firemud.accountservice.service.TenantGenerationProjection; +import net.firedevops.firemud.common.account.authority.TenantGenerationAuthorityEventV1Codec; +import org.junit.jupiter.api.Test; + +class TenantGenerationProjectionTest { + private static final UUID TENANT_ID = UUID.fromString("10000000-0000-0000-0000-000000000001"); + private static final String TENANT_TEXT = TENANT_ID.toString(); + private static final String STREAM_KEY = "account:auth-authority:v1:tenant/" + TENANT_TEXT; + + @Test + void emitsExactSequenceZeroBaselineWithoutAnEventFromTypedCurrentSource() { + TenantGenerationProjection projection = + TenantGenerationProjection.fromSource( + new TenantAuthoritySnapshot(TENANT_ID, 1L, 1L, STREAM_KEY, 0L, Optional.empty())); + + assertThat(projection.key()).isEqualTo("session:auth:generation:tenant:" + TENANT_TEXT); + assertThat(projection.toJson()) + .isEqualTo( + "{\"schemaVersion\":\"account-auth-tenant-generation-projection/v1\"," + + "\"tenantId\":\"" + + TENANT_TEXT + + "\",\"tenantAuthorityGeneration\":\"1\",\"sourceVersion\":\"1\"," + + "\"outboxStreamKey\":\"" + + STREAM_KEY + + "\",\"outboxSequence\":\"0\"}"); + assertThat(TenantGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + } + + @Test + void storesTheExactLatestClosedTenantEventAndDigestAsOneJsonString() { + String eventJson = tenantEvent("4", "4", "3", TENANT_TEXT); + TenantGenerationAuthorityEventV1Codec.TenantGenerationAuthorityEvent event = + TenantGenerationAuthorityEventV1Codec.verify(eventJson); + TenantGenerationProjection projection = + TenantGenerationProjection.fromSource( + new TenantAuthoritySnapshot(TENANT_ID, 4L, 4L, STREAM_KEY, 3L, Optional.of(event))); + TenantGenerationProjection parsed = TenantGenerationProjection.parse(projection.toJson()); + + assertThat(parsed).isEqualTo(projection); + assertThat(parsed.sourceEvent()).contains(eventJson); + assertThat(parsed.toJson()).contains("\"sourceEvent\":\"{" + "\\\"eventDigest\\\""); + assertThat(TenantGenerationAuthorityEventV1Codec.verify(eventJson).canonicalJson()) + .isEqualTo(eventJson); + } + + @Test + void acceptsLargeCountersWithArbitraryPrecisionAndExactProgression() { + String generation = "922337203685477580812345678901234567890"; + String sequence = new BigInteger(generation).subtract(BigInteger.ONE).toString(); + TenantGenerationProjection projection = + projection( + generation, + generation, + sequence, + Optional.of(tenantEvent(generation, generation, sequence, TENANT_TEXT))); + + assertThat(projection.generationValue()).isEqualTo(new BigInteger(generation)); + assertThat(projection.sourceVersionValue()).isEqualTo(new BigInteger(generation)); + assertThat(projection.outboxSequenceValue()).isEqualTo(new BigInteger(sequence)); + assertThat(TenantGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + } + + @Test + void closesProjectionFieldsAndRejectsDuplicateUnknownNullAndNoncanonicalJson() { + String baseline = projection("1", "1", "0", Optional.empty()).toJson(); + String duplicateTenantId = + baseline.replace( + "\"tenantId\":\"" + TENANT_TEXT + "\"", + "\"tenantId\":\"" + TENANT_TEXT + "\",\"tenantId\":\"" + TENANT_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-tenant-generation-projection/v1\"," + + "\"tenantId\":\"" + + TENANT_TEXT + + "\",", + "\"tenantId\":\"" + + TENANT_TEXT + + "\",\"schemaVersion\":\"account-auth-tenant-generation-projection/v1\","); + String trailing = baseline + " {}"; + + assertThatThrownBy(() -> TenantGenerationProjection.parse(duplicateTenantId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TenantGenerationProjection.parse(unknownField)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TenantGenerationProjection.parse(nullEvent)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TenantGenerationProjection.parse(noncanonicalSequence)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TenantGenerationProjection.parse(reordered)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TenantGenerationProjection.parse(trailing)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresOriginalBaselineAndPositiveEventAtTheExactSourceCheckpoint() { + assertThatThrownBy(() -> projection("2", "1", "0", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence zero"); + assertThatThrownBy(() -> projection("2", "2", "0", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence zero"); + assertThatThrownBy(() -> projection("2", "2", "1", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence+1"); + assertThatThrownBy( + () -> projection("3", "3", "1", Optional.of(tenantEvent("3", "3", "1", TENANT_TEXT)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence+1"); + assertThatThrownBy( + () -> + projection( + "2", + "2", + "1", + Optional.of( + tenantEvent("2", "2", "1", "10000000-0000-0000-0000-000000000002")))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("checkpoint"); + } + + @Test + void rejectsChangedEventDigestAndUnknownEventProperties() { + String event = tenantEvent("2", "2", "1", TENANT_TEXT); + String changedEvent = event.replace("\"sourceVersion\":\"2\"", "\"sourceVersion\":\"3\""); + String unknownFieldEvent = event.substring(0, event.length() - 1) + ",\"extra\":\"x\"}"; + + assertThatThrownBy(() -> projection("2", "2", "1", Optional.of(changedEvent))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> projection("2", "2", "1", Optional.of(unknownFieldEvent))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static TenantGenerationProjection projection( + String generation, String sourceVersion, String sequence, Optional sourceEvent) { + return new TenantGenerationProjection( + TENANT_TEXT, generation, sourceVersion, STREAM_KEY, sequence, sourceEvent); + } + + private static String tenantEvent( + String generation, String sourceVersion, String sequence, String tenantId) { + String requestId = "11111111-1111-4111-8111-111111111111"; + var evidence = + TenantGenerationAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", TenantGenerationAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", TenantGenerationAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", TenantGenerationAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId), + Map.entry("tenantId", tenantId), + Map.entry("sourceScope", "tenant/" + tenantId), + Map.entry("outboxStreamKey", "account:auth-authority:v1:tenant/" + tenantId), + Map.entry("outboxSequence", sequence), + Map.entry("tenantAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion))); + return new String(evidence.canonicalJsonUtf8(), StandardCharsets.UTF_8); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerAuthorityProjectionV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerAuthorityProjectionV1Codec.java new file mode 100644 index 0000000000..622dc27fc4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerAuthorityProjectionV1Codec.java @@ -0,0 +1,256 @@ +package net.firedevops.firemud.common.account.authority; + +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.node.ObjectNode; +import java.io.IOException; +import java.math.BigInteger; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; + +/** Strict verifier for the closed Game Session issuer-authority projection schema. */ +public final class IssuerAuthorityProjectionV1Codec { + 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 Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]*)"); + private static final Set BASE_FIELDS = + Set.of( + "schemaVersion", + "issuerId", + "lastAppliedIssuerGeneration", + "lastAppliedSourceOutboxSequence", + "outboxStreamKey", + "appliedAt", + "appliedSourceEvidence"); + private static final Set POSITIVE_FIELDS = + Set.of("lastAppliedSourceEventId", "lastAppliedSourceEventDigest"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + private IssuerAuthorityProjectionV1Codec() {} + + /** Verifies one projection supplied as JSON-compatible map data. */ + public static Projection verify(Map supplied) { + if (supplied == null) { + throw invalid("projection", "must be present"); + } + return verifyFields(supplied); + } + + /** Verifies one projection JSON object, rejecting duplicate properties and trailing content. */ + public static Projection verify(String exactJson) { + if (exactJson == null) { + throw invalid("projection JSON", "must be present"); + } + final JsonNode tree; + try { + tree = JSON.readTree(exactJson); + } catch (IOException exception) { + throw new IllegalArgumentException("projection JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode object)) { + throw invalid("projection", "must be a JSON object"); + } + Map fields = + JSON.convertValue(object, new TypeReference>() {}); + return verifyFields(fields); + } + + private static Projection verifyFields(Map supplied) { + String schema = requiredString(supplied, "schemaVersion"); + String issuer = requiredString(supplied, "issuerId"); + String generationText = requiredString(supplied, "lastAppliedIssuerGeneration"); + String sequenceText = requiredString(supplied, "lastAppliedSourceOutboxSequence"); + String stream = requiredString(supplied, "outboxStreamKey"); + String appliedAt = requiredString(supplied, "appliedAt"); + if (!SCHEMA_VERSION.equals(schema) || issuer.isBlank() || appliedAt.isBlank()) { + throw invalid("projection", "identity, schema, or appliedAt 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 invalid("projection.outboxStreamKey", "does not match the exact issuer stream"); + } + + Set expectedFields = new HashSet<>(BASE_FIELDS); + if (!sequence.equals(ZERO)) { + expectedFields.addAll(POSITIVE_FIELDS); + } + if (!supplied.keySet().equals(expectedFields)) { + throw invalid("projection", "must contain exactly the declared schema fields"); + } + + Object evidenceValue = supplied.get("appliedSourceEvidence"); + if (!(evidenceValue instanceof Map evidence)) { + throw invalid("projection.appliedSourceEvidence", "must be an object"); + } + + IssuerGenerationAuthorityEvent latest = null; + BigInteger sourceVersion = ONE; + if (sequence.equals(ZERO)) { + if (!generation.equals(ONE) || !evidence.isEmpty()) { + throw invalid("projection", "zero checkpoint requires the original 1/1 baseline"); + } + } else { + if (evidence.size() != 1) { + throw invalid("projection.appliedSourceEvidence", "must retain its current checkpoint"); + } + Map.Entry entry = evidence.entrySet().iterator().next(); + if (!(entry.getKey() instanceof String evidenceSequence) + || !(entry.getValue() instanceof String canonicalEvent)) { + throw invalid("projection.appliedSourceEvidence", "must contain string key/value data"); + } + BigInteger parsedEvidenceSequence = + positiveDecimal(evidenceSequence, "projection evidence sequence"); + if (!sequence.equals(parsedEvidenceSequence) || !sequenceText.equals(evidenceSequence)) { + throw invalid("projection.appliedSourceEvidence", "must identify the current checkpoint"); + } + + 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, "lastAppliedSourceEventId").equals(latest.eventId()) + || !requiredString(supplied, "lastAppliedSourceEventDigest") + .equals(latest.eventDigest())) { + throw invalid("projection", "event does not match its exact checkpoint"); + } + sourceVersion = positiveDecimal(latest.sourceVersion(), "projection event source version"); + } + + return new Projection(issuer, generation, sourceVersion, sequence, stream, latest, appliedAt); + } + + private static IssuerGenerationAuthorityEvent verifiedProjectionEvent(String canonicalEvent) { + final IssuerGenerationAuthorityEvent event; + try { + event = IssuerGenerationAuthorityEventV1Codec.verify(canonicalEvent); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException("projection source event is malformed", malformed); + } + if (!event.canonicalJson().equals(canonicalEvent)) { + throw invalid("projection source event", "must use its exact canonical JSON bytes"); + } + UUID requestId; + try { + requestId = UUID.fromString(event.requestId()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "projection source event requestId is malformed", malformed); + } + if (new UUID(0L, 0L).equals(requestId) + || !requestId.toString().equals(event.requestId()) + || !(EVENT_ID_PREFIX + event.requestId()).equals(event.eventId())) { + throw invalid("projection source event", "eventId does not bind its canonical requestId"); + } + return event; + } + + 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 String requiredString(Map fields, String name) { + Object value = fields.get(name); + if (!(value instanceof String text)) { + throw invalid("projection." + name, "must be a required string"); + } + return text; + } + + private static BigInteger positiveDecimal(String value, String label) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw invalid(label, "must be a positive canonical decimal"); + } + return new BigInteger(value); + } + + private static BigInteger nonnegativeDecimal(String value, String label) { + if (value == null || !NONNEGATIVE_DECIMAL.matcher(value).matches()) { + throw invalid(label, "must be a canonical nonnegative decimal"); + } + return new BigInteger(value); + } + + private static IllegalArgumentException invalid(String field, String message) { + return new IllegalArgumentException(field + " " + message); + } + + /** Privately minted immutable projection evidence. */ + public static final class Projection { + private final String issuerId; + private final BigInteger generation; + private final BigInteger sourceVersion; + private final BigInteger sequence; + private final String streamKey; + private final Optional latestEvent; + private final String appliedAt; + + private Projection( + String issuerId, + BigInteger generation, + BigInteger sourceVersion, + BigInteger sequence, + String streamKey, + IssuerGenerationAuthorityEvent latestEvent, + String appliedAt) { + this.issuerId = issuerId; + this.generation = generation; + this.sourceVersion = sourceVersion; + this.sequence = sequence; + this.streamKey = streamKey; + this.latestEvent = Optional.ofNullable(latestEvent); + this.appliedAt = appliedAt; + } + + public String issuerId() { + return issuerId; + } + + public BigInteger generation() { + return generation; + } + + public BigInteger sourceVersion() { + return sourceVersion; + } + + public BigInteger sequence() { + return sequence; + } + + public String streamKey() { + return streamKey; + } + + public Optional latestEvent() { + return latestEvent; + } + + public String appliedAt() { + return appliedAt; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerProjectionInstallationAcknowledgmentDigestV1.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerProjectionInstallationAcknowledgmentDigestV1.java new file mode 100644 index 0000000000..982046b307 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerProjectionInstallationAcknowledgmentDigestV1.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.common.account.authority; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; + +/** Shared immutable digest for Account's issuer projection installation acknowledgment. */ +public final class IssuerProjectionInstallationAcknowledgmentDigestV1 { + public static final int VERSION = 1; + public static final int MAX_INSTALLED_PROJECTION_UTF8_BYTES = 65_536; + + private static final String DIGEST_SCHEMA = "issuer-projection-installation-ack/v1"; + private static final String OPERATION = "ISSUER_PROJECTION_INSTALLATION_ACK"; + private static final String PROJECTION_KEY_PREFIX = "session:game:auth:issuer-generation:v1:"; + + private IssuerProjectionInstallationAcknowledgmentDigestV1() {} + + /** + * Computes the exact ten-field, byte-length-framed SHA-256 acknowledgment request digest. + * + *

Every field is encoded as strict UTF-8 and framed as canonical ASCII decimal byte length, a + * colon, and the exact bytes. The installed projection is bounded by the storage contract. + */ + public static String digest( + String issuerId, + String callerWorkloadIdentity, + String projectionKey, + UUID captureOperationId, + UUID captureRequestId, + int captureRequestDigestVersion, + String captureRequestDigest, + String installedProjectionJson) { + requireText(issuerId, "issuer ID", 512); + requireText(callerWorkloadIdentity, "caller workload identity", 512); + requireText(projectionKey, "projection key", 2048); + requireUuid(captureOperationId, "capture operation ID"); + requireUuid(captureRequestId, "capture request ID"); + if (!projectionKey.equals(PROJECTION_KEY_PREFIX + issuerId) + || captureRequestDigestVersion != VERSION + || captureRequestDigest == null + || !captureRequestDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "Issuer projection acknowledgment capture binding is malformed"); + } + + if (installedProjectionJson == null + || installedProjectionJson.length() > MAX_INSTALLED_PROJECTION_UTF8_BYTES) { + throw new IllegalArgumentException( + "Installed projection JSON must contain 1 to " + + MAX_INSTALLED_PROJECTION_UTF8_BYTES + + " UTF-8 bytes"); + } + byte[] projectionBytes = encodeUtf8(installedProjectionJson); + if (projectionBytes.length == 0 + || projectionBytes.length > MAX_INSTALLED_PROJECTION_UTF8_BYTES) { + throw new IllegalArgumentException( + "Installed projection JSON must contain 1 to " + + MAX_INSTALLED_PROJECTION_UTF8_BYTES + + " UTF-8 bytes"); + } + return digestFields( + DIGEST_SCHEMA, + OPERATION, + issuerId, + callerWorkloadIdentity, + projectionKey, + captureOperationId.toString(), + captureRequestId.toString(), + Integer.toString(captureRequestDigestVersion), + captureRequestDigest, + installedProjectionJson); + } + + private static String digestFields(String... fields) { + ByteArrayOutputStream framed = new ByteArrayOutputStream(); + for (String field : fields) { + byte[] bytes = encodeUtf8(field); + framed.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + framed.write(':'); + framed.writeBytes(bytes); + } + return HexFormat.of().formatHex(sha256(framed.toByteArray())); + } + + private static byte[] encodeUtf8(String value) { + if (value == null) { + throw new IllegalArgumentException("Installed projection JSON is required"); + } + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] result = new byte[encoded.remaining()]; + encoded.get(result); + return result; + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException( + "Installed projection JSON is not valid Unicode", malformed); + } + } + + private static void requireText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + field + " must contain 1 to " + maximumLength + " characters"); + } + } + + private static void requireUuid(UUID value, String field) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerProjectionReconciliationRequestDigestV1.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerProjectionReconciliationRequestDigestV1.java new file mode 100644 index 0000000000..2a237c725a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/IssuerProjectionReconciliationRequestDigestV1.java @@ -0,0 +1,59 @@ +package net.firedevops.firemud.common.account.authority; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; + +/** Computes the versioned Account issuer projection reconciliation request digest. */ +public final class IssuerProjectionReconciliationRequestDigestV1 { + public static final int VERSION = 1; + + private static final String SCHEMA_VERSION = "issuer-projection-reconciliation-request/v1"; + private static final String OPERATION = "ISSUER_PROJECTION_SNAPSHOT_CAPTURE"; + private static final String PROJECTION_KEY_PREFIX = "session:game:auth:issuer-generation:v1:"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private IssuerProjectionReconciliationRequestDigestV1() {} + + /** Returns the lowercase SHA-256 digest of the exact six-field UTF-8 byte-framed request. */ + public static String digest( + String issuerId, String callerIdentity, String projectionKey, UUID requestId) { + requireText(issuerId, "issuer ID", 512); + requireText(callerIdentity, "caller workload identity", 512); + requireText(projectionKey, "projection key", 2048); + if (!projectionKey.equals(PROJECTION_KEY_PREFIX + issuerId)) { + throw new IllegalArgumentException( + "projection key must be the exact derived issuer projection key"); + } + if (requestId == null || NIL_UUID.equals(requestId)) { + throw new IllegalArgumentException("request ID must be a canonical non-nil UUID"); + } + + String[] fields = { + SCHEMA_VERSION, OPERATION, issuerId, callerIdentity, projectionKey, requestId.toString() + }; + ByteArrayOutputStream framed = new ByteArrayOutputStream(); + for (String field : fields) { + byte[] bytes = field.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + framed.write(':'); + framed.writeBytes(bytes); + } + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(framed.toByteArray())); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static void requireText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + field + " must contain 1 to " + maximumLength + " characters"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerAuthorityProjectionV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerAuthorityProjectionV1CodecTest.java new file mode 100644 index 0000000000..22ce8de7af --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerAuthorityProjectionV1CodecTest.java @@ -0,0 +1,198 @@ +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.databind.ObjectMapper; +import java.math.BigInteger; +import java.util.LinkedHashMap; +import java.util.Map; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import org.junit.jupiter.api.Test; + +class IssuerAuthorityProjectionV1CodecTest { + private static final String ISSUER_ID = "https://accounts.example.test/issuer"; + private static final String REQUEST_ID = "11111111-1111-4111-8111-111111111111"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void verifiesOriginalZeroCheckpointAndOmitsEventEvidence() { + IssuerAuthorityProjectionV1Codec.Projection projection = + IssuerAuthorityProjectionV1Codec.verify(zeroProjection()); + + assertThat(projection.issuerId()).isEqualTo(ISSUER_ID); + assertThat(projection.generation()).isEqualTo(BigInteger.ONE); + assertThat(projection.sourceVersion()).isEqualTo(BigInteger.ONE); + assertThat(projection.sequence()).isEqualTo(BigInteger.ZERO); + assertThat(projection.streamKey()) + .isEqualTo( + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER_ID); + assertThat(projection.appliedAt()).isEqualTo("stable-time"); + assertThat(projection.latestEvent()).isEmpty(); + } + + @Test + void verifiesPositiveUnicodeCanonicalEventAndArbitraryPrecisionCounters() throws Exception { + String unicodeIssuer = "https://accounts.example.test/issüer"; + String sequence = "18446744073709551616000000000000000001"; + String generation = "92233720368547758081234567890123456789"; + String sourceVersion = "90071992547409931234567890123456789"; + IssuerGenerationAuthorityEvent event = + event(unicodeIssuer, sequence, generation, sourceVersion); + Map supplied = positiveProjection(unicodeIssuer, event); + + IssuerAuthorityProjectionV1Codec.Projection fromMap = + IssuerAuthorityProjectionV1Codec.verify(supplied); + IssuerAuthorityProjectionV1Codec.Projection fromJson = + IssuerAuthorityProjectionV1Codec.verify(JSON.writeValueAsString(supplied)); + + assertThat(event.canonicalJson()).contains("issüer"); + assertThat(fromMap.generation()).isEqualTo(new BigInteger(generation)); + assertThat(fromMap.sourceVersion()).isEqualTo(new BigInteger(sourceVersion)); + assertThat(fromMap.sequence()).isEqualTo(new BigInteger(sequence)); + assertThat(fromMap.latestEvent()).isPresent(); + assertThat(fromMap.latestEvent().orElseThrow().canonicalJson()) + .isEqualTo(event.canonicalJson()); + assertThat(fromJson.latestEvent().orElseThrow().canonicalJson()) + .isEqualTo(event.canonicalJson()); + } + + @Test + void rejectsUnknownNullAliasAndNoncanonicalProjectionValues() { + Map unknown = zeroProjection(); + unknown.put("unexpected", "value"); + assertRejected(unknown); + + Map nullAppliedAt = zeroProjection(); + nullAppliedAt.put("appliedAt", null); + assertRejected(nullAppliedAt); + + Map nullEvidence = zeroProjection(); + nullEvidence.put("appliedSourceEvidence", null); + assertRejected(nullEvidence); + + Map oldAlias = zeroProjection(); + oldAlias.put("issuerAuthGeneration", "1"); + assertRejected(oldAlias); + + Map oldSourceAliases = zeroProjection(); + oldSourceAliases.put("sourceOutboxStreamKey", "legacy-stream"); + oldSourceAliases.put("sourceEventId", "legacy-event"); + oldSourceAliases.put("sourceEventDigest", "legacy-digest"); + assertRejected(oldSourceAliases); + + Map leadingZeroGeneration = zeroProjection(); + leadingZeroGeneration.put("lastAppliedIssuerGeneration", "01"); + assertRejected(leadingZeroGeneration); + + Map leadingZeroSequence = zeroProjection(); + leadingZeroSequence.put("lastAppliedSourceOutboxSequence", "00"); + assertRejected(leadingZeroSequence); + + assertThatThrownBy(() -> IssuerAuthorityProjectionV1Codec.verify((Map) null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsContradictoryZeroBaselineAndNoncurrentOrMismatchedEventEvidence() { + Map zeroWithEvent = zeroProjection(); + zeroWithEvent.put("appliedSourceEvidence", Map.of("1", "event")); + assertRejected(zeroWithEvent); + + IssuerGenerationAuthorityEvent event = event(ISSUER_ID, "2", "3", "4"); + Map mismatchedIssuer = positiveProjection("https://other.test/issuer", event); + assertRejected(mismatchedIssuer); + + Map mismatchedEventId = positiveProjection(ISSUER_ID, event); + mismatchedEventId.put("lastAppliedSourceEventId", "wrong-event"); + assertRejected(mismatchedEventId); + + Map mismatchedDigest = positiveProjection(ISSUER_ID, event); + mismatchedDigest.put("lastAppliedSourceEventDigest", "sha256:" + "0".repeat(64)); + assertRejected(mismatchedDigest); + + Map wrongEvidenceSequence = positiveProjection(ISSUER_ID, event); + wrongEvidenceSequence.put("appliedSourceEvidence", Map.of("1", event.canonicalJson())); + assertRejected(wrongEvidenceSequence); + + Map multipleEvidenceEntries = positiveProjection(ISSUER_ID, event); + multipleEvidenceEntries.put( + "appliedSourceEvidence", Map.of("2", event.canonicalJson(), "1", event.canonicalJson())); + assertRejected(multipleEvidenceEntries); + } + + @Test + void jsonDecoderRejectsDuplicatePropertiesTrailingContentAndUnknownFields() throws Exception { + String json = JSON.writeValueAsString(zeroProjection()); + String duplicate = + "{\"schemaVersion\":\"" + + IssuerAuthorityProjectionV1Codec.SCHEMA_VERSION + + "\"," + + json.substring(1); + + assertThatThrownBy(() -> IssuerAuthorityProjectionV1Codec.verify(duplicate)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> IssuerAuthorityProjectionV1Codec.verify(json + " {}")) + .isInstanceOf(IllegalArgumentException.class); + + Map unknown = zeroProjection(); + unknown.put("schemaAlias", "legacy"); + assertThatThrownBy( + () -> IssuerAuthorityProjectionV1Codec.verify(JSON.writeValueAsString(unknown))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Map zeroProjection() { + Map projection = new LinkedHashMap<>(); + projection.put("schemaVersion", IssuerAuthorityProjectionV1Codec.SCHEMA_VERSION); + projection.put("issuerId", ISSUER_ID); + projection.put("lastAppliedIssuerGeneration", "1"); + projection.put("lastAppliedSourceOutboxSequence", "0"); + projection.put( + "outboxStreamKey", + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER_ID); + projection.put("appliedAt", "stable-time"); + projection.put("appliedSourceEvidence", Map.of()); + return projection; + } + + private static Map positiveProjection( + String issuerId, IssuerGenerationAuthorityEvent event) { + Map projection = new LinkedHashMap<>(); + projection.put("schemaVersion", IssuerAuthorityProjectionV1Codec.SCHEMA_VERSION); + projection.put("issuerId", issuerId); + projection.put("lastAppliedIssuerGeneration", event.issuerAuthGeneration()); + projection.put("lastAppliedSourceOutboxSequence", event.outboxSequence()); + projection.put( + "outboxStreamKey", + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + issuerId); + projection.put("lastAppliedSourceEventId", event.eventId()); + projection.put("lastAppliedSourceEventDigest", event.eventDigest()); + projection.put("appliedAt", "stable-time"); + projection.put("appliedSourceEvidence", Map.of(event.outboxSequence(), event.canonicalJson())); + return projection; + } + + private static IssuerGenerationAuthorityEvent event( + String issuerId, String sequence, String generation, String sourceVersion) { + Map preimage = new LinkedHashMap<>(); + preimage.put("schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION); + preimage.put("eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE); + preimage.put("eventId", "account-issuer-authority-event-v1:" + REQUEST_ID); + preimage.put("requestId", REQUEST_ID); + preimage.put("issuerId", issuerId); + preimage.put("sourceScope", "issuer/" + issuerId); + preimage.put( + "outboxStreamKey", + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + issuerId); + preimage.put("outboxSequence", sequence); + preimage.put("issuerAuthGeneration", generation); + preimage.put("sourceVersion", sourceVersion); + return IssuerGenerationAuthorityEventV1Codec.seal(preimage); + } + + private static void assertRejected(Map supplied) { + assertThatThrownBy(() -> IssuerAuthorityProjectionV1Codec.verify(supplied)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerProjectionInstallationAcknowledgmentDigestV1Test.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerProjectionInstallationAcknowledgmentDigestV1Test.java new file mode 100644 index 0000000000..8dda4365be --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerProjectionInstallationAcknowledgmentDigestV1Test.java @@ -0,0 +1,248 @@ +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.util.UUID; +import org.junit.jupiter.api.Test; + +class IssuerProjectionInstallationAcknowledgmentDigestV1Test { + private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String CALLER_IDENTITY = + "spiffe://firemud/ns/firemud-test/sa/game-session-service"; + private static final String PROJECTION_KEY = + "session:game:auth:issuer-generation:v1:" + ISSUER_ID; + private static final UUID CAPTURE_OPERATION_ID = + UUID.fromString("91b0eb2d-f7b1-4d88-8db4-2b81cacfc96a"); + private static final UUID CAPTURE_REQUEST_ID = + UUID.fromString("f50e8400-e29b-41d4-a716-446655440000"); + private static final String CAPTURE_REQUEST_DIGEST = "a".repeat(64); + private static final String PROJECTION_JSON = + "{\"schemaVersion\":\"game-session-auth-issuer-projection/v1\"," + + "\"issuerId\":\"https://account.example.test/issuer\"," + + "\"lastAppliedIssuerGeneration\":\"1\"," + + "\"lastAppliedSourceOutboxSequence\":\"0\"," + + "\"outboxStreamKey\":\"account:auth-authority:v1:issuer/" + + "https://account.example.test/issuer\"," + + "\"appliedAt\":\"2026-10-03T00:00:00Z\"," + + "\"appliedSourceEvidence\":{}}"; + + @Test + void digestMatchesFixedAsciiAndUnicodeVectors() { + assertThat( + digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON)) + .isEqualTo("18971fbc3cd529421f6f4af5bcf68a9b2e060bc6b4c5b73c74ac9daf00acc507"); + + String unicodeProjection = + PROJECTION_JSON.replace("2026-10-03T00:00:00Z", "2026-10-03T00:00:00Z-ä"); + assertThat( + digest( + ISSUER_ID, + "spiffe://firemud/ns/ä/sa/game-session-service", + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + CAPTURE_REQUEST_DIGEST, + unicodeProjection)) + .isEqualTo("658a31737ceb9a3c34b8810f437da1eedf67dc3b762bdde7ea6f717ad3a87e2e"); + } + + @Test + void changingAnyVariablePreimageFieldChangesTheDigest() { + String original = + digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON); + + assertThat( + digest( + ISSUER_ID + "/next", + CALLER_IDENTITY, + "session:game:auth:issuer-generation:v1:" + ISSUER_ID + "/next", + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON)) + .isNotEqualTo(original); + assertThat( + digest( + ISSUER_ID, + CALLER_IDENTITY + "/changed", + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON)) + .isNotEqualTo(original); + assertThat( + digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + UUID.fromString("a1b0eb2d-f7b1-4d88-8db4-2b81cacfc96a"), + CAPTURE_REQUEST_ID, + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON)) + .isNotEqualTo(original); + assertThat( + digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + UUID.fromString("a50e8400-e29b-41d4-a716-446655440000"), + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON)) + .isNotEqualTo(original); + assertThat( + digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + "b".repeat(64), + PROJECTION_JSON)) + .isNotEqualTo(original); + assertThat( + digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON + " ")) + .isNotEqualTo(original); + } + + @Test + void rejectsInvalidCaptureBindingsAndNilIds() { + assertThatThrownBy( + () -> + digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY + ":other", + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("capture binding"); + assertThatThrownBy( + () -> + IssuerProjectionInstallationAcknowledgmentDigestV1.digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + new UUID(0L, 0L), + CAPTURE_REQUEST_ID, + 1, + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + assertThatThrownBy( + () -> + IssuerProjectionInstallationAcknowledgmentDigestV1.digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + 2, + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("capture binding"); + assertThatThrownBy( + () -> + digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + "A".repeat(64), + PROJECTION_JSON)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("capture binding"); + } + + @Test + void rejectsMalformedUnicodeAndProjectionBytesOverTheStorageBound() { + String unpairedSurrogate = String.valueOf((char) 0xd800); + assertThatThrownBy( + () -> + digest( + ISSUER_ID, + CALLER_IDENTITY + unpairedSurrogate, + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("valid Unicode"); + assertThatThrownBy( + () -> + digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + CAPTURE_REQUEST_DIGEST, + PROJECTION_JSON + unpairedSurrogate)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("valid Unicode"); + assertThatThrownBy( + () -> + digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + CAPTURE_OPERATION_ID, + CAPTURE_REQUEST_ID, + CAPTURE_REQUEST_DIGEST, + "x" + .repeat( + IssuerProjectionInstallationAcknowledgmentDigestV1 + .MAX_INSTALLED_PROJECTION_UTF8_BYTES + + 1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("65536 UTF-8 bytes"); + } + + private static String digest( + String issuerId, + String callerIdentity, + String projectionKey, + UUID captureOperationId, + UUID captureRequestId, + String captureRequestDigest, + String installedProjectionJson) { + return IssuerProjectionInstallationAcknowledgmentDigestV1.digest( + issuerId, + callerIdentity, + projectionKey, + captureOperationId, + captureRequestId, + 1, + captureRequestDigest, + installedProjectionJson); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerProjectionReconciliationRequestDigestV1Test.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerProjectionReconciliationRequestDigestV1Test.java new file mode 100644 index 0000000000..ec70b79803 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/IssuerProjectionReconciliationRequestDigestV1Test.java @@ -0,0 +1,71 @@ +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.util.UUID; +import org.junit.jupiter.api.Test; + +class IssuerProjectionReconciliationRequestDigestV1Test { + private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String CALLER_IDENTITY = + "spiffe://firemud/ns/account-unit/sa/game-session-service"; + private static final String PROJECTION_KEY = + "session:game:auth:issuer-generation:v1:" + ISSUER_ID; + private static final UUID REQUEST_ID = UUID.fromString("a3a69671-8149-4d97-86f8-25a2582fdd68"); + + @Test + void digestMatchesFixedAsciiAndUtf8ByteFramingVectors() { + assertThat( + IssuerProjectionReconciliationRequestDigestV1.digest( + ISSUER_ID, CALLER_IDENTITY, PROJECTION_KEY, REQUEST_ID)) + .isEqualTo("240027543295dc990703ec833578b423f1cdc51e91333d8b58c91d6c5f571d15"); + + assertThat( + IssuerProjectionReconciliationRequestDigestV1.digest( + ISSUER_ID, + "spiffe://firemud/ns/ä/sa/game-session-service", + PROJECTION_KEY, + REQUEST_ID)) + .isEqualTo("197ffafb768bc6973f08219426121d55d09403777ee4963d341d218c4a76bcec"); + } + + @Test + void changingAnyValidRequestBindingChangesTheDigest() { + String original = digest(ISSUER_ID, CALLER_IDENTITY, PROJECTION_KEY, REQUEST_ID); + + assertThat( + digest( + ISSUER_ID + "/next", + CALLER_IDENTITY, + "session:game:auth:issuer-generation:v1:" + ISSUER_ID + "/next", + REQUEST_ID)) + .isNotEqualTo(original); + assertThat(digest(ISSUER_ID, CALLER_IDENTITY + "/changed", PROJECTION_KEY, REQUEST_ID)) + .isNotEqualTo(original); + assertThat( + digest( + ISSUER_ID, + CALLER_IDENTITY, + PROJECTION_KEY, + UUID.fromString("b3a69671-8149-4d97-86f8-25a2582fdd68"))) + .isNotEqualTo(original); + } + + @Test + void rejectsNonDerivedProjectionKeysAndNilRequestIds() { + assertThatThrownBy( + () -> digest(ISSUER_ID, CALLER_IDENTITY, PROJECTION_KEY + ":other", REQUEST_ID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact derived issuer projection key"); + assertThatThrownBy(() -> digest(ISSUER_ID, CALLER_IDENTITY, PROJECTION_KEY, new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + } + + private static String digest( + String issuerId, String callerIdentity, String projectionKey, UUID requestId) { + return IssuerProjectionReconciliationRequestDigestV1.digest( + issuerId, callerIdentity, projectionKey, requestId); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java index f0b3cd2df5..cb5ac03aa7 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameSessionTenantAssociationRepositoryIntegrationTest.java @@ -304,11 +304,13 @@ void applyRequiresOwnerTransactionAndReadRequiresExactCommittedScope() throws Ex assertThatThrownBy(() -> fixture.apply(signed, "another-namespace")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("different namespace"); - byte[] alteredSignatureBytes = Base64.getDecoder().decode(signed.ed25519Signature()); - alteredSignatureBytes[0] ^= 0x01; - Signed malformedSignature = - new Signed(signed.manifest(), Base64.getEncoder().encodeToString(alteredSignatureBytes)); - assertThat(malformedSignature.ed25519Signature()).isNotEqualTo(signed.ed25519Signature()); + byte[] originalSignatureBytes = Base64.getDecoder().decode(signed.ed25519Signature()); + byte[] malformedSignatureBytes = originalSignatureBytes.clone(); + malformedSignatureBytes[0] ^= 0x01; + assertThat(malformedSignatureBytes[0]).isNotEqualTo(originalSignatureBytes[0]); + String malformedSignatureBase64 = Base64.getEncoder().encodeToString(malformedSignatureBytes); + assertThat(malformedSignatureBase64).isNotEqualTo(signed.ed25519Signature()); + Signed malformedSignature = new Signed(signed.manifest(), malformedSignatureBase64); assertThatThrownBy(() -> fixture.apply(malformedSignature, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("signature"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClient.java index d00684e8cb..511a93f0b7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClient.java @@ -3,16 +3,30 @@ import io.grpc.ManagedChannel; import java.io.IOException; import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.Optional; import java.util.UUID; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AcknowledgeIssuerProjectionForRuntimeRequest; +import net.firedevops.firemud.account.v1.AcknowledgeIssuerProjectionForRuntimeResponse; +import net.firedevops.firemud.account.v1.CaptureIssuerProjectionForRuntimeRequest; +import net.firedevops.firemud.account.v1.CaptureIssuerProjectionForRuntimeResponse; 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.IssuerAuthorityProjectionV1Codec; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.account.authority.IssuerProjectionInstallationAcknowledgmentDigestV1; +import net.firedevops.firemud.common.account.authority.IssuerProjectionReconciliationRequestDigestV1; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; @@ -20,21 +34,29 @@ 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.gamesession.service.IssuerAuthorityProjectionRedisContract; +import net.firedevops.firemud.gamesession.service.IssuerProjectionReconciliationInstaller.InstallationReceipt; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ProjectionSnapshot; -/** Unwired Game Session client for authenticated Account issuer-source readback only. */ +/** Unwired Game Session client for authenticated Account issuer-source evidence. */ public final class AccountIssuerAuthorityClient extends AbstractReloadingBlockingGrpcClient< IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub> { private static final long CALL_DEADLINE_SECONDS = 5L; private static final String READBACK_SCHEMA_VERSION = "account-auth-issuer-source-readback/v1"; + private static final String CAPTURE_SCHEMA_VERSION = "account-auth-issuer-projection-capture/v1"; + private static final String INSTALLATION_ACK_SCHEMA_VERSION = + "account-auth-issuer-projection-installation-ack/v1"; private static final String EVENT_ID_PREFIX = "account-issuer-authority-event-v1:"; + private static final String PROJECTION_KEY_PREFIX = "session:game:auth:issuer-generation:v1:"; private final String workloadNamespace; private final String expectedIssuerId; /** - * Creates a source-only client. Construction does not initialize a channel or enable the RPC. The - * supplied customizer is the existing Game Session internal-RPC middleware seam. + * Creates an unwired issuer-authority client. Construction does not initialize a channel or + * enable its RPCs. The supplied customizer is the existing Game Session internal-RPC middleware + * seam. */ public AccountIssuerAuthorityClient( ServiceEndpointsProperties endpoints, @@ -103,6 +125,292 @@ public SourceReadback readCommittedEvent( return read(requestId, requestedSequence); } + /** + * Captures Account's immutable issuer-projection reconciliation receipt. A receipt is historical + * source evidence only; this method does not install or authorize a Game Session projection. + */ + public ProjectionCaptureReceipt captureProjection(String canonicalRequestId) { + UUID requestId = parseCanonicalNonNilUuid(canonicalRequestId, "request ID"); + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException("Account issuer authority client is not initialized"); + } + + CaptureIssuerProjectionForRuntimeRequest request = + CaptureIssuerProjectionForRuntimeRequest.newBuilder() + .setIssuerId(expectedIssuerId) + .setRequestId(requestId.toString()) + .build(); + CaptureIssuerProjectionForRuntimeResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .captureIssuerProjectionForRuntime(request); + return verifyCaptureResponse(response, requestId); + } + + /** + * Durably acknowledges only the installer's privately verified local receipt. The returned + * evidence is historical Account readback, not current readiness or recipient authorization. + */ + public InstallationAcknowledgmentReceipt acknowledgeInstallation( + InstallationReceipt installationReceipt) { + VerifiedInstallation installation = verifyInstallationReceipt(installationReceipt); + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException("Account issuer authority client is not initialized"); + } + + AcknowledgeIssuerProjectionForRuntimeRequest request = + AcknowledgeIssuerProjectionForRuntimeRequest.newBuilder() + .setIssuerId(expectedIssuerId) + .setCaptureOperationId(installation.operationId().toString()) + .setCaptureRequestId(installation.requestId().toString()) + .setCaptureRequestDigestVersion(IssuerProjectionReconciliationRequestDigestV1.VERSION) + .setCaptureRequestDigest(installation.captureRequestDigest()) + .setProjectionKey(installation.projectionKey()) + .setInstalledProjectionJson(installation.projectionJson()) + .build(); + AcknowledgeIssuerProjectionForRuntimeResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .acknowledgeIssuerProjectionForRuntime(request); + return verifyInstallationAcknowledgmentResponse(response, installation); + } + + private VerifiedInstallation verifyInstallationReceipt(InstallationReceipt receipt) { + if (receipt == null) { + throw invalidInstallationReceipt("receipt is absent"); + } + + UUID operationId = receipt.operationId(); + UUID requestId = receipt.requestId(); + if (operationId == null || requestId == null || isNil(operationId) || isNil(requestId)) { + throw invalidInstallationReceipt("capture identity is not canonical non-nil UUID evidence"); + } + + SourceSnapshot captured = receipt.capturedSource(); + ProjectionSnapshot projectionSnapshot = receipt.projectionSnapshot(); + if (captured == null || projectionSnapshot == null) { + throw invalidInstallationReceipt("captured source or exact installed projection is absent"); + } + + String caller = expectedGameSessionWorkloadIdentity(); + String expectedProjectionKey; + try { + expectedProjectionKey = IssuerAuthorityProjectionRedisContract.keyForIssuer(expectedIssuerId); + } catch (IllegalArgumentException malformedIssuer) { + throw invalidInstallationReceipt("configured issuer cannot derive its projection key"); + } + if (!expectedIssuerId.equals(captured.issuerId()) + || !expectedProjectionKey.equals(projectionSnapshot.key())) { + throw invalidInstallationReceipt("issuer or installed projection key changed"); + } + + String expectedCaptureDigest = + IssuerProjectionReconciliationRequestDigestV1.digest( + expectedIssuerId, caller, expectedProjectionKey, requestId); + if (!expectedCaptureDigest.equals(receipt.requestDigest())) { + throw invalidInstallationReceipt("original capture request digest changed"); + } + + verifyCapturedSource(captured); + if (projectionSnapshot.json() == null) { + throw invalidInstallationReceipt("exact stored projection readback is absent"); + } + String projectionJson = projectionSnapshot.json(); + byte[] projectionBytes = encodeUtf8Strict(projectionJson, "installed projection"); + final IssuerAuthorityProjectionV1Codec.Projection projection; + try { + projection = IssuerAuthorityProjectionV1Codec.verify(projectionJson); + } catch (IllegalArgumentException malformed) { + throw invalidInstallationReceipt("installed projection is not a closed valid projection"); + } + + if (!expectedIssuerId.equals(projection.issuerId()) + || !captured.sourceScope().equals("issuer/" + projection.issuerId()) + || !captured.outboxStreamKey().equals(projection.streamKey()) + || !new BigInteger(captured.issuerAuthGeneration()).equals(projection.generation()) + || !new BigInteger(captured.sourceVersion()).equals(projection.sourceVersion()) + || !new BigInteger(captured.outboxSequence()).equals(projection.sequence()) + || projection.latestEvent().isPresent() != captured.latestEvent().isPresent() + || (captured.latestEvent().isPresent() + && !captured + .latestEvent() + .orElseThrow() + .canonicalJson() + .equals(projection.latestEvent().orElseThrow().canonicalJson()))) { + throw invalidInstallationReceipt( + "installed projection does not preserve the complete captured checkpoint and event"); + } + + String requestDigest = + IssuerProjectionInstallationAcknowledgmentDigestV1.digest( + expectedIssuerId, + caller, + expectedProjectionKey, + operationId, + requestId, + IssuerProjectionReconciliationRequestDigestV1.VERSION, + expectedCaptureDigest, + projectionJson); + return new VerifiedInstallation( + operationId, + requestId, + caller, + expectedProjectionKey, + expectedCaptureDigest, + projectionJson, + projectionBytes, + requestDigest); + } + + private void verifyCapturedSource(SourceSnapshot captured) { + String expectedSourceScope = "issuer/" + expectedIssuerId; + String expectedStreamKey = + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + expectedSourceScope; + if (captured == null + || !expectedIssuerId.equals(captured.issuerId()) + || !expectedSourceScope.equals(captured.sourceScope()) + || !expectedStreamKey.equals(captured.outboxStreamKey())) { + throw invalidInstallationReceipt("captured source scope or issuer changed"); + } + BigInteger generation = + parseInstallationPositiveDecimal(captured.issuerAuthGeneration(), "issuer generation"); + BigInteger sourceVersion = + parseInstallationPositiveDecimal(captured.sourceVersion(), "source version"); + BigInteger sequence = + parseInstallationNonnegativeDecimal(captured.outboxSequence(), "outbox sequence"); + IssuerGenerationAuthorityEvent latest = captured.latestEvent().orElse(null); + if (sequence.signum() == 0) { + if (!BigInteger.ONE.equals(generation) + || !BigInteger.ONE.equals(sourceVersion) + || latest != null) { + throw invalidInstallationReceipt("captured zero checkpoint is not the original baseline"); + } + return; + } + if (latest == null) { + throw invalidInstallationReceipt("positive captured checkpoint has no canonical event"); + } + final IssuerGenerationAuthorityEvent verified; + try { + verified = + verifyEvent( + latest.canonicalJson(), + "captured source event", + expectedIssuerId, + captured.sourceScope(), + captured.outboxStreamKey()); + } catch (IllegalStateException malformed) { + throw invalidInstallationReceipt("captured source event is invalid", malformed); + } + if (!sequence.equals( + parseInstallationPositiveDecimal(verified.outboxSequence(), "event sequence")) + || !generation.equals( + parseInstallationPositiveDecimal(verified.issuerAuthGeneration(), "event generation")) + || !sourceVersion.equals( + parseInstallationPositiveDecimal(verified.sourceVersion(), "event source version"))) { + throw invalidInstallationReceipt("captured event does not match its complete checkpoint"); + } + } + + private InstallationAcknowledgmentReceipt verifyInstallationAcknowledgmentResponse( + AcknowledgeIssuerProjectionForRuntimeResponse response, VerifiedInstallation installation) { + if (response == null) { + throw invalidInstallationAcknowledgmentResponse("response is absent"); + } + if (!response.getUnknownFields().asMap().isEmpty() || response.getAllFields().size() != 14) { + throw invalidInstallationAcknowledgmentResponse( + "response contains unsupported, missing, or defaulted fields"); + } + + UUID acknowledgmentId; + try { + acknowledgmentId = + parseCanonicalNonNilUuid(response.getAcknowledgmentId(), "acknowledgment ID"); + } catch (IllegalArgumentException malformed) { + throw invalidInstallationAcknowledgmentResponse( + "acknowledgment ID is not a canonical non-nil UUID", malformed); + } + + String expectedProjectionSha256 = sha256Hex(installation.projectionBytes()); + if (!INSTALLATION_ACK_SCHEMA_VERSION.equals(response.getSchemaVersion()) + || !workloadNamespace.equals(response.getTargetNamespace()) + || !expectedIssuerId.equals(response.getIssuerId()) + || !installation.callerWorkloadIdentity().equals(response.getCallerWorkloadIdentity()) + || !installation.projectionKey().equals(response.getProjectionKey()) + || !installation.operationId().toString().equals(response.getCaptureOperationId()) + || !installation.requestId().toString().equals(response.getCaptureRequestId()) + || response.getCaptureRequestDigestVersion() + != IssuerProjectionReconciliationRequestDigestV1.VERSION + || !installation.captureRequestDigest().equals(response.getCaptureRequestDigest()) + || response.getRequestDigestVersion() + != IssuerProjectionInstallationAcknowledgmentDigestV1.VERSION + || !installation.requestDigest().equals(response.getRequestDigest()) + || !installation.projectionJson().equals(response.getInstalledProjectionJson()) + || !expectedProjectionSha256.equals(response.getInstalledProjectionSha256())) { + throw invalidInstallationAcknowledgmentResponse( + "schema, namespace, acknowledgment bindings, digest, or exact projection changed"); + } + + return new InstallationAcknowledgmentReceipt( + acknowledgmentId, + installation.operationId(), + installation.requestId(), + expectedIssuerId, + workloadNamespace, + installation.callerWorkloadIdentity(), + installation.projectionKey(), + installation.captureRequestDigest(), + IssuerProjectionReconciliationRequestDigestV1.VERSION, + installation.requestDigest(), + IssuerProjectionInstallationAcknowledgmentDigestV1.VERSION, + installation.projectionJson(), + expectedProjectionSha256); + } + + private static BigInteger parseInstallationPositiveDecimal(String value, String label) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw invalidInstallationReceipt(label + " is not a canonical positive decimal"); + } + return new BigInteger(value); + } + + private static BigInteger parseInstallationNonnegativeDecimal(String value, String label) { + if (value == null || !value.matches("(?:0|[1-9][0-9]*)")) { + throw invalidInstallationReceipt(label + " is not a canonical nonnegative decimal"); + } + return new BigInteger(value); + } + + private static boolean isNil(UUID value) { + return new UUID(0L, 0L).equals(value); + } + + private static byte[] encodeUtf8Strict(String value, String label) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException malformed) { + throw invalidInstallationReceipt(label + " is not exact valid UTF-8 text", malformed); + } + } + + private static String sha256Hex(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + private SourceReadback read(UUID requestId, BigInteger requestedSequence) { IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub currentStub = stub(); if (currentStub == null) { @@ -145,7 +453,101 @@ private SourceReadback verifyResponse( throw invalidResponse("response schema, namespace, or request echo changed"); } - IssuerAuthoritySourceSnapshot wireSnapshot = response.getSourceSnapshot(); + SourceSnapshot snapshot = verifySnapshot(response.getSourceSnapshot()); + BigInteger generation = new BigInteger(snapshot.issuerAuthGeneration()); + BigInteger sourceVersion = new BigInteger(snapshot.sourceVersion()); + BigInteger currentSequence = new BigInteger(snapshot.outboxSequence()); + IssuerGenerationAuthorityEvent latestEvent = snapshot.latestEvent().orElse(null); + + IssuerGenerationAuthorityEvent requestedEvent = null; + if (requestedSequence != null) { + if (!response.hasRequestedEventCanonicalJson()) { + throw invalidResponse("historical selection has no requested event"); + } + requestedEvent = + verifyEvent( + response.getRequestedEventCanonicalJson(), + "requested historical event", + expectedIssuerId, + snapshot.sourceScope(), + snapshot.outboxStreamKey()); + BigInteger selectedEventSequence = + parseResponsePositiveDecimal(requestedEvent.outboxSequence(), "requested event sequence"); + BigInteger selectedGeneration = + parseResponsePositiveDecimal( + requestedEvent.issuerAuthGeneration(), "requested event generation"); + BigInteger selectedVersion = + parseResponsePositiveDecimal( + requestedEvent.sourceVersion(), "requested event source version"); + if (!requestedSequence.equals(selectedEventSequence) + || selectedEventSequence.compareTo(currentSequence) > 0 + || selectedGeneration.compareTo(generation) > 0 + || selectedVersion.compareTo(sourceVersion) > 0) { + throw invalidResponse( + "requested historical event is not exact or is ahead of the snapshot"); + } + if (selectedEventSequence.equals(currentSequence) + && (latestEvent == null + || !requestedEvent.canonicalJson().equals(latestEvent.canonicalJson()))) { + throw invalidResponse("current-sequence historical event differs from the latest event"); + } + } + + return new SourceReadback(requestId.toString(), workloadNamespace, snapshot, requestedEvent); + } + + private ProjectionCaptureReceipt verifyCaptureResponse( + CaptureIssuerProjectionForRuntimeResponse response, UUID requestId) { + if (response == null) { + throw invalidCaptureResponse("response is absent"); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw invalidCaptureResponse("response contains unsupported fields"); + } + + UUID operationUUID; + try { + operationUUID = parseCanonicalNonNilUuid(response.getOperationId(), "operation ID"); + } catch (IllegalArgumentException exception) { + throw invalidCaptureResponse("operation ID is not a canonical non-nil UUID", exception); + } + + String callerWorkloadIdentity = expectedGameSessionWorkloadIdentity(); + String expectedProjectionKey = PROJECTION_KEY_PREFIX + expectedIssuerId; + String expectedRequestDigest = + IssuerProjectionReconciliationRequestDigestV1.digest( + expectedIssuerId, callerWorkloadIdentity, expectedProjectionKey, requestId); + if (!CAPTURE_SCHEMA_VERSION.equals(response.getSchemaVersion()) + || !workloadNamespace.equals(response.getTargetNamespace()) + || !requestId.toString().equals(response.getRequestId()) + || !expectedIssuerId.equals(response.getIssuerId()) + || !callerWorkloadIdentity.equals(response.getCallerWorkloadIdentity()) + || !expectedProjectionKey.equals(response.getProjectionKey()) + || response.getRequestDigestVersion() != 1 + || !expectedRequestDigest.equals(response.getRequestDigest())) { + throw invalidCaptureResponse("schema, identity, binding, or request digest changed"); + } + if (!response.hasCapturedSourceSnapshot()) { + throw invalidCaptureResponse("captured source snapshot is absent"); + } + + SourceSnapshot capturedSource = verifySnapshot(response.getCapturedSourceSnapshot()); + return new ProjectionCaptureReceipt( + operationUUID, + requestId, + expectedIssuerId, + callerWorkloadIdentity, + expectedProjectionKey, + response.getRequestDigestVersion(), + expectedRequestDigest, + capturedSource); + } + + /** Validates the complete issuer source snapshot without fabricating a read RPC envelope. */ + private SourceSnapshot verifySnapshot(IssuerAuthoritySourceSnapshot wireSnapshot) { + if (wireSnapshot == null) { + throw invalidResponse("source snapshot is absent"); + } if (!wireSnapshot.getUnknownFields().asMap().isEmpty()) { throw invalidResponse("source snapshot contains unsupported fields"); } @@ -165,10 +567,10 @@ private SourceReadback verifyResponse( wireSnapshot.getIssuerAuthGeneration(), "issuer auth generation"); BigInteger sourceVersion = parseResponsePositiveDecimal(wireSnapshot.getSourceVersion(), "source version"); - BigInteger currentSequence = + BigInteger sequence = parseNonnegativeDecimal(wireSnapshot.getOutboxSequence(), "outbox sequence"); IssuerGenerationAuthorityEvent latestEvent = null; - if (currentSequence.signum() == 0) { + if (sequence.signum() == 0) { if (!BigInteger.ONE.equals(generation) || !BigInteger.ONE.equals(sourceVersion) || wireSnapshot.hasLatestEventCanonicalJson()) { @@ -185,7 +587,7 @@ private SourceReadback verifyResponse( expectedIssuerId, sourceScope, streamKey); - if (!currentSequence.equals( + if (!sequence.equals( parseResponsePositiveDecimal(latestEvent.outboxSequence(), "event sequence")) || !generation.equals( parseResponsePositiveDecimal(latestEvent.issuerAuthGeneration(), "event generation")) @@ -194,51 +596,18 @@ private SourceReadback verifyResponse( throw invalidResponse("latest event does not match the complete source checkpoint"); } } + return new SourceSnapshot( + expectedIssuerId, + sourceScope, + streamKey, + generation.toString(), + sourceVersion.toString(), + sequence.toString(), + latestEvent); + } - IssuerGenerationAuthorityEvent requestedEvent = null; - if (requestedSequence != null) { - if (!response.hasRequestedEventCanonicalJson()) { - throw invalidResponse("historical selection has no requested event"); - } - requestedEvent = - verifyEvent( - response.getRequestedEventCanonicalJson(), - "requested historical event", - expectedIssuerId, - sourceScope, - streamKey); - BigInteger selectedEventSequence = - parseResponsePositiveDecimal(requestedEvent.outboxSequence(), "requested event sequence"); - BigInteger selectedGeneration = - parseResponsePositiveDecimal( - requestedEvent.issuerAuthGeneration(), "requested event generation"); - BigInteger selectedVersion = - parseResponsePositiveDecimal( - requestedEvent.sourceVersion(), "requested event source version"); - if (!requestedSequence.equals(selectedEventSequence) - || selectedEventSequence.compareTo(currentSequence) > 0 - || selectedGeneration.compareTo(generation) > 0 - || selectedVersion.compareTo(sourceVersion) > 0) { - throw invalidResponse( - "requested historical event is not exact or is ahead of the snapshot"); - } - if (selectedEventSequence.equals(currentSequence) - && (latestEvent == null - || !requestedEvent.canonicalJson().equals(latestEvent.canonicalJson()))) { - throw invalidResponse("current-sequence historical event differs from the latest event"); - } - } - - SourceSnapshot snapshot = - new SourceSnapshot( - expectedIssuerId, - sourceScope, - streamKey, - generation.toString(), - sourceVersion.toString(), - currentSequence.toString(), - latestEvent); - return new SourceReadback(requestId.toString(), workloadNamespace, snapshot, requestedEvent); + private String expectedGameSessionWorkloadIdentity() { + return "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; } private static IssuerGenerationAuthorityEvent verifyEvent( @@ -311,6 +680,37 @@ private static IllegalStateException invalidResponse(String message) { return new IllegalStateException("Account issuer authority response " + message); } + private static IllegalStateException invalidCaptureResponse(String message) { + return new IllegalStateException("Account issuer projection capture response " + message); + } + + private static IllegalStateException invalidCaptureResponse( + String message, IllegalArgumentException cause) { + return new IllegalStateException( + "Account issuer projection capture response " + message, cause); + } + + private static IllegalArgumentException invalidInstallationReceipt(String message) { + return new IllegalArgumentException("Game Session issuer installation receipt " + message); + } + + private static IllegalArgumentException invalidInstallationReceipt( + String message, Throwable cause) { + return new IllegalArgumentException( + "Game Session issuer installation receipt " + message, cause); + } + + private static IllegalStateException invalidInstallationAcknowledgmentResponse(String message) { + return new IllegalStateException( + "Account issuer projection installation acknowledgment response " + message); + } + + private static IllegalStateException invalidInstallationAcknowledgmentResponse( + String message, IllegalArgumentException cause) { + return new IllegalStateException( + "Account issuer projection installation acknowledgment response " + message, cause); + } + private static CommonGrpcClientProperties requireGameSessionMtls( CommonGrpcClientProperties tlsProps) { if (tlsProps == null) { @@ -431,4 +831,175 @@ public Optional requestedEvent() { return Optional.ofNullable(requestedEvent); } } + + /** Immutable authenticated Account capture receipt; it is not projection-install authority. */ + public static final class ProjectionCaptureReceipt { + private final UUID operationUUID; + private final UUID requestUUID; + private final String issuerId; + private final String callerWorkloadIdentity; + private final String projectionKey; + private final int requestDigestVersion; + private final String requestDigest; + private final SourceSnapshot capturedSource; + + private ProjectionCaptureReceipt( + UUID operationUUID, + UUID requestUUID, + String issuerId, + String callerWorkloadIdentity, + String projectionKey, + int requestDigestVersion, + String requestDigest, + SourceSnapshot capturedSource) { + this.operationUUID = operationUUID; + this.requestUUID = requestUUID; + this.issuerId = issuerId; + this.callerWorkloadIdentity = callerWorkloadIdentity; + this.projectionKey = projectionKey; + this.requestDigestVersion = requestDigestVersion; + this.requestDigest = requestDigest; + this.capturedSource = capturedSource; + } + + public UUID operationUUID() { + return operationUUID; + } + + public UUID requestUUID() { + return requestUUID; + } + + public String issuerId() { + return issuerId; + } + + public String callerWorkloadIdentity() { + return callerWorkloadIdentity; + } + + public String projectionKey() { + return projectionKey; + } + + public int requestDigestVersion() { + return requestDigestVersion; + } + + public String requestDigest() { + return requestDigest; + } + + public SourceSnapshot capturedSource() { + return capturedSource; + } + } + + private record VerifiedInstallation( + UUID operationId, + UUID requestId, + String callerWorkloadIdentity, + String projectionKey, + String captureRequestDigest, + String projectionJson, + byte[] projectionBytes, + String requestDigest) {} + + /** Immutable historical Account acknowledgment, not current readiness or recipient authority. */ + public static final class InstallationAcknowledgmentReceipt { + private final UUID acknowledgmentId; + private final UUID captureOperationId; + private final UUID captureRequestId; + private final String issuerId; + private final String targetNamespace; + private final String callerWorkloadIdentity; + private final String projectionKey; + private final String captureRequestDigest; + private final int captureRequestDigestVersion; + private final String requestDigest; + private final int requestDigestVersion; + private final String installedProjectionJson; + private final String installedProjectionSha256; + + private InstallationAcknowledgmentReceipt( + UUID acknowledgmentId, + UUID captureOperationId, + UUID captureRequestId, + String issuerId, + String targetNamespace, + String callerWorkloadIdentity, + String projectionKey, + String captureRequestDigest, + int captureRequestDigestVersion, + String requestDigest, + int requestDigestVersion, + String installedProjectionJson, + String installedProjectionSha256) { + this.acknowledgmentId = acknowledgmentId; + this.captureOperationId = captureOperationId; + this.captureRequestId = captureRequestId; + this.issuerId = issuerId; + this.targetNamespace = targetNamespace; + this.callerWorkloadIdentity = callerWorkloadIdentity; + this.projectionKey = projectionKey; + this.captureRequestDigest = captureRequestDigest; + this.captureRequestDigestVersion = captureRequestDigestVersion; + this.requestDigest = requestDigest; + this.requestDigestVersion = requestDigestVersion; + this.installedProjectionJson = installedProjectionJson; + this.installedProjectionSha256 = installedProjectionSha256; + } + + public UUID acknowledgmentId() { + return acknowledgmentId; + } + + public UUID captureOperationId() { + return captureOperationId; + } + + public UUID captureRequestId() { + return captureRequestId; + } + + public String issuerId() { + return issuerId; + } + + public String targetNamespace() { + return targetNamespace; + } + + public String callerWorkloadIdentity() { + return callerWorkloadIdentity; + } + + public String projectionKey() { + return projectionKey; + } + + public String captureRequestDigest() { + return captureRequestDigest; + } + + public int captureRequestDigestVersion() { + return captureRequestDigestVersion; + } + + public String requestDigest() { + return requestDigest; + } + + public int requestDigestVersion() { + return requestDigestVersion; + } + + public String installedProjectionJson() { + return installedProjectionJson; + } + + public String installedProjectionSha256() { + return installedProjectionSha256; + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java index 5cf08a6f40..eb38cbade7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java @@ -1,11 +1,13 @@ package net.firedevops.firemud.gamesession.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data public class GameInstance { private Long id; + private UUID gameInstanceUuid; private Long tenantId; private String runtimeVersion; private String scriptPatchVersion; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java index 87c810d4ad..996985acda 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java @@ -14,10 +14,10 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameInstance; -import net.firedevops.firemud.gamesession.jooq.tables.records.GameInstancesRecord; import net.firedevops.firemud.gamesession.service.AccountIds; import net.firedevops.firemud.gamesession.service.RuntimeVersionIdResolver; import net.firedevops.firemud.gamesession.service.ScriptPinTupleCoherence; +import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -32,8 +32,11 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class GameInstanceRepository { + private static final Field GAME_INSTANCE_UUID = + DSL.field(DSL.name("game_instance_uuid"), UUID.class); private static final Field[] SELECT_FIELDS = { GAME_INSTANCES.ID, + GAME_INSTANCE_UUID, GAME_INSTANCES.TENANT_ID, GAME_INSTANCES.RUNTIME_VERSION, GAME_INSTANCES.SCRIPT_PATCH_VERSION, @@ -93,6 +96,56 @@ public Optional findByTenantIdAndRunOwnedStartRequestIdForUpdate( .fetchOptional(this::toEntity); } + /** + * Reads the existing Game Session owner's canonical UUID for an internal numeric selector. + * + *

This is strict owner readback, not an allocator or a numeric-to-UUID derivation. Missing + * rows, retained rows without a UUID, invalid identity state, or conflicting UUID claims deny + * resolution. + */ + public String requireCanonicalGameInstanceUuidByTenantIdAndPrivateId( + Long tenantId, Long privateGameInstanceId) { + if (tenantId == null || tenantId <= 0L) { + throw new IllegalArgumentException("tenantId must be a positive internal selector"); + } + if (privateGameInstanceId == null || privateGameInstanceId <= 0L) { + throw new IllegalArgumentException( + "privateGameInstanceId must be a positive internal selector"); + } + + Record source = + dsl.select(GAME_INSTANCE_UUID) + .from(GAME_INSTANCES) + .where( + GAME_INSTANCES + .ID + .eq(privateGameInstanceId) + .and(GAME_INSTANCES.TENANT_ID.eq(tenantId))) + .fetchOne(); + if (source == null) { + throw new IllegalArgumentException("Game instance not found in tenant scope"); + } + + UUID uuid = source.get(GAME_INSTANCE_UUID); + if (uuid == null) { + throw new IllegalStateException("Game instance has no canonical UUID mapping"); + } + String canonicalUuid = uuid.toString(); + if (!AccountIds.isCanonicalNonNilUuid(canonicalUuid)) { + throw new IllegalStateException("Game instance has an invalid canonical UUID mapping"); + } + + Long claimCount = + dsl.selectCount() + .from(GAME_INSTANCES) + .where(GAME_INSTANCE_UUID.eq(uuid)) + .fetchOne(0, Long.class); + if (claimCount == null || claimCount != 1L) { + throw new IllegalStateException("Game instance UUID mapping is conflicting"); + } + return canonicalUuid; + } + /** * Reads the authoritative game instance while holding its row lock. * @@ -167,6 +220,9 @@ public GameInstance save(GameInstance entity) { throw new IllegalArgumentException( "New game instances require a canonical ownerAccountId UUID"); } + if (entity.getId() == null && entity.getGameInstanceUuid() != null) { + throw new IllegalArgumentException("New game instance UUIDs are allocated by Game Session"); + } if (entity.getId() == null && entity.getLegacyOwnerAccountId() != null) { throw new IllegalArgumentException("New game instances cannot use a legacy numeric owner"); } @@ -175,14 +231,68 @@ public GameInstance save(GameInstance entity) { entity.getScriptPinEpoch(), entity.getScriptPatchPinnedControlPlaneRequestId()); if (entity.getId() == null) { - GameInstancesRecord record = dsl.newRecord(GAME_INSTANCES); - populate(record, entity, ownerAccountUuid); long initialRowVersion = entity.getRowVersion() == null ? 0L : entity.getRowVersion(); - record.setRowVersion(initialRowVersion); - record.store(); - return findById(record.getId()).orElseThrow(); + UUID gameInstanceUuid = UUID.randomUUID(); + if (!AccountIds.isCanonicalNonNilUuid(gameInstanceUuid.toString())) { + throw new IllegalStateException("Game Session generated an invalid game instance UUID"); + } + Record inserted = + dsl.insertInto(GAME_INSTANCES) + .set(GAME_INSTANCES.TENANT_ID, entity.getTenantId()) + .set(GAME_INSTANCES.RUNTIME_VERSION, entity.getRuntimeVersion()) + .set(GAME_INSTANCES.SCRIPT_PATCH_VERSION, entity.getScriptPatchVersion()) + .set( + GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID, entity.getScriptPatchBaseVersionId()) + .set(GAME_INSTANCES.SCRIPT_PIN_EPOCH, entity.getScriptPinEpoch()) + .set(GAME_INSTANCES.GAME_TEMPLATE_ID, entity.getGameTemplateId()) + .set(GAME_INSTANCES.LAUNCH_DESCRIPTOR_ID, entity.getLaunchDescriptorId()) + .set(GAME_INSTANCES.VERSION_ID, entity.getVersionId()) + .set(GAME_INSTANCES.RELEASE_BUNDLE_ID, entity.getReleaseBundleId()) + .set(GAME_INSTANCES.VERSION_STATE_EPOCH, entity.getVersionStateEpoch()) + .set(GAME_INSTANCES.GENERATION_CONFIG_REVISION, entity.getGenerationConfigRevision()) + .set(GAME_INSTANCES.REMAP_SET_ID, entity.getRemapSetId()) + .set( + GAME_INSTANCES.SCRIPT_PATCH_PINNED_AT, + toLocalDateTime(entity.getScriptPatchPinnedAt())) + .set(GAME_INSTANCES.SCRIPT_PATCH_PINNED_BY, entity.getScriptPatchPinnedBy()) + .set(GAME_INSTANCES.SCRIPT_PATCH_PINNED_REASON, entity.getScriptPatchPinnedReason()) + .set( + GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID, + entity.getScriptPatchPinnedControlPlaneRequestId()) + .set(GAME_INSTANCES.OWNER_ACCOUNT_ID, (Long) null) + .set(GAME_INSTANCES.OWNER_ACCOUNT_UUID, ownerAccountUuid) + .set(GAME_INSTANCES.STATUS, entity.getStatus()) + .set(GAME_INSTANCES.ROW_VERSION, initialRowVersion) + .set(GAME_INSTANCES.RUN_OWNED_START_REQUEST_ID, entity.getRunOwnedStartRequestId()) + .set( + GAME_INSTANCES.RUN_OWNED_START_REQUEST_DIGEST, + entity.getRunOwnedStartRequestDigest()) + .set( + GAME_INSTANCES.RUN_OWNED_START_PUBLISHED_RELEASE_BUNDLE_REF, + entity.getRunOwnedStartPublishedReleaseBundleRef()) + .set( + GAME_INSTANCES.RUN_OWNED_START_PREPARING_EPOCH, + entity.getRunOwnedStartPreparingEpoch()) + .set( + GAME_INSTANCES.RUN_OWNED_START_ACTIVE_EPOCH, entity.getRunOwnedStartActiveEpoch()) + .set(GAME_INSTANCE_UUID, gameInstanceUuid) + .returning(GAME_INSTANCES.ID) + .fetchOne(); + if (inserted == null) { + throw new IllegalStateException("Failed to insert game instance"); + } + return findById(inserted.get(GAME_INSTANCES.ID)).orElseThrow(); } + UUID expectedGameInstanceUuid = entity.getGameInstanceUuid(); + if (expectedGameInstanceUuid != null + && !AccountIds.isCanonicalNonNilUuid(expectedGameInstanceUuid.toString())) { + throw new IllegalArgumentException("gameInstanceUuid must be a canonical non-nil UUID"); + } + Condition expectedGameInstanceIdentity = + expectedGameInstanceUuid == null + ? GAME_INSTANCE_UUID.isNull() + : GAME_INSTANCE_UUID.eq(expectedGameInstanceUuid); long currentRowVersion = entity.getRowVersion() == null ? 0L : entity.getRowVersion(); long nextRowVersion = currentRowVersion + 1L; int updated = @@ -218,7 +328,8 @@ public GameInstance save(GameInstance entity) { GAME_INSTANCES .ID .eq(entity.getId()) - .and(GAME_INSTANCES.ROW_VERSION.eq(currentRowVersion))) + .and(GAME_INSTANCES.ROW_VERSION.eq(currentRowVersion)) + .and(expectedGameInstanceIdentity)) .execute(); if (updated != 1) { throw new IllegalStateException("Failed to update game_instance id=" + entity.getId()); @@ -888,38 +999,15 @@ private String normalizePatch(String value) { return isAbsent(value) ? null : value; } - private void populate(GameInstancesRecord record, GameInstance entity, UUID ownerAccountUuid) { - record.setTenantId(entity.getTenantId()); - record.setRuntimeVersion(entity.getRuntimeVersion()); - record.setScriptPatchVersion(entity.getScriptPatchVersion()); - record.setScriptPatchBaseVersionId(entity.getScriptPatchBaseVersionId()); - record.setScriptPinEpoch(entity.getScriptPinEpoch()); - record.setGameTemplateId(entity.getGameTemplateId()); - record.setLaunchDescriptorId(entity.getLaunchDescriptorId()); - record.setVersionId(entity.getVersionId()); - record.setReleaseBundleId(entity.getReleaseBundleId()); - record.setVersionStateEpoch(entity.getVersionStateEpoch()); - record.setGenerationConfigRevision(entity.getGenerationConfigRevision()); - record.setRemapSetId(entity.getRemapSetId()); - record.setScriptPatchPinnedAt(toLocalDateTime(entity.getScriptPatchPinnedAt())); - record.setScriptPatchPinnedBy(entity.getScriptPatchPinnedBy()); - record.setScriptPatchPinnedReason(entity.getScriptPatchPinnedReason()); - record.setScriptPatchPinnedControlPlaneRequestId( - entity.getScriptPatchPinnedControlPlaneRequestId()); - record.setOwnerAccountId(null); - record.setOwnerAccountUuid(ownerAccountUuid); - record.setStatus(entity.getStatus()); - record.setRunOwnedStartRequestId(entity.getRunOwnedStartRequestId()); - record.setRunOwnedStartRequestDigest(entity.getRunOwnedStartRequestDigest()); - record.setRunOwnedStartPublishedReleaseBundleRef( - entity.getRunOwnedStartPublishedReleaseBundleRef()); - record.setRunOwnedStartPreparingEpoch(entity.getRunOwnedStartPreparingEpoch()); - record.setRunOwnedStartActiveEpoch(entity.getRunOwnedStartActiveEpoch()); - } - private GameInstance toEntity(Record record) { GameInstance entity = new GameInstance(); entity.setId(record.get(GAME_INSTANCES.ID)); + UUID gameInstanceUuid = record.get(GAME_INSTANCE_UUID); + if (gameInstanceUuid != null + && !AccountIds.isCanonicalNonNilUuid(gameInstanceUuid.toString())) { + throw new IllegalStateException("Stored game instance UUID is not canonical and non-nil"); + } + entity.setGameInstanceUuid(gameInstanceUuid); entity.setTenantId(record.get(GAME_INSTANCES.TENANT_ID)); entity.setRuntimeVersion(record.get(GAME_INSTANCES.RUNTIME_VERSION)); entity.setScriptPatchVersion(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)); 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 index d55623afe1..dcafc74153 100644 --- 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 @@ -8,33 +8,24 @@ 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.IssuerAuthorityProjectionV1Codec; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.account.authority.IssuerProjectionReconciliationRequestDigestV1; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.ProjectionCaptureReceipt; 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"; + public static final String SCHEMA_VERSION = IssuerAuthorityProjectionV1Codec.SCHEMA_VERSION; 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() {} /** @@ -167,6 +158,150 @@ public static Decision decide( } } + /** + * Reconciles a valid local projection against one privately verified Account capture and its + * matching current readback. A captured checkpoint may bridge a locally missed event range; + * ordinary selected-event delivery remains contiguous through {@link #decide}. + */ + public static Decision reconcile( + Map existingProjection, + ProjectionCaptureReceipt capture, + SourceReadback current, + String appliedAt) { + Optional> observed = immutableObserved(existingProjection); + ExistingProjection existing = null; + if (existingProjection != null) { + try { + existing = parseExistingProjection(existingProjection); + } catch (IllegalArgumentException malformed) { + return new Quarantine(observed, QuarantineReason.MALFORMED_EXISTING_PROJECTION); + } + } + + final Checkpoint captured; + try { + captured = verifyCaptureAndCurrent(capture, current); + } catch (EvidenceRejected rejected) { + return new Quarantine(observed, rejected.reason()); + } catch (IllegalArgumentException malformed) { + return new Quarantine(observed, QuarantineReason.MALFORMED_CAPTURE_EVIDENCE); + } + + if (existing == null) { + try { + requireAppliedAt(appliedAt); + return new Mutation( + Optional.empty(), + projectionFor(captured, appliedAt), + MutationKind.CAPTURE_RECONCILIATION); + } catch (EvidenceRejected rejected) { + return new Quarantine(Optional.empty(), rejected.reason()); + } + } + + if (!existing.issuerId().equals(captured.issuerId()) + || !existing.streamKey().equals(captured.streamKey())) { + return new Quarantine(observed, QuarantineReason.ISSUER_OR_STREAM_CHANGED); + } + + int sequenceOrder = existing.sequence().compareTo(captured.sequence()); + if (sequenceOrder > 0) { + return new Quarantine(observed, QuarantineReason.CAPTURE_PROJECTION_AHEAD); + } + if (existing.generation().compareTo(captured.generation()) > 0 + || existing.sourceVersion().compareTo(captured.sourceVersion()) > 0) { + return new Quarantine(observed, QuarantineReason.CAPTURE_SOURCE_REGRESSED); + } + + if (sequenceOrder == 0) { + if (!existing.generation().equals(captured.generation()) + || !existing.sourceVersion().equals(captured.sourceVersion()) + || !sameEvent(existing.latestEvent(), captured.latestEvent())) { + return new Quarantine(observed, QuarantineReason.CAPTURE_SAME_CHECKPOINT_DISAGREEMENT); + } + return new NoOp(NoOpReason.CAPTURE_ALREADY_INSTALLED); + } + + if (captured.sourceVersion().compareTo(existing.sourceVersion()) <= 0) { + return new Quarantine(observed, QuarantineReason.CAPTURE_SOURCE_REGRESSED); + } + try { + requireAppliedAt(appliedAt); + return new Mutation( + observed, projectionFor(captured, appliedAt), MutationKind.CAPTURE_RECONCILIATION); + } catch (EvidenceRejected rejected) { + return new Quarantine(observed, rejected.reason()); + } + } + + private static Checkpoint verifyCaptureAndCurrent( + ProjectionCaptureReceipt capture, SourceReadback current) { + if (capture == null + || capture.operationUUID() == null + || capture.requestUUID() == null + || capture.issuerId() == null + || capture.callerWorkloadIdentity() == null + || capture.projectionKey() == null + || capture.requestDigest() == null + || capture.capturedSource() == null + || current == null + || current.targetNamespace() == null + || current.targetNamespace().isBlank()) { + throw reject(QuarantineReason.MALFORMED_CAPTURE_EVIDENCE); + } + + UUID nil = new UUID(0L, 0L); + if (nil.equals(capture.operationUUID()) + || nil.equals(capture.requestUUID()) + || !capture.requestUUID().toString().equals(current.requestId())) { + throw reject(QuarantineReason.CAPTURE_BINDING_MISMATCH); + } + String expectedCaller = + "spiffe://firemud/ns/" + current.targetNamespace() + "/sa/game-session-service"; + String expectedKey = IssuerAuthorityProjectionRedisContract.keyForIssuer(capture.issuerId()); + if (capture.issuerId().isBlank() + || !expectedCaller.equals(capture.callerWorkloadIdentity()) + || !expectedKey.equals(capture.projectionKey()) + || capture.requestDigestVersion() != IssuerProjectionReconciliationRequestDigestV1.VERSION + || !IssuerProjectionReconciliationRequestDigestV1.digest( + capture.issuerId(), + capture.callerWorkloadIdentity(), + capture.projectionKey(), + capture.requestUUID()) + .equals(capture.requestDigest())) { + throw reject(QuarantineReason.CAPTURE_BINDING_MISMATCH); + } + + VerifiedReadback verifiedCurrent = verifyReadback(current); + if (verifiedCurrent.selectedEvent().isPresent()) { + throw reject(QuarantineReason.CAPTURE_REQUIRES_CURRENT_READBACK); + } + Checkpoint captured = verifySnapshot(capture.capturedSource()); + Checkpoint currentCheckpoint = verifiedCurrent.snapshot(); + if (!capture.issuerId().equals(captured.issuerId()) + || !sameCheckpoint(captured, currentCheckpoint)) { + throw reject(QuarantineReason.CAPTURE_CURRENT_SOURCE_MISMATCH); + } + return captured; + } + + private static boolean sameCheckpoint(Checkpoint left, Checkpoint right) { + return left.issuerId().equals(right.issuerId()) + && left.streamKey().equals(right.streamKey()) + && left.generation().equals(right.generation()) + && left.sourceVersion().equals(right.sourceVersion()) + && left.sequence().equals(right.sequence()) + && sameEvent(left.latestEvent(), right.latestEvent()); + } + + private static boolean sameEvent( + IssuerGenerationAuthorityEvent left, IssuerGenerationAuthorityEvent right) { + if (left == null || right == null) { + return left == right; + } + return left.canonicalJson().equals(right.canonicalJson()); + } + private static VerifiedReadback verifyReadback(SourceReadback readback) { if (readback == null || readback.requestId() == null @@ -331,12 +466,12 @@ private static Map projectionMap( Map fields = new LinkedHashMap<>(); fields.put("schemaVersion", SCHEMA_VERSION); fields.put("issuerId", issuerId); - fields.put("issuerAuthGeneration", issuerGeneration); + fields.put("lastAppliedIssuerGeneration", issuerGeneration); fields.put("lastAppliedSourceOutboxSequence", sequence); - fields.put("sourceOutboxStreamKey", streamKey); + fields.put("outboxStreamKey", streamKey); if (latestEvent != null) { - fields.put("sourceEventId", latestEvent.eventId()); - fields.put("sourceEventDigest", latestEvent.eventDigest()); + fields.put("lastAppliedSourceEventId", latestEvent.eventId()); + fields.put("lastAppliedSourceEventDigest", latestEvent.eventDigest()); } fields.put("appliedAt", appliedAt); fields.put("appliedSourceEvidence", appliedSourceEvidence); @@ -344,97 +479,15 @@ private static Map projectionMap( } 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; + IssuerAuthorityProjectionV1Codec.Projection projection = + IssuerAuthorityProjectionV1Codec.verify(supplied); + return new ExistingProjection( + projection.issuerId(), + projection.generation(), + projection.sourceVersion(), + projection.sequence(), + projection.streamKey(), + projection.latestEvent().orElse(null)); } private static BigInteger positiveDecimal(String value, String label) { @@ -543,17 +596,25 @@ public sealed interface Decision permits Mutation, NoOp, Quarantine {} public enum MutationKind { BOOTSTRAP, - ADVANCE + ADVANCE, + CAPTURE_RECONCILIATION } public enum NoOpReason { EXACT_DUPLICATE, - VERIFIED_HISTORICAL_DUPLICATE + VERIFIED_HISTORICAL_DUPLICATE, + CAPTURE_ALREADY_INSTALLED } public enum QuarantineReason { APPLIED_AT_REQUIRED, BOOTSTRAP_REQUIRES_CURRENT_READBACK, + CAPTURE_BINDING_MISMATCH, + CAPTURE_CURRENT_SOURCE_MISMATCH, + CAPTURE_PROJECTION_AHEAD, + CAPTURE_REQUIRES_CURRENT_READBACK, + CAPTURE_SAME_CHECKPOINT_DISAGREEMENT, + CAPTURE_SOURCE_REGRESSED, CURRENT_CHECKPOINT_CONFLICT, CURRENT_CHECKPOINT_REGRESSED, DUPLICATE_EVENT_CONFLICT, @@ -562,6 +623,7 @@ public enum QuarantineReason { EVENT_SOURCE_VERSION_REGRESSED, HISTORICAL_EVENT_PROGRESS_CONFLICT, ISSUER_OR_STREAM_CHANGED, + MALFORMED_CAPTURE_EVIDENCE, MALFORMED_ACCOUNT_READBACK, MALFORMED_EXISTING_PROJECTION, MISSING_EXISTING_PROJECTION, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerProjectionReconciliationInstaller.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerProjectionReconciliationInstaller.java new file mode 100644 index 0000000000..2405cc7ace --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/IssuerProjectionReconciliationInstaller.java @@ -0,0 +1,221 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.IssuerProjectionReconciliationRequestDigestV1; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.ProjectionCaptureReceipt; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceSnapshot; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ApplyResult; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ProjectionSnapshot; + +/** Explicit, unwired local capture-to-projection reconciliation operation for Game Session. */ +public final class IssuerProjectionReconciliationInstaller { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AccountIssuerAuthorityClient accountClient; + private final RedisIssuerAuthorityProjectionStore projectionStore; + + public IssuerProjectionReconciliationInstaller( + AccountIssuerAuthorityClient accountClient, + RedisIssuerAuthorityProjectionStore projectionStore) { + this.accountClient = Objects.requireNonNull(accountClient, "Account issuer client is required"); + this.projectionStore = + Objects.requireNonNull(projectionStore, "issuer projection store is required"); + } + + /** + * Captures once, proves that capture is still current before local installation, and verifies + * current Account authority again after the registered Redis store returns an exact readback. + */ + public Result install(String requestId, String appliedAt) { + if (!isCanonicalNonNilUuid(requestId)) { + return result(Outcome.QUARANTINED, "INVALID_REQUEST_ID"); + } + + ProjectionCaptureReceipt capture = accountClient.captureProjection(requestId); + SourceReadback currentBefore = accountClient.readCurrent(requestId); + if (!currentMatchesCapture(capture, currentBefore)) { + return result(Outcome.STALE_SOURCE, "CAPTURE_NOT_CURRENT_BEFORE_INSTALLATION"); + } + + ApplyResult installed = projectionStore.installCapture(capture, currentBefore, appliedAt); + RedisIssuerAuthorityProjectionStore.Outcome storeOutcome = installed.outcome(); + if (storeOutcome == RedisIssuerAuthorityProjectionStore.Outcome.STALE) { + return result(Outcome.QUARANTINED, installed.detail().orElse("STORE_CAS_STALE")); + } + if (storeOutcome == RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED) { + return result(Outcome.QUARANTINED, installed.detail().orElse("STORE_QUARANTINED")); + } + if (storeOutcome != RedisIssuerAuthorityProjectionStore.Outcome.APPLIED + && storeOutcome != RedisIssuerAuthorityProjectionStore.Outcome.REPLAYED + && storeOutcome != RedisIssuerAuthorityProjectionStore.Outcome.NO_OP) { + return result(Outcome.QUARANTINED, "STORE_RETURNED_UNSUPPORTED_OUTCOME"); + } + + ProjectionSnapshot projection = installed.snapshot().orElse(null); + if (projection == null + || !IssuerAuthorityProjectionRedisContract.keyForIssuer(capture.issuerId()) + .equals(projection.key())) { + return result(Outcome.QUARANTINED, "STORE_READBACK_BINDING_MISSING"); + } + + SourceReadback currentAfter = accountClient.readCurrent(requestId); + if (!currentMatchesCapture(capture, currentAfter)) { + return result(Outcome.STALE_SOURCE, "CAPTURE_NOT_CURRENT_AFTER_INSTALLATION"); + } + if (!projectionStore.verifiesCaptureSnapshot(capture, currentAfter, projection)) { + return result(Outcome.QUARANTINED, "STORE_SNAPSHOT_DOES_NOT_MATCH_CAPTURE"); + } + + Outcome outcome = + storeOutcome == RedisIssuerAuthorityProjectionStore.Outcome.APPLIED + ? Outcome.INSTALLED + : Outcome.REPLAYED; + return new Result( + outcome, + Optional.of( + new InstallationReceipt( + capture.operationUUID(), + capture.requestUUID(), + capture.requestDigest(), + capture.capturedSource(), + projection)), + Optional.empty()); + } + + private static boolean currentMatchesCapture( + ProjectionCaptureReceipt capture, SourceReadback readback) { + if (capture == null + || readback == null + || capture.requestUUID() == null + || !capture.requestUUID().toString().equals(readback.requestId()) + || readback.targetNamespace() == null + || readback.targetNamespace().isBlank() + || readback.sourceSnapshot() == null + || readback.requestedEvent().isPresent() + || capture.operationUUID() == null + || capture.requestDigest() == null + || capture.requestDigestVersion() != IssuerProjectionReconciliationRequestDigestV1.VERSION + || capture.capturedSource() == null) { + return false; + } + String expectedCaller = + "spiffe://firemud/ns/" + readback.targetNamespace() + "/sa/game-session-service"; + final String expectedProjectionKey; + try { + expectedProjectionKey = + IssuerAuthorityProjectionRedisContract.keyForIssuer(capture.issuerId()); + } catch (IllegalArgumentException malformedIssuer) { + return false; + } + if (!expectedCaller.equals(capture.callerWorkloadIdentity()) + || !expectedProjectionKey.equals(capture.projectionKey()) + || !Objects.equals(capture.issuerId(), capture.capturedSource().issuerId()) + || !IssuerProjectionReconciliationRequestDigestV1.digest( + capture.issuerId(), + capture.callerWorkloadIdentity(), + capture.projectionKey(), + capture.requestUUID()) + .equals(capture.requestDigest())) { + return false; + } + return sameSource(capture.capturedSource(), readback.sourceSnapshot()); + } + + private static boolean sameSource(SourceSnapshot captured, SourceSnapshot current) { + return Objects.equals(captured.issuerId(), current.issuerId()) + && Objects.equals(captured.sourceScope(), current.sourceScope()) + && Objects.equals(captured.outboxStreamKey(), current.outboxStreamKey()) + && Objects.equals(captured.issuerAuthGeneration(), current.issuerAuthGeneration()) + && Objects.equals(captured.sourceVersion(), current.sourceVersion()) + && Objects.equals(captured.outboxSequence(), current.outboxSequence()) + && sameEvent( + captured.latestEvent().map(event -> event.canonicalJson()).orElse(null), + current.latestEvent().map(event -> event.canonicalJson()).orElse(null)); + } + + private static boolean sameEvent(String captured, String current) { + return Objects.equals(captured, current); + } + + private static boolean isCanonicalNonNilUuid(String value) { + if (value == null) { + return false; + } + try { + UUID parsed = UUID.fromString(value); + return !NIL_UUID.equals(parsed) && parsed.toString().equals(value); + } catch (IllegalArgumentException malformed) { + return false; + } + } + + private static Result result(Outcome outcome, String detail) { + return new Result(outcome, Optional.empty(), Optional.of(detail)); + } + + public enum Outcome { + INSTALLED, + REPLAYED, + STALE_SOURCE, + QUARANTINED + } + + public record Result( + Outcome outcome, Optional receipt, Optional detail) { + public Result { + Objects.requireNonNull(outcome, "installation outcome is required"); + receipt = Objects.requireNonNull(receipt, "installation receipt optional is required"); + detail = Objects.requireNonNull(detail, "installation detail optional is required"); + if ((outcome == Outcome.INSTALLED || outcome == Outcome.REPLAYED) != receipt.isPresent()) { + throw new IllegalArgumentException("only verified local installations carry a receipt"); + } + } + } + + /** Historical local proof only; construction is restricted to this installer. */ + public static final class InstallationReceipt { + private final UUID operationId; + private final UUID requestId; + private final String requestDigest; + private final SourceSnapshot capturedSource; + private final ProjectionSnapshot projectionSnapshot; + + private InstallationReceipt( + UUID operationId, + UUID requestId, + String requestDigest, + SourceSnapshot capturedSource, + ProjectionSnapshot projectionSnapshot) { + this.operationId = Objects.requireNonNull(operationId, "capture operation ID is required"); + this.requestId = Objects.requireNonNull(requestId, "capture request ID is required"); + this.requestDigest = Objects.requireNonNull(requestDigest, "request digest is required"); + this.capturedSource = Objects.requireNonNull(capturedSource, "captured source is required"); + this.projectionSnapshot = + Objects.requireNonNull(projectionSnapshot, "projection snapshot is required"); + } + + public UUID operationId() { + return operationId; + } + + public UUID requestId() { + return requestId; + } + + public String requestDigest() { + return requestDigest; + } + + public SourceSnapshot capturedSource() { + return capturedSource; + } + + public ProjectionSnapshot projectionSnapshot() { + return projectionSnapshot; + } + } +} 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 index 5ea3f9d901..f9bf09b4a2 100644 --- 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 @@ -22,6 +22,7 @@ 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.ProjectionCaptureReceipt; import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.Decision; import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions.Mutation; @@ -103,8 +104,9 @@ public synchronized void init() { } /** - * 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. + * Applies one privately verified Account readback. This path performs an exact pre-read, at most + * one registered owner-script call, and an exact post-script readback after a positive script + * outcome; it never retries after a stale result. */ public synchronized ApplyResult apply(SourceReadback readback, String appliedAt) { requireInitialized(); @@ -147,6 +149,79 @@ public synchronized ApplyResult apply(SourceReadback readback, String appliedAt) } } + return executeDecision(key, observedJson, decision); + } + + /** + * Installs one captured checkpoint only after validating its exact current Account readback. The + * capture path may bridge a locally missed event range but uses this store's same registered + * single-key script and exact persistent post-script readback. + */ + public synchronized ApplyResult installCapture( + ProjectionCaptureReceipt capture, SourceReadback current, String appliedAt) { + requireInitialized(); + if (capture == null || current == null) { + return quarantined("MALFORMED_CAPTURE_EVIDENCE", Optional.empty()); + } + if (!expectedWorkloadNamespace.equals(current.targetNamespace())) { + return quarantined("ACCOUNT_NAMESPACE_MISMATCH", Optional.empty()); + } + + final String key; + try { + key = IssuerAuthorityProjectionRedisContract.keyForIssuer(capture.issuerId()); + } catch (IllegalArgumentException malformed) { + return quarantined("MALFORMED_CAPTURE_EVIDENCE", 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.reconcile(null, capture, current, appliedAt); + } else { + try { + observedJson = decodeUtf8(observed.bytes()); + Map observedProjection = parseProjection(observedJson); + decision = + IssuerAuthorityProjectionTransitions.reconcile( + observedProjection, capture, current, appliedAt); + } catch (IOException | IllegalArgumentException malformed) { + return quarantined("MALFORMED_STORED_JSON", Optional.empty()); + } + } + return executeDecision(key, observedJson, decision); + } + + /** Validates a positive result snapshot against the capture and current Account evidence. */ + boolean verifiesCaptureSnapshot( + ProjectionCaptureReceipt capture, SourceReadback current, ProjectionSnapshot snapshot) { + if (snapshot == null || capture == null || current == null) { + return false; + } + try { + if (!IssuerAuthorityProjectionRedisContract.keyForIssuer(capture.issuerId()) + .equals(snapshot.key())) { + return false; + } + Map projection = parseProjection(snapshot.json()); + Decision decision = + IssuerAuthorityProjectionTransitions.reconcile( + projection, capture, current, "capture-snapshot-validation"); + return decision instanceof NoOp noOp + && noOp.reason() + == IssuerAuthorityProjectionTransitions.NoOpReason.CAPTURE_ALREADY_INSTALLED; + } catch (IOException | IllegalArgumentException malformed) { + return false; + } + } + + private ApplyResult executeDecision(String key, String observedJson, Decision decision) { if (decision instanceof Quarantine quarantine) { return quarantined(quarantine.reason().name(), Optional.of(decision)); } @@ -156,11 +231,7 @@ public synchronized ApplyResult apply(SourceReadback readback, String appliedAt) } 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 exactReadback(key, observedJson, Outcome.NO_OP, decision); } return mutationOutcome(result, key, observedJson, decision); } @@ -197,18 +268,10 @@ public synchronized void close() { 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)); + return exactReadback(key, candidateJson, Outcome.APPLIED, decision); } if ("REPLAY".equals(result)) { - return new ApplyResult( - Outcome.REPLAYED, - Optional.of(new ProjectionSnapshot(key, candidateJson)), - Optional.empty(), - Optional.of(decision)); + return exactReadback(key, candidateJson, Outcome.REPLAYED, decision); } if ("STALE".equals(result)) { return new ApplyResult( @@ -225,6 +288,32 @@ private ApplyResult mutationOutcome( Optional.of(decision)); } + private ApplyResult exactReadback( + String key, String expectedJson, Outcome outcome, Decision decision) { + StoredValue readback = readStoredValue(key); + if (readback.bytes() == null) { + return quarantined("POST_SCRIPT_READBACK_MISSING", Optional.of(decision)); + } + if (readback.ttlMillis() != -1L) { + return quarantined("TTL_PRESENT", Optional.of(decision)); + } + + byte[] expectedBytes = expectedJson.getBytes(StandardCharsets.UTF_8); + if (!MessageDigest.isEqual(expectedBytes, readback.bytes())) { + return quarantined("POST_SCRIPT_READBACK_MISMATCH", Optional.of(decision)); + } + + try { + return new ApplyResult( + outcome, + Optional.of(new ProjectionSnapshot(key, decodeUtf8(readback.bytes()))), + Optional.empty(), + Optional.of(decision)); + } catch (CharacterCodingException malformedUtf8) { + return quarantined("POST_SCRIPT_READBACK_INVALID_UTF8", Optional.of(decision)); + } + } + private String executeRegistered( String key, String expectedMode, String expectedBytes, String candidateBytes) { RedisInvocationContract invocation = diff --git a/services/game-session-service/src/main/resources/db/migration/V11.1__game_instance_uuid_identity.sql b/services/game-session-service/src/main/resources/db/migration/V11.1__game_instance_uuid_identity.sql new file mode 100644 index 0000000000..06722e22f6 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V11.1__game_instance_uuid_identity.sql @@ -0,0 +1,34 @@ +-- Canonical identity belongs to Game Session. Retained numeric rows remain explicitly unmapped. +ALTER TABLE game_instances + ADD COLUMN game_instance_uuid uuid; + +ALTER TABLE game_instances + ADD CONSTRAINT game_instances_game_instance_uuid_non_nil + CHECK ( + game_instance_uuid IS NULL + OR game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::uuid + ); + +ALTER TABLE game_instances + ADD CONSTRAINT uq_game_instances_game_instance_uuid UNIQUE (game_instance_uuid); + +-- [jooq ignore start] +CREATE FUNCTION enforce_game_instance_uuid_immutable() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.game_instance_uuid IS DISTINCT FROM OLD.game_instance_uuid THEN + RAISE EXCEPTION 'Game Session game_instance_uuid identity is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'game_instances_game_instance_uuid_immutable'; + END IF; + + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_instances_game_instance_uuid_immutable + BEFORE UPDATE OF game_instance_uuid ON game_instances + FOR EACH ROW + EXECUTE FUNCTION enforce_game_instance_uuid_immutable(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java index 0a5dc3fc86..ac211b96e5 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcMtlsCrossServiceTest.java @@ -8,6 +8,7 @@ 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; @@ -26,20 +27,30 @@ import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.HashMap; +import java.util.HexFormat; 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.AcknowledgeIssuerProjectionForRuntimeRequest; +import net.firedevops.firemud.account.v1.AcknowledgeIssuerProjectionForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionAcknowledgmentRepository.Acknowledgment; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository.Receipt; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthorityEventReadback; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityGrpcService; +import net.firedevops.firemud.accountservice.service.AccountIssuerProjectionAcknowledgmentService; +import net.firedevops.firemud.accountservice.service.AccountIssuerProjectionReconciliationService; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.account.authority.IssuerProjectionInstallationAcknowledgmentDigestV1; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -52,7 +63,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -/** Physical mutual-TLS proof for the deliberately unwired issuer-source readback handoff. */ +/** Physical mutual-TLS proof for the deliberately unwired issuer-source handoffs. */ class AccountIssuerAuthorityGrpcMtlsCrossServiceTest { @TempDir private Path tempDir; @@ -60,6 +71,8 @@ class AccountIssuerAuthorityGrpcMtlsCrossServiceTest { private static final String NAMESPACE = "test"; private static final String ISSUER_ID = "https://account.example.test/issuer"; + private static final String GAME_SESSION_PEER_URI = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; private static final String SOURCE_SCOPE = "issuer/" + ISSUER_ID; private static final String STREAM_KEY = IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + SOURCE_SCOPE; @@ -67,6 +80,13 @@ class AccountIssuerAuthorityGrpcMtlsCrossServiceTest { private static final String HISTORICAL_EVENT_REQUEST_ID = "22222222-2222-4222-8222-222222222222"; private static final String CURRENT_READ_REQUEST_ID = "33333333-3333-4333-8333-333333333333"; private static final String HISTORICAL_READ_REQUEST_ID = "44444444-4444-4444-8444-444444444444"; + private static final String ZERO_CAPTURE_REQUEST_ID = "55555555-5555-4555-8555-555555555555"; + private static final String POSITIVE_CAPTURE_REQUEST_ID = "66666666-6666-4666-8666-666666666666"; + private static final String CAPTURE_EVENT_REQUEST_ID = "77777777-7777-4777-8777-777777777777"; + private static final String ACK_OPERATION_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + private static final String ACK_REQUEST_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + private static final String ACK_ID = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; + private static final String ACK_CAPTURE_DIGEST = "a".repeat(64); @Test void exactWorkloadIdentitiesCarryCurrentAndHistoricalReadbacksOverSocketMtls() throws Exception { @@ -99,6 +119,173 @@ void exactWorkloadIdentitiesCarryCurrentAndHistoricalReadbacksOverSocketMtls() t } } + @Test + void exactWorkloadIdentitiesCarryZeroAndPositiveCaptureReceiptsOverSocketMtls() throws Exception { + AccountIssuerAuthorityEventProducer producer = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationService captureService = + mock(AccountIssuerProjectionReconciliationService.class); + UUID zeroRequestId = UUID.fromString(ZERO_CAPTURE_REQUEST_ID); + UUID positiveRequestId = UUID.fromString(POSITIVE_CAPTURE_REQUEST_ID); + IssuerAuthoritySnapshot zeroSource = + new IssuerAuthoritySnapshot(ISSUER_ID, 1L, 1L, STREAM_KEY, 0L, Optional.empty()); + IssuerGenerationAuthorityEvent positiveEvent = event(CAPTURE_EVENT_REQUEST_ID, 4L, 7L, 9L); + IssuerAuthoritySnapshot positiveSource = + new IssuerAuthoritySnapshot(ISSUER_ID, 7L, 9L, STREAM_KEY, 4L, Optional.of(positiveEvent)); + Receipt zeroReceipt = + captureReceipt( + UUID.fromString("88888888-8888-4888-8888-888888888888"), zeroRequestId, zeroSource); + Receipt positiveReceipt = + captureReceipt( + UUID.fromString("99999999-9999-4999-8999-999999999999"), + positiveRequestId, + positiveSource); + when(captureService.capture(ISSUER_ID, GAME_SESSION_PEER_URI, zeroRequestId)) + .thenReturn(zeroReceipt); + when(captureService.capture(ISSUER_ID, GAME_SESSION_PEER_URI, positiveRequestId)) + .thenReturn(positiveReceipt); + + Server server = startServer("account", producer, captureService); + try (AccountIssuerAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + AccountIssuerAuthorityClient.ProjectionCaptureReceipt zero = + client.captureProjection(ZERO_CAPTURE_REQUEST_ID); + AccountIssuerAuthorityClient.ProjectionCaptureReceipt positive = + client.captureProjection(POSITIVE_CAPTURE_REQUEST_ID); + + assertThat(zero.operationUUID()).isEqualTo(zeroReceipt.operationId()); + assertThat(zero.requestUUID()).isEqualTo(zeroRequestId); + assertThat(zero.issuerId()).isEqualTo(ISSUER_ID); + assertThat(zero.callerWorkloadIdentity()).isEqualTo(GAME_SESSION_PEER_URI); + assertThat(zero.projectionKey()) + .isEqualTo("session:game:auth:issuer-generation:v1:" + ISSUER_ID); + assertThat(zero.requestDigestVersion()).isEqualTo(1); + assertThat(zero.requestDigest()).isEqualTo(zeroReceipt.requestDigest()); + assertThat(zero.capturedSource().outboxSequence()).isEqualTo("0"); + assertThat(zero.capturedSource().latestEvent()).isEmpty(); + + assertThat(positive.operationUUID()).isEqualTo(positiveReceipt.operationId()); + assertThat(positive.requestUUID()).isEqualTo(positiveRequestId); + assertThat(positive.issuerId()).isEqualTo(ISSUER_ID); + assertThat(positive.callerWorkloadIdentity()).isEqualTo(GAME_SESSION_PEER_URI); + assertThat(positive.projectionKey()) + .isEqualTo("session:game:auth:issuer-generation:v1:" + ISSUER_ID); + assertThat(positive.requestDigestVersion()).isEqualTo(1); + assertThat(positive.requestDigest()).isEqualTo(positiveReceipt.requestDigest()); + assertThat(positive.capturedSource().issuerAuthGeneration()).isEqualTo("7"); + assertThat(positive.capturedSource().sourceVersion()).isEqualTo("9"); + assertThat(positive.capturedSource().outboxSequence()).isEqualTo("4"); + assertThat(positive.capturedSource().latestEvent()).isPresent(); + assertThat(positive.capturedSource().latestEvent().orElseThrow().canonicalJson()) + .isEqualTo(positiveEvent.canonicalJson()); + + verify(captureService).capture(ISSUER_ID, GAME_SESSION_PEER_URI, zeroRequestId); + verify(captureService).capture(ISSUER_ID, GAME_SESSION_PEER_URI, positiveRequestId); + verifyNoInteractions(producer); + } finally { + stop(server); + } + } + + @Test + void exactGameSessionPeerCarriesTheClosedInstallationAcknowledgmentOverSocketMtls() + throws Exception { + String projectionJson = zeroProjectionJson(); + UUID operationId = UUID.fromString(ACK_OPERATION_ID); + UUID requestId = UUID.fromString(ACK_REQUEST_ID); + String projectionKey = "session:game:auth:issuer-generation:v1:" + ISSUER_ID; + String requestDigest = + Acknowledgment.requestDigestFor( + ISSUER_ID, + GAME_SESSION_PEER_URI, + projectionKey, + operationId, + requestId, + 1, + ACK_CAPTURE_DIGEST, + projectionJson); + byte[] projectionBytes = projectionJson.getBytes(StandardCharsets.UTF_8); + Acknowledgment acknowledgment = + new Acknowledgment( + UUID.fromString(ACK_ID), + operationId, + requestId, + ISSUER_ID, + GAME_SESSION_PEER_URI, + projectionKey, + 1, + ACK_CAPTURE_DIGEST, + IssuerProjectionInstallationAcknowledgmentDigestV1.VERSION, + requestDigest, + projectionBytes, + sha256(projectionBytes)); + AcknowledgeIssuerProjectionForRuntimeRequest request = + AcknowledgeIssuerProjectionForRuntimeRequest.newBuilder() + .setIssuerId(ISSUER_ID) + .setCaptureOperationId(ACK_OPERATION_ID) + .setCaptureRequestId(ACK_REQUEST_ID) + .setCaptureRequestDigestVersion(1) + .setCaptureRequestDigest(ACK_CAPTURE_DIGEST) + .setProjectionKey(projectionKey) + .setInstalledProjectionJson(projectionJson) + .build(); + AccountIssuerAuthorityEventProducer producer = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationService captureService = + mock(AccountIssuerProjectionReconciliationService.class); + AccountIssuerProjectionAcknowledgmentService acknowledgmentService = + mock(AccountIssuerProjectionAcknowledgmentService.class); + when(acknowledgmentService.acknowledge( + ISSUER_ID, + GAME_SESSION_PEER_URI, + operationId, + requestId, + 1, + ACK_CAPTURE_DIGEST, + projectionJson)) + .thenReturn(acknowledgment); + Server server = startServer("account", producer, captureService, acknowledgmentService); + + ManagedChannel channel = newRawClientChannel(server.getPort(), "game-session"); + try { + AcknowledgeIssuerProjectionForRuntimeResponse response = + IssuerAuthorityServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .acknowledgeIssuerProjectionForRuntime(request); + + assertThat(response.getAllFields()).hasSize(14); + assertThat(response.getSchemaVersion()) + .isEqualTo("account-auth-issuer-projection-installation-ack/v1"); + assertThat(response.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(response.getAcknowledgmentId()).isEqualTo(ACK_ID); + assertThat(response.getIssuerId()).isEqualTo(ISSUER_ID); + assertThat(response.getCallerWorkloadIdentity()).isEqualTo(GAME_SESSION_PEER_URI); + assertThat(response.getProjectionKey()).isEqualTo(projectionKey); + assertThat(response.getCaptureOperationId()).isEqualTo(ACK_OPERATION_ID); + assertThat(response.getCaptureRequestId()).isEqualTo(ACK_REQUEST_ID); + assertThat(response.getCaptureRequestDigestVersion()).isEqualTo(1); + assertThat(response.getCaptureRequestDigest()).isEqualTo(ACK_CAPTURE_DIGEST); + assertThat(response.getRequestDigestVersion()) + .isEqualTo(IssuerProjectionInstallationAcknowledgmentDigestV1.VERSION); + assertThat(response.getRequestDigest()).isEqualTo(requestDigest); + assertThat(response.getInstalledProjectionJson()).isEqualTo(projectionJson); + assertThat(response.getInstalledProjectionSha256()) + .isEqualTo(HexFormat.of().formatHex(sha256(projectionBytes))); + verify(acknowledgmentService) + .acknowledge( + ISSUER_ID, + GAME_SESSION_PEER_URI, + operationId, + requestId, + 1, + ACK_CAPTURE_DIGEST, + projectionJson); + verifyNoInteractions(producer, captureService); + } finally { + shutdown(channel); + stop(server); + } + } + @ParameterizedTest @ValueSource(strings = {"wrong-service", "wrong-namespace"}) void trustedButWrongGameSessionPeerIsDeniedBeforeProducerAccess(String clientIdentity) @@ -120,10 +307,66 @@ void trustedButWrongGameSessionPeerIsDeniedBeforeProducerAccess(String clientIde } } + @ParameterizedTest(name = "capture caller {0}") + @ValueSource(strings = {"wrong-service", "wrong-namespace"}) + void trustedButWrongGameSessionPeerIsDeniedBeforeCaptureOrSourceAccess(String clientIdentity) + throws Exception { + AccountIssuerAuthorityEventProducer producer = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationService captureService = + mock(AccountIssuerProjectionReconciliationService.class); + Server server = startServer("account", producer, captureService); + try (AccountIssuerAuthorityClient client = newClient(server.getPort(), clientIdentity)) { + client.init(); + + assertThatThrownBy(() -> client.captureProjection(ZERO_CAPTURE_REQUEST_ID)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + verifyNoInteractions(captureService, producer); + } finally { + stop(server); + } + } + + @ParameterizedTest(name = "acknowledgment caller {0}") + @ValueSource(strings = {"wrong-service", "wrong-namespace"}) + void trustedButWrongGameSessionPeerIsDeniedBeforeAcknowledgmentOwnerAccess(String clientIdentity) + throws Exception { + AccountIssuerAuthorityEventProducer producer = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationService captureService = + mock(AccountIssuerProjectionReconciliationService.class); + AccountIssuerProjectionAcknowledgmentService acknowledgmentService = + mock(AccountIssuerProjectionAcknowledgmentService.class); + Server server = startServer("account", producer, captureService, acknowledgmentService); + ManagedChannel channel = newRawClientChannel(server.getPort(), clientIdentity); + try { + assertThatThrownBy( + () -> + IssuerAuthorityServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .acknowledgeIssuerProjectionForRuntime(validAcknowledgmentRequest())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + verifyNoInteractions(acknowledgmentService, captureService, producer); + } finally { + shutdown(channel); + stop(server); + } + } + @Test void missingClientCertificateFailsTheRequiredTlsHandshakeBeforeProducerAccess() throws Exception { AccountIssuerAuthorityEventProducer producer = mock(AccountIssuerAuthorityEventProducer.class); - Server server = startServer("account", producer); + AccountIssuerProjectionReconciliationService captureService = + mock(AccountIssuerProjectionReconciliationService.class); + AccountIssuerProjectionAcknowledgmentService acknowledgmentService = + mock(AccountIssuerProjectionAcknowledgmentService.class); + Server server = startServer("account", producer, captureService, acknowledgmentService); SSLContext trustOnlyClientContext = trustOnlyClientContext(); try { Throwable handshakeFailure = @@ -161,6 +404,8 @@ void missingClientCertificateFailsTheRequiredTlsHandshakeBeforeProducerAccess() .as("failure must identify client-certificate rejection: %s", describe(handshakeFailure)) .isTrue(); verifyNoInteractions(producer); + verifyNoInteractions(captureService); + verifyNoInteractions(acknowledgmentService); } finally { stop(server); } @@ -187,6 +432,39 @@ void trustedAccountServerWithWrongServiceOrNamespaceIsRejectedBeforeResponseAcce } } + @ParameterizedTest(name = "capture server {0}") + @ValueSource(strings = {"game-session", "wrong-account-namespace"}) + void wrongAccountServerIdentityCannotReturnATypedCaptureReceipt(String serverIdentity) + throws Exception { + AccountIssuerAuthorityEventProducer producer = mock(AccountIssuerAuthorityEventProducer.class); + AccountIssuerProjectionReconciliationService captureService = + mock(AccountIssuerProjectionReconciliationService.class); + UUID requestId = UUID.fromString(ZERO_CAPTURE_REQUEST_ID); + IssuerAuthoritySnapshot capturedSource = + new IssuerAuthoritySnapshot(ISSUER_ID, 1L, 1L, STREAM_KEY, 0L, Optional.empty()); + when(captureService.capture(ISSUER_ID, GAME_SESSION_PEER_URI, requestId)) + .thenReturn( + captureReceipt( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + requestId, + capturedSource)); + Server server = startServer(serverIdentity, producer, captureService); + try (AccountIssuerAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + assertThatThrownBy(() -> client.captureProjection(ZERO_CAPTURE_REQUEST_ID)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + verify(captureService).capture(ISSUER_ID, GAME_SESSION_PEER_URI, requestId); + verifyNoInteractions(producer); + } finally { + stop(server); + } + } + private static AccountIssuerAuthorityEventProducer producerWithPositiveReadbacks() { AccountIssuerAuthorityEventProducer producer = mock(AccountIssuerAuthorityEventProducer.class); IssuerGenerationAuthorityEvent latest = event(CURRENT_EVENT_REQUEST_ID, 2L, 3L, 3L); @@ -199,6 +477,64 @@ private static AccountIssuerAuthorityEventProducer producerWithPositiveReadbacks return producer; } + private static Receipt captureReceipt( + UUID operationId, UUID requestId, IssuerAuthoritySnapshot capturedSource) { + String projectionKey = "session:game:auth:issuer-generation:v1:" + ISSUER_ID; + return new Receipt( + operationId, + requestId, + ISSUER_ID, + GAME_SESSION_PEER_URI, + projectionKey, + 1, + Receipt.requestDigestFor(ISSUER_ID, GAME_SESSION_PEER_URI, projectionKey, requestId), + capturedSource); + } + + private static AcknowledgeIssuerProjectionForRuntimeRequest validAcknowledgmentRequest() { + return AcknowledgeIssuerProjectionForRuntimeRequest.newBuilder() + .setIssuerId(ISSUER_ID) + .setCaptureOperationId(ACK_OPERATION_ID) + .setCaptureRequestId(ACK_REQUEST_ID) + .setCaptureRequestDigestVersion(1) + .setCaptureRequestDigest(ACK_CAPTURE_DIGEST) + .setProjectionKey("session:game:auth:issuer-generation:v1:" + ISSUER_ID) + .setInstalledProjectionJson(zeroProjectionJson()) + .build(); + } + + private static String zeroProjectionJson() { + return "{\"schemaVersion\":\"game-session-auth-issuer-projection/v1\"," + + "\"issuerId\":\"" + + ISSUER_ID + + "\",\"lastAppliedIssuerGeneration\":\"1\"," + + "\"lastAppliedSourceOutboxSequence\":\"0\",\"outboxStreamKey\":\"" + + STREAM_KEY + + "\",\"appliedAt\":\"2026-10-03T09:30:00Z\"," + + "\"appliedSourceEvidence\":{}}"; + } + + private static byte[] sha256(byte[] value) { + try { + return java.security.MessageDigest.getInstance("SHA-256").digest(value); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private ManagedChannel newRawClientChannel(int port, String clientIdentity) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate(clientIdentity + ".crt").toString()); + tls.setPrivateKey(certificate(clientIdentity + ".key").toString()); + tls.setCaCert(certificate("ca.crt").toString()); + return new GrpcChannelFactory().buildChannel("localhost:" + port, 6565, tls, false); + } + + private static void shutdown(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + channel.awaitTermination(2, TimeUnit.SECONDS); + } + private AccountIssuerAuthorityClient newClient(int port, String clientIdentity) throws Exception { ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + port); @@ -217,6 +553,31 @@ private AccountIssuerAuthorityClient newClient(int port, String clientIdentity) private Server startServer(String serverIdentity, AccountIssuerAuthorityEventProducer producer) throws Exception { + return startServer( + serverIdentity, + producer, + mock(AccountIssuerProjectionReconciliationService.class), + mock(AccountIssuerProjectionAcknowledgmentService.class)); + } + + private Server startServer( + String serverIdentity, + AccountIssuerAuthorityEventProducer producer, + AccountIssuerProjectionReconciliationService captureService) + throws Exception { + return startServer( + serverIdentity, + producer, + captureService, + mock(AccountIssuerProjectionAcknowledgmentService.class)); + } + + private Server startServer( + String serverIdentity, + AccountIssuerAuthorityEventProducer producer, + AccountIssuerProjectionReconciliationService captureService, + AccountIssuerProjectionAcknowledgmentService acknowledgmentService) + throws Exception { return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .sslContext( GrpcSslContexts.forServer( @@ -227,7 +588,8 @@ private Server startServer(String serverIdentity, AccountIssuerAuthorityEventPro .build()) .addService( ServerInterceptors.intercept( - new AccountIssuerAuthorityGrpcService(producer, NAMESPACE), + new AccountIssuerAuthorityGrpcService( + producer, captureService, acknowledgmentService, NAMESPACE), new GrpcPeerIdentityInterceptor())) .build() .start(); diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest.java index 9d0c8700b9..9758d455d0 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest.java @@ -3,6 +3,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ClientInterceptor; +import io.grpc.ForwardingClientCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; @@ -10,27 +20,52 @@ 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.AbstractStub; 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.HashMap; +import java.util.HexFormat; import java.util.Map; +import java.util.Objects; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AcknowledgeIssuerProjectionForRuntimeRequest; +import net.firedevops.firemud.account.v1.CaptureIssuerProjectionForRuntimeRequest; +import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionAcknowledgmentRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionAcknowledgmentRepository.Acknowledgment; +import net.firedevops.firemud.accountservice.repository.AccountIssuerProjectionReconciliationRepository; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityGrpcService; +import net.firedevops.firemud.accountservice.service.AccountIssuerProjectionAcknowledgmentService; +import net.firedevops.firemud.accountservice.service.AccountIssuerProjectionReconciliationService; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.account.authority.IssuerProjectionInstallationAcknowledgmentDigestV1; 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.gamesession.client.AccountIssuerAuthorityClient; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.InstallationAcknowledgmentReceipt; +import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.ProjectionCaptureReceipt; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionRedisContract; +import net.firedevops.firemud.gamesession.service.IssuerProjectionReconciliationInstaller; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ApplyResult; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ProjectionSnapshot; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -39,18 +74,21 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +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; -/** - * PostgreSQL-backed Account issuer readback composed with the physical Game Session mTLS client. - */ +/** PostgreSQL-backed Account issuer handoffs composed with physical Game Session mTLS and Redis. */ @Testcontainers(disabledWithoutDocker = true) class AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest { private static final String NAMESPACE = "test"; @@ -59,6 +97,36 @@ class AccountIssuerAuthorityGrpcPostgresMtlsCrossServiceTest { private static final String BOOTSTRAP_READ_REQUEST_ID = "11111111-1111-4111-8111-111111111111"; private static final String CURRENT_READ_REQUEST_ID = "22222222-2222-4222-8222-222222222222"; private static final String HISTORICAL_READ_REQUEST_ID = "33333333-3333-4333-8333-333333333333"; + private static final String ZERO_CAPTURE_REQUEST_ID = "44444444-4444-4444-8444-444444444444"; + private static final String POSITIVE_CAPTURE_REQUEST_ID = "55555555-5555-4555-8555-555555555555"; + private static final String FIRST_ADVANCE_REQUEST_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + private static final String SECOND_ADVANCE_REQUEST_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + private static final String NO_SOURCE_CAPTURE_REQUEST_ID = "66666666-6666-4666-8666-666666666666"; + private static final String RECONCILE_GAP_REQUEST_ID = "77777777-7777-4777-8777-777777777777"; + private static final String RECONCILE_BASELINE_REQUEST_ID = + "77777777-0000-4777-8777-777777777777"; + private static final String RECONCILE_ZERO_REQUEST_ID = "88888888-8888-4888-8888-888888888888"; + private static final String RECONCILE_RETRY_REQUEST_ID = "99999999-9999-4999-8999-999999999999"; + private static final String RECONCILE_CONCURRENT_REQUEST_ID = + "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"; + private static final String RECONCILE_STALE_REQUEST_ID = "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb"; + private static final String RECONCILE_RACE_REQUEST_ID = "cccccccc-3333-4333-8333-cccccccccccc"; + private static final String RECONCILE_REDIS_REFUSAL_REQUEST_ID = + "dddddddd-4444-4444-8444-dddddddddddd"; + private static final String ORDINARY_EVENT_READ_REQUEST_ID = + "eeeeeeee-5555-4555-8555-eeeeeeeeeeee"; + private static final String ACK_ZERO_REQUEST_ID = "12121212-1212-4121-8121-121212121212"; + private static final String ACK_POSITIVE_REQUEST_ID = "13131313-1313-4131-8131-131313131313"; + private static final String ACK_RETRY_REQUEST_ID = "14141414-1414-4141-8141-141414141414"; + private static final String ACK_CONCURRENT_REQUEST_ID = "15151515-1515-4151-8151-151515151515"; + private static final String ACK_STALE_REQUEST_ID = "16161616-1616-4161-8161-161616161616"; + private static final String ACK_MUTATION_REQUEST_ID = "17171717-1717-4171-8171-171717171717"; + private static final String ACK_WRONG_SERVER_REQUEST_ID = "18181818-1818-4181-8181-181818181818"; + private static final String COORD_PASSWORD = "issuer-reconciliation-proof-secret"; + private static final String APPLIED_AT = "2026-10-03T09:30:00Z"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String GAME_SESSION_PEER_URI = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; @Container static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -73,7 +141,8 @@ void postgresIssuerSourceReturnsBootstrapCurrentAndHistoricalEvidenceOverSocketM AccountFixture account = newAccountFixture(); account.seedIssuer(); AccountIssuerAuthorityEventProducer producer = account.producer(); - Server server = startServer(producer); + Server server = + startServer(producer, account.captureService(), account.acknowledgmentService()); try (AccountIssuerAuthorityClient client = newClient(server.getPort(), "game-session")) { client.init(); @@ -129,6 +198,475 @@ void postgresIssuerSourceReturnsBootstrapCurrentAndHistoricalEvidenceOverSocketM } } + @Test + void postgresCapturePreservesZeroAndOriginalPositiveReceiptAfterLaterSourceAdvance() + throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + Server server = + startServer(producer, account.captureService(), account.acknowledgmentService()); + + try (AccountIssuerAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + + AccountIssuerAuthorityClient.ProjectionCaptureReceipt zero = + client.captureProjection(ZERO_CAPTURE_REQUEST_ID); + assertCaptureBindings(zero, ZERO_CAPTURE_REQUEST_ID); + assertThat(zero.capturedSource().issuerAuthGeneration()).isEqualTo("1"); + assertThat(zero.capturedSource().sourceVersion()).isEqualTo("1"); + assertThat(zero.capturedSource().outboxSequence()).isEqualTo("0"); + assertThat(zero.capturedSource().latestEvent()).isEmpty(); + assertDatabaseState(account, new DatabaseState(1L, 0L, 0L, 1L)); + + IssuerGenerationAuthorityEvent first = + producer.advance(ISSUER_ID, UUID.fromString(FIRST_ADVANCE_REQUEST_ID), 1L, 1L); + assertDatabaseState(account, new DatabaseState(1L, 1L, 1L, 1L)); + + // Discard the successful socket acknowledgement to model a committed capture whose caller + // did not retain the response. This is not a simulated network outage. + client.captureProjection(POSITIVE_CAPTURE_REQUEST_ID); + assertDatabaseState(account, new DatabaseState(1L, 1L, 1L, 2L)); + StoredReceipt committedPositive = + account.readReceipt(UUID.fromString(POSITIVE_CAPTURE_REQUEST_ID)); + assertThat(committedPositive.outboxSequence()).isEqualTo(1L); + assertThat(committedPositive.eventPayload()).containsExactly(first.canonicalJsonUtf8()); + assertStoredEventBytes(account, 1L, committedPositive.eventPayload()); + + IssuerGenerationAuthorityEvent second = + producer.advance(ISSUER_ID, UUID.fromString(SECOND_ADVANCE_REQUEST_ID), 2L, 2L); + assertDatabaseState(account, new DatabaseState(1L, 1L, 2L, 2L)); + + AccountIssuerAuthorityClient.ProjectionCaptureReceipt retry = + client.captureProjection(POSITIVE_CAPTURE_REQUEST_ID); + assertCaptureBindings(retry, POSITIVE_CAPTURE_REQUEST_ID); + assertThat(retry.operationUUID()).isEqualTo(committedPositive.operationId()); + assertThat(HexFormat.of().formatHex(committedPositive.requestDigest())) + .isEqualTo(retry.requestDigest()); + assertThat(retry.capturedSource().issuerAuthGeneration()).isEqualTo("2"); + assertThat(retry.capturedSource().sourceVersion()).isEqualTo("2"); + assertThat(retry.capturedSource().outboxSequence()).isEqualTo("1"); + assertThat(retry.capturedSource().latestEvent()).isPresent(); + assertThat(retry.capturedSource().latestEvent().orElseThrow().canonicalJson()) + .isEqualTo(new String(committedPositive.eventPayload(), StandardCharsets.UTF_8)); + assertThat(retry.capturedSource().latestEvent().orElseThrow().canonicalJsonUtf8()) + .containsExactly(committedPositive.eventPayload()); + + IssuerAuthoritySnapshot current = producer.readCurrent(ISSUER_ID); + assertThat(current.outboxSequence()).isEqualTo(2L); + assertThat(current.latestEvent()).isPresent(); + assertSameEvent(second, current.latestEvent().orElseThrow()); + assertStoredEventBytes(account, 2L, second.canonicalJsonUtf8()); + assertDatabaseState(account, new DatabaseState(1L, 1L, 2L, 2L)); + } finally { + stop(server); + } + } + + @Test + void concurrentExactPostgresCapturesFromSeparateSocketClientsReturnOneDurableReceipt() + throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + Server server = + startServer(producer, account.captureService(), account.acknowledgmentService()); + ExecutorService executor = Executors.newFixedThreadPool(2); + + try (AccountIssuerAuthorityClient firstClient = newClient(server.getPort(), "game-session"); + AccountIssuerAuthorityClient secondClient = newClient(server.getPort(), "game-session")) { + firstClient.init(); + secondClient.init(); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + Future first = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "First capture client did not reach the start gate"); + } + return firstClient.captureProjection(POSITIVE_CAPTURE_REQUEST_ID); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "Second capture client did not reach the start gate"); + } + return secondClient.captureProjection(POSITIVE_CAPTURE_REQUEST_ID); + }); + + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + AccountIssuerAuthorityClient.ProjectionCaptureReceipt firstReceipt = + first.get(10, TimeUnit.SECONDS); + AccountIssuerAuthorityClient.ProjectionCaptureReceipt secondReceipt = + second.get(10, TimeUnit.SECONDS); + + assertCaptureBindings(firstReceipt, POSITIVE_CAPTURE_REQUEST_ID); + assertSameCaptureReceipt(firstReceipt, secondReceipt); + assertThat(firstReceipt.capturedSource().issuerAuthGeneration()).isEqualTo("1"); + assertThat(firstReceipt.capturedSource().sourceVersion()).isEqualTo("1"); + assertThat(firstReceipt.capturedSource().outboxSequence()).isEqualTo("0"); + assertThat(firstReceipt.capturedSource().latestEvent()).isEmpty(); + assertDatabaseState(account, new DatabaseState(1L, 0L, 0L, 1L)); + assertThat(producer.readCurrent(ISSUER_ID).outboxSequence()).isZero(); + } finally { + executor.shutdownNow(); + stop(server); + } + } + + @Test + void postgresZeroAndPositiveInstallationsReceiveFullDurableAcknowledgmentsOverSocketMtls() + throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + + try (InstallationFixture fixture = newInstallationFixture(account, producer)) { + var zeroInstallation = + fixture.installer().install(ACK_ZERO_REQUEST_ID, APPLIED_AT).receipt().orElseThrow(); + DatabaseState zeroInstalledState = new DatabaseState(1L, 0L, 0L, 1L); + assertDatabaseState(account, zeroInstalledState); + assertThat(account.acknowledgmentCount()).isZero(); + IssuerAuthoritySnapshot zeroSourceBeforeAck = producer.readCurrent(ISSUER_ID); + + InstallationAcknowledgmentReceipt zeroAcknowledgment = + fixture.client().acknowledgeInstallation(zeroInstallation); + assertSameSourceSnapshot(zeroSourceBeforeAck, producer.readCurrent(ISSUER_ID)); + assertAcknowledgmentBindings(zeroAcknowledgment, zeroInstallation); + assertThat( + JSON.readTree(zeroAcknowledgment.installedProjectionJson()) + .has("lastAppliedSourceEventId")) + .isFalse(); + assertDatabaseState(account, zeroInstalledState); + assertThat(account.acknowledgmentCount()).isEqualTo(1L); + assertStoredAcknowledgment(account, zeroAcknowledgment, zeroInstallation); + + IssuerGenerationAuthorityEvent positiveEvent = advance(producer, 1L); + var positiveInstallation = + fixture + .installer() + .install(ACK_POSITIVE_REQUEST_ID, "2026-10-03T09:31:00Z") + .receipt() + .orElseThrow(); + DatabaseState positiveInstalledState = new DatabaseState(1L, 1L, 1L, 2L); + assertThat(positiveInstallation.capturedSource().issuerAuthGeneration()).isEqualTo("2"); + assertThat(positiveInstallation.capturedSource().sourceVersion()).isEqualTo("2"); + assertThat(positiveInstallation.capturedSource().outboxSequence()).isEqualTo("1"); + assertThat(positiveInstallation.capturedSource().latestEvent()).isPresent(); + assertSameEvent( + positiveEvent, positiveInstallation.capturedSource().latestEvent().orElseThrow()); + assertDatabaseState(account, positiveInstalledState); + IssuerAuthoritySnapshot positiveSourceBeforeAck = producer.readCurrent(ISSUER_ID); + + InstallationAcknowledgmentReceipt positiveAcknowledgment = + fixture.client().acknowledgeInstallation(positiveInstallation); + assertSameSourceSnapshot(positiveSourceBeforeAck, producer.readCurrent(ISSUER_ID)); + assertAcknowledgmentBindings(positiveAcknowledgment, positiveInstallation); + JsonNode positiveJson = JSON.readTree(positiveAcknowledgment.installedProjectionJson()); + assertThat(positiveJson.path("lastAppliedIssuerGeneration").asText()).isEqualTo("2"); + assertThat(positiveJson.path("lastAppliedSourceOutboxSequence").asText()).isEqualTo("1"); + assertThat(positiveJson.path("lastAppliedSourceEventId").asText()) + .isEqualTo(positiveEvent.eventId()); + assertThat(positiveJson.path("lastAppliedSourceEventDigest").asText()) + .isEqualTo(positiveEvent.eventDigest()); + assertDatabaseState(account, positiveInstalledState); + assertThat(account.acknowledgmentCount()).isEqualTo(2L); + assertStoredAcknowledgment(account, positiveAcknowledgment, positiveInstallation); + assertStoredEventBytes(account, 1L, positiveEvent.canonicalJsonUtf8()); + } + } + + @Test + void exactAcknowledgmentRetryReturnsOriginalAfterDiscardedResponseAndLaterSourceProgress() + throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + advance(producer, 1L); + + try (InstallationFixture fixture = newInstallationFixture(account, producer)) { + var installation = + fixture.installer().install(ACK_RETRY_REQUEST_ID, APPLIED_AT).receipt().orElseThrow(); + DatabaseState installedState = new DatabaseState(1L, 1L, 1L, 1L); + assertDatabaseState(account, installedState); + assertThat(account.acknowledgmentCount()).isZero(); + IssuerAuthoritySnapshot sourceBeforeDiscardedAck = producer.readCurrent(ISSUER_ID); + + // Discard the successful typed response as a lost-response simulation. This models the + // caller losing its result without simulating a network outage or process restart. + fixture.client().acknowledgeInstallation(installation); + assertSameSourceSnapshot(sourceBeforeDiscardedAck, producer.readCurrent(ISSUER_ID)); + StoredAcknowledgment original = account.readAcknowledgment(installation.operationId()); + assertDatabaseState(account, installedState); + assertThat(account.acknowledgmentCount()).isEqualTo(1L); + + IssuerGenerationAuthorityEvent laterEvent = advance(producer, 2L); + DatabaseState afterSourceProgress = new DatabaseState(1L, 1L, 2L, 1L); + assertDatabaseState(account, afterSourceProgress); + IssuerAuthoritySnapshot sourceBeforeRetry = producer.readCurrent(ISSUER_ID); + assertStoredEventBytes( + account, + 1L, + installation.capturedSource().latestEvent().orElseThrow().canonicalJsonUtf8()); + assertStoredEventBytes(account, 2L, laterEvent.canonicalJsonUtf8()); + + InstallationAcknowledgmentReceipt retry = + fixture.client().acknowledgeInstallation(installation); + assertAcknowledgmentBindings(retry, installation); + assertThat(retry.acknowledgmentId()).isEqualTo(original.acknowledgmentId()); + assertThat(retry.installedProjectionJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(original.installedProjectionJson()); + assertThat(retry.requestDigest()).isEqualTo(original.requestDigest()); + assertThat(JSON.readTree(retry.installedProjectionJson()).path("appliedAt").asText()) + .isEqualTo(APPLIED_AT); + assertDatabaseState(account, afterSourceProgress); + assertSameSourceSnapshot(sourceBeforeRetry, producer.readCurrent(ISSUER_ID)); + assertThat(account.acknowledgmentCount()).isEqualTo(1L); + assertStoredAcknowledgment(account, retry, installation); + assertThat(producer.readCurrent(ISSUER_ID).outboxSequence()).isEqualTo(2L); + } + } + + @Test + void concurrentExactAcknowledgmentsReturnOneV44ResultOverSeparateSocketClients() + throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + advance(producer, 1L); + + try (InstallationFixture fixture = newInstallationFixture(account, producer); + AccountIssuerAuthorityClient secondClient = + newClient(fixture.server().getPort(), "game-session")) { + secondClient.init(); + var installation = + fixture + .installer() + .install(ACK_CONCURRENT_REQUEST_ID, APPLIED_AT) + .receipt() + .orElseThrow(); + assertDatabaseState(account, new DatabaseState(1L, 1L, 1L, 1L)); + assertThat(account.acknowledgmentCount()).isZero(); + IssuerAuthoritySnapshot sourceBeforeAck = producer.readCurrent(ISSUER_ID); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + Future first = + executor.submit( + () -> concurrentAcknowledgment(fixture.client(), installation, ready, start)); + Future second = + executor.submit( + () -> concurrentAcknowledgment(secondClient, installation, ready, start)); + + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + InstallationAcknowledgmentReceipt firstResult = first.get(15, TimeUnit.SECONDS); + InstallationAcknowledgmentReceipt secondResult = second.get(15, TimeUnit.SECONDS); + assertSameSourceSnapshot(sourceBeforeAck, producer.readCurrent(ISSUER_ID)); + + assertAcknowledgmentBindings(firstResult, installation); + assertAcknowledgmentBindings(secondResult, installation); + assertThat(secondResult.acknowledgmentId()).isEqualTo(firstResult.acknowledgmentId()); + assertThat(secondResult.requestDigest()).isEqualTo(firstResult.requestDigest()); + assertDatabaseState(account, new DatabaseState(1L, 1L, 1L, 1L)); + assertThat(account.acknowledgmentCount()).isEqualTo(1L); + assertStoredAcknowledgment(account, firstResult, installation); + } finally { + executor.shutdownNow(); + } + } + } + + @Test + void firstAcknowledgmentOfCaptureThatIsStaleAfterSourceAdvanceIsDeniedWithoutAckRow() + throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + advance(producer, 1L); + + try (InstallationFixture fixture = newInstallationFixture(account, producer)) { + var installation = + fixture.installer().install(ACK_STALE_REQUEST_ID, APPLIED_AT).receipt().orElseThrow(); + assertDatabaseState(account, new DatabaseState(1L, 1L, 1L, 1L)); + IssuerGenerationAuthorityEvent currentEvent = advance(producer, 2L); + DatabaseState advancedState = new DatabaseState(1L, 1L, 2L, 1L); + IssuerAuthoritySnapshot sourceBeforeDeniedAck = producer.readCurrent(ISSUER_ID); + + assertThatThrownBy(() -> fixture.client().acknowledgeInstallation(installation)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + + assertDatabaseState(account, advancedState); + assertSameSourceSnapshot(sourceBeforeDeniedAck, producer.readCurrent(ISSUER_ID)); + assertThat(account.acknowledgmentCount()).isZero(); + assertThat(account.readAcknowledgmentOptional(installation.operationId())).isEmpty(); + assertThat(producer.readCurrent(ISSUER_ID).outboxSequence()).isEqualTo(2L); + assertStoredEventBytes( + account, + 1L, + installation.capturedSource().latestEvent().orElseThrow().canonicalJsonUtf8()); + assertStoredEventBytes(account, 2L, currentEvent.canonicalJsonUtf8()); + } + } + + @Test + void rawSamePeerAcknowledgmentRejectsChangedProjectionBytesAndCaptureBinding() throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + + try (InstallationFixture fixture = newInstallationFixture(account, producer)) { + var installation = + fixture.installer().install(ACK_MUTATION_REQUEST_ID, APPLIED_AT).receipt().orElseThrow(); + DatabaseState committedState = new DatabaseState(1L, 0L, 0L, 1L); + assertDatabaseState(account, committedState); + assertThat(account.acknowledgmentCount()).isZero(); + IssuerAuthoritySnapshot sourceBeforeAcceptedAck = producer.readCurrent(ISSUER_ID); + InstallationAcknowledgmentReceipt accepted = + fixture.client().acknowledgeInstallation(installation); + assertSameSourceSnapshot(sourceBeforeAcceptedAck, producer.readCurrent(ISSUER_ID)); + assertDatabaseState(account, committedState); + assertThat(account.acknowledgmentCount()).isEqualTo(1L); + IssuerAuthoritySnapshot sourceBeforeRawDenials = producer.readCurrent(ISSUER_ID); + ManagedChannel channel = newRawClientChannel(fixture.server().getPort(), "game-session"); + try { + String changedProjection = + installation + .projectionSnapshot() + .json() + .replace( + "\"appliedAt\":\"" + APPLIED_AT + "\"", + "\"appliedAt\": \"" + APPLIED_AT + "\""); + assertThat(changedProjection).isNotEqualTo(installation.projectionSnapshot().json()); + assertRawAcknowledgmentDenied( + channel, + rawAcknowledgmentRequest(installation, changedProjection, installation.requestDigest()), + Status.Code.ALREADY_EXISTS); + assertRawAcknowledgmentDenied( + channel, + rawAcknowledgmentRequest( + installation, installation.projectionSnapshot().json(), "f".repeat(64)), + Status.Code.ALREADY_EXISTS); + } finally { + shutdown(channel); + } + + assertDatabaseState(account, committedState); + assertSameSourceSnapshot(sourceBeforeRawDenials, producer.readCurrent(ISSUER_ID)); + assertThat(account.acknowledgmentCount()).isEqualTo(1L); + assertStoredAcknowledgment(account, accepted, installation); + } + } + + @ParameterizedTest(name = "acknowledgment server {0}") + @ValueSource(strings = {"game-session", "wrong-account-namespace"}) + void wrongAccountServerIdentityCannotReturnTypedInstallationAcknowledgment(String serverIdentity) + throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + + try (InstallationFixture fixture = newInstallationFixture(account, producer)) { + var installation = + fixture + .installer() + .install(ACK_WRONG_SERVER_REQUEST_ID, APPLIED_AT) + .receipt() + .orElseThrow(); + DatabaseState installedState = new DatabaseState(1L, 0L, 0L, 1L); + assertDatabaseState(account, installedState); + assertThat(account.acknowledgmentCount()).isZero(); + IssuerAuthoritySnapshot sourceBeforeWrongServerAck = producer.readCurrent(ISSUER_ID); + Server wrongServer = + startServer( + serverIdentity, producer, account.captureService(), account.acknowledgmentService()); + try (AccountIssuerAuthorityClient wrongServerClient = + newClient(wrongServer.getPort(), "game-session")) { + wrongServerClient.init(); + assertThatThrownBy(() -> wrongServerClient.acknowledgeInstallation(installation)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertSameSourceSnapshot(sourceBeforeWrongServerAck, producer.readCurrent(ISSUER_ID)); + assertDatabaseState(account, installedState); + } finally { + stop(wrongServer); + } + + // The request may have committed at the owner despite rejection of its server identity; + // retrying through the exact Account identity returns the same private typed result. + InstallationAcknowledgmentReceipt accepted = + fixture.client().acknowledgeInstallation(installation); + assertSameSourceSnapshot(sourceBeforeWrongServerAck, producer.readCurrent(ISSUER_ID)); + assertAcknowledgmentBindings(accepted, installation); + assertDatabaseState(account, new DatabaseState(1L, 0L, 0L, 1L)); + assertThat(account.acknowledgmentCount()).isEqualTo(1L); + assertStoredAcknowledgment(account, accepted, installation); + } + } + + @Test + void postgresCaptureRejectsMalformedAndMissingSourceRequestsWithoutSqlMutation() + throws Exception { + AccountFixture account = newAccountFixture(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + Server server = + startServer(producer, account.captureService(), account.acknowledgmentService()); + + try { + assertDatabaseState(account, new DatabaseState(0L, 0L, 0L, 0L)); + ManagedChannel rawChannel = newRawClientChannel(server.getPort(), "game-session"); + try { + CaptureIssuerProjectionForRuntimeRequest malformedRequest = + CaptureIssuerProjectionForRuntimeRequest.newBuilder() + .setIssuerId(ISSUER_ID) + .setRequestId("not-a-canonical-uuid") + .build(); + assertThatThrownBy( + () -> + IssuerAuthorityServiceGrpc.newBlockingStub(rawChannel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .captureIssuerProjectionForRuntime(malformedRequest)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT)); + } finally { + shutdown(rawChannel); + } + + try (AccountIssuerAuthorityClient client = newClient(server.getPort(), "game-session")) { + client.init(); + assertThatThrownBy(() -> client.captureProjection(NO_SOURCE_CAPTURE_REQUEST_ID)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + + assertDatabaseState(account, new DatabaseState(0L, 0L, 0L, 0L)); + } finally { + stop(server); + } + } + @ParameterizedTest @ValueSource(strings = {"wrong-service", "wrong-namespace"}) void trustedButWrongGameSessionIdentityIsDeniedWithoutChangingPostgresSource( @@ -136,7 +674,8 @@ void trustedButWrongGameSessionIdentityIsDeniedWithoutChangingPostgresSource( AccountFixture account = newAccountFixture(); account.seedIssuer(); AccountIssuerAuthorityEventProducer producer = account.producer(); - Server server = startServer(producer); + Server server = + startServer(producer, account.captureService(), account.acknowledgmentService()); try (AccountIssuerAuthorityClient client = newClient(server.getPort(), clientIdentity)) { client.init(); @@ -155,8 +694,384 @@ void trustedButWrongGameSessionIdentityIsDeniedWithoutChangingPostgresSource( } } + @ParameterizedTest(name = "capture postgres caller {0}") + @ValueSource(strings = {"wrong-service", "wrong-namespace"}) + void postgresCaptureRejectsWrongGameSessionIdentityWithoutChangingAnyOwnerRows( + String clientIdentity) throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + IssuerAuthoritySnapshot before = producer.readCurrent(ISSUER_ID); + Server server = + startServer(producer, account.captureService(), account.acknowledgmentService()); + + try (AccountIssuerAuthorityClient client = newClient(server.getPort(), clientIdentity)) { + client.init(); + assertDatabaseState(account, new DatabaseState(1L, 0L, 0L, 0L)); + + assertThatThrownBy(() -> client.captureProjection(POSITIVE_CAPTURE_REQUEST_ID)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(producer.readCurrent(ISSUER_ID)).isEqualTo(before); + assertDatabaseState(account, new DatabaseState(1L, 0L, 0L, 0L)); + } finally { + stop(server); + } + } + + @Test + void capturedLatestCheckpointInstallsAcrossMissedEventsThenOrdinaryDeliveryIsContiguous() + throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + advance(producer, 1L); + + try (InstallationFixture fixture = newInstallationFixture(account, producer)) { + IssuerProjectionReconciliationInstaller.Result baseline = + fixture.installer().install(RECONCILE_BASELINE_REQUEST_ID, "2026-10-03T09:29:00Z"); + assertThat(baseline.outcome()) + .isEqualTo(IssuerProjectionReconciliationInstaller.Outcome.INSTALLED); + assertThat(baseline.receipt().orElseThrow().capturedSource().outboxSequence()).isEqualTo("1"); + + advance(producer, 2L); + advance(producer, 3L); + IssuerProjectionReconciliationInstaller.Result installed = + fixture.installer().install(RECONCILE_GAP_REQUEST_ID, APPLIED_AT); + + assertThat(installed.outcome()) + .isEqualTo(IssuerProjectionReconciliationInstaller.Outcome.INSTALLED); + var receipt = installed.receipt().orElseThrow(); + assertThat(receipt.requestId()).isEqualTo(UUID.fromString(RECONCILE_GAP_REQUEST_ID)); + assertThat(receipt.capturedSource().issuerAuthGeneration()).isEqualTo("4"); + assertThat(receipt.capturedSource().sourceVersion()).isEqualTo("4"); + assertThat(receipt.capturedSource().outboxSequence()).isEqualTo("3"); + assertThat(receipt.capturedSource().latestEvent()).isPresent(); + + ProjectionSnapshot installedProjection = receipt.projectionSnapshot(); + JsonNode installedJson = JSON.readTree(installedProjection.json()); + assertThat(installedJson.path("lastAppliedIssuerGeneration").asText()).isEqualTo("4"); + assertThat(installedJson.path("lastAppliedSourceOutboxSequence").asText()).isEqualTo("3"); + assertThat(installedJson.path("lastAppliedSourceEventId").asText()) + .isEqualTo(receipt.capturedSource().latestEvent().orElseThrow().eventId()); + assertThat(installedJson.path("lastAppliedSourceEventDigest").asText()) + .isEqualTo(receipt.capturedSource().latestEvent().orElseThrow().eventDigest()); + assertThat(installedJson.path("appliedAt").asText()).isEqualTo(APPLIED_AT); + assertRedisExact(fixture.redis(), installedProjection); + assertDatabaseState(account, new DatabaseState(1L, 1L, 3L, 2L)); + + IssuerGenerationAuthorityEvent fourth = advance(producer, 4L); + AccountIssuerAuthorityClient.SourceReadback delivered = + fixture.client().readCommittedEvent(ORDINARY_EVENT_READ_REQUEST_ID, "4"); + assertThat(delivered.sourceSnapshot().outboxSequence()).isEqualTo("4"); + assertSameEvent(fourth, delivered.requestedEvent().orElseThrow()); + + ApplyResult ordinaryEvent = fixture.redis().store().apply(delivered, "2026-10-03T09:31:00Z"); + assertThat(ordinaryEvent.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.APPLIED); + JsonNode advancedJson = JSON.readTree(ordinaryEvent.snapshot().orElseThrow().json()); + assertThat(advancedJson.path("lastAppliedSourceOutboxSequence").asText()).isEqualTo("4"); + assertThat(advancedJson.path("lastAppliedIssuerGeneration").asText()).isEqualTo("5"); + assertRedisExact(fixture.redis(), ordinaryEvent.snapshot().orElseThrow()); + assertDatabaseState(account, new DatabaseState(1L, 1L, 4L, 2L)); + } + } + + @Test + void zeroCheckpointInstallsWithoutEventEvidenceThenAcceptsSequenceOne() throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + + try (InstallationFixture fixture = newInstallationFixture(account, producer)) { + IssuerProjectionReconciliationInstaller.Result installed = + fixture.installer().install(RECONCILE_ZERO_REQUEST_ID, APPLIED_AT); + + assertThat(installed.outcome()) + .isEqualTo(IssuerProjectionReconciliationInstaller.Outcome.INSTALLED); + var receipt = installed.receipt().orElseThrow(); + assertThat(receipt.capturedSource().issuerAuthGeneration()).isEqualTo("1"); + assertThat(receipt.capturedSource().sourceVersion()).isEqualTo("1"); + assertThat(receipt.capturedSource().outboxSequence()).isEqualTo("0"); + assertThat(receipt.capturedSource().latestEvent()).isEmpty(); + JsonNode zeroJson = JSON.readTree(receipt.projectionSnapshot().json()); + assertThat(zeroJson.path("lastAppliedIssuerGeneration").asText()).isEqualTo("1"); + assertThat(zeroJson.path("lastAppliedSourceOutboxSequence").asText()).isEqualTo("0"); + assertThat(zeroJson.has("lastAppliedSourceEventId")).isFalse(); + assertThat(zeroJson.has("lastAppliedSourceEventDigest")).isFalse(); + assertRedisExact(fixture.redis(), receipt.projectionSnapshot()); + assertDatabaseState(account, new DatabaseState(1L, 0L, 0L, 1L)); + + IssuerGenerationAuthorityEvent first = advance(producer, 1L); + AccountIssuerAuthorityClient.SourceReadback delivered = + fixture.client().readCommittedEvent(ORDINARY_EVENT_READ_REQUEST_ID, "1"); + assertThat(delivered.sourceSnapshot().outboxSequence()).isEqualTo("1"); + assertSameEvent(first, delivered.requestedEvent().orElseThrow()); + + ApplyResult ordinaryEvent = fixture.redis().store().apply(delivered, "2026-10-03T09:31:00Z"); + assertThat(ordinaryEvent.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.APPLIED); + JsonNode firstJson = JSON.readTree(ordinaryEvent.snapshot().orElseThrow().json()); + assertThat(firstJson.path("lastAppliedSourceOutboxSequence").asText()).isEqualTo("1"); + assertThat(firstJson.path("lastAppliedSourceEventId").asText()).isEqualTo(first.eventId()); + assertThat(firstJson.path("lastAppliedSourceEventDigest").asText()) + .isEqualTo(first.eventDigest()); + assertRedisExact(fixture.redis(), ordinaryEvent.snapshot().orElseThrow()); + assertDatabaseState(account, new DatabaseState(1L, 1L, 1L, 1L)); + } + } + + @Test + void exactInstallRetryPreservesOriginalReceiptProjectionBytesAndAppliedAt() throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + advance(producer, 1L); + + try (InstallationFixture fixture = newInstallationFixture(account, producer)) { + IssuerProjectionReconciliationInstaller.Result first = + fixture.installer().install(RECONCILE_RETRY_REQUEST_ID, APPLIED_AT); + assertThat(first.outcome()) + .isEqualTo(IssuerProjectionReconciliationInstaller.Outcome.INSTALLED); + var originalReceipt = first.receipt().orElseThrow(); + RedisValue originalRedis = fixture.redis().read(originalReceipt.projectionSnapshot().key()); + DatabaseState committedState = new DatabaseState(1L, 1L, 1L, 1L); + assertDatabaseState(account, committedState); + + IssuerProjectionReconciliationInstaller.Result retry = + fixture.installer().install(RECONCILE_RETRY_REQUEST_ID, "2026-10-03T09:32:00Z"); + assertThat(retry.outcome()) + .isEqualTo(IssuerProjectionReconciliationInstaller.Outcome.REPLAYED); + var retriedReceipt = retry.receipt().orElseThrow(); + assertThat(retriedReceipt.operationId()).isEqualTo(originalReceipt.operationId()); + assertThat(retriedReceipt.requestId()).isEqualTo(originalReceipt.requestId()); + assertThat(retriedReceipt.requestDigest()).isEqualTo(originalReceipt.requestDigest()); + assertThat(retriedReceipt.capturedSource().outboxSequence()) + .isEqualTo(originalReceipt.capturedSource().outboxSequence()); + assertThat(retriedReceipt.projectionSnapshot()) + .isEqualTo(originalReceipt.projectionSnapshot()); + RedisValue retriedRedis = fixture.redis().read(originalReceipt.projectionSnapshot().key()); + assertThat(retriedRedis.bytes()).containsExactly(originalRedis.bytes()); + assertThat(retriedRedis.ttlMillis()).isEqualTo(originalRedis.ttlMillis()); + assertThat(originalRedis.ttlMillis()).isEqualTo(-1L); + assertThat(JSON.readTree(originalRedis.bytes()).path("appliedAt").asText()) + .isEqualTo(APPLIED_AT); + assertDatabaseState(account, committedState); + } + } + + @Test + void concurrentExactInstallersDoNotDuplicateAccountSourceOrCaptureRows() throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + advance(producer, 1L); + + try (InstallationFixture fixture = newInstallationFixture(account, producer)) { + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + Future first = + executor.submit(() -> concurrentInstall(fixture.installer(), ready, start)); + Future second = + executor.submit(() -> concurrentInstall(fixture.installer(), ready, start)); + + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var firstResult = first.get(15, TimeUnit.SECONDS); + var secondResult = second.get(15, TimeUnit.SECONDS); + var results = java.util.List.of(firstResult, secondResult); + + assertThat(results.stream().filter(result -> result.receipt().isPresent()).count()) + .isBetween(1L, 2L); + assertThat( + results.stream() + .filter( + result -> + result.outcome() + == IssuerProjectionReconciliationInstaller.Outcome.INSTALLED) + .count()) + .isEqualTo(1L); + assertThat(results) + .allSatisfy( + result -> + assertThat(result.outcome()) + .isIn( + IssuerProjectionReconciliationInstaller.Outcome.INSTALLED, + IssuerProjectionReconciliationInstaller.Outcome.REPLAYED, + IssuerProjectionReconciliationInstaller.Outcome.QUARANTINED)); + var receipts = results.stream().flatMap(result -> result.receipt().stream()).toList(); + assertThat( + receipts.stream() + .map(IssuerProjectionReconciliationInstaller.InstallationReceipt::operationId) + .distinct()) + .hasSize(1); + assertThat( + receipts.stream() + .map(IssuerProjectionReconciliationInstaller.InstallationReceipt::requestId) + .distinct()) + .containsExactly(UUID.fromString(RECONCILE_CONCURRENT_REQUEST_ID)); + assertThat( + receipts.stream() + .map(IssuerProjectionReconciliationInstaller.InstallationReceipt::requestDigest) + .distinct()) + .hasSize(1); + assertDatabaseState(account, new DatabaseState(1L, 1L, 1L, 1L)); + + ProjectionSnapshot installedProjection = receipts.get(0).projectionSnapshot(); + for (IssuerProjectionReconciliationInstaller.InstallationReceipt receipt : receipts) { + assertThat(receipt.projectionSnapshot()).isEqualTo(installedProjection); + } + assertRedisExact(fixture.redis(), installedProjection); + } finally { + executor.shutdownNow(); + } + } + } + + @Test + void capturedSourceThatAdvancesBeforeStoreWriteReturnsNoVerifiedReceipt() throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + advance(producer, 1L); + + try (InstallationFixture fixture = newInstallationFixture(account, producer)) { + ProjectionCaptureReceipt captured = + fixture.client().captureProjection(RECONCILE_STALE_REQUEST_ID); + assertThat(captured.capturedSource().outboxSequence()).isEqualTo("1"); + advance(producer, 2L); + DatabaseState sourceAfterAdvance = new DatabaseState(1L, 1L, 2L, 1L); + + IssuerProjectionReconciliationInstaller.Result stale = + fixture.installer().install(RECONCILE_STALE_REQUEST_ID, APPLIED_AT); + assertThat(stale.outcome()) + .isEqualTo(IssuerProjectionReconciliationInstaller.Outcome.STALE_SOURCE); + assertThat(stale.receipt()).isEmpty(); + assertThat(fixture.redis().read(projectionKey()).bytes()).isNull(); + assertThat(fixture.redis().read(projectionKey()).ttlMillis()).isEqualTo(-2L); + assertDatabaseState(account, sourceAfterAdvance); + + ProjectionCaptureReceipt exactRetry = + fixture.client().captureProjection(RECONCILE_STALE_REQUEST_ID); + assertThat(exactRetry.operationUUID()).isEqualTo(captured.operationUUID()); + assertThat(exactRetry.requestDigest()).isEqualTo(captured.requestDigest()); + assertThat(exactRetry.capturedSource().outboxSequence()).isEqualTo("1"); + assertDatabaseState(account, sourceAfterAdvance); + } + } + + @Test + void sourceAdvanceBetweenRedisWriteAndFinalAccountReadbackWithholdsReceipt() throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + advance(producer, 1L); + AtomicInteger currentReads = new AtomicInteger(); + BlockingGrpcStubCustomizer sourceAdvanceBeforeSecondRead = + interceptorCustomizer( + new ClientInterceptor() { + @Override + public ClientCall interceptCall( + MethodDescriptor method, + CallOptions callOptions, + Channel next) { + ClientCall call = next.newCall(method, callOptions); + return new ForwardingClientCall.SimpleForwardingClientCall<>(call) { + @Override + public void start( + ClientCall.Listener responseListener, Metadata headers) { + if ("account.v1.IssuerAuthorityService/ReadIssuerAuthorityForRuntime" + .equals(method.getFullMethodName()) + && currentReads.incrementAndGet() == 2) { + advance(producer, 2L); + } + super.start(responseListener, headers); + } + }; + } + }); + + try (InstallationFixture fixture = + newInstallationFixture(account, producer, COORD_PASSWORD, sourceAdvanceBeforeSecondRead)) { + IssuerProjectionReconciliationInstaller.Result stale = + fixture.installer().install(RECONCILE_RACE_REQUEST_ID, APPLIED_AT); + + assertThat(currentReads.get()).isEqualTo(2); + assertThat(stale.outcome()) + .isEqualTo(IssuerProjectionReconciliationInstaller.Outcome.STALE_SOURCE); + assertThat(stale.receipt()).isEmpty(); + JsonNode retainedProjection = JSON.readTree(fixture.redis().read(projectionKey()).bytes()); + assertThat(retainedProjection.path("lastAppliedSourceOutboxSequence").asText()) + .isEqualTo("1"); + assertThat(retainedProjection.path("lastAppliedIssuerGeneration").asText()).isEqualTo("2"); + assertThat(retainedProjection.path("appliedAt").asText()).isEqualTo(APPLIED_AT); + assertThat(fixture.redis().read(projectionKey()).ttlMillis()).isEqualTo(-1L); + assertDatabaseState(account, new DatabaseState(1L, 1L, 2L, 1L)); + assertThat(producer.readCurrent(ISSUER_ID).outboxSequence()).isEqualTo(2L); + + ProjectionCaptureReceipt original = + fixture.client().captureProjection(RECONCILE_RACE_REQUEST_ID); + assertThat(original.capturedSource().outboxSequence()).isEqualTo("1"); + assertDatabaseState(account, new DatabaseState(1L, 1L, 2L, 1L)); + } + } + + @Test + void redisAuthenticationRefusalLeavesCapturedAccountReceiptAndSourceUntouched() throws Exception { + AccountFixture account = newAccountFixture(); + account.seedIssuer(); + AccountIssuerAuthorityEventProducer producer = account.producer(); + advance(producer, 1L); + IssuerAuthoritySnapshot sourceBeforeRefusal = producer.readCurrent(ISSUER_ID); + + try (InstallationFixture fixture = + newInstallationFixture( + account, producer, "wrong-issuer-proof-password", BlockingGrpcStubCustomizer.noop())) { + assertThatThrownBy( + () -> fixture.installer().install(RECONCILE_REDIS_REFUSAL_REQUEST_ID, APPLIED_AT)) + .satisfies(failure -> assertThat(exceptionMessageChain(failure)).contains("WRONGPASS")); + DatabaseState capturedSource = new DatabaseState(1L, 1L, 1L, 1L); + assertDatabaseState(account, capturedSource); + IssuerAuthoritySnapshot sourceAfterRefusal = producer.readCurrent(ISSUER_ID); + assertThat(sourceAfterRefusal.issuerId()).isEqualTo(sourceBeforeRefusal.issuerId()); + assertThat(sourceAfterRefusal.issuerAuthGeneration()) + .isEqualTo(sourceBeforeRefusal.issuerAuthGeneration()); + assertThat(sourceAfterRefusal.sourceVersion()).isEqualTo(sourceBeforeRefusal.sourceVersion()); + assertThat(sourceAfterRefusal.outboxStreamKey()) + .isEqualTo(sourceBeforeRefusal.outboxStreamKey()); + assertThat(sourceAfterRefusal.outboxSequence()) + .isEqualTo(sourceBeforeRefusal.outboxSequence()); + assertThat(sourceBeforeRefusal.latestEvent()).isPresent(); + assertThat(sourceAfterRefusal.latestEvent()).isPresent(); + assertSameEvent( + sourceBeforeRefusal.latestEvent().orElseThrow(), + sourceAfterRefusal.latestEvent().orElseThrow()); + + ProjectionCaptureReceipt retained = + fixture.client().captureProjection(RECONCILE_REDIS_REFUSAL_REQUEST_ID); + assertThat(retained.capturedSource().outboxSequence()).isEqualTo("1"); + StoredReceipt storedReceipt = + account.readReceipt(UUID.fromString(RECONCILE_REDIS_REFUSAL_REQUEST_ID)); + assertThat(retained.operationUUID()).isEqualTo(storedReceipt.operationId()); + assertThat(retained.requestDigest()) + .isEqualTo(HexFormat.of().formatHex(storedReceipt.requestDigest())); + assertThat(fixture.redis().read(projectionKey()).bytes()).isNull(); + assertThat(fixture.redis().read(projectionKey()).ttlMillis()).isEqualTo(-2L); + assertDatabaseState(account, capturedSource); + } + } + private AccountFixture newAccountFixture() { String schema = "issuer_authority_grpc_proof_" + UUID.randomUUID().toString().replace("-", ""); + if (schema.length() >= 63) { + throw new IllegalStateException("Issuer proof schema must remain shorter than 63 bytes"); + } DriverManagerDataSource dataSource = new DriverManagerDataSource(); String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); @@ -180,6 +1095,128 @@ private AccountFixture newAccountFixture() { return new AccountFixture(generations, outbox, transactionDsl, transactionManager); } + private InstallationFixture newInstallationFixture( + AccountFixture account, AccountIssuerAuthorityEventProducer producer) throws Exception { + return newInstallationFixture( + account, producer, COORD_PASSWORD, BlockingGrpcStubCustomizer.noop()); + } + + private InstallationFixture newInstallationFixture( + AccountFixture account, + AccountIssuerAuthorityEventProducer producer, + String redisPassword, + BlockingGrpcStubCustomizer stubCustomizer) + throws Exception { + RedisFixture redis = newRedisFixture(redisPassword); + Server server = null; + AccountIssuerAuthorityClient client = null; + try { + server = startServer(producer, account.captureService(), account.acknowledgmentService()); + client = newClient(server.getPort(), "game-session", stubCustomizer); + client.init(); + return new InstallationFixture( + server, + client, + redis, + new IssuerProjectionReconciliationInstaller(client, redis.store())); + } catch (Exception failure) { + if (client != null) { + client.close(); + } + if (server != null) { + stop(server); + } + redis.close(); + throw failure; + } + } + + private RedisFixture newRedisFixture(String password) { + GenericContainer redisContainer = + 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"); + redisContainer.start(); + RedisIssuerAuthorityProjectionStore store = + new RedisIssuerAuthorityProjectionStore( + NAMESPACE, + new RedisIssuerAuthorityProjectionStore.CoordinationEndpoint( + redisContainer.getHost(), + redisContainer.getMappedPort(6379), + "gamesession_coord_app", + password), + new RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint( + "redis-cache.test.invalid", 6380)); + LettuceConnectionFactory adminConnectionFactory = null; + try { + store.init(); + adminConnectionFactory = + new LettuceConnectionFactory( + new RedisStandaloneConfiguration( + redisContainer.getHost(), redisContainer.getMappedPort(6379))); + adminConnectionFactory.afterPropertiesSet(); + StringRedisTemplate adminTemplate = new StringRedisTemplate(adminConnectionFactory); + adminTemplate.afterPropertiesSet(); + return new RedisFixture(redisContainer, store, adminConnectionFactory, adminTemplate); + } catch (RuntimeException failure) { + store.close(); + if (adminConnectionFactory != null) { + adminConnectionFactory.destroy(); + } + redisContainer.stop(); + throw failure; + } + } + + private BlockingGrpcStubCustomizer interceptorCustomizer(ClientInterceptor interceptor) { + return new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T stub) { + return stub.withInterceptors(interceptor); + } + }; + } + + private IssuerGenerationAuthorityEvent advance( + AccountIssuerAuthorityEventProducer producer, long expectedVersion) { + return producer.advance(ISSUER_ID, UUID.randomUUID(), expectedVersion, expectedVersion); + } + + private IssuerProjectionReconciliationInstaller.Result concurrentInstall( + IssuerProjectionReconciliationInstaller installer, CountDownLatch ready, CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent installer did not reach the start gate"); + } + return installer.install(RECONCILE_CONCURRENT_REQUEST_ID, APPLIED_AT); + } + + private static String projectionKey() { + return IssuerAuthorityProjectionRedisContract.keyForIssuer(ISSUER_ID); + } + + private void assertRedisExact(RedisFixture redis, ProjectionSnapshot expected) { + RedisValue actual = redis.read(expected.key()); + assertThat(actual.bytes()).containsExactly(expected.json().getBytes(StandardCharsets.UTF_8)); + assertThat(actual.ttlMillis()).isEqualTo(-1L); + } + private static Path accountMigrationDirectory() { Path current = Path.of("").toAbsolutePath().normalize(); while (current != null) { @@ -194,23 +1231,43 @@ private static Path accountMigrationDirectory() { throw new IllegalStateException("Unable to locate the Account service migration directory"); } - private Server startServer(AccountIssuerAuthorityEventProducer producer) throws Exception { + private Server startServer( + AccountIssuerAuthorityEventProducer producer, + AccountIssuerProjectionReconciliationService captureService, + AccountIssuerProjectionAcknowledgmentService acknowledgmentService) + throws Exception { + return startServer("account", producer, captureService, acknowledgmentService); + } + + private Server startServer( + String serverIdentity, + AccountIssuerAuthorityEventProducer producer, + AccountIssuerProjectionReconciliationService captureService, + AccountIssuerProjectionAcknowledgmentService acknowledgmentService) + throws Exception { return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .sslContext( GrpcSslContexts.forServer( - certificate("account.crt").toFile(), certificate("account.key").toFile()) + certificate(serverIdentity + ".crt").toFile(), + certificate(serverIdentity + ".key").toFile()) .trustManager(certificate("ca.crt").toFile()) .clientAuth(ClientAuth.REQUIRE) .build()) .addService( ServerInterceptors.intercept( - new AccountIssuerAuthorityGrpcService(producer, NAMESPACE), + new AccountIssuerAuthorityGrpcService( + producer, captureService, acknowledgmentService, NAMESPACE), new GrpcPeerIdentityInterceptor())) .build() .start(); } private AccountIssuerAuthorityClient newClient(int port, String clientIdentity) throws Exception { + return newClient(port, clientIdentity, BlockingGrpcStubCustomizer.noop()); + } + + private AccountIssuerAuthorityClient newClient( + int port, String clientIdentity, BlockingGrpcStubCustomizer stubCustomizer) throws Exception { ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + port); CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); @@ -218,12 +1275,15 @@ private AccountIssuerAuthorityClient newClient(int port, String clientIdentity) tls.setPrivateKey(certificate(clientIdentity + ".key").toString()); tls.setCaCert(certificate("ca.crt").toString()); return new AccountIssuerAuthorityClient( - endpoints, - tls, - new GrpcChannelFactory(), - BlockingGrpcStubCustomizer.noop(), - NAMESPACE, - ISSUER_ID); + endpoints, tls, new GrpcChannelFactory(), stubCustomizer, NAMESPACE, ISSUER_ID); + } + + private ManagedChannel newRawClientChannel(int port, String clientIdentity) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate(clientIdentity + ".crt").toString()); + tls.setPrivateKey(certificate(clientIdentity + ".key").toString()); + tls.setCaCert(certificate("ca.crt").toString()); + return new GrpcChannelFactory().buildChannel("localhost:" + port, 6565, tls, false); } private Path certificate(String name) throws IOException { @@ -249,9 +1309,217 @@ private Path certificate(String name) throws IOException { private void assertSameEvent( IssuerGenerationAuthorityEvent expected, IssuerGenerationAuthorityEvent actual) { assertThat(actual.canonicalJson()).isEqualTo(expected.canonicalJson()); + assertThat(actual.canonicalJsonUtf8()).containsExactly(expected.canonicalJsonUtf8()); assertThat(actual.eventDigest()).isEqualTo(expected.eventDigest()); } + private void assertSameSourceSnapshot( + IssuerAuthoritySnapshot expected, IssuerAuthoritySnapshot actual) { + assertThat(actual.issuerId()).isEqualTo(expected.issuerId()); + assertThat(actual.issuerAuthGeneration()).isEqualTo(expected.issuerAuthGeneration()); + assertThat(actual.sourceVersion()).isEqualTo(expected.sourceVersion()); + assertThat(actual.outboxStreamKey()).isEqualTo(expected.outboxStreamKey()); + assertThat(actual.outboxSequence()).isEqualTo(expected.outboxSequence()); + assertThat(actual.latestEvent().isPresent()).isEqualTo(expected.latestEvent().isPresent()); + if (expected.latestEvent().isPresent()) { + assertSameEvent(expected.latestEvent().orElseThrow(), actual.latestEvent().orElseThrow()); + } + } + + private void assertCaptureBindings( + AccountIssuerAuthorityClient.ProjectionCaptureReceipt receipt, String requestId) { + UUID requestUUID = UUID.fromString(requestId); + String projectionKey = "session:game:auth:issuer-generation:v1:" + ISSUER_ID; + assertThat(receipt.operationUUID()).isNotNull(); + assertThat(receipt.operationUUID()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(receipt.requestUUID()).isEqualTo(requestUUID); + assertThat(receipt.issuerId()).isEqualTo(ISSUER_ID); + assertThat(receipt.callerWorkloadIdentity()).isEqualTo(GAME_SESSION_PEER_URI); + assertThat(receipt.projectionKey()).isEqualTo(projectionKey); + assertThat(receipt.requestDigestVersion()).isEqualTo(1); + assertThat(receipt.capturedSource().issuerId()).isEqualTo(ISSUER_ID); + assertThat(receipt.capturedSource().sourceScope()).isEqualTo("issuer/" + ISSUER_ID); + assertThat(receipt.capturedSource().outboxStreamKey()).isEqualTo(STREAM_KEY); + assertThat(receipt.requestDigest()) + .isEqualTo( + AccountIssuerProjectionReconciliationRepository.Receipt.requestDigestFor( + ISSUER_ID, GAME_SESSION_PEER_URI, projectionKey, requestUUID)); + } + + private void assertSameCaptureReceipt( + AccountIssuerAuthorityClient.ProjectionCaptureReceipt first, + AccountIssuerAuthorityClient.ProjectionCaptureReceipt second) { + assertThat(second.operationUUID()).isEqualTo(first.operationUUID()); + assertThat(second.requestUUID()).isEqualTo(first.requestUUID()); + assertThat(second.issuerId()).isEqualTo(first.issuerId()); + assertThat(second.callerWorkloadIdentity()).isEqualTo(first.callerWorkloadIdentity()); + assertThat(second.projectionKey()).isEqualTo(first.projectionKey()); + assertThat(second.requestDigestVersion()).isEqualTo(first.requestDigestVersion()); + assertThat(second.requestDigest()).isEqualTo(first.requestDigest()); + assertThat(second.capturedSource().issuerAuthGeneration()) + .isEqualTo(first.capturedSource().issuerAuthGeneration()); + assertThat(second.capturedSource().sourceVersion()) + .isEqualTo(first.capturedSource().sourceVersion()); + assertThat(second.capturedSource().outboxSequence()) + .isEqualTo(first.capturedSource().outboxSequence()); + assertThat( + second + .capturedSource() + .latestEvent() + .map(IssuerGenerationAuthorityEvent::canonicalJson)) + .isEqualTo( + first + .capturedSource() + .latestEvent() + .map(IssuerGenerationAuthorityEvent::canonicalJson)); + } + + private void assertStoredEventBytes(AccountFixture account, long sequence, byte[] expected) { + byte[] outboxPayload = + account + .transactionDsl() + .resultQuery( + "SELECT payload FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ? AND outbox_sequence = ?", + STREAM_KEY, + sequence) + .fetchOne(0, byte[].class); + assertThat(outboxPayload).containsExactly(expected); + } + + private void assertDatabaseState(AccountFixture account, DatabaseState expected) { + assertThat(account.databaseState()).isEqualTo(expected); + } + + private void assertAcknowledgmentBindings( + InstallationAcknowledgmentReceipt acknowledgment, + IssuerProjectionReconciliationInstaller.InstallationReceipt installation) { + assertThat(acknowledgment.acknowledgmentId()).isNotNull(); + assertThat(acknowledgment.acknowledgmentId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(acknowledgment.captureOperationId()).isEqualTo(installation.operationId()); + assertThat(acknowledgment.captureRequestId()).isEqualTo(installation.requestId()); + assertThat(acknowledgment.issuerId()).isEqualTo(ISSUER_ID); + assertThat(acknowledgment.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(acknowledgment.callerWorkloadIdentity()).isEqualTo(GAME_SESSION_PEER_URI); + assertThat(acknowledgment.projectionKey()).isEqualTo(projectionKey()); + assertThat(acknowledgment.captureRequestDigestVersion()).isEqualTo(1); + assertThat(acknowledgment.captureRequestDigest()).isEqualTo(installation.requestDigest()); + assertThat(acknowledgment.requestDigestVersion()) + .isEqualTo(IssuerProjectionInstallationAcknowledgmentDigestV1.VERSION); + assertThat(acknowledgment.requestDigest()) + .isEqualTo( + Acknowledgment.requestDigestFor( + ISSUER_ID, + GAME_SESSION_PEER_URI, + projectionKey(), + installation.operationId(), + installation.requestId(), + 1, + installation.requestDigest(), + installation.projectionSnapshot().json())); + assertThat(acknowledgment.installedProjectionJson()) + .isEqualTo(installation.projectionSnapshot().json()); + assertThat(acknowledgment.installedProjectionSha256()) + .isEqualTo( + HexFormat.of() + .formatHex( + sha256( + installation + .projectionSnapshot() + .json() + .getBytes(StandardCharsets.UTF_8)))); + } + + private void assertStoredAcknowledgment( + AccountFixture account, + InstallationAcknowledgmentReceipt acknowledgment, + IssuerProjectionReconciliationInstaller.InstallationReceipt installation) { + StoredAcknowledgment stored = account.readAcknowledgment(installation.operationId()); + assertThat(stored.acknowledgmentId()).isEqualTo(acknowledgment.acknowledgmentId()); + assertThat(stored.captureOperationId()).isEqualTo(acknowledgment.captureOperationId()); + assertThat(stored.captureRequestId()).isEqualTo(acknowledgment.captureRequestId()); + assertThat(stored.issuerId()).isEqualTo(acknowledgment.issuerId()); + assertThat(stored.callerWorkloadIdentity()).isEqualTo(acknowledgment.callerWorkloadIdentity()); + assertThat(stored.projectionKey()).isEqualTo(acknowledgment.projectionKey()); + assertThat(stored.captureRequestDigestVersion()) + .isEqualTo(acknowledgment.captureRequestDigestVersion()); + assertThat(stored.captureRequestDigest()).isEqualTo(acknowledgment.captureRequestDigest()); + assertThat(stored.requestDigestVersion()).isEqualTo(acknowledgment.requestDigestVersion()); + assertThat(stored.requestDigest()).isEqualTo(acknowledgment.requestDigest()); + assertThat(stored.installedProjectionJson()) + .containsExactly(acknowledgment.installedProjectionJson().getBytes(StandardCharsets.UTF_8)); + assertThat(stored.installedProjectionSha256()) + .isEqualTo(acknowledgment.installedProjectionSha256()); + } + + private AcknowledgeIssuerProjectionForRuntimeRequest rawAcknowledgmentRequest( + IssuerProjectionReconciliationInstaller.InstallationReceipt installation, + String installedProjectionJson, + String captureRequestDigest) { + return AcknowledgeIssuerProjectionForRuntimeRequest.newBuilder() + .setIssuerId(ISSUER_ID) + .setCaptureOperationId(installation.operationId().toString()) + .setCaptureRequestId(installation.requestId().toString()) + .setCaptureRequestDigestVersion(1) + .setCaptureRequestDigest(captureRequestDigest) + .setProjectionKey(projectionKey()) + .setInstalledProjectionJson(installedProjectionJson) + .build(); + } + + private void assertRawAcknowledgmentDenied( + ManagedChannel channel, + AcknowledgeIssuerProjectionForRuntimeRequest request, + Status.Code expectedCode) { + assertThatThrownBy( + () -> + IssuerAuthorityServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .acknowledgeIssuerProjectionForRuntime(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expectedCode)); + } + + private InstallationAcknowledgmentReceipt concurrentAcknowledgment( + AccountIssuerAuthorityClient client, + IssuerProjectionReconciliationInstaller.InstallationReceipt installation, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "Concurrent acknowledgment client did not reach the start gate"); + } + return client.acknowledgeInstallation(installation); + } + + private static byte[] sha256(byte[] value) { + try { + return java.security.MessageDigest.getInstance("SHA-256").digest(value); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static String exceptionMessageChain(Throwable failure) { + StringBuilder messages = new StringBuilder(); + Throwable current = failure; + while (current != null) { + if (current.getMessage() != null) { + messages.append(current.getMessage()).append('\n'); + } + current = current.getCause(); + } + return messages.toString(); + } + + private static void shutdown(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + channel.awaitTermination(2, TimeUnit.SECONDS); + } + private static void stop(Server server) throws InterruptedException { server.shutdownNow(); server.awaitTermination(2, TimeUnit.SECONDS); @@ -271,5 +1539,186 @@ private AccountIssuerAuthorityEventProducer producer() { return new AccountIssuerAuthorityEventProducer( ISSUER_ID, generations, outbox, transactionDsl, transactionManager); } + + private AccountIssuerProjectionReconciliationService captureService() { + return new AccountIssuerProjectionReconciliationService( + ISSUER_ID, + GAME_SESSION_PEER_URI, + producer(), + new AccountIssuerProjectionReconciliationRepository(transactionDsl), + transactionManager); + } + + private AccountIssuerProjectionAcknowledgmentService acknowledgmentService() { + return new AccountIssuerProjectionAcknowledgmentService( + ISSUER_ID, + GAME_SESSION_PEER_URI, + captureService(), + new AccountIssuerProjectionAcknowledgmentRepository(transactionDsl), + transactionManager); + } + + private long acknowledgmentCount() { + return count( + "SELECT COUNT(*) FROM account_issuer_projection_installation_acknowledgments " + + "WHERE issuer_id = ?", + ISSUER_ID); + } + + private java.util.Optional readAcknowledgmentOptional( + UUID captureOperationId) { + org.jooq.Record row = + transactionDsl.fetchOne( + "SELECT acknowledgment_id, capture_operation_id, capture_request_id, issuer_id, " + + "caller_workload_identity, projection_key, capture_request_digest_version, " + + "encode(capture_request_digest, 'hex') AS capture_request_digest, " + + "request_digest_version, encode(request_digest, 'hex') AS request_digest, " + + "installed_projection_json, " + + "encode(installed_projection_sha256, 'hex') AS installed_projection_sha256 " + + "FROM account_issuer_projection_installation_acknowledgments " + + "WHERE capture_operation_id = ?", + captureOperationId); + if (row == null) { + return java.util.Optional.empty(); + } + return java.util.Optional.of( + new StoredAcknowledgment( + row.get("acknowledgment_id", UUID.class), + row.get("capture_operation_id", UUID.class), + row.get("capture_request_id", UUID.class), + row.get("issuer_id", String.class), + row.get("caller_workload_identity", String.class), + row.get("projection_key", String.class), + row.get("capture_request_digest_version", Integer.class), + row.get("capture_request_digest", String.class), + row.get("request_digest_version", Integer.class), + row.get("request_digest", String.class), + row.get("installed_projection_json", byte[].class), + row.get("installed_projection_sha256", String.class))); + } + + private StoredAcknowledgment readAcknowledgment(UUID captureOperationId) { + return readAcknowledgmentOptional(captureOperationId) + .orElseThrow( + () -> new IllegalStateException("Expected durable issuer acknowledgment is absent")); + } + + private DatabaseState databaseState() { + return new DatabaseState( + count( + "SELECT COUNT(*) FROM account_authority_generations " + + "WHERE scope_kind = 'ISSUER' AND issuer_id = ?", + ISSUER_ID), + count( + "SELECT COUNT(*) FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + STREAM_KEY), + count( + "SELECT COUNT(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + STREAM_KEY), + count( + "SELECT COUNT(*) FROM account_issuer_projection_reconciliation_receipts " + + "WHERE issuer_id = ?", + ISSUER_ID)); + } + + private StoredReceipt readReceipt(UUID requestId) { + org.jooq.Record row = + transactionDsl.fetchOne( + "SELECT operation_id, request_digest, outbox_sequence, event_payload " + + "FROM account_issuer_projection_reconciliation_receipts " + + "WHERE issuer_id = ? AND request_id = ?", + ISSUER_ID, + requestId); + if (row == null) { + throw new IllegalStateException("Expected committed issuer capture receipt is absent"); + } + byte[] requestDigest = row.get("request_digest", byte[].class); + byte[] eventPayload = row.get("event_payload", byte[].class); + if (requestDigest == null || eventPayload == null) { + throw new IllegalStateException("Expected positive issuer capture evidence is absent"); + } + return new StoredReceipt( + row.get("operation_id", UUID.class), + row.get("outbox_sequence", Long.class), + requestDigest, + eventPayload); + } + + private long count(String sql, Object... bindings) { + return Objects.requireNonNull( + transactionDsl.resultQuery(sql, bindings).fetchOne(0, Long.class), + "Issuer proof row count query returned no value"); + } + } + + private record DatabaseState( + long sourceRows, long outboxStreamRows, long outboxEventRows, long receiptRows) {} + + private record StoredReceipt( + UUID operationId, long outboxSequence, byte[] requestDigest, byte[] eventPayload) {} + + private record StoredAcknowledgment( + UUID acknowledgmentId, + UUID captureOperationId, + UUID captureRequestId, + String issuerId, + String callerWorkloadIdentity, + String projectionKey, + int captureRequestDigestVersion, + String captureRequestDigest, + int requestDigestVersion, + String requestDigest, + byte[] installedProjectionJson, + String installedProjectionSha256) {} + + private record RedisValue(byte[] bytes, long ttlMillis) {} + + private record InstallationFixture( + Server server, + AccountIssuerAuthorityClient client, + RedisFixture redis, + IssuerProjectionReconciliationInstaller installer) + implements AutoCloseable { + @Override + public void close() throws Exception { + try { + client.close(); + } finally { + try { + redis.close(); + } finally { + stop(server); + } + } + } + } + + private record RedisFixture( + GenericContainer container, + RedisIssuerAuthorityProjectionStore store, + LettuceConnectionFactory adminConnectionFactory, + StringRedisTemplate adminTemplate) + implements AutoCloseable { + private RedisValue read(String key) { + RedisValue value = + adminTemplate.execute( + (RedisCallback) + connection -> { + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + byte[] bytes = connection.stringCommands().get(keyBytes); + long ttlMillis = bytes == null ? -2L : connection.keyCommands().pTtl(keyBytes); + return new RedisValue(bytes, ttlMillis); + }); + return Objects.requireNonNull(value, "Redis test read returned no result"); + } + + @Override + public void close() { + store.close(); + adminConnectionFactory.destroy(); + container.stop(); + } } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java index f263d592f1..0075b1d015 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java @@ -4,7 +4,9 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -24,6 +26,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.service.impl.TickScheduler; import net.firedevops.firemud.gamesession.testsupport.GameplayWebSocketDriver; import net.firedevops.firemud.gamesession.testsupport.InMemorySessionContextTestConfiguration; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; @@ -54,6 +57,7 @@ class GameSessionLoginIntegrationTest { @MockitoBean private AccountClient accountClient; @MockitoBean private GameInstanceRepository gameInstanceRepository; + @MockitoBean private TickScheduler tickScheduler; @MockitoBean private CommandService commandService; @MockitoBean @@ -111,7 +115,7 @@ void setUp() { instance.setId(1L); instance.setTenantId(42L); instance.setOwnerAccountId(OWNER_ACCOUNT_UUID); - when(gameInstanceRepository.findById(anyLong())).thenReturn(Optional.of(instance)); + doReturn(Optional.of(instance)).when(gameInstanceRepository).findById(anyLong()); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(42L, 1L)) .thenReturn( List.of( @@ -146,5 +150,6 @@ void loginCallsAccountServiceAndReturnsOk() throws Exception { assertThat(sessionContextService.findByTenantAndSessionId(42L, 1L)).isPresent(); verify(accountClient).authenticate(eq("demo@example.com"), eq("swordfish")); + verify(gameInstanceRepository, never()).findByStatus(anyString()); } } 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 index b7708ea0b9..367e1d4263 100644 --- 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 @@ -163,8 +163,18 @@ void authenticatedCurrentBootstrapAndContiguousEventUseDeterministicPersistentSn 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"); + JsonNode firstProjection = parse(firstSnapshot.json()); + assertThat(firstProjection.path("lastAppliedIssuerGeneration").asText()).isEqualTo("2"); + assertThat(firstProjection.path("lastAppliedSourceOutboxSequence").asText()).isEqualTo("1"); + assertThat(firstProjection.path("outboxStreamKey").asText()).isEqualTo(first.outboxStreamKey()); + assertThat(firstProjection.path("lastAppliedSourceEventId").asText()) + .isEqualTo(first.eventId()); + assertThat(firstProjection.path("lastAppliedSourceEventDigest").asText()) + .isEqualTo(first.eventDigest()); + assertThat(firstProjection.has("issuerAuthGeneration")).isFalse(); + assertThat(firstProjection.has("sourceOutboxStreamKey")).isFalse(); + assertThat(firstProjection.has("sourceEventId")).isFalse(); + assertThat(firstProjection.has("sourceEventDigest")).isFalse(); assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(firstSnapshot.json()); assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); @@ -191,7 +201,15 @@ void authenticatedSequenceZeroAbsenceBootstrapsWithoutEventIdentityOrAdmissionEv assertThat(bootstrap.outcome()).isEqualTo(Outcome.APPLIED); JsonNode projection = parse(bootstrap.snapshot().orElseThrow().json()); + assertThat(projection.path("lastAppliedIssuerGeneration").asText()).isEqualTo("1"); assertThat(projection.path("lastAppliedSourceOutboxSequence").asText()).isEqualTo("0"); + assertThat(projection.path("outboxStreamKey").asText()) + .isEqualTo( + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + issuerId); + assertThat(projection.has("lastAppliedSourceEventId")).isFalse(); + assertThat(projection.has("lastAppliedSourceEventDigest")).isFalse(); + assertThat(projection.has("issuerAuthGeneration")).isFalse(); + assertThat(projection.has("sourceOutboxStreamKey")).isFalse(); assertThat(projection.has("sourceEventId")).isFalse(); assertThat(projection.has("sourceEventDigest")).isFalse(); assertThat(projection.path("appliedSourceEvidence").isEmpty()).isTrue(); @@ -260,6 +278,28 @@ void unknownOrDuplicateJsonFieldsQuarantineWithoutChangingBytesOrTtl() throws Ex assertThat(adminTemplate.getExpire(key, TimeUnit.MILLISECONDS)).isEqualTo(-1L); } + @Test + void obsoletePersistedAliasesQuarantineWithoutChangingBytesOrTtl() throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "3", 10); + ApplyResult bootstrap = store.apply(readback("2", "3", "1", first, null), "stable-time"); + String canonicalJson = bootstrap.snapshot().orElseThrow().json(); + String obsoleteJson = + canonicalJson + .replace("\"lastAppliedIssuerGeneration\"", "\"issuerAuthGeneration\"") + .replace("\"outboxStreamKey\"", "\"sourceOutboxStreamKey\"") + .replace("\"lastAppliedSourceEventId\"", "\"sourceEventId\"") + .replace("\"lastAppliedSourceEventDigest\"", "\"sourceEventDigest\""); + adminTemplate.opsForValue().set(key(), obsoleteJson); + + ApplyResult result = + store.apply(readback("2", "3", "1", first, first), "ignored-for-obsolete-alias"); + + assertThat(result.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(result.detail()).contains("MALFORMED_EXISTING_PROJECTION"); + assertThat(adminTemplate.opsForValue().get(key())).isEqualTo(obsoleteJson); + assertThat(adminTemplate.getExpire(key(), TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } + @Test void expiringProjectionIsQuarantinedWithoutChangingItsBytesOrExpiration() throws Exception { IssuerGenerationAuthorityEvent first = event("1", "2", "3", 8); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java index 6e66caa4a8..8c1d40b107 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java @@ -57,7 +57,8 @@ void migrationPreservesNumericHistoryAndStoresCanonicalOwnerUuid() { String legacyRowAfterMigration = dsl.resultQuery( - "SELECT (to_jsonb(game_instance) - 'owner_account_uuid')::text " + "SELECT (to_jsonb(game_instance) - 'owner_account_uuid' " + + "- 'game_instance_uuid')::text " + "FROM game_instances AS game_instance WHERE id = 7001") .fetchOne(0, String.class); assertThat(legacyRowAfterMigration).isEqualTo(legacyRowBeforeMigration); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceUuidIdentityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceUuidIdentityIntegrationTest.java new file mode 100644 index 0000000000..701199dbee --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceUuidIdentityIntegrationTest.java @@ -0,0 +1,192 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.GameInstance; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Testcontainers; + +@SuppressWarnings("resource") +@Testcontainers(disabledWithoutDocker = true) +class GameInstanceUuidIdentityIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final long RETAINED_INSTANCE_ID = 4_242L; + private static final long RETAINED_TENANT_ID = 77L; + private static final long RETAINED_OWNER_ID = 9_007_199_254_740_993L; + private static final String OWNER_UUID = "123e4567-e89b-12d3-a456-426614174000"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @Test + void freshRepositoryIdentityIsPersistedAndRetainedRowsRemainUnmapped() { + try (PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine")) { + postgres.start(); + DriverManagerDataSource dataSource = dataSource(postgres); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("10")) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, script_patch_version, " + + "script_pin_epoch, script_patch_pinned_control_plane_request_id, " + + "owner_account_id, status, row_version) " + + "VALUES (?, ?, 'retained-runtime', 'retained-patch', 3, 'retained-pin-request', " + + "?, 'STOPPED', 17)", + RETAINED_INSTANCE_ID, + RETAINED_TENANT_ID, + RETAINED_OWNER_ID); + String retainedBeforeMigration = + dsl.resultQuery( + "SELECT to_jsonb(game_instance)::text FROM game_instances AS game_instance " + + "WHERE id = ?", + RETAINED_INSTANCE_ID) + .fetchOne(0, String.class); + + Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + + String retainedAfterMigration = + dsl.resultQuery( + "SELECT (to_jsonb(game_instance) - 'game_instance_uuid')::text " + + "FROM game_instances AS game_instance WHERE id = ?", + RETAINED_INSTANCE_ID) + .fetchOne(0, String.class); + assertThat(retainedAfterMigration).isEqualTo(retainedBeforeMigration); + Record retainedUuid = + dsl.fetchOne( + "SELECT game_instance_uuid FROM game_instances WHERE id = ?", RETAINED_INSTANCE_ID); + assertThat(retainedUuid.get("game_instance_uuid", UUID.class)).isNull(); + + GameInstanceRepository repository = new GameInstanceRepository(dsl); + GameInstance retained = repository.findById(RETAINED_INSTANCE_ID).orElseThrow(); + assertThat(retained.getGameInstanceUuid()).isNull(); + assertThatThrownBy( + () -> + repository.requireCanonicalGameInstanceUuidByTenantIdAndPrivateId( + RETAINED_TENANT_ID, RETAINED_INSTANCE_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no canonical UUID mapping"); + assertThatThrownBy( + () -> + repository.requireCanonicalGameInstanceUuidByTenantIdAndPrivateId( + RETAINED_TENANT_ID + 1, RETAINED_INSTANCE_ID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not found in tenant scope"); + + GameInstance fresh = new GameInstance(); + fresh.setTenantId(RETAINED_TENANT_ID); + fresh.setRuntimeVersion("fresh-runtime"); + fresh.setOwnerAccountId(OWNER_UUID); + fresh.setStatus("STOPPED"); + GameInstance saved = repository.save(fresh); + UUID persistedUuid = saved.getGameInstanceUuid(); + assertThat(persistedUuid).isNotNull().isNotEqualTo(NIL_UUID); + assertThat(persistedUuid.toString()) + .matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); + assertThat( + repository.requireCanonicalGameInstanceUuidByTenantIdAndPrivateId( + RETAINED_TENANT_ID, saved.getId())) + .isEqualTo(persistedUuid.toString()); + assertThat( + dsl.resultQuery( + "SELECT game_instance_uuid FROM game_instances WHERE id = ?", saved.getId()) + .fetchOne(0, UUID.class)) + .isEqualTo(persistedUuid); + + saved.setStatus("RUNNING"); + GameInstance updated = repository.save(saved); + assertThat(updated.getGameInstanceUuid()).isEqualTo(persistedUuid); + assertThat(repository.findById(saved.getId()).orElseThrow().getGameInstanceUuid()) + .isEqualTo(persistedUuid); + + GameInstance attemptedIdentityRemoval = repository.findById(saved.getId()).orElseThrow(); + attemptedIdentityRemoval.setGameInstanceUuid(null); + attemptedIdentityRemoval.setStatus("STOPPED"); + assertThatThrownBy(() -> repository.save(attemptedIdentityRemoval)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Failed to update game_instance"); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_instances SET game_instance_uuid = NULL WHERE id = ?", + saved.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Game Session game_instance_uuid identity is immutable"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_instances SET game_instance_uuid = ? WHERE id = ?", + UUID.fromString("123e4567-e89b-12d3-a456-426614174099"), + saved.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Game Session game_instance_uuid identity is immutable"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_instances SET game_instance_uuid = ? WHERE id = ?", + UUID.fromString("123e4567-e89b-12d3-a456-426614174099"), + RETAINED_INSTANCE_ID)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Game Session game_instance_uuid identity is immutable"); + assertThat( + dsl.resultQuery( + "SELECT game_instance_uuid FROM game_instances WHERE id = ?", saved.getId()) + .fetchOne(0, UUID.class)) + .isEqualTo(persistedUuid); + assertThat( + dsl.resultQuery( + "SELECT game_instance_uuid FROM game_instances WHERE id = ?", + RETAINED_INSTANCE_ID) + .fetchOne(0, UUID.class)) + .isNull(); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO game_instances (tenant_id, runtime_version, " + + "owner_account_uuid, status, game_instance_uuid) " + + "VALUES (?, 'duplicate-runtime', ?, 'STOPPED', ?)", + RETAINED_TENANT_ID, + UUID.fromString(OWNER_UUID), + persistedUuid)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("uq_game_instances_game_instance_uuid"); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO game_instances (tenant_id, runtime_version, " + + "owner_account_uuid, status, game_instance_uuid) " + + "VALUES (?, 'nil-runtime', ?, 'STOPPED', ?)", + RETAINED_TENANT_ID, + UUID.fromString(OWNER_UUID), + NIL_UUID)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("game_instances_game_instance_uuid_non_nil"); + } + } + + private static DriverManagerDataSource dataSource(PostgreSQLContainer postgres) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } +} diff --git a/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java b/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java index 50d22bc6bb..5f518df665 100644 --- a/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java +++ b/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java @@ -54,6 +54,7 @@ void keepsAdmissionPointerMigrationsUniqueAndOrderedFromTheV7AuditThroughV12() "V10__run_owned_initial_launch_identity.sql", "V10.1__game_instance_owner_account_uuid.sql", "V11__enforce_tenant_public_realm_cardinality.sql", + "V11.1__game_instance_uuid_identity.sql", "V12__index_gameplay_admission_pointer_event_tenant_lookup.sql"); String v7 = readMigration("V7__audit_gameplay_catalog_revision.sql"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClientTest.java index a884e3c860..bb2f8428f8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountIssuerAuthorityClientTest.java @@ -4,12 +4,15 @@ 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.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.protobuf.UnknownFieldSet; import io.grpc.Attributes; import io.grpc.ClientCall; @@ -19,29 +22,54 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.security.MessageDigest; import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.AcknowledgeIssuerProjectionForRuntimeRequest; +import net.firedevops.firemud.account.v1.AcknowledgeIssuerProjectionForRuntimeResponse; +import net.firedevops.firemud.account.v1.CaptureIssuerProjectionForRuntimeRequest; +import net.firedevops.firemud.account.v1.CaptureIssuerProjectionForRuntimeResponse; 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.IssuerAuthorityProjectionV1Codec; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent; +import net.firedevops.firemud.common.account.authority.IssuerProjectionInstallationAcknowledgmentDigestV1; +import net.firedevops.firemud.common.account.authority.IssuerProjectionReconciliationRequestDigestV1; 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.service.IssuerAuthorityProjectionRedisContract; +import net.firedevops.firemud.gamesession.service.IssuerProjectionReconciliationInstaller; +import net.firedevops.firemud.gamesession.service.IssuerProjectionReconciliationInstaller.InstallationReceipt; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.CoordinationEndpoint; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; +import org.springframework.core.io.ClassPathResource; +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 AccountIssuerAuthorityClientTest { private static final String NAMESPACE = "test"; @@ -52,7 +80,15 @@ class AccountIssuerAuthorityClientTest { private static final UUID REQUEST_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); private static final UUID EVENT_REQUEST_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final String LARGE_COUNTER = "922337203685477580812345678901234567890"; + private static final String CAPTURE_CALLER = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final String CAPTURE_PROJECTION_KEY = + "session:game:auth:issuer-generation:v1:" + ISSUER_ID; + private static final UUID ACKNOWLEDGMENT_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final ObjectMapper JSON = new ObjectMapper(); @Test void currentReadVerifiesAndReturnsTheSequenceZeroPositiveBaseline() throws Exception { @@ -148,6 +184,377 @@ void historicalReadAtCurrentSequenceRequiresTheCompleteLatestEvent() throws Exce assertLatestEvent(readback.requestedEvent().orElseThrow(), event); } + @Test + void captureRequestUsesOnlyIssuerAndStableRequestAndReturnsTypedZeroBaseline() throws Exception { + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + when(stub.captureIssuerProjectionForRuntime(any())) + .thenReturn(captureResponse(REQUEST_ID, OPERATION_ID, sourceSnapshot("1", "1", "0", null))); + AccountIssuerAuthorityClient client = newClient(stub); + + AccountIssuerAuthorityClient.ProjectionCaptureReceipt receipt = + client.captureProjection(REQUEST_ID.toString()); + + assertThat(receipt.operationUUID()).isEqualTo(OPERATION_ID); + assertThat(receipt.requestUUID()).isEqualTo(REQUEST_ID); + assertThat(receipt.issuerId()).isEqualTo(ISSUER_ID); + assertThat(receipt.callerWorkloadIdentity()).isEqualTo(CAPTURE_CALLER); + assertThat(receipt.projectionKey()).isEqualTo(CAPTURE_PROJECTION_KEY); + assertThat(receipt.requestDigestVersion()).isEqualTo(1); + assertThat(receipt.requestDigest()) + .isEqualTo( + IssuerProjectionReconciliationRequestDigestV1.digest( + ISSUER_ID, CAPTURE_CALLER, CAPTURE_PROJECTION_KEY, REQUEST_ID)); + assertThat(receipt.capturedSource().issuerAuthGeneration()).isEqualTo("1"); + assertThat(receipt.capturedSource().sourceVersion()).isEqualTo("1"); + assertThat(receipt.capturedSource().outboxSequence()).isEqualTo("0"); + assertThat(receipt.capturedSource().latestEvent()).isEmpty(); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(CaptureIssuerProjectionForRuntimeRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).captureIssuerProjectionForRuntime(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getIssuerId()).isEqualTo(ISSUER_ID); + assertThat(requestCaptor.getValue().getRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(requestCaptor.getValue().getAllFields()).hasSize(2); + } + + @Test + void captureVerifiesSharedAsciiDigestVectorAndLargeIndependentSourceCounters() throws Exception { + String namespace = "account-unit"; + String issuerId = "https://account.example.test/issuer"; + UUID requestId = UUID.fromString("a3a69671-8149-4d97-86f8-25a2582fdd68"); + UUID operationId = UUID.fromString("4ed42a0f-80e4-44db-8f4e-16c70e2c70a3"); + String caller = "spiffe://firemud/ns/account-unit/sa/game-session-service"; + String projectionKey = "session:game:auth:issuer-generation:v1:" + issuerId; + String digest = "240027543295dc990703ec833578b423f1cdc51e91333d8b58c91d6c5f571d15"; + String generation = LARGE_COUNTER + "1"; + String sourceVersion = LARGE_COUNTER + "2"; + String sequence = LARGE_COUNTER + "3"; + IssuerGenerationAuthorityEvent event = + event(sequence, generation, sourceVersion, EVENT_REQUEST_ID, issuerId); + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + when(stub.captureIssuerProjectionForRuntime(any())) + .thenReturn( + captureResponse( + namespace, + issuerId, + requestId, + operationId, + caller, + projectionKey, + 1, + digest, + sourceSnapshot( + issuerId, generation, sourceVersion, sequence, event.canonicalJson()))); + AccountIssuerAuthorityClient client = newClient(stub, namespace, issuerId); + + AccountIssuerAuthorityClient.ProjectionCaptureReceipt receipt = + client.captureProjection(requestId.toString()); + + assertThat(receipt.requestDigest()).isEqualTo(digest); + assertThat(receipt.capturedSource().issuerAuthGeneration()).isEqualTo(generation); + assertThat(receipt.capturedSource().sourceVersion()).isEqualTo(sourceVersion); + assertThat(receipt.capturedSource().outboxSequence()).isEqualTo(sequence); + assertLatestEvent(receipt.capturedSource().latestEvent().orElseThrow(), event); + } + + @Test + void exactCaptureRetryReturnsItsUnchangedHistoricalSnapshot() throws Exception { + IssuerGenerationAuthorityEvent historical = event("3", "7", "9", EVENT_REQUEST_ID); + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + when(stub.captureIssuerProjectionForRuntime(any())) + .thenReturn( + captureResponse( + REQUEST_ID, + OPERATION_ID, + sourceSnapshot("7", "9", "3", historical.canonicalJson()))); + AccountIssuerAuthorityClient client = newClient(stub); + + AccountIssuerAuthorityClient.ProjectionCaptureReceipt receipt = + client.captureProjection(REQUEST_ID.toString()); + + assertThat(receipt.operationUUID()).isEqualTo(OPERATION_ID); + assertThat(receipt.capturedSource().outboxSequence()).isEqualTo("3"); + assertLatestEvent(receipt.capturedSource().latestEvent().orElseThrow(), historical); + verify(stub).captureIssuerProjectionForRuntime(any()); + } + + @Test + void installationAcknowledgmentUsesPrivateReceiptAndReplaysOriginalAcknowledgment() + throws Exception { + InstallationFixture fixture = installationFixture(sourceSnapshot("1", "1", "0", null)); + try { + InstallationReceipt installation = + fixture + .installer() + .install(REQUEST_ID.toString(), "original-applied-at") + .receipt() + .orElseThrow(); + AcknowledgeIssuerProjectionForRuntimeResponse originalResponse = + installationAcknowledgmentResponse(installation, NAMESPACE, ISSUER_ID, ACKNOWLEDGMENT_ID); + when(fixture.stub().acknowledgeIssuerProjectionForRuntime(any())) + .thenReturn(originalResponse); + + AccountIssuerAuthorityClient.InstallationAcknowledgmentReceipt original = + fixture.client().acknowledgeInstallation(installation); + AccountIssuerAuthorityClient.InstallationAcknowledgmentReceipt retry = + fixture.client().acknowledgeInstallation(installation); + + assertThat(original.acknowledgmentId()).isEqualTo(ACKNOWLEDGMENT_ID); + assertThat(retry.acknowledgmentId()).isEqualTo(original.acknowledgmentId()); + assertThat(original.captureOperationId()).isEqualTo(installation.operationId()); + assertThat(original.captureRequestId()).isEqualTo(installation.requestId()); + assertThat(original.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(original.captureRequestDigest()).isEqualTo(installation.requestDigest()); + assertThat(original.captureRequestDigestVersion()).isEqualTo(1); + assertThat(original.requestDigestVersion()) + .isEqualTo(IssuerProjectionInstallationAcknowledgmentDigestV1.VERSION); + assertThat(original.installedProjectionJson()) + .isEqualTo(installation.projectionSnapshot().json()) + .contains("\"appliedAt\":\"original-applied-at\""); + assertThat(original.installedProjectionSha256()) + .isEqualTo(originalResponse.getInstalledProjectionSha256()); + assertThat( + AccountIssuerAuthorityClient.InstallationAcknowledgmentReceipt.class + .getConstructors()) + .isEmpty(); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(AcknowledgeIssuerProjectionForRuntimeRequest.class); + verify(fixture.stub(), times(5)).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(fixture.stub(), times(2)) + .acknowledgeIssuerProjectionForRuntime(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()).hasSize(2); + for (AcknowledgeIssuerProjectionForRuntimeRequest request : requestCaptor.getAllValues()) { + assertThat(request.getIssuerId()).isEqualTo(ISSUER_ID); + assertThat(request.getCaptureOperationId()) + .isEqualTo(installation.operationId().toString()); + assertThat(request.getCaptureRequestId()).isEqualTo(installation.requestId().toString()); + assertThat(request.getCaptureRequestDigestVersion()).isEqualTo(1); + assertThat(request.getCaptureRequestDigest()).isEqualTo(installation.requestDigest()); + assertThat(request.getProjectionKey()).isEqualTo(CAPTURE_PROJECTION_KEY); + assertThat(request.getInstalledProjectionJson()) + .isEqualTo(installation.projectionSnapshot().json()); + assertThat(request.getAllFields()).hasSize(7); + } + verify(fixture.stub(), times(1)).captureIssuerProjectionForRuntime(any()); + verify(fixture.stub(), times(2)).readIssuerAuthorityForRuntime(any()); + } finally { + fixture.store().close(); + } + } + + @Test + void rejectsChangedInstallationAcknowledgmentBindingsDigestsBytesAndEvent() throws Exception { + IssuerGenerationAuthorityEvent capturedEvent = event("2", "3", "3", EVENT_REQUEST_ID); + InstallationFixture fixture = + installationFixture(sourceSnapshot("3", "3", "2", capturedEvent.canonicalJson())); + try { + InstallationReceipt installation = + fixture + .installer() + .install(REQUEST_ID.toString(), "original-applied-at") + .receipt() + .orElseThrow(); + AcknowledgeIssuerProjectionForRuntimeResponse valid = + installationAcknowledgmentResponse(installation, NAMESPACE, ISSUER_ID, ACKNOWLEDGMENT_ID); + AtomicReference response = + new AtomicReference<>(valid); + when(fixture.stub().acknowledgeIssuerProjectionForRuntime(any())) + .thenAnswer(ignored -> response.get()); + + IssuerGenerationAuthorityEvent changedEvent = + event("2", "3", "3", UUID.fromString("55555555-5555-4555-8555-555555555555")); + String changedEventProjection = + replaceProjectionEvent( + installation.projectionSnapshot().json(), capturedEvent, changedEvent); + assertThat( + IssuerAuthorityProjectionV1Codec.verify(changedEventProjection) + .latestEvent() + .orElseThrow() + .canonicalJson()) + .isEqualTo(changedEvent.canonicalJson()); + AcknowledgeIssuerProjectionForRuntimeResponse changedEventResponse = + valid.toBuilder() + .setInstalledProjectionJson(changedEventProjection) + .setInstalledProjectionSha256(sha256Hex(changedEventProjection)) + .setRequestDigest( + installationAcknowledgmentDigest(installation, changedEventProjection)) + .build(); + + List invalidResponses = + List.of( + AcknowledgeIssuerProjectionForRuntimeResponse.getDefaultInstance(), + valid.toBuilder().setUnknownFields(unknownFields()).build(), + valid.toBuilder().setSchemaVersion("other").build(), + valid.toBuilder().setTargetNamespace("other").build(), + valid.toBuilder().setAcknowledgmentId("not-a-uuid").build(), + valid.toBuilder().setIssuerId("other").build(), + valid.toBuilder().setCallerWorkloadIdentity("other").build(), + valid.toBuilder().setProjectionKey("other").build(), + valid.toBuilder().setCaptureOperationId(EVENT_REQUEST_ID.toString()).build(), + valid.toBuilder().setCaptureRequestId(EVENT_REQUEST_ID.toString()).build(), + valid.toBuilder().setCaptureRequestDigestVersion(2).build(), + valid.toBuilder().setCaptureRequestDigest("0".repeat(64)).build(), + valid.toBuilder().setRequestDigestVersion(2).build(), + valid.toBuilder().setRequestDigest("0".repeat(64)).build(), + valid.toBuilder() + .setInstalledProjectionJson( + installation + .projectionSnapshot() + .json() + .replace("original-applied-at", "changed-applied-at")) + .build(), + valid.toBuilder().setInstalledProjectionSha256("0".repeat(64)).build(), + changedEventResponse); + + for (AcknowledgeIssuerProjectionForRuntimeResponse invalid : invalidResponses) { + response.set(invalid); + assertThatThrownBy(() -> fixture.client().acknowledgeInstallation(installation)) + .isInstanceOf(IllegalStateException.class); + } + verify(fixture.stub(), times(invalidResponses.size())) + .acknowledgeIssuerProjectionForRuntime(any()); + } finally { + fixture.store().close(); + } + } + + @Test + void rejectsInstallationReceiptForDifferentConfiguredIssuerOrNamespaceBeforeRpc() + throws Exception { + InstallationFixture fixture = installationFixture(sourceSnapshot("1", "1", "0", null)); + try { + InstallationReceipt installation = + fixture + .installer() + .install(REQUEST_ID.toString(), "original-applied-at") + .receipt() + .orElseThrow(); + AccountIssuerAuthorityClient wrongIssuer = + newClient(fixture.stub(), NAMESPACE, "https://other.example.test/issuer"); + AccountIssuerAuthorityClient wrongNamespace = newClient(fixture.stub(), "other", ISSUER_ID); + + assertThatThrownBy(() -> fixture.client().acknowledgeInstallation(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> wrongIssuer.acknowledgeInstallation(installation)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> wrongNamespace.acknowledgeInstallation(installation)) + .isInstanceOf(IllegalArgumentException.class); + verify(fixture.stub(), never()).acknowledgeIssuerProjectionForRuntime(any()); + } finally { + fixture.store().close(); + } + } + + @Test + void rejectsCaptureResponseBindingSnapshotEventAndUnknownFieldDeviations() throws Exception { + IssuerAuthoritySourceSnapshot baseline = sourceSnapshot("1", "1", "0", null); + CaptureIssuerProjectionForRuntimeResponse valid = + captureResponse(REQUEST_ID, OPERATION_ID, baseline); + assertCaptureRejected(null); + assertCaptureRejected(valid.toBuilder().setSchemaVersion("other").build()); + assertCaptureRejected(valid.toBuilder().setTargetNamespace("other").build()); + assertCaptureRejected(valid.toBuilder().setRequestId(EVENT_REQUEST_ID.toString()).build()); + assertCaptureRejected(valid.toBuilder().setOperationId("not-a-uuid").build()); + assertCaptureRejected( + valid.toBuilder().setOperationId("00000000-0000-0000-0000-000000000000").build()); + assertCaptureRejected(valid.toBuilder().setIssuerId("other").build()); + assertCaptureRejected(valid.toBuilder().setCallerWorkloadIdentity("other").build()); + assertCaptureRejected(valid.toBuilder().setProjectionKey("other").build()); + assertCaptureRejected(valid.toBuilder().setRequestDigestVersion(2).build()); + assertCaptureRejected(valid.toBuilder().setRequestDigest("0".repeat(64)).build()); + assertCaptureRejected(valid.toBuilder().clearCapturedSourceSnapshot().build()); + assertCaptureRejected( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build()); + assertCaptureRejected( + valid.toBuilder() + .setCapturedSourceSnapshot(baseline.toBuilder().setIssuerId("other").build()) + .build()); + assertCaptureRejected( + valid.toBuilder() + .setCapturedSourceSnapshot(baseline.toBuilder().setSourceScope("issuer/other").build()) + .build()); + assertCaptureRejected( + valid.toBuilder() + .setCapturedSourceSnapshot(baseline.toBuilder().setOutboxStreamKey("other").build()) + .build()); + assertCaptureRejected( + valid.toBuilder() + .setCapturedSourceSnapshot(baseline.toBuilder().setIssuerAuthGeneration("01").build()) + .build()); + assertCaptureRejected( + valid.toBuilder() + .setCapturedSourceSnapshot(baseline.toBuilder().setSourceVersion("0").build()) + .build()); + assertCaptureRejected( + valid.toBuilder() + .setCapturedSourceSnapshot(baseline.toBuilder().setOutboxSequence("00").build()) + .build()); + assertCaptureRejected( + valid.toBuilder() + .setCapturedSourceSnapshot(baseline.toBuilder().setLatestEventCanonicalJson("").build()) + .build()); + assertCaptureRejected( + valid.toBuilder() + .setCapturedSourceSnapshot( + baseline.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build()) + .build()); + + IssuerGenerationAuthorityEvent latest = event("1", "2", "2", EVENT_REQUEST_ID); + assertCaptureRejected( + valid.toBuilder().setCapturedSourceSnapshot(sourceSnapshot("2", "2", "1", null)).build()); + assertCaptureRejected( + valid.toBuilder() + .setCapturedSourceSnapshot(sourceSnapshot("3", "2", "1", latest.canonicalJson())) + .build()); + assertCaptureRejected( + valid.toBuilder() + .setCapturedSourceSnapshot(sourceSnapshot("2", "3", "1", latest.canonicalJson())) + .build()); + assertCaptureRejected( + valid.toBuilder() + .setCapturedSourceSnapshot( + sourceSnapshot( + "2", + "2", + "1", + latest + .canonicalJson() + .replace( + "\"eventDigest\":\"sha256:", + "\"unexpected\":true,\"eventDigest\":\"sha256:"))) + .build()); + } + + @Test + void unavailableCaptureStatusPropagatesOnceWithoutReplacementIdentityOrRetry() throws Exception { + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + StatusRuntimeException unavailable = + new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Account unavailable")); + when(stub.captureIssuerProjectionForRuntime(any())).thenThrow(unavailable); + AccountIssuerAuthorityClient client = newClient(stub); + + assertThatThrownBy(() -> client.captureProjection(REQUEST_ID.toString())).isSameAs(unavailable); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(CaptureIssuerProjectionForRuntimeRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).captureIssuerProjectionForRuntime(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getRequestId()).isEqualTo(REQUEST_ID.toString()); + verify(stub, never()).withDeadlineAfter(10L, TimeUnit.SECONDS); + } + @Test void rejectsMalformedRequestIdentityOrNoncanonicalHistoricalSelectorBeforeStubUse() { GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); @@ -163,6 +570,8 @@ void rejectsMalformedRequestIdentityOrNoncanonicalHistoricalSelectorBeforeStubUs .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> client.readCommittedEvent(invalid, "1")) .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.captureProjection(invalid)) + .isInstanceOf(IllegalArgumentException.class); } for (String invalid : List.of("", "0", "00", "01", "+1", "-1", "1.0", " 1")) { assertThatThrownBy(() -> client.readCommittedEvent(REQUEST_ID.toString(), invalid)) @@ -420,9 +829,206 @@ void installedPeerInterceptorDeniesMissingAndWrongServerCertificateIdentity() th .isInstanceOf(StatusRuntimeException.class) .extracting(exception -> ((StatusRuntimeException) exception).getStatus().getCode()) .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy( + () -> + stub.captureIssuerProjectionForRuntime( + CaptureIssuerProjectionForRuntimeRequest.newBuilder() + .setIssuerId(ISSUER_ID) + .setRequestId(REQUEST_ID.toString()) + .build())) + .isInstanceOf(StatusRuntimeException.class) + .extracting(exception -> ((StatusRuntimeException) exception).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy( + () -> + stub.acknowledgeIssuerProjectionForRuntime( + AcknowledgeIssuerProjectionForRuntimeRequest.getDefaultInstance())) + .isInstanceOf(StatusRuntimeException.class) + .extracting(exception -> ((StatusRuntimeException) exception).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); } } + private static void assertCaptureRejected(CaptureIssuerProjectionForRuntimeResponse response) + throws Exception { + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + when(stub.captureIssuerProjectionForRuntime(any())).thenReturn(response); + AccountIssuerAuthorityClient client = newClient(stub); + assertThatThrownBy(() -> client.captureProjection(REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class); + } + + private static InstallationFixture installationFixture(IssuerAuthoritySourceSnapshot snapshot) + throws Exception { + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); + when(stub.captureIssuerProjectionForRuntime(any())) + .thenReturn(captureResponse(REQUEST_ID, OPERATION_ID, snapshot)); + when(stub.readIssuerAuthorityForRuntime(any())).thenReturn(snapshotOnly(snapshot)); + AccountIssuerAuthorityClient client = newClient(stub); + RedisFixture redis = redisFixture(); + RedisIssuerAuthorityProjectionStore store = storeWithConnection(); + Field templateField = + RedisIssuerAuthorityProjectionStore.class.getDeclaredField("redisTemplate"); + templateField.setAccessible(true); + templateField.set(store, redis.template()); + return new InstallationFixture( + stub, client, store, new IssuerProjectionReconciliationInstaller(client, store)); + } + + private static RedisFixture redisFixture() throws Exception { + byte[] script; + try (var input = + new ClassPathResource(IssuerAuthorityProjectionRedisContract.RESOURCE_PATH) + .getInputStream()) { + script = input.readAllBytes(); + } + String sha1 = + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(script)); + 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); + AtomicReference storedValue = new AtomicReference<>(); + when(stringCommands.get(any(byte[].class))) + .thenAnswer( + ignored -> { + byte[] value = storedValue.get(); + return value == null ? null : value.clone(); + }); + when(keyCommands.pTtl(any(byte[].class))).thenReturn(-1L); + when(scriptingCommands.scriptLoad(any(byte[].class))).thenReturn(sha1); + when(scriptingCommands.evalSha(eq(sha1), eq(ReturnType.VALUE), eq(1), any(byte[][].class))) + .thenAnswer( + invocation -> { + byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; + String mode = new String(arguments[1], StandardCharsets.US_ASCII); + byte[] expected = arguments[2]; + byte[] candidate = arguments[3]; + byte[] current = storedValue.get(); + String result; + if (mode.equals("VERIFY")) { + result = Arrays.equals(current, expected) ? "REPLAY" : "STALE"; + } else if (mode.equals("ABSENT") && current == null) { + storedValue.set(candidate.clone()); + result = "APPLIED"; + } else if (mode.equals("PRESENT") && Arrays.equals(current, expected)) { + storedValue.set(candidate.clone()); + result = "APPLIED"; + } else if (Arrays.equals(current, candidate)) { + result = "REPLAY"; + } else { + result = "STALE"; + } + return result.getBytes(StandardCharsets.US_ASCII); + }); + StringRedisTemplate template = mock(StringRedisTemplate.class); + doAnswer( + invocation -> { + RedisCallback callback = invocation.getArgument(0); + return callback.doInRedis(connection); + }) + .when(template) + .execute(any(RedisCallback.class)); + return new RedisFixture(template); + } + + private static RedisIssuerAuthorityProjectionStore storeWithConnection() { + RedisIssuerAuthorityProjectionStore store = + new RedisIssuerAuthorityProjectionStore( + NAMESPACE, + new CoordinationEndpoint("127.0.0.1", 1, "gamesession_coord_app", "test-secret"), + new CacheRateLimitEndpoint("127.0.0.1", 2)); + store.init(); + return store; + } + + private static AcknowledgeIssuerProjectionForRuntimeResponse installationAcknowledgmentResponse( + InstallationReceipt installation, String namespace, String issuerId, UUID acknowledgmentId) + throws Exception { + String caller = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + String projectionKey = IssuerAuthorityProjectionRedisContract.keyForIssuer(issuerId); + String projectionJson = installation.projectionSnapshot().json(); + String requestDigest = + IssuerProjectionInstallationAcknowledgmentDigestV1.digest( + issuerId, + caller, + projectionKey, + installation.operationId(), + installation.requestId(), + 1, + installation.requestDigest(), + projectionJson); + return AcknowledgeIssuerProjectionForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-projection-installation-ack/v1") + .setTargetNamespace(namespace) + .setAcknowledgmentId(acknowledgmentId.toString()) + .setIssuerId(issuerId) + .setCallerWorkloadIdentity(caller) + .setProjectionKey(projectionKey) + .setCaptureOperationId(installation.operationId().toString()) + .setCaptureRequestId(installation.requestId().toString()) + .setCaptureRequestDigestVersion(1) + .setCaptureRequestDigest(installation.requestDigest()) + .setRequestDigestVersion(IssuerProjectionInstallationAcknowledgmentDigestV1.VERSION) + .setRequestDigest(requestDigest) + .setInstalledProjectionJson(projectionJson) + .setInstalledProjectionSha256(sha256Hex(projectionJson)) + .build(); + } + + private static String installationAcknowledgmentDigest( + InstallationReceipt installation, String projectionJson) { + return IssuerProjectionInstallationAcknowledgmentDigestV1.digest( + ISSUER_ID, + CAPTURE_CALLER, + CAPTURE_PROJECTION_KEY, + installation.operationId(), + installation.requestId(), + 1, + installation.requestDigest(), + projectionJson); + } + + private static String sha256Hex(String text) throws Exception { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); + } + + private static String replaceProjectionEvent( + String projectionJson, + IssuerGenerationAuthorityEvent original, + IssuerGenerationAuthorityEvent replacement) + throws Exception { + return projectionJson + .replace( + JSON.writeValueAsString(original.canonicalJson()), + JSON.writeValueAsString(replacement.canonicalJson())) + .replace( + "\"lastAppliedSourceEventId\":\"" + original.eventId() + "\"", + "\"lastAppliedSourceEventId\":\"" + replacement.eventId() + "\"") + .replace( + "\"lastAppliedSourceEventDigest\":\"" + original.eventDigest() + "\"", + "\"lastAppliedSourceEventDigest\":\"" + replacement.eventDigest() + "\""); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private record InstallationFixture( + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub, + AccountIssuerAuthorityClient client, + RedisIssuerAuthorityProjectionStore store, + IssuerProjectionReconciliationInstaller installer) {} + + private record RedisFixture(StringRedisTemplate template) {} + private static void assertCurrentRejected(ReadIssuerAuthorityForRuntimeResponse response) throws Exception { IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mockStub(); @@ -443,7 +1049,22 @@ private static void assertHistoricalRejected( private static AccountIssuerAuthorityClient newClient( IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub) throws Exception { - AccountIssuerAuthorityClient client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + return newClient(stub, NAMESPACE, ISSUER_ID); + } + + private static AccountIssuerAuthorityClient newClient( + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub, + String namespace, + 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); @@ -488,6 +1109,17 @@ private static ReadIssuerAuthorityForRuntimeResponse snapshotResponse( String sequence, String latestEvent, String requestedEvent) { + ReadIssuerAuthorityForRuntimeResponse.Builder response = + envelope() + .setSourceSnapshot(sourceSnapshot(generation, sourceVersion, sequence, latestEvent)); + if (requestedEvent != null) { + response.setRequestedEventCanonicalJson(requestedEvent); + } + return response.build(); + } + + private static IssuerAuthoritySourceSnapshot sourceSnapshot( + String generation, String sourceVersion, String sequence, String latestEvent) { IssuerAuthoritySourceSnapshot.Builder snapshot = IssuerAuthoritySourceSnapshot.newBuilder() .setIssuerId(ISSUER_ID) @@ -499,12 +1131,67 @@ private static ReadIssuerAuthorityForRuntimeResponse snapshotResponse( if (latestEvent != null) { snapshot.setLatestEventCanonicalJson(latestEvent); } - ReadIssuerAuthorityForRuntimeResponse.Builder response = - envelope().setSourceSnapshot(snapshot.build()); - if (requestedEvent != null) { - response.setRequestedEventCanonicalJson(requestedEvent); + return snapshot.build(); + } + + private static IssuerAuthoritySourceSnapshot sourceSnapshot( + String issuerId, + String generation, + String sourceVersion, + String sequence, + String latestEvent) { + String scope = "issuer/" + issuerId; + IssuerAuthoritySourceSnapshot.Builder snapshot = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(issuerId) + .setSourceScope(scope) + .setOutboxStreamKey(IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope) + .setIssuerAuthGeneration(generation) + .setSourceVersion(sourceVersion) + .setOutboxSequence(sequence); + if (latestEvent != null) { + snapshot.setLatestEventCanonicalJson(latestEvent); } - return response.build(); + return snapshot.build(); + } + + private static CaptureIssuerProjectionForRuntimeResponse captureResponse( + UUID requestId, UUID operationId, IssuerAuthoritySourceSnapshot sourceSnapshot) { + return captureResponse( + NAMESPACE, + ISSUER_ID, + requestId, + operationId, + CAPTURE_CALLER, + CAPTURE_PROJECTION_KEY, + 1, + IssuerProjectionReconciliationRequestDigestV1.digest( + ISSUER_ID, CAPTURE_CALLER, CAPTURE_PROJECTION_KEY, requestId), + sourceSnapshot); + } + + private static CaptureIssuerProjectionForRuntimeResponse captureResponse( + String namespace, + String issuerId, + UUID requestId, + UUID operationId, + String caller, + String projectionKey, + int digestVersion, + String digest, + IssuerAuthoritySourceSnapshot sourceSnapshot) { + return CaptureIssuerProjectionForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-projection-capture/v1") + .setTargetNamespace(namespace) + .setOperationId(operationId.toString()) + .setRequestId(requestId.toString()) + .setIssuerId(issuerId) + .setCallerWorkloadIdentity(caller) + .setProjectionKey(projectionKey) + .setRequestDigestVersion(digestVersion) + .setRequestDigest(digest) + .setCapturedSourceSnapshot(sourceSnapshot) + .build(); } private static ReadIssuerAuthorityForRuntimeResponse.Builder envelope() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameInstanceRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameInstanceRepositoryTest.java index bdb1d1e261..fd6a7c032d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameInstanceRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameInstanceRepositoryTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.when; import java.util.Optional; +import java.util.UUID; import org.assertj.core.api.Assertions; import org.jooq.Condition; import org.jooq.DSLContext; @@ -156,4 +157,21 @@ void saveRejectsIncoherentScriptPinTupleBeforeInsertOrUpdate() { verifyNoInteractions(dsl); } + + @Test + void newSaveRejectsCallerSuppliedGameInstanceUuidBeforeDatabaseAccess() { + DSLContext dsl = mock(DSLContext.class); + GameInstanceRepository repository = new GameInstanceRepository(dsl); + net.firedevops.firemud.gamesession.entity.GameInstance instance = + new net.firedevops.firemud.gamesession.entity.GameInstance(); + instance.setTenantId(3L); + instance.setOwnerAccountId("123e4567-e89b-12d3-a456-426614174000"); + instance.setGameInstanceUuid(UUID.fromString("123e4567-e89b-12d3-a456-426614174001")); + + IllegalArgumentException error = + assertThrows(IllegalArgumentException.class, () -> repository.save(instance)); + + assertEquals("New game instance UUIDs are allocated by Game Session", error.getMessage()); + verifyNoInteractions(dsl); + } } 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 index fef3948c4a..c27214f697 100644 --- 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 @@ -12,18 +12,21 @@ import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.CaptureIssuerProjectionForRuntimeResponse; 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.account.authority.IssuerProjectionReconciliationRequestDigestV1; 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.ProjectionCaptureReceipt; import net.firedevops.firemud.gamesession.client.AccountIssuerAuthorityClient.SourceReadback; import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions; import org.junit.jupiter.api.Test; @@ -49,11 +52,30 @@ void bootstrapAtProvedSequenceZeroOmitsEventIdentityAndKeepsCallerAppliedAt() th assertThat(mutation.nextProjection()) .containsEntry("schemaVersion", IssuerAuthorityProjectionTransitions.SCHEMA_VERSION) .containsEntry("issuerId", ISSUER_ID) - .containsEntry("issuerAuthGeneration", "1") + .containsEntry("lastAppliedIssuerGeneration", "1") .containsEntry("lastAppliedSourceOutboxSequence", "0") + .containsEntry( + "outboxStreamKey", + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER_ID) .containsEntry("appliedAt", "2026-10-02T11:00:00Z") .containsEntry("appliedSourceEvidence", Map.of()); - assertThat(mutation.nextProjection()).doesNotContainKeys("sourceEventId", "sourceEventDigest"); + assertThat(mutation.nextProjection()) + .doesNotContainKeys( + "lastAppliedSourceEventId", + "lastAppliedSourceEventDigest", + "issuerAuthGeneration", + "sourceOutboxStreamKey", + "sourceEventId", + "sourceEventDigest"); + assertThat(mutation.nextProjection().keySet()) + .containsExactlyInAnyOrder( + "schemaVersion", + "issuerId", + "lastAppliedIssuerGeneration", + "lastAppliedSourceOutboxSequence", + "outboxStreamKey", + "appliedAt", + "appliedSourceEvidence"); } @Test @@ -66,12 +88,27 @@ void bootstrapPositiveCurrentCheckpointRetainsCompleteLatestEventEvidence() thro IssuerAuthorityProjectionTransitions.bootstrap(readback, "stable-time"); assertThat(mutation.nextProjection()) - .containsEntry("issuerAuthGeneration", "92") + .containsEntry("lastAppliedIssuerGeneration", "92") .containsEntry("lastAppliedSourceOutboxSequence", "7") - .containsEntry("sourceEventId", event.eventId()) - .containsEntry("sourceEventDigest", event.eventDigest()) + .containsEntry("outboxStreamKey", event.outboxStreamKey()) + .containsEntry("lastAppliedSourceEventId", event.eventId()) + .containsEntry("lastAppliedSourceEventDigest", event.eventDigest()) .containsEntry("appliedSourceEvidence", Map.of("7", event.canonicalJson())); - assertThat(mutation.nextProjection()).doesNotContainKey("admitted"); + assertThat(mutation.nextProjection()) + .doesNotContainKey("admitted") + .doesNotContainKeys( + "issuerAuthGeneration", "sourceOutboxStreamKey", "sourceEventId", "sourceEventDigest"); + assertThat(mutation.nextProjection().keySet()) + .containsExactlyInAnyOrder( + "schemaVersion", + "issuerId", + "lastAppliedIssuerGeneration", + "lastAppliedSourceOutboxSequence", + "outboxStreamKey", + "lastAppliedSourceEventId", + "lastAppliedSourceEventDigest", + "appliedAt", + "appliedSourceEvidence"); } @Test @@ -123,10 +160,11 @@ void selectedContiguousEventAdvancesWatermarkAndCheckpointEvenWhenGenerationIsEq .isEqualTo(IssuerAuthorityProjectionTransitions.MutationKind.ADVANCE); assertThat(mutation.expectedProjection()).contains(existing); assertThat(mutation.nextProjection()) - .containsEntry("issuerAuthGeneration", "80") + .containsEntry("lastAppliedIssuerGeneration", "80") .containsEntry("lastAppliedSourceOutboxSequence", "5") - .containsEntry("sourceEventId", next.eventId()) - .containsEntry("sourceEventDigest", next.eventDigest()) + .containsEntry("outboxStreamKey", next.outboxStreamKey()) + .containsEntry("lastAppliedSourceEventId", next.eventId()) + .containsEntry("lastAppliedSourceEventDigest", next.eventDigest()) .containsEntry("appliedSourceEvidence", Map.of("5", next.canonicalJson())); } @@ -142,7 +180,7 @@ void selectedContiguousEventUsesHigherGenerationWhenAccountAdvancedIt() throws E IssuerAuthorityProjectionTransitions.decide(existing, readback, "stable-applied-at"); assertThat(mutation.nextProjection()) - .containsEntry("issuerAuthGeneration", "81") + .containsEntry("lastAppliedIssuerGeneration", "81") .containsEntry("lastAppliedSourceOutboxSequence", "5"); } @@ -167,7 +205,7 @@ void malformedExistingProjectionQuarantinesBeforeConsideringAccountEvent() throw 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"); + malformedProjection.put("lastAppliedIssuerGeneration", "02"); IssuerGenerationAuthorityEvent next = event("2", "2", "3", 23, ISSUER_ID); SourceReadback readback = readback(ISSUER_ID, "2", "3", "2", next, next); @@ -182,6 +220,27 @@ void malformedExistingProjectionQuarantinesBeforeConsideringAccountEvent() throw assertThat(decision.expectedProjection()).contains(malformedProjection); } + @Test + void obsoleteStoredAliasesQuarantineBeforeConsideringAccountEvent() throws Exception { + IssuerGenerationAuthorityEvent first = event("1", "2", "2", 22, ISSUER_ID); + Map validProjection = bootstrapProjection("2", "2", "1", first); + Map obsoleteProjection = new LinkedHashMap<>(validProjection); + obsoleteProjection.remove("lastAppliedIssuerGeneration"); + obsoleteProjection.put("issuerAuthGeneration", "2"); + 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( + obsoleteProjection, readback, "stable-applied-at"); + + assertThat(decision.reason()) + .isEqualTo( + IssuerAuthorityProjectionTransitions.QuarantineReason.MALFORMED_EXISTING_PROJECTION); + assertThat(decision.expectedProjection()).contains(obsoleteProjection); + } + @Test void exactDuplicateIsNoOpAndDoesNotReplaceAppliedAt() throws Exception { IssuerGenerationAuthorityEvent applied = event("2", "3", "4", 8, ISSUER_ID); @@ -285,10 +344,221 @@ void countersBeyondLongRemainExactAndNoSequenceGenerationEquationIsAssumed() thr assertThat(mutation.nextProjection()) .containsEntry("lastAppliedSourceOutboxSequence", sequence.toString()) - .containsEntry("issuerAuthGeneration", generation) - .containsEntry("sourceEventId", next.eventId()); + .containsEntry("lastAppliedIssuerGeneration", generation) + .containsEntry("lastAppliedSourceEventId", next.eventId()); + } + + @Test + void captureReconciliationBootstrapsZeroAndPositiveSnapshots() throws Exception { + CaptureEvidence zero = captureEvidence(ISSUER_ID, "1", "1", "0", null); + IssuerAuthorityProjectionTransitions.Mutation zeroMutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.reconcile( + null, zero.capture(), zero.current(), "zero-applied-at"); + assertThat(zeroMutation.kind()) + .isEqualTo(IssuerAuthorityProjectionTransitions.MutationKind.CAPTURE_RECONCILIATION); + assertThat(zeroMutation.nextProjection()) + .containsEntry("lastAppliedSourceOutboxSequence", "0") + .containsEntry("appliedAt", "zero-applied-at") + .containsEntry("appliedSourceEvidence", Map.of()) + .doesNotContainKeys("lastAppliedSourceEventId", "lastAppliedSourceEventDigest"); + + IssuerGenerationAuthorityEvent event = event("5", "11", "19", 64, ISSUER_ID); + CaptureEvidence positive = captureEvidence(ISSUER_ID, "11", "19", "5", event); + IssuerAuthorityProjectionTransitions.Mutation positiveMutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.reconcile( + null, positive.capture(), positive.current(), "positive-applied-at"); + assertThat(positiveMutation.nextProjection()) + .containsEntry("lastAppliedSourceOutboxSequence", "5") + .containsEntry("lastAppliedSourceEventId", event.eventId()) + .containsEntry("lastAppliedSourceEventDigest", event.eventDigest()) + .containsEntry("appliedSourceEvidence", Map.of("5", event.canonicalJson())); } + @Test + void captureReconciliationMayJumpAValidBehindProjectionAcrossMissedEvents() throws Exception { + IssuerGenerationAuthorityEvent existingEvent = event("1", "2", "3", 65, ISSUER_ID); + Map existing = bootstrapProjection("2", "3", "1", existingEvent); + IssuerGenerationAuthorityEvent capturedEvent = event("5", "8", "12", 66, ISSUER_ID); + CaptureEvidence evidence = captureEvidence(ISSUER_ID, "8", "12", "5", capturedEvent); + + IssuerAuthorityProjectionTransitions.Mutation mutation = + (IssuerAuthorityProjectionTransitions.Mutation) + IssuerAuthorityProjectionTransitions.reconcile( + existing, evidence.capture(), evidence.current(), "reconciled-at"); + + assertThat(mutation.kind()) + .isEqualTo(IssuerAuthorityProjectionTransitions.MutationKind.CAPTURE_RECONCILIATION); + assertThat(mutation.expectedProjection()).contains(existing); + assertThat(mutation.nextProjection()) + .containsEntry("lastAppliedSourceOutboxSequence", "5") + .containsEntry("lastAppliedIssuerGeneration", "8") + .containsEntry("appliedAt", "reconciled-at") + .containsEntry("appliedSourceEvidence", Map.of("5", capturedEvent.canonicalJson())); + } + + @Test + void captureReconciliationExactCheckpointIsNoOpAndPreservesStoredAppliedAt() throws Exception { + IssuerGenerationAuthorityEvent currentEvent = event("3", "6", "9", 67, ISSUER_ID); + Map existing = bootstrapProjection("6", "9", "3", currentEvent); + CaptureEvidence evidence = captureEvidence(ISSUER_ID, "6", "9", "3", currentEvent); + + IssuerAuthorityProjectionTransitions.NoOp noOp = + (IssuerAuthorityProjectionTransitions.NoOp) + IssuerAuthorityProjectionTransitions.reconcile( + existing, evidence.capture(), evidence.current(), "new-retry-time"); + + assertThat(noOp.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.NoOpReason.CAPTURE_ALREADY_INSTALLED); + assertThat(existing).containsEntry("appliedAt", "stable-time"); + } + + @Test + void captureReconciliationDeniesAheadAndOrdinaryEventGapsRemainDenied() throws Exception { + IssuerGenerationAuthorityEvent currentEvent = event("3", "6", "9", 68, ISSUER_ID); + Map existing = + bootstrapProjection("7", "12", "4", event("4", "7", "12", 69, ISSUER_ID)); + CaptureEvidence evidence = captureEvidence(ISSUER_ID, "6", "9", "3", currentEvent); + + IssuerAuthorityProjectionTransitions.Quarantine ahead = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.reconcile( + existing, evidence.capture(), evidence.current(), "ignored"); + assertThat(ahead.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.CAPTURE_PROJECTION_AHEAD); + + IssuerGenerationAuthorityEvent prior = event("1", "2", "3", 70, ISSUER_ID); + Map behind = bootstrapProjection("2", "3", "1", prior); + IssuerGenerationAuthorityEvent gap = event("3", "4", "5", 71, ISSUER_ID); + SourceReadback selectedGap = readback(ISSUER_ID, "4", "5", "3", gap, gap); + IssuerAuthorityProjectionTransitions.Quarantine ordinaryGap = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.decide(behind, selectedGap, "ignored"); + assertThat(ordinaryGap.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.EVENT_SEQUENCE_GAP); + } + + @Test + void captureReconciliationRejectsASeparatelyVerifiedReadbackFromAnotherNamespace() + throws Exception { + CaptureEvidence captureEvidence = captureEvidence(ISSUER_ID, "1", "1", "0", null); + SourceReadback otherNamespace = currentReadback("other", ISSUER_ID, "1", "1", "0", null); + + IssuerAuthorityProjectionTransitions.Quarantine decision = + (IssuerAuthorityProjectionTransitions.Quarantine) + IssuerAuthorityProjectionTransitions.reconcile( + null, captureEvidence.capture(), otherNamespace, "stable-time"); + + assertThat(decision.reason()) + .isEqualTo(IssuerAuthorityProjectionTransitions.QuarantineReason.CAPTURE_BINDING_MISMATCH); + } + + private static CaptureEvidence captureEvidence( + String issuerId, + String generation, + String sourceVersion, + String sequence, + IssuerGenerationAuthorityEvent event) + throws Exception { + return captureEvidence(NAMESPACE, issuerId, generation, sourceVersion, sequence, event); + } + + private static CaptureEvidence captureEvidence( + String namespace, + String issuerId, + String generation, + String sourceVersion, + String sequence, + IssuerGenerationAuthorityEvent event) + throws Exception { + String scope = "issuer/" + issuerId; + IssuerAuthoritySourceSnapshot.Builder source = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(issuerId) + .setSourceScope(scope) + .setOutboxStreamKey(IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope) + .setIssuerAuthGeneration(generation) + .setSourceVersion(sourceVersion) + .setOutboxSequence(sequence); + if (event != null) { + source.setLatestEventCanonicalJson(event.canonicalJson()); + } + IssuerAuthoritySourceSnapshot snapshot = source.build(); + String caller = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + String projectionKey = IssuerAuthorityProjectionTransitions.KEY_PREFIX + issuerId; + java.util.UUID requestId = java.util.UUID.fromString(QUERY_ID); + java.util.UUID operationId = java.util.UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = + mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.captureIssuerProjectionForRuntime(any())) + .thenReturn( + CaptureIssuerProjectionForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-projection-capture/v1") + .setTargetNamespace(namespace) + .setOperationId(operationId.toString()) + .setRequestId(requestId.toString()) + .setIssuerId(issuerId) + .setCallerWorkloadIdentity(caller) + .setProjectionKey(projectionKey) + .setRequestDigestVersion(1) + .setRequestDigest( + IssuerProjectionReconciliationRequestDigestV1.digest( + issuerId, caller, projectionKey, requestId)) + .setCapturedSourceSnapshot(snapshot) + .build()); + when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) + .thenReturn( + ReadIssuerAuthorityForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-source-readback/v1") + .setTargetNamespace(namespace) + .setRequestId(QUERY_ID) + .setSourceSnapshot(snapshot) + .build()); + AccountIssuerAuthorityClient client = newClient(stub, issuerId, namespace); + ProjectionCaptureReceipt capture = client.captureProjection(QUERY_ID); + SourceReadback current = client.readCurrent(QUERY_ID); + return new CaptureEvidence(capture, current); + } + + private static SourceReadback currentReadback( + String namespace, + String issuerId, + String generation, + String sourceVersion, + String sequence, + IssuerGenerationAuthorityEvent event) + throws Exception { + String scope = "issuer/" + issuerId; + IssuerAuthoritySourceSnapshot.Builder snapshot = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(issuerId) + .setSourceScope(scope) + .setOutboxStreamKey(IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope) + .setIssuerAuthGeneration(generation) + .setSourceVersion(sourceVersion) + .setOutboxSequence(sequence); + if (event != null) { + snapshot.setLatestEventCanonicalJson(event.canonicalJson()); + } + ReadIssuerAuthorityForRuntimeResponse response = + ReadIssuerAuthorityForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-source-readback/v1") + .setTargetNamespace(namespace) + .setRequestId(QUERY_ID) + .setSourceSnapshot(snapshot.build()) + .build(); + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = + mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) + .thenReturn(response); + return newClient(stub, issuerId, namespace).readCurrent(QUERY_ID); + } + + private record CaptureEvidence(ProjectionCaptureReceipt capture, SourceReadback current) {} + private static Map bootstrapProjection( String generation, String sourceVersion, @@ -375,13 +645,21 @@ private static IssuerGenerationAuthorityEvent event( private static AccountIssuerAuthorityClient newClient( IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub, String issuerId) throws Exception { + return newClient(stub, issuerId, NAMESPACE); + } + + private static AccountIssuerAuthorityClient newClient( + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub, + String issuerId, + String namespace) + throws Exception { AccountIssuerAuthorityClient client = new AccountIssuerAuthorityClient( new ServiceEndpointsProperties(), mtlsProperties(), mock(GrpcChannelFactory.class), BlockingGrpcStubCustomizer.noop(), - NAMESPACE, + namespace, issuerId); Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); stubField.setAccessible(true); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerProjectionReconciliationInstallerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerProjectionReconciliationInstallerTest.java new file mode 100644 index 0000000000..67e310ac8f --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/IssuerProjectionReconciliationInstallerTest.java @@ -0,0 +1,669 @@ +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.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.CaptureIssuerProjectionForRuntimeResponse; +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.account.authority.IssuerProjectionReconciliationRequestDigestV1; +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.service.IssuerAuthorityProjectionRedisContract; +import net.firedevops.firemud.gamesession.service.IssuerAuthorityProjectionTransitions; +import net.firedevops.firemud.gamesession.service.IssuerProjectionReconciliationInstaller; +import net.firedevops.firemud.gamesession.service.IssuerProjectionReconciliationInstaller.InstallationReceipt; +import net.firedevops.firemud.gamesession.service.IssuerProjectionReconciliationInstaller.Outcome; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.ApplyResult; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.CacheRateLimitEndpoint; +import net.firedevops.firemud.gamesession.service.RedisIssuerAuthorityProjectionStore.CoordinationEndpoint; +import org.junit.jupiter.api.Test; +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.StringRedisTemplate; + +class IssuerProjectionReconciliationInstallerTest { + private static final String NAMESPACE = "test"; + private static final String ISSUER_ID = "https://accounts.example.test/issuer"; + private static final String REQUEST_ID = "11111111-1111-4111-8111-111111111111"; + private static final String OPERATION_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + private static final String COORD_PASSWORD = "coordination-secret"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void installsZeroAndPositiveCaptureSnapshotsThroughVerifiedAccountClient() throws Exception { + Fixture zero = fixture(snapshot("1", "1", "0", null)); + try { + var zeroResult = zero.installer().install(REQUEST_ID, "zero-applied-at"); + + assertThat(zeroResult.outcome()).isEqualTo(Outcome.INSTALLED); + InstallationReceipt zeroReceipt = zeroResult.receipt().orElseThrow(); + assertThat(zeroReceipt.operationId()).hasToString(OPERATION_ID); + assertThat(zeroReceipt.requestId()).hasToString(REQUEST_ID); + assertThat(zeroReceipt.capturedSource().outboxSequence()).isEqualTo("0"); + assertThat(zeroReceipt.projectionSnapshot().json()) + .contains("\"lastAppliedSourceOutboxSequence\":\"0\"") + .contains("\"appliedAt\":\"zero-applied-at\"") + .doesNotContain("lastAppliedSourceEventId"); + assertThat(zero.redis().scriptCount()).hasValue(1); + assertThat(zero.redis().getCount()).hasValue(2); + assertAccountCalls(zero.stub(), 1, 2); + assertThat(InstallationReceipt.class.getConstructors()).isEmpty(); + } finally { + zero.store().close(); + } + + IssuerGenerationAuthorityEvent event = event("7", "20", "35", 22); + Fixture positive = fixture(snapshot("20", "35", "7", event.canonicalJson())); + try { + var result = positive.installer().install(REQUEST_ID, "positive-applied-at"); + + assertThat(result.outcome()).isEqualTo(Outcome.INSTALLED); + assertThat( + result + .receipt() + .orElseThrow() + .capturedSource() + .latestEvent() + .orElseThrow() + .canonicalJson()) + .isEqualTo(event.canonicalJson()); + assertThat(result.receipt().orElseThrow().projectionSnapshot().json()) + .contains("\"lastAppliedSourceOutboxSequence\":\"7\"") + .contains("\"lastAppliedSourceEventId\":\"" + event.eventId() + "\"") + .contains(JSON.writeValueAsString(event.canonicalJson())); + assertThat(positive.redis().scriptCount()).hasValue(1); + assertThat(positive.redis().getCount()).hasValue(2); + } finally { + positive.store().close(); + } + } + + @Test + void exactRetryPreservesRedisBytesAndOriginalAppliedAt() throws Exception { + Fixture fixture = fixture(snapshot("1", "1", "0", null)); + try { + var first = fixture.installer().install(REQUEST_ID, "original-applied-at"); + byte[] originalBytes = fixture.redis().storedValue().get().clone(); + + var retry = fixture.installer().install(REQUEST_ID, "different-retry-time"); + + assertThat(first.outcome()).isEqualTo(Outcome.INSTALLED); + assertThat(retry.outcome()).isEqualTo(Outcome.REPLAYED); + assertThat(retry.receipt().orElseThrow().operationId()) + .isEqualTo(first.receipt().orElseThrow().operationId()); + assertThat(retry.receipt().orElseThrow().requestId()) + .isEqualTo(first.receipt().orElseThrow().requestId()); + assertThat(retry.receipt().orElseThrow().projectionSnapshot().json()) + .contains("\"appliedAt\":\"original-applied-at\""); + assertThat(fixture.redis().storedValue().get()).containsExactly(originalBytes); + assertThat(fixture.redis().scriptCount()).hasValue(2); + assertThat(fixture.redis().getCount()).hasValue(4); + } finally { + fixture.store().close(); + } + } + + @Test + void sourceAdvanceBeforeCasPreventsAnyRedisReadOrWrite() throws Exception { + IssuerGenerationAuthorityEvent advanced = event("1", "2", "2", 23); + Fixture fixture = + fixture( + snapshot("1", "1", "0", null), + List.of(snapshot("2", "2", "1", advanced.canonicalJson()))); + try { + var result = fixture.installer().install(REQUEST_ID, "stable-time"); + + assertThat(result.outcome()).isEqualTo(Outcome.STALE_SOURCE); + assertThat(result.receipt()).isEmpty(); + assertThat(fixture.redis().scriptCount()).hasValue(0); + assertThat(fixture.redis().getCount()).hasValue(0); + assertAccountCalls(fixture.stub(), 1, 1); + } finally { + fixture.store().close(); + } + } + + @Test + void sourceAdvanceAfterCasWithholdsReceiptAndDoesNotCompensate() throws Exception { + IssuerGenerationAuthorityEvent advanced = event("1", "2", "2", 24); + Fixture fixture = + fixture( + snapshot("1", "1", "0", null), + List.of( + snapshot("1", "1", "0", null), snapshot("2", "2", "1", advanced.canonicalJson()))); + try { + var result = fixture.installer().install(REQUEST_ID, "stable-time"); + + assertThat(result.outcome()).isEqualTo(Outcome.STALE_SOURCE); + assertThat(result.receipt()).isEmpty(); + assertThat(fixture.redis().scriptCount()).hasValue(1); + assertThat(fixture.redis().getCount()).hasValue(2); + assertThat(fixture.redis().storedValue()).isNotNull(); + assertAccountCalls(fixture.stub(), 1, 2); + } finally { + fixture.store().close(); + } + } + + @Test + void lostCasResponseRetryUsesSameCaptureIdentityAndStoredBytes() throws Exception { + Fixture fixture = fixture(snapshot("1", "1", "0", null)); + fixture.redis().loseNextAppliedResponse().set(true); + try { + assertThatThrownBy(() -> fixture.installer().install(REQUEST_ID, "first-attempt")) + .isInstanceOf(DataAccessResourceFailureException.class); + byte[] committedBytes = fixture.redis().storedValue().get().clone(); + + var retry = fixture.installer().install(REQUEST_ID, "retry-at"); + + assertThat(retry.outcome()).isEqualTo(Outcome.REPLAYED); + assertThat(retry.receipt().orElseThrow().operationId()).hasToString(OPERATION_ID); + assertThat(retry.receipt().orElseThrow().requestId()).hasToString(REQUEST_ID); + assertThat(fixture.redis().storedValue().get()).containsExactly(committedBytes); + assertThat(retry.receipt().orElseThrow().projectionSnapshot().json()) + .contains("\"appliedAt\":\"first-attempt\""); + assertThat(fixture.redis().scriptCount()).hasValue(2); + assertAccountCalls(fixture.stub(), 2, 3); + } finally { + fixture.store().close(); + } + } + + @Test + void rejectsCaptureBindingBeforeAnyRedisInvocation() throws Exception { + Fixture fixture = fixture(snapshot("1", "1", "0", null), List.of(), "wrong-caller"); + try { + assertThatThrownBy(() -> fixture.installer().install(REQUEST_ID, "stable-time")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("capture"); + assertThat(fixture.redis().scriptCount()).hasValue(0); + assertThat(fixture.redis().getCount()).hasValue(0); + } finally { + fixture.store().close(); + } + } + + @Test + void quarantinesPoisonTtlAheadStateAndCasStaleWithoutReceipt() throws Exception { + Fixture poison = + fixture( + snapshot("1", "1", "0", null), + List.of(), + "valid", + "{}".getBytes(StandardCharsets.UTF_8), + -1L); + assertDirectStoreQuarantine(poison, "MALFORMED_EXISTING_PROJECTION", 0, 1); + + byte[] ttlProjection = JSON.writeValueAsBytes(projection("2", "2", "1", "prior-applied-at")); + Fixture ttl = fixture(snapshot("1", "1", "0", null), List.of(), "valid", ttlProjection, 0L); + assertDirectStoreQuarantine(ttl, "TTL_PRESENT", 0, 1); + + Map aheadProjection = projection("2", "2", "1", "prior-applied-at"); + byte[] aheadBytes = JSON.writeValueAsBytes(aheadProjection); + Fixture ahead = fixture(snapshot("1", "1", "0", null), List.of(), "valid", aheadBytes, -1L); + assertDirectStoreQuarantine(ahead, "CAPTURE_PROJECTION_AHEAD", 0, 1); + + Fixture staleCas = fixture(snapshot("1", "1", "0", null)); + staleCas.redis().forceStaleNextScript().set(true); + try { + ApplyResult result = + staleCas + .store() + .installCapture( + staleCas.client().captureProjection(REQUEST_ID), + staleCas.client().readCurrent(REQUEST_ID), + "stable-time"); + assertThat(result.outcome()).isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.STALE); + assertThat(result.snapshot()).isEmpty(); + assertThat(staleCas.redis().scriptCount()).hasValue(1); + assertThat(staleCas.redis().getCount()).hasValue(1); + } finally { + staleCas.store().close(); + } + } + + @Test + void storeRechecksCurrentSourceAndRejectsRegressedOrConflictingProjection() throws Exception { + IssuerGenerationAuthorityEvent advanced = event("1", "2", "2", 27); + Fixture changedSource = + fixture( + snapshot("1", "1", "0", null), + List.of(snapshot("2", "2", "1", advanced.canonicalJson()))); + try { + ApplyResult result = + changedSource + .store() + .installCapture( + changedSource.client().captureProjection(REQUEST_ID), + changedSource.client().readCurrent(REQUEST_ID), + "stable-time"); + assertThat(result.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains("CAPTURE_CURRENT_SOURCE_MISMATCH"); + assertThat(changedSource.redis().scriptCount()).hasValue(0); + assertThat(changedSource.redis().getCount()).hasValue(1); + } finally { + changedSource.store().close(); + } + + IssuerGenerationAuthorityEvent capturedEvent = event("3", "6", "9", 28); + byte[] conflictingBytes = + JSON.writeValueAsBytes(projection("6", "9", "3", "original-applied-at")); + Fixture conflicting = + fixture( + snapshot("6", "9", "3", capturedEvent.canonicalJson()), + List.of(), + "valid", + conflictingBytes, + -1L); + assertDirectStoreQuarantine(conflicting, "CAPTURE_SAME_CHECKPOINT_DISAGREEMENT", 0, 1); + + byte[] regressedBytes = + JSON.writeValueAsBytes(projection("8", "8", "2", "original-applied-at")); + Fixture regressed = + fixture( + snapshot("6", "9", "3", capturedEvent.canonicalJson()), + List.of(), + "valid", + regressedBytes, + -1L); + assertDirectStoreQuarantine(regressed, "CAPTURE_SOURCE_REGRESSED", 0, 1); + } + + @Test + void storeRequiresItsConfiguredCallerNamespaceBeforeRedisAccess() throws Exception { + Fixture fixture = fixture(snapshot("1", "1", "0", null)); + RedisIssuerAuthorityProjectionStore wrongNamespaceStore = storeWithNamespace("other"); + Field templateField = + RedisIssuerAuthorityProjectionStore.class.getDeclaredField("redisTemplate"); + templateField.setAccessible(true); + templateField.set(wrongNamespaceStore, fixture.redis().template()); + try { + ApplyResult result = + wrongNamespaceStore.installCapture( + fixture.client().captureProjection(REQUEST_ID), + fixture.client().readCurrent(REQUEST_ID), + "stable-time"); + assertThat(result.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains("ACCOUNT_NAMESPACE_MISMATCH"); + assertThat(fixture.redis().getCount()).hasValue(0); + assertThat(fixture.redis().scriptCount()).hasValue(0); + } finally { + wrongNamespaceStore.close(); + fixture.store().close(); + } + } + + @Test + void constructorRequiresBothDependencies() throws Exception { + Fixture fixture = fixture(snapshot("1", "1", "0", null)); + try { + AccountIssuerAuthorityClient client = newClient(fixture.stub()); + assertThatThrownBy(() -> new IssuerProjectionReconciliationInstaller(null, fixture.store())) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Account issuer client"); + assertThatThrownBy(() -> new IssuerProjectionReconciliationInstaller(client, null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("projection store"); + } finally { + fixture.store().close(); + } + } + + private static void assertDirectStoreQuarantine( + Fixture fixture, String detail, int scripts, int reads) { + try { + var result = + fixture + .store() + .installCapture( + fixture.client().captureProjection(REQUEST_ID), + fixture.client().readCurrent(REQUEST_ID), + "stable-time"); + assertThat(result.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED); + assertThat(result.detail()).contains(detail); + assertThat(fixture.redis().scriptCount()).hasValue(scripts); + assertThat(fixture.redis().getCount()).hasValue(reads); + } finally { + fixture.store().close(); + } + } + + private static Fixture fixture(IssuerAuthoritySourceSnapshot captured) throws Exception { + return fixture(captured, List.of(captured, captured)); + } + + private static Fixture fixture( + IssuerAuthoritySourceSnapshot captured, List readbacks) + throws Exception { + return fixture(captured, readbacks, "valid", null, -1L, captured); + } + + private static Fixture fixture( + IssuerAuthoritySourceSnapshot captured, + List readbacks, + String captureBinding) + throws Exception { + return fixture(captured, readbacks, captureBinding, null, -1L, captured); + } + + private static Fixture fixture( + IssuerAuthoritySourceSnapshot captured, + List readbacks, + String captureBinding, + byte[] initialRedis, + long ttlMillis) + throws Exception { + return fixture(captured, readbacks, captureBinding, initialRedis, ttlMillis, captured); + } + + private static Fixture fixture( + IssuerAuthoritySourceSnapshot captured, + List readbacks, + String captureBinding, + byte[] initialRedis, + long ttlMillis, + IssuerAuthoritySourceSnapshot before) + throws Exception { + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = + mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + String caller = "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + String projectedKey = IssuerAuthorityProjectionTransitions.KEY_PREFIX + ISSUER_ID; + String responseCaller = "wrong-caller".equals(captureBinding) ? "spiffe://wrong" : caller; + when(stub.captureIssuerProjectionForRuntime(any())) + .thenReturn( + CaptureIssuerProjectionForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-projection-capture/v1") + .setTargetNamespace(NAMESPACE) + .setOperationId(OPERATION_ID) + .setRequestId(REQUEST_ID) + .setIssuerId(ISSUER_ID) + .setCallerWorkloadIdentity(responseCaller) + .setProjectionKey(projectedKey) + .setRequestDigestVersion(1) + .setRequestDigest( + IssuerProjectionReconciliationRequestDigestV1.digest( + ISSUER_ID, caller, projectedKey, java.util.UUID.fromString(REQUEST_ID))) + .setCapturedSourceSnapshot(captured) + .build()); + + List replies = new ArrayList<>(readbacks); + if (replies.isEmpty()) { + replies.add(before); + } + AtomicInteger responseIndex = new AtomicInteger(); + when(stub.readIssuerAuthorityForRuntime(any(ReadIssuerAuthorityForRuntimeRequest.class))) + .thenAnswer( + invocation -> { + int index = responseIndex.getAndIncrement(); + IssuerAuthoritySourceSnapshot reply = + replies.get(Math.min(index, replies.size() - 1)); + return readResponse(reply); + }); + + AccountIssuerAuthorityClient client = newClient(stub); + RedisFixture redis = redisFixture(initialRedis, ttlMillis); + RedisIssuerAuthorityProjectionStore store = storeWithConnection(); + Field templateField = + RedisIssuerAuthorityProjectionStore.class.getDeclaredField("redisTemplate"); + templateField.setAccessible(true); + templateField.set(store, redis.template()); + return new Fixture( + stub, client, store, redis, new IssuerProjectionReconciliationInstaller(client, store)); + } + + private static AccountIssuerAuthorityClient newClient( + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub) throws Exception { + 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(), + NAMESPACE, + ISSUER_ID); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static ReadIssuerAuthorityForRuntimeResponse readResponse( + IssuerAuthoritySourceSnapshot source) { + return ReadIssuerAuthorityForRuntimeResponse.newBuilder() + .setSchemaVersion("account-auth-issuer-source-readback/v1") + .setTargetNamespace(NAMESPACE) + .setRequestId(REQUEST_ID) + .setSourceSnapshot(source) + .build(); + } + + private static IssuerAuthoritySourceSnapshot snapshot( + String generation, String sourceVersion, String sequence, String latestEvent) { + String scope = "issuer/" + ISSUER_ID; + IssuerAuthoritySourceSnapshot.Builder result = + IssuerAuthoritySourceSnapshot.newBuilder() + .setIssuerId(ISSUER_ID) + .setSourceScope(scope) + .setOutboxStreamKey(IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope) + .setIssuerAuthGeneration(generation) + .setSourceVersion(sourceVersion) + .setOutboxSequence(sequence); + if (latestEvent != null) { + result.setLatestEventCanonicalJson(latestEvent); + } + return result.build(); + } + + private static IssuerGenerationAuthorityEvent event( + String sequence, String generation, String sourceVersion, int requestNumber) { + String requestId = + String.format(java.util.Locale.ROOT, "00000000-0000-4000-8000-%012d", requestNumber); + String scope = "issuer/" + ISSUER_ID; + return IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", "account-issuer-authority-event-v1:" + requestId, + "requestId", requestId, + "issuerId", ISSUER_ID, + "sourceScope", scope, + "outboxStreamKey", IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + scope, + "outboxSequence", sequence, + "issuerAuthGeneration", generation, + "sourceVersion", sourceVersion)); + } + + private static Map projection( + String generation, String sourceVersion, String sequence, String appliedAt) { + IssuerGenerationAuthorityEvent prior = event(sequence, generation, sourceVersion, 26); + return Map.of( + "schemaVersion", + IssuerAuthorityProjectionTransitions.SCHEMA_VERSION, + "issuerId", + ISSUER_ID, + "lastAppliedIssuerGeneration", + generation, + "lastAppliedSourceOutboxSequence", + sequence, + "outboxStreamKey", + prior.outboxStreamKey(), + "lastAppliedSourceEventId", + prior.eventId(), + "lastAppliedSourceEventDigest", + prior.eventDigest(), + "appliedAt", + appliedAt, + "appliedSourceEvidence", + Map.of(sequence, prior.canonicalJson())); + } + + private static void assertAccountCalls( + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub, + int captureCalls, + int readCalls) { + verify(stub, times(captureCalls)).captureIssuerProjectionForRuntime(any()); + verify(stub, times(readCalls)).readIssuerAuthorityForRuntime(any()); + } + + private static RedisFixture redisFixture(byte[] initial, long ttlMillis) throws Exception { + byte[] script = scriptBytes(); + String sha1 = sha1(script); + 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); + AtomicReference storedValue = + new AtomicReference<>(initial == null ? null : initial.clone()); + AtomicInteger getCount = new AtomicInteger(); + AtomicInteger scriptCount = new AtomicInteger(); + AtomicBoolean loseNextAppliedResponse = new AtomicBoolean(); + AtomicBoolean forceStaleNextScript = new AtomicBoolean(); + when(stringCommands.get(any(byte[].class))) + .thenAnswer( + ignored -> { + getCount.incrementAndGet(); + byte[] value = storedValue.get(); + return value == null ? null : value.clone(); + }); + when(keyCommands.pTtl(any(byte[].class))).thenReturn(ttlMillis); + when(scriptingCommands.scriptLoad(any(byte[].class))).thenReturn(sha1); + when(scriptingCommands.evalSha(eq(sha1), eq(ReturnType.VALUE), eq(1), any(byte[][].class))) + .thenAnswer( + invocation -> { + scriptCount.incrementAndGet(); + byte[][] args = (byte[][]) invocation.getRawArguments()[3]; + assertThat(args.length) + .as("registered issuer CAS receives one key and three script arguments") + .isEqualTo(4); + assertThat(new String(args[0], StandardCharsets.UTF_8)) + .as("registered issuer CAS targets the capture's exact Redis key") + .isEqualTo(IssuerAuthorityProjectionRedisContract.keyForIssuer(ISSUER_ID)); + String mode = new String(args[1], StandardCharsets.US_ASCII); + byte[] expected = args[2]; + byte[] candidate = args[3]; + byte[] current = storedValue.get(); + String result; + if (forceStaleNextScript.getAndSet(false)) { + result = "STALE"; + } else if (mode.equals("VERIFY")) { + result = java.util.Arrays.equals(current, expected) ? "REPLAY" : "STALE"; + } else if (current != null && java.util.Arrays.equals(current, candidate)) { + result = "REPLAY"; + } else if ((mode.equals("ABSENT") && current == null) + || (mode.equals("PRESENT") && java.util.Arrays.equals(current, expected))) { + storedValue.set(candidate.clone()); + result = "APPLIED"; + } else { + result = "STALE"; + } + if ("APPLIED".equals(result) && loseNextAppliedResponse.getAndSet(false)) { + throw new DataAccessResourceFailureException("lost response after Redis commit"); + } + return result.getBytes(StandardCharsets.US_ASCII); + }); + + StringRedisTemplate template = mock(StringRedisTemplate.class); + doAnswer( + invocation -> { + RedisCallback callback = invocation.getArgument(0); + return callback.doInRedis(connection); + }) + .when(template) + .execute(any(RedisCallback.class)); + return new RedisFixture( + connection, + template, + storedValue, + getCount, + scriptCount, + loseNextAppliedResponse, + forceStaleNextScript); + } + + private static RedisIssuerAuthorityProjectionStore storeWithConnection() { + return storeWithNamespace(NAMESPACE); + } + + private static RedisIssuerAuthorityProjectionStore storeWithNamespace(String namespace) { + RedisIssuerAuthorityProjectionStore store = + new RedisIssuerAuthorityProjectionStore( + namespace, + new CoordinationEndpoint("127.0.0.1", 1, "gamesession_coord_app", COORD_PASSWORD), + new CacheRateLimitEndpoint("127.0.0.1", 2)); + store.init(); + return store; + } + + private static byte[] scriptBytes() throws Exception { + try (var input = + new ClassPathResource(IssuerAuthorityProjectionRedisContract.RESOURCE_PATH) + .getInputStream()) { + return input.readAllBytes(); + } + } + + private static String sha1(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(value)); + } + + private record Fixture( + IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub, + AccountIssuerAuthorityClient client, + RedisIssuerAuthorityProjectionStore store, + RedisFixture redis, + IssuerProjectionReconciliationInstaller installer) {} + + private record RedisFixture( + RedisConnection connection, + StringRedisTemplate template, + AtomicReference storedValue, + AtomicInteger getCount, + AtomicInteger scriptCount, + AtomicBoolean loseNextAppliedResponse, + AtomicBoolean forceStaleNextScript) {} +} 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 index 507d1769d1..a78ecab709 100644 --- 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 @@ -7,6 +7,8 @@ import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -15,7 +17,9 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; +import java.util.Map; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.IssuerAuthorityServiceGrpc; import net.firedevops.firemud.account.v1.IssuerAuthoritySourceSnapshot; @@ -108,7 +112,16 @@ void appliesWithTheExactRegisteredScriptLoadedThenExecutedByEvalSha() throws Exc when(connection.stringCommands()).thenReturn(stringCommands); when(connection.keyCommands()).thenReturn(keyCommands); when(connection.scriptingCommands()).thenReturn(scriptingCommands); - when(stringCommands.get(any(byte[].class))).thenReturn(null); + AtomicReference storedValue = new AtomicReference<>(); + AtomicInteger readCount = new AtomicInteger(); + when(stringCommands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + readCount.incrementAndGet(); + byte[] value = storedValue.get(); + return value == null ? null : value.clone(); + }); + when(keyCommands.pTtl(any(byte[].class))).thenReturn(-1L); AtomicReference loadedScript = new AtomicReference<>(); AtomicReference evalShaArguments = new AtomicReference<>(); when(scriptingCommands.scriptLoad(any(byte[].class))) @@ -123,6 +136,7 @@ void appliesWithTheExactRegisteredScriptLoadedThenExecutedByEvalSha() throws Exc .thenAnswer( invocation -> { evalShaArguments.set((byte[][]) invocation.getRawArguments()[3]); + storedValue.set(evalShaArguments.get()[3].clone()); return "APPLIED".getBytes(StandardCharsets.US_ASCII); }); @@ -132,6 +146,16 @@ void appliesWithTheExactRegisteredScriptLoadedThenExecutedByEvalSha() throws Exc assertThat(result.outcome()).isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.APPLIED); ProjectionSnapshot projection = result.snapshot().orElseThrow(); + assertThat(projection.json()) + .contains("\"lastAppliedIssuerGeneration\"") + .contains("\"outboxStreamKey\"") + .contains("\"lastAppliedSourceOutboxSequence\"") + .doesNotContain("\"lastAppliedSourceEventId\"") + .doesNotContain("\"lastAppliedSourceEventDigest\"") + .doesNotContain("\"issuerAuthGeneration\"") + .doesNotContain("\"sourceOutboxStreamKey\"") + .doesNotContain("\"sourceEventId\"") + .doesNotContain("\"sourceEventDigest\""); InOrder order = inOrder(scriptingCommands); order.verify(scriptingCommands).scriptLoad(any(byte[].class)); order @@ -145,12 +169,156 @@ void appliesWithTheExactRegisteredScriptLoadedThenExecutedByEvalSha() throws Exc assertThat(new String(invocationArguments[2], StandardCharsets.UTF_8)).isEmpty(); assertThat(new String(invocationArguments[3], StandardCharsets.UTF_8)) .isEqualTo(projection.json()); + assertThat(readCount).hasValue(2); verifyNoMoreInteractions(scriptingCommands); } finally { store.close(); } } + @Test + void appliedScriptWithoutStoredValueReturnsNoPositiveSnapshot() throws Exception { + StoreFixture fixture = storeFixture(PostReadbackMode.MISSING, "APPLIED"); + try { + var result = fixture.store().apply(sourceReadback("test"), "stable-time"); + + assertThat(result.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED); + assertThat(result.snapshot()).isEmpty(); + assertThat(result.detail()).contains("POST_SCRIPT_READBACK_MISSING"); + fixture.assertOneScriptCall(); + assertThat(fixture.getCount()).hasValue(2); + } finally { + fixture.store().close(); + } + } + + @Test + void appliedScriptWithChangedStoredBytesReturnsNoPositiveSnapshot() throws Exception { + StoreFixture fixture = storeFixture(PostReadbackMode.CHANGED, "APPLIED"); + try { + var result = fixture.store().apply(sourceReadback("test"), "stable-time"); + + assertThat(result.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED); + assertThat(result.snapshot()).isEmpty(); + assertThat(result.detail()).contains("POST_SCRIPT_READBACK_MISMATCH"); + fixture.assertOneScriptCall(); + } finally { + fixture.store().close(); + } + } + + @Test + void appliedScriptWithExpiringStoredValueReturnsNoPositiveSnapshot() throws Exception { + StoreFixture fixture = storeFixture(PostReadbackMode.TTL, "APPLIED"); + try { + var result = fixture.store().apply(sourceReadback("test"), "stable-time"); + + assertThat(result.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED); + assertThat(result.snapshot()).isEmpty(); + assertThat(result.detail()).contains("TTL_PRESENT"); + fixture.assertOneScriptCall(); + } finally { + fixture.store().close(); + } + } + + @Test + void postScriptReadbackFailurePropagatesWithoutRetryOrPositiveSnapshot() throws Exception { + StoreFixture fixture = storeFixture(PostReadbackMode.UNAVAILABLE, "APPLIED"); + try { + assertThatThrownBy(() -> fixture.store().apply(sourceReadback("test"), "stable-time")) + .isSameAs(fixture.readbackFailure()); + + fixture.assertOneScriptCall(); + } finally { + fixture.store().close(); + } + } + + @Test + void verifyReplayRequiresExactPostScriptReadback() throws Exception { + StoreFixture fixture = storeFixture(PostReadbackMode.EXACT, "APPLIED", "REPLAY"); + try { + var applied = fixture.store().apply(sourceReadbackWithEvent("test", false), "stable-time"); + var result = fixture.store().apply(sourceReadbackWithEvent("test", true), "stable-time"); + + assertThat(applied.outcome()).isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.APPLIED); + assertThat(result.outcome()).isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.NO_OP); + assertThat(result.snapshot()) + .isPresent() + .get() + .extracting(ProjectionSnapshot::json) + .isEqualTo(applied.snapshot().orElseThrow().json()); + fixture.assertScriptCalls(2); + assertThat(fixture.getCount()).hasValue(4); + } finally { + fixture.store().close(); + } + } + + @Test + void verifyReplayWithChangedPostScriptReadbackReturnsNoPositiveSnapshot() throws Exception { + StoreFixture fixture = storeFixture(PostReadbackMode.EXACT, "APPLIED", "REPLAY"); + try { + fixture.store().apply(sourceReadbackWithEvent("test", false), "stable-time"); + fixture.setPostReadbackMode(PostReadbackMode.CHANGED); + var result = fixture.store().apply(sourceReadbackWithEvent("test", true), "stable-time"); + + assertThat(result.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED); + assertThat(result.snapshot()).isEmpty(); + assertThat(result.detail()).contains("POST_SCRIPT_READBACK_MISMATCH"); + fixture.assertScriptCalls(2); + assertThat(fixture.getCount()).hasValue(4); + } finally { + fixture.store().close(); + } + } + + @Test + void verifyReplayWithMissingPostScriptReadbackReturnsNoPositiveSnapshot() throws Exception { + StoreFixture fixture = storeFixture(PostReadbackMode.EXACT, "APPLIED", "REPLAY"); + try { + fixture.store().apply(sourceReadbackWithEvent("test", false), "stable-time"); + fixture.setPostReadbackMode(PostReadbackMode.MISSING); + var result = fixture.store().apply(sourceReadbackWithEvent("test", true), "stable-time"); + + assertThat(result.outcome()) + .isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.QUARANTINED); + assertThat(result.snapshot()).isEmpty(); + assertThat(result.detail()).contains("POST_SCRIPT_READBACK_MISSING"); + fixture.assertScriptCalls(2); + assertThat(fixture.getCount()).hasValue(4); + } finally { + fixture.store().close(); + } + } + + @Test + void mutationReplayRequiresExactPostScriptReadback() throws Exception { + StoreFixture fixture = storeFixture(PostReadbackMode.EXACT, "APPLIED", "REPLAY"); + try { + fixture.store().apply(sourceReadbackWithEvent("test", false), "stable-time"); + var result = + fixture + .store() + .apply( + sourceReadbackWithEvent( + "test", true, "33333333-3333-4333-8333-333333333333", "2", "3", "3"), + "stable-time"); + + assertThat(result.outcome()).isEqualTo(RedisIssuerAuthorityProjectionStore.Outcome.REPLAYED); + assertThat(result.snapshot()).isPresent(); + fixture.assertScriptCalls(2); + assertThat(fixture.getCount()).hasValue(4); + } finally { + fixture.store().close(); + } + } + @Test void noscriptFromEvalShaPropagatesWithoutEvalFallback() throws Exception { byte[] resourceBytes = scriptBytes(); @@ -267,23 +435,77 @@ private static byte[] scriptBytes() throws Exception { } private static SourceReadback sourceReadback(String targetNamespace) throws Exception { + return sourceReadback(targetNamespace, null, false); + } + + private static SourceReadback sourceReadbackWithEvent(String targetNamespace, boolean selectEvent) + throws Exception { + return sourceReadbackWithEvent( + targetNamespace, selectEvent, "22222222-2222-4222-8222-222222222222", "1", "2", "2"); + } + + private static SourceReadback sourceReadbackWithEvent( + String targetNamespace, + boolean selectEvent, + String eventRequestId, + String sequence, + String generation, + String sourceVersion) + throws Exception { + var event = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.of( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION, + "eventType", + IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE, + "eventId", + "account-issuer-authority-event-v1:" + eventRequestId, + "requestId", + eventRequestId, + "issuerId", + ISSUER_ID, + "sourceScope", + "issuer/" + ISSUER_ID, + "outboxStreamKey", + IssuerGenerationAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER_ID, + "outboxSequence", + sequence, + "issuerAuthGeneration", + generation, + "sourceVersion", + sourceVersion)); + return sourceReadback(targetNamespace, event, selectEvent); + } + + private static SourceReadback sourceReadback( + String targetNamespace, + IssuerGenerationAuthorityEventV1Codec.IssuerGenerationAuthorityEvent event, + boolean selectEvent) + 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") + .setIssuerAuthGeneration(event == null ? "1" : event.issuerAuthGeneration()) + .setSourceVersion(event == null ? "1" : event.sourceVersion()) + .setOutboxSequence(event == null ? "0" : event.outboxSequence()) .build(); - ReadIssuerAuthorityForRuntimeResponse response = + if (event != null) { + snapshot = snapshot.toBuilder().setLatestEventCanonicalJson(event.canonicalJson()).build(); + } + ReadIssuerAuthorityForRuntimeResponse.Builder responseBuilder = ReadIssuerAuthorityForRuntimeResponse.newBuilder() .setSchemaVersion("account-auth-issuer-source-readback/v1") .setTargetNamespace(targetNamespace) .setRequestId(REQUEST_ID) - .setSourceSnapshot(snapshot) - .build(); + .setSourceSnapshot(snapshot); + if (selectEvent) { + responseBuilder.setRequestedEventCanonicalJson(event.canonicalJson()); + } + ReadIssuerAuthorityForRuntimeResponse response = responseBuilder.build(); IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub stub = mock(IssuerAuthorityServiceGrpc.IssuerAuthorityServiceBlockingStub.class); when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); @@ -304,6 +526,106 @@ private static SourceReadback sourceReadback(String targetNamespace) throws Exce Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); stubField.setAccessible(true); stubField.set(client, stub); - return client.readCurrent(REQUEST_ID); + return selectEvent + ? client.readCommittedEvent(REQUEST_ID, event.outboxSequence()) + : client.readCurrent(REQUEST_ID); + } + + private static StoreFixture storeFixture(PostReadbackMode mode, String... scriptResults) + 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); + + AtomicReference currentMode = new AtomicReference<>(mode); + AtomicReference storedValue = new AtomicReference<>(); + AtomicInteger getCount = new AtomicInteger(); + AtomicInteger scriptCount = new AtomicInteger(); + DataAccessResourceFailureException readbackFailure = + new DataAccessResourceFailureException("post-script GET unavailable"); + when(stringCommands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + int read = getCount.incrementAndGet(); + if (read % 2 == 0) { + switch (currentMode.get()) { + case MISSING -> { + return null; + } + case CHANGED -> { + return "changed-projection-bytes".getBytes(StandardCharsets.UTF_8); + } + case UNAVAILABLE -> throw readbackFailure; + case EXACT, TTL -> {} + } + } + byte[] value = storedValue.get(); + return value == null ? null : value.clone(); + }); + when(keyCommands.pTtl(any(byte[].class))) + .thenAnswer( + invocation -> + getCount.get() % 2 == 0 && currentMode.get() == PostReadbackMode.TTL ? 0L : -1L); + when(scriptingCommands.scriptLoad(any(byte[].class))).thenReturn(expectedSha1); + when(scriptingCommands.evalSha( + eq(expectedSha1), eq(ReturnType.VALUE), eq(1), any(byte[][].class))) + .thenAnswer( + invocation -> { + int index = scriptCount.getAndIncrement(); + String result = scriptResults[index]; + byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; + if ("APPLIED".equals(result) + || ("REPLAY".equals(result) + && !"VERIFY".equals(new String(arguments[1], StandardCharsets.US_ASCII)))) { + storedValue.set(arguments[3].clone()); + } + return result.getBytes(StandardCharsets.US_ASCII); + }); + + return new StoreFixture( + storeWithConnection(connection), + scriptingCommands, + getCount, + scriptCount, + currentMode, + readbackFailure, + expectedSha1); + } + + private enum PostReadbackMode { + EXACT, + MISSING, + CHANGED, + TTL, + UNAVAILABLE + } + + private record StoreFixture( + RedisIssuerAuthorityProjectionStore store, + RedisScriptingCommands scriptingCommands, + AtomicInteger getCount, + AtomicInteger scriptCount, + AtomicReference mode, + DataAccessResourceFailureException readbackFailure, + String scriptSha1) { + private void setPostReadbackMode(PostReadbackMode newMode) { + mode.set(newMode); + } + + private void assertOneScriptCall() { + assertScriptCalls(1); + } + + private void assertScriptCalls(int expectedCount) { + assertThat(scriptCount).hasValue(expectedCount); + verify(scriptingCommands, times(expectedCount)) + .evalSha(eq(scriptSha1), eq(ReturnType.VALUE), eq(1), any(byte[][].class)); + } } }