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 93c4d7acb6..e79b1b2fdc 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -398,6 +398,8 @@ The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V Proof qualification for the Account source/currentness cut: historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` results remain historical evidence only. Physical Account job `114042562197` on `c69fa3645f3ddf16d2eaafd3838a29a52141736f` executed 98 integration cases with zero skips and one canonical-order Game Logic fixture failure; its correction passed Account job `114050124577` on `fb6ca4dd29fa3f39407f7f2cc32a016fab155403`. The subsequent `f1ed94a42dfdcb1f63bf52c95c60e9e5744af4b7` Account job `114059401680` in run `38001172632`, artifact `11648894382`, executed 101 PostgreSQL integration cases with zero skips and one trigger-catalog fixture failure. The new inspection-lock, immutable TRUNCATE and exact disclosure-source regressions passed. PostgreSQL truncates identifiers to its `name` type's capacity; the catalog assertion now compares through `?::name` while retaining enabled statement-level TRUNCATE checks and actual rejection tests. The final `14eaa6c9568928f0079830159ac66f37ead2c146` Account job `114067421524` in run `38003644164` passed its physical integration task with Docker active, including the corrected settlement/source-vector fixture classes in its aggregate JaCoCo execution inventory. Successful case-level JUnit totals were not retained, so no new exact per-case counts are claimed. All five required exact-head gates and subsequent metadata-preservation gates passed. This bounded evidence does not establish runtime activation or playable closure. +Current Account authority proof receiving in #3034 preserves the canonical production and migration owners while adapting eight retained test/resource paths. R1369 freshly passes 14 Common logout/reset codec cases, eight Account request-binding cases, and 25 PostgreSQL cases across source guards and security-state operations, with zero failures, errors or skips. The database cases cover observed lock contention, mixed-owner outcomes, rollback, immutable terminal retry, forged checkpoint refusal, retained receipts and populated V78→V79 history without backfill. Affected enabled test/static analysis and Java formatting pass. The retained v1 vector values are unchanged; obsolete issuer schemas, historical migration names and weaker source guards are not restored. These are controlled storage/source fixtures, not authenticated production mutation, runtime registration, genuine issuer custody or public-admission proof. Earlier snapshots below retain their original source attribution. R1382 strengthens the accepted CLI proof gaps without changing production or fixed vector JSON: every vector collection must be nonempty, malformed non-digest preimages must independently fail sealing, and uppercase logout request IDs fail with a coherent event identity. Corruption fixtures first prove committed, settled source evidence and then require the exact owner or PostgreSQL guard, including SQLSTATE and message for receipt protection. Fifteen Common codec cases and all 15 security-state PostgreSQL cases pass with zero failures, errors or skips, alongside enabled affected static analysis, full Java formatting and documentation checks. Its initial PostgreSQL command failed compilation on a test-only void-lambda error before execution; the corrected native recovery is separate. + Canonical first-JOIN membership-event production requires current public-JOIN entitlement; a bare fresh tenant 1/1 baseline is denied and does not preserve admission. Tenant authority requires Account's exact typed tenant event, fresh Game Design provenance, and matching composite generation/source-version and billing coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Historical gate 108 passed 593 Account unit cases and five focused shared World hold cases. Later gate 123 passed 598 Account unit cases, and gate 124 passed 27 focused shared-evidence cases across a broader selection; these are distinct executed snapshots and suite scopes, not conflicting totals. jOOQ generation and integration-test compilation passed. Published checkpoint `b5234acd7f93440170178d1b808e19b4a00ac644` subsequently passed required CI. PostgreSQL-backed integration sources, including the later-generation JOIN and exact outbox replay cases, remain unexecuted locally; neither unit proof nor historical CI establishes fresh-image playable proof for subsequent corrections. Earlier Account checkpoints `d619948920469228814d8d2ef60f9dac8672e7ea` and `f086de2896f885e33745d1482872ec2ae1c480c2` have reported green required CI, including full-stack Smoke. Reported local validation passed 535 Account unit tests, integration-test source compilation, and documentation checks; local physical PostgreSQL validation was not run. The newer reconciled head `5deaf573be3774b4eb8285ff857907f03b2ba5e0` and subsequent retained-source denial correction do not inherit an exact-head green claim. The correction passed 249 focused Account unit tests, integration-test source compilation, and documentation checks; exact-head required CI and physical PostgreSQL proof remain pending. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java index eccc4280bd..885f7fc151 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java @@ -10,8 +10,13 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChangeAbortReason; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; @@ -230,6 +235,428 @@ void waitingAndRevokeIntentCanStillBeRecordedWhileActualMutationStaysDenied() { changePassword(c, binding.actorAccountId(), "test-only-after-aborts"); } + @Test + void everyMixedOwnerOutcomePairingRemainsFencedUnderBothOrderings() { + for (DraftAuthorizationFenceRepository.Ordering ordering : + List.of( + DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER, + DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER)) { + for (Outcome worldOutcome : Outcome.values()) { + for (Outcome gameDesignOutcome : Outcome.values()) { + if (worldOutcome == gameDesignOutcome) { + continue; + } + Context c = context(); + var binding = binding(c); + var change = sourceChange(binding); + c.tx( + () -> { + c.fences.reserve(binding); + if (ordering == DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER) { + c.fences.claimCommitOrder(binding); + } else { + assertThat(c.fences.requestSourceChange(change)).isFalse(); + } + return null; + }); + terminal(c, binding, Owner.WORLD, worldOutcome); + terminal(c, binding, Owner.GAME_DESIGN, gameDesignOutcome); + + assertThat(c.tx(() -> c.fences.readSettlement(binding))) + .as("%s with WORLD %s and GAME_DESIGN %s", ordering, worldOutcome, gameDesignOutcome) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.PENDING); + assertThatThrownBy( + () -> changePassword(c, binding.actorAccountId(), "test-only-mixed-outcome")) + .isInstanceOf(DataAccessException.class); + if (ordering == DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER) { + assertThat(c.tx(() -> c.fences.sourceMutationPermitted(change))).isFalse(); + assertThat(c.tx(() -> c.fences.sourceAbortPermitted(change))).isFalse(); + } + } + } + } + } + + @Test + void overlappingSourceChangeClaimsObserveBackendWaitWhileDisjointSourcesProceed() + throws Exception { + Context c = context(); + var binding = binding(c); + var firstChange = sourceChange(binding); + var overlappingChange = sourceChange(binding); + c.tx(() -> c.fences.reserve(binding)); + + CountDownLatch firstIntentRecorded = new CountDownLatch(1); + CountDownLatch releaseFirstIntent = new CountDownLatch(1); + AtomicReference firstFailure = new AtomicReference<>(); + AtomicInteger firstPid = new AtomicInteger(); + Thread firstClaim = + new Thread( + () -> { + try { + c.tx( + () -> { + firstPid.set( + Objects.requireNonNull(c.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + assertThat(c.fences.requestSourceChange(firstChange)).isFalse(); + firstIntentRecorded.countDown(); + await(releaseFirstIntent); + return null; + }); + } catch (Throwable failure) { + firstFailure.set(failure); + firstIntentRecorded.countDown(); + } + }, + "draft-source-change-first-claim"); + firstClaim.start(); + + assertThat(firstIntentRecorded.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(firstFailure.get()).isNull(); + + CountDownLatch overlappingStarted = new CountDownLatch(1); + AtomicInteger overlappingPid = new AtomicInteger(); + AtomicReference overlappingFailure = new AtomicReference<>(); + Thread overlappingClaim = + startContender( + c, + overlappingStarted, + overlappingPid, + overlappingFailure, + () -> c.fences.requestSourceChange(overlappingChange)); + try { + assertThat(overlappingStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitBackendLock(c, overlappingPid.get(), List.of(firstPid.get())); + + var disjointBinding = binding(c); + var disjointChange = sourceChange(disjointBinding); + c.tx(() -> c.fences.reserve(disjointBinding)); + assertThat(c.tx(() -> c.fences.requestSourceChange(disjointChange))).isFalse(); + assertThat(c.tx(() -> c.fences.read(disjointBinding)).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER); + assertThat(c.tx(() -> c.fences.readSourceChange(disjointChange).status())) + .isEqualTo("WAITING"); + } finally { + releaseFirstIntent.countDown(); + } + + join(firstClaim); + join(overlappingClaim); + assertThat(firstFailure.get()).isNull(); + assertThat(overlappingFailure.get()) + .isInstanceOf(DraftAuthorizationFenceRepository.PendingSourceChangeException.class); + assertThat(c.tx(() -> c.fences.readSourceChange(firstChange).status())).isEqualTo("WAITING"); + assertThatThrownBy(() -> c.tx(() -> c.fences.readSourceChange(overlappingChange))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Absent or changed immutable source mutation intent"); + } + + @Test + void commitOrderAndRevocationContendersSerializeBehindObservedPostgresLocks() throws Exception { + assertContendedOrderingWins(true); + assertContendedOrderingWins(false); + } + + @Test + void reservationAndSourceChangeIntentRollbackLeavesRowsUnchangedAndAllowsDisjointWork() { + Context c = context(); + var binding = binding(c); + var change = sourceChange(binding); + Map before = authorizationRowCounts(c); + String passwordBefore = accountPassword(c, binding.actorAccountId()); + + assertThatThrownBy( + () -> + c.tx( + () -> { + c.fences.reserve(binding); + assertThat(c.fences.requestSourceChange(change)).isFalse(); + throw new IllegalStateException("test-only transaction rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("test-only transaction rollback"); + + assertThat(authorizationRowCounts(c)).isEqualTo(before); + assertThat(accountPassword(c, binding.actorAccountId())).isEqualTo(passwordBefore); + assertThat(c.tx(() -> c.fences.readOriginalBinding(binding.operationId()))) + .as("the reservation rolled back with its source-change intent") + .isEmpty(); + assertThatThrownBy(() -> c.tx(() -> c.fences.readSourceChange(change))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Absent or changed immutable source mutation intent"); + + var disjointBinding = binding(c); + var disjointChange = sourceChange(disjointBinding); + c.tx(() -> c.fences.reserve(disjointBinding)); + assertThat(c.tx(() -> c.fences.requestSourceChange(disjointChange))).isFalse(); + assertThat(c.tx(() -> c.fences.read(disjointBinding).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER); + assertThat(c.tx(() -> c.fences.readSourceChange(disjointChange).status())).isEqualTo("WAITING"); + } + + @Test + void exactSourceAbortRetryPreservesTerminalReadbackAndCannotReopen() { + Context c = context(); + var binding = binding(c); + var change = sourceChange(binding); + c.tx( + () -> { + c.fences.reserve(binding); + assertThat(c.fences.requestSourceChange(change)).isFalse(); + return null; + }); + terminal(c, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + terminal(c, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThat(c.tx(() -> c.fences.sourceAbortPermitted(change))).isTrue(); + + c.tx( + () -> { + c.fences.markSourceAborted(change, SourceChangeAbortReason.EXPIRED); + return null; + }); + var aborted = c.tx(() -> c.fences.readSourceChange(change)); + String abortedRowVersion = sourceChangeRowVersion(c, change.changeId()); + assertThat(aborted.status()).isEqualTo("SOURCE_ABORTED"); + assertThat(aborted.requestedAt()).isNotNull(); + assertThat(aborted.committedAt()).isNull(); + assertThat(aborted.abortedAt()).isNotNull(); + assertThat(aborted.abortReason()).isEqualTo(SourceChangeAbortReason.EXPIRED); + + c.tx( + () -> { + c.fences.markSourceAborted(change, SourceChangeAbortReason.EXPIRED); + return null; + }); + assertSourceChangeUnchanged(c.tx(() -> c.fences.readSourceChange(change)), aborted); + assertThat(sourceChangeRowVersion(c, change.changeId())).isEqualTo(abortedRowVersion); + + assertThatThrownBy( + () -> + c.tx( + () -> { + c.fences.markSourceAborted(change, SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Source change abort reason differs from readback"); + assertSourceChangeUnchanged(c.tx(() -> c.fences.readSourceChange(change)), aborted); + + assertThatThrownBy(() -> c.tx(() -> c.fences.requestSourceChange(change))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Aborted source change cannot be requested again"); + assertThatThrownBy( + () -> + c.tx( + () -> { + c.fences.markSourceCommitted(change); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Aborted source change cannot be committed"); + assertSourceChangeUnchanged(c.tx(() -> c.fences.readSourceChange(change)), aborted); + assertThat(sourceChangeRowVersion(c, change.changeId())).isEqualTo(abortedRowVersion); + } + + private static void assertContendedOrderingWins(boolean commitOrderWins) throws Exception { + Context c = context(); + var binding = binding(c); + var change = sourceChange(binding); + c.tx(() -> c.fences.reserve(binding)); + + try (Connection blocker = c.source.getConnection()) { + blocker.setAutoCommit(false); + try (var statement = + blocker.prepareStatement( + "SELECT source_key FROM account_draft_authorization_source_locks" + + " WHERE source_key = ? FOR UPDATE")) { + statement.setString(1, binding.sources().getFirst().key()); + assertThat(statement.executeQuery().next()).isTrue(); + } + + int blockerPid; + try (var statement = blocker.createStatement(); + var rows = statement.executeQuery("SELECT pg_backend_pid()")) { + assertThat(rows.next()).isTrue(); + blockerPid = rows.getInt(1); + } + CountDownLatch firstStarted = new CountDownLatch(1); + AtomicInteger firstPid = new AtomicInteger(); + AtomicReference firstFailure = new AtomicReference<>(); + Thread firstContender = + startContender( + c, + firstStarted, + firstPid, + firstFailure, + () -> { + if (commitOrderWins) { + c.fences.claimCommitOrder(binding); + } else { + c.fences.requestSourceChange(change); + } + }); + Thread secondContender = null; + AtomicReference secondFailure = new AtomicReference<>(); + try { + assertThat(firstStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitBackendLock(c, firstPid.get(), List.of(blockerPid)); + + CountDownLatch secondStarted = new CountDownLatch(1); + AtomicInteger secondPid = new AtomicInteger(); + secondContender = + startContender( + c, + secondStarted, + secondPid, + secondFailure, + () -> { + if (commitOrderWins) { + c.fences.requestSourceChange(change); + } else { + c.fences.claimCommitOrder(binding); + } + }); + assertThat(secondStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitBackendLock(c, secondPid.get(), List.of(blockerPid, firstPid.get())); + } finally { + blocker.commit(); + } + join(firstContender); + if (secondContender != null) { + join(secondContender); + } + assertThat(firstFailure.get()).isNull(); + if (commitOrderWins) { + assertThat(secondFailure.get()).isNull(); + } else { + assertThat(secondFailure.get()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Revocation precedes this owner commit"); + } + } + + if (commitOrderWins) { + assertThat(c.tx(() -> c.fences.read(binding).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER); + assertThat(c.tx(() -> c.fences.readSourceChange(change).status())).isEqualTo("WAITING"); + } else { + assertThat(c.tx(() -> c.fences.read(binding).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER); + assertThatThrownBy(() -> c.tx(() -> c.fences.claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Revocation precedes this owner commit"); + } + } + + private static Thread startContender( + Context c, + CountDownLatch started, + AtomicInteger backendPid, + AtomicReference failure, + Runnable action) { + Thread contender = + new Thread( + () -> { + try { + c.tx( + () -> { + backendPid.set( + Objects.requireNonNull(c.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + started.countDown(); + action.run(); + return null; + }); + } catch (Throwable thrown) { + failure.set(thrown); + started.countDown(); + } + }, + "draft-fence-postgres-contender"); + contender.start(); + return contender; + } + + private static void awaitBackendLock(Context c, int backendPid, List expectedBlockers) + throws InterruptedException { + long deadline = System.nanoTime() + Duration.ofSeconds(5).toNanos(); + while (System.nanoTime() < deadline) { + for (int expectedBlocker : expectedBlockers) { + var activity = + c.dsl.fetchOne( + "SELECT wait_event_type = 'Lock' AND ? = ANY(pg_blocking_pids(pid)) " + + "FROM pg_stat_activity WHERE pid = ?", + expectedBlocker, + backendPid); + if (activity != null && Boolean.TRUE.equals(activity.get(0, Boolean.class))) { + return; + } + } + Thread.sleep(10); + } + throw new AssertionError( + "PostgreSQL backend " + backendPid + " did not wait behind " + expectedBlockers); + } + + private static void join(Thread thread) throws InterruptedException { + thread.join(Duration.ofSeconds(10).toMillis()); + assertThat(thread.isAlive()).as("PostgreSQL contention worker finished").isFalse(); + } + + private static void await(CountDownLatch latch) { + try { + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while holding a test transaction", interrupted); + } + } + + private static Map authorizationRowCounts(Context c) { + return Map.of( + "source_locks", c.dsl.fetchCount(DSL.table("account_draft_authorization_source_locks")), + "fences", c.dsl.fetchCount(DSL.table("account_draft_authorization_fences")), + "sources", c.dsl.fetchCount(DSL.table("account_draft_authorization_sources")), + "owner_readbacks", + c.dsl.fetchCount(DSL.table("account_draft_authorization_owner_readbacks")), + "source_changes", c.dsl.fetchCount(DSL.table("account_draft_authorization_source_changes")), + "changed_scopes", + c.dsl.fetchCount(DSL.table("account_draft_authorization_changed_scopes"))); + } + + private static String accountPassword(Context c, UUID accountId) { + return Objects.requireNonNull( + c.dsl.fetchOne("SELECT password_hash FROM accounts WHERE account_uuid = ?", accountId)) + .get("password_hash", String.class); + } + + private static DraftAuthorizationFenceRepository.SourceChange sourceChange( + DraftAuthorizationFenceBinding binding) { + return new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), binding.sources(), new byte[] {17}); + } + + private static void assertSourceChangeUnchanged( + DraftAuthorizationFenceRepository.SourceChangeSnapshot actual, + DraftAuthorizationFenceRepository.SourceChangeSnapshot expected) { + assertThat(actual.changeId()).isEqualTo(expected.changeId()); + assertThat(actual.binding()).containsExactly(expected.binding()); + assertThat(actual.status()).isEqualTo(expected.status()); + assertThat(actual.requestedAt()).isEqualTo(expected.requestedAt()); + assertThat(actual.committedAt()).isEqualTo(expected.committedAt()); + assertThat(actual.abortedAt()).isEqualTo(expected.abortedAt()); + assertThat(actual.abortReason()).isEqualTo(expected.abortReason()); + } + + private static String sourceChangeRowVersion(Context c, UUID changeId) { + return Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT xmin::text FROM account_draft_authorization_source_changes WHERE change_id = ?", + changeId)) + .get(0, String.class); + } + private static void terminal( Context c, DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { c.tx( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java new file mode 100644 index 0000000000..1fa9e678d0 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -0,0 +1,1475 @@ +package integration.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +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.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Synthetic owner producer/correlation fixtures; these are not authenticated runtime mutations. */ +@Testcontainers(disabledWithoutDocker = true) +class AccountSecurityStateOperationPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + var actualSource = + tx( + fixture, + () -> { + var sources = + new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository( + fixture.dsl(), fixture.generations(), fixture.outbox()); + sources.initializeIssuerIfAbsent("firemud-account-service"); + return sources + .readCurrentIssuerAccountSources( + "firemud-account-service", seed.account().getAccountUuid()) + .account(); + }); + assertThat(actualSource.initializationProvenance()).isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + assertThat(actualSource.checkpoint().sequence()).isZero(); + assertThat(actualSource.initializationTransactionId()) + .isEqualTo(actualSource.accountRepositoryInsertTransactionId()); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams WHERE outbox_stream_key = ?", + stream(seed.account().getAccountUuid())), + "Expected persisted Account authority outbox stream row") + .get(0, Long.class)) + .isZero(); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + var first = tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + var retry = tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + assertThat(first.claimed()).isTrue(); + assertThat(retry.claimed()).isFalse(); + assertThat(retry.operation().receipt()).isEmpty(); + assertThat( + AccountSecurityStateOperationRepository.captureBytes( + pending.request(), retry.operation().capture())) + .isEqualTo( + AccountSecurityStateOperationRepository.captureBytes( + pending.request(), pending.capture())); + assertThat( + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid())))) + .isEqualTo(seed.source()); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row") + .get(0, Boolean.class)) + .isFalse(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + } + + @Test + void zeroReceiptRejectsAbsentMismatchedAndFabricatedV40BaselineWithoutMutation() { + for (String corruption : + List.of( + "DELETE FROM account_authority_source_records WHERE account_uuid = ?", + "UPDATE account_authority_source_records SET account_source_numeric_id = account_source_numeric_id + 1 WHERE account_uuid = ?", + "UPDATE account_authority_source_records SET initialization_transaction_id = initialization_transaction_id + 1, account_repository_insert_transaction_id = account_repository_insert_transaction_id + 1 WHERE account_uuid = ?")) { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + // Fault injection only after genuine owner insertion: never create a passing raw baseline. + fixture.dsl().execute("ALTER TABLE account_authority_source_records DISABLE TRIGGER USER"); + try { + fixture.dsl().execute(corruption, seed.account().getAccountUuid()); + } finally { + fixture.dsl().execute("ALTER TABLE account_authority_source_records ENABLE TRIGGER USER"); + } + assertThatThrownBy( + () -> + tx( + fixture, + () -> fixture.operations().claim(pending.request(), pending.capture()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Security-state pristine baseline is not proved"); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + assertThat(tx(fixture, () -> fixture.generations().read(seed.source().scope()))) + .isEqualTo(seed.source()); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row after rejected security-state operation") + .get(0, Boolean.class)) + .isFalse(); + } + } + + @Test + void accountRepositoryRoleSavePersistsGenericHistoryButNotCanonicalRoleAuthority() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + var roleSourceBefore = + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_global_role_sources WHERE account_uuid = ?", + seed.account().getAccountUuid()); + assertThat(roleSourceBefore).isNotNull(); + assertThat(roleSourceBefore.get("global_roles", String[].class)).isEmpty(); + assertThat(roleSourceBefore.get("global_role_source_version", Long.class)).isEqualTo(1L); + + Account saved = + tx( + fixture, + () -> { + Account owner = + new AccountRepository(fixture.dsl()) + .findById(seed.account().getId()) + .orElseThrow(); + owner.setRole("player"); + return new AccountRepository(fixture.dsl()).save(owner); + }); + assertThat(saved.getRole()).isEqualTo("player"); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT role FROM accounts WHERE account_uuid = ?", + saved.getAccountUuid()), + "Expected persisted Account role row") + .get("role", String.class)) + .isEqualTo("player"); + + ScopeState current = + tx( + fixture, + () -> fixture.generations().read(AuthorityScope.account(saved.getAccountUuid()))); + assertThat(current.generation()).isEqualTo(2L); + assertThat(current.sourceVersion()).isEqualTo(2L); + assertThat(current.issuanceFence().value()).isEqualTo(2L); + assertThat(current.issuanceFence().sourceVersion()).isEqualTo(2L); + Event genericEvent = + tx( + fixture, + () -> fixture.outbox().findEvent(stream(saved.getAccountUuid()), 1L).orElseThrow()); + var verifiedGenericEvent = + (net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec + .AccountEvent) + net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec + .verify(new String(genericEvent.payload(), StandardCharsets.UTF_8)); + assertThat(verifiedGenericEvent.accountState().globalRole()).isEqualTo("player"); + assertThat(verifiedGenericEvent.mutationKinds()).containsExactly("GLOBAL_ROLE_CHANGED"); + assertThat(verifiedGenericEvent.accountAuthorityGeneration()) + .isEqualTo(Long.toString(current.generation())); + assertThat(verifiedGenericEvent.sourceVersion()) + .isEqualTo(Long.toString(current.sourceVersion())); + assertThat(verifiedGenericEvent.issuanceFence()) + .isEqualTo(Long.toString(current.issuanceFence().value())); + assertThat(verifiedGenericEvent.issuanceFenceSourceVersion()) + .isEqualTo(Long.toString(current.issuanceFence().sourceVersion())); + var currentSourceRecord = + fixture + .dsl() + .fetchOne( + "SELECT current_generation, current_source_version, current_issuance_fence, " + + "current_issuance_fence_source_version, last_outbox_sequence, last_event_id, " + + "last_event_digest FROM account_authority_source_records " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + saved.getAccountUuid()); + assertThat(currentSourceRecord.get("current_generation", Long.class)).isEqualTo(2L); + assertThat(currentSourceRecord.get("current_source_version", Long.class)).isEqualTo(2L); + assertThat(currentSourceRecord.get("current_issuance_fence", Long.class)).isEqualTo(2L); + assertThat(currentSourceRecord.get("current_issuance_fence_source_version", Long.class)) + .isEqualTo(2L); + assertThat(currentSourceRecord.get("last_outbox_sequence", Long.class)).isEqualTo(1L); + assertThat(currentSourceRecord.get("last_event_id", String.class)) + .isEqualTo(genericEvent.eventId()); + assertThat(currentSourceRecord.get("last_event_digest", String.class)) + .isEqualTo(genericEvent.eventDigest()); + + var roleSourceAfter = + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_global_role_sources WHERE account_uuid = ?", + saved.getAccountUuid()); + assertThat(roleSourceAfter).isEqualTo(roleSourceBefore); + assertThat(roleSourceAfter.get("global_roles", String[].class)).isEmpty(); + assertThat(roleSourceAfter.get("global_role_source_version", Long.class)).isEqualTo(1L); + assertThatThrownBy( + () -> + tx( + fixture, + () -> { + sourceReadback(fixture).requireCurrentLatest(saved, current); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> sourceReader(fixture).readCurrent(saved.getAccountUuid())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void originalCallerAndFamilyBindingsCannotBeChangedOnRetry() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + var request = pending.request(); + var changed = + new AccountSecurityStateMutationRequest( + request.requestId(), + request.accountUuid(), + correlation(UUID.randomUUID(), request.requestId()), + request.expectedGeneration(), + request.expectedSourceVersion(), + request.mutationKinds(), + request.desiredState()); + assertThatThrownBy( + () -> tx(fixture, () -> fixture.operations().claim(changed, pending.capture()))) + .isInstanceOf(AccountSecurityStateOperationRepository.OperationConflictException.class); + var wrongKinds = + new AccountSecurityStateMutationRequest( + UUID.randomUUID(), + request.accountUuid(), + request.callerProofBinding(), + 1L, + 1L, + List.of("LOGIN_AUTH_MODES_CHANGED"), + state(true)); + assertThatThrownBy( + () -> tx(fixture, () -> fixture.operations().claim(wrongKinds, pending.capture()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("capture differs"); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + } + + @Test + void concurrentExactClaimsSerializeToOneOriginalRequest() throws Exception { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + CountDownLatch ready = new CountDownLatch(2); + try (var executor = Executors.newFixedThreadPool(2)) { + var tasks = + List.of(1, 2).stream() + .map( + ignored -> + executor.submit( + () -> + tx( + fixture, + () -> { + ready.countDown(); + try { + if (!ready.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException( + "Concurrent claims did not start"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return fixture + .operations() + .claim(pending.request(), pending.capture()) + .claimed(); + }))) + .toList(); + assertThat( + List.of( + tasks.get(0).get(20, TimeUnit.SECONDS), tasks.get(1).get(20, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + } + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + } + + @Test + void exactExistingOutboxReceiptCompletesOnceAndHistoricalImagesSurviveLaterAdvance() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending first = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(first.request(), first.capture())); + Event event = producerFixture(fixture, first, false); + var sourceHead = + fixture + .dsl() + .fetchOne( + "SELECT last_outbox_sequence, last_event_id, last_event_digest " + + "FROM account_authority_source_records WHERE account_uuid = ?", + seed.account().getAccountUuid()); + assertThat(sourceHead.get("last_outbox_sequence", Long.class)) + .isEqualTo(event.outboxSequence()); + assertThat(sourceHead.get("last_event_id", String.class)).isEqualTo(event.eventId()); + assertThat(sourceHead.get("last_event_digest", String.class)).isEqualTo(event.eventDigest()); + assertThat(sourceReader(fixture).readCurrent(seed.account().getAccountUuid()).latestEvent()) + .contains(event); + tx( + fixture, + () -> { + var latest = + sourceReadback(fixture) + .requireCurrentLatest( + new AccountRepository(fixture.dsl()) + .findById(seed.account().getId()) + .orElseThrow(), + fixture.generations().read(seed.source().scope())); + assertThat(latest.latestEvent()).contains(event); + return null; + }); + var retained = + tx( + fixture, + () -> fixture.operations().findByRequestId(first.request().requestId()).orElseThrow()); + assertThat(retained.receipt().orElseThrow().event()).isEqualTo(event); + ScopeState current = + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid()))); + Seed newer = new Seed(seed.account(), current); + AccountState after = new AccountState(true, List.of("PASSWORD"), List.of(), "ACTIVE"); + Pending second = pending(fixture, newer, state(true), after, 1L, event.payload()); + tx(fixture, () -> fixture.operations().claim(second.request(), second.capture())); + producerFixture(fixture, second, false); + assertThat( + sourceReader(fixture) + .readCommittedEvent(seed.account().getAccountUuid(), 1L) + .requestedEvent()) + .isEqualTo(event); + tx( + fixture, + () -> { + var account = + new AccountRepository(fixture.dsl()).findById(seed.account().getId()).orElseThrow(); + var source = fixture.generations().read(seed.source().scope()); + sourceReadback(fixture).requireRetainedEvent(account, event, source); + assertThat(sourceReadback(fixture).requireCurrentLatest(account, source).outboxSequence()) + .isEqualTo(2L); + return null; + }); + var retry = tx(fixture, () -> fixture.operations().claim(first.request(), second.capture())); + assertThat(retry.claimed()).isFalse(); + assertThat(retry.operation().receipt().orElseThrow().event().payload()) + .isEqualTo(event.payload()); + assertThat(retry.operation().capture().beforeState()).isEqualTo(state(false)); + assertThat(retry.operation().request().desiredState()).isEqualTo(state(true)); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isEqualTo(2); + } + + @Test + void unownedPrivateFenceAdvanceIsRejectedWithoutChangingSourceOrOriginalReceipt() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + Event event = producerFixture(fixture, pending, false); + var original = + tx( + fixture, + () -> + fixture.operations().findByRequestId(pending.request().requestId()).orElseThrow()); + var originalRow = + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_security_state_operations WHERE request_id = ?", + pending.request().requestId()); + assertThatThrownBy( + () -> + tx( + fixture, + () -> { + var source = fixture.generations().read(seed.source().scope()); + fixture + .dsl() + .execute( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = issuance_fence + 1, source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE account_uuid = ? AND issuance_fence = ? AND source_version = ?", + seed.account().getAccountUuid(), + source.issuanceFence().value(), + source.issuanceFence().sourceVersion()); + return null; + })) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .hasMessageContaining("Account issuance fence advance lacks exact owner source evidence"); + var snapshot = sourceReader(fixture).readCurrent(seed.account().getAccountUuid()); + assertThat(snapshot.latestEvent()).contains(event); + assertThat(snapshot.sourceState()).isEqualTo(original.receipt().orElseThrow().sourceState()); + var retained = + tx( + fixture, + () -> + fixture.operations().findByRequestId(pending.request().requestId()).orElseThrow()); + assertThat(retained.receipt()).isEqualTo(original.receipt()); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_security_state_operations WHERE request_id = ?", + pending.request().requestId())) + .isEqualTo(originalRow); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isEqualTo(1); + } + + @Test + void lateReceiptFailureRollsBackEntireFixtureProducerButRetainsOriginalWaitingIntent() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + assertThatThrownBy(() -> producerFixture(fixture, pending, true)) + .isInstanceOf(IllegalStateException.class); + assertThat( + tx( + fixture, + () -> + fixture + .operations() + .findByRequestId(pending.request().requestId()) + .orElseThrow()) + .receipt()) + .isEmpty(); + assertThat( + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid())))) + .isEqualTo(seed.source()); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row after rollback") + .get(0, Boolean.class)) + .isFalse(); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT status FROM account_draft_authorization_source_changes WHERE change_id = ?", + pending.capture().sourceChange().changeId()), + "Expected original V76 source-change row after rollback") + .get(0, String.class)) + .isEqualTo("WAITING"); + } + + @Test + void requestCaptureResultsDeletesAndTruncationRemainGuarded() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + for (String sql : + List.of( + "UPDATE account_security_state_operations SET request_digest = repeat('b',64)", + "UPDATE account_security_state_operations SET expected_generation = 2", + "DELETE FROM account_security_state_operations", + "TRUNCATE account_security_state_operations")) { + assertThatThrownBy(() -> fixture.dsl().execute(sql)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + producerFixture(fixture, pending, false); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("UPDATE account_security_state_operations SET event_id = 'changed'")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + } + + @Test + void substitutedEventStateCannotBecomeTheOriginalReceipt() { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + assertThatThrownBy( + () -> + tx( + fixture, + () -> { + var wrong = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + pending.request().requestId(), + pending.request().accountUuid(), + "2", + "2", + "1", + pending.request().mutationKinds(), + state(false))); + var event = + fixture + .outbox() + .append( + stream(seed), + pending.request().requestId().toString(), + sequence -> + new EventEvidence( + wrong.eventId(), + wrong.eventDigest(), + wrong.canonicalJsonUtf8())); + fixture + .operations() + .complete( + pending.request(), + event, + new ScopeState( + seed.source().scope(), + 2L, + 2L, + new AccountAuthorityGenerationRepository.IssuanceFence( + seed.account().getAccountUuid(), 2L, 2L)), + 1L); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("receipt differs"); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + } + + @Test + void corruptPositiveCheckpointMetadataAndPayloadDenyBeforeNewIntentOrSourceMutation() { + for (String corruption : + List.of( + "event_id = 'substituted'", + "request_id = 'substituted'", + "event_digest = 'sha256:' || repeat('b',64)", + "payload = convert_to('{}','UTF8')")) { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending first = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(first.request(), first.capture())); + Event event = producerFixture(fixture, first, false); + var committed = + tx( + fixture, + () -> + fixture.operations().findByRequestId(first.request().requestId()).orElseThrow()); + assertThat(committed.receipt()).isPresent(); + assertThat( + tx( + fixture, + () -> fixture.fences().readSourceChange(first.capture().sourceChange()).status())) + .isEqualTo("SOURCE_COMMITTED"); + ScopeState current = + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid()))); + Pending second = + pending( + fixture, + new Seed(seed.account(), current), + state(true), + new AccountState(true, List.of("PASSWORD"), List.of(), "ACTIVE"), + 1L, + event.payload()); + // Deliberately corrupt immutable storage as a superuser fixture, not a production operation. + fixture.dsl().execute("ALTER TABLE account_authority_outbox_events DISABLE TRIGGER USER"); + fixture.dsl().execute("UPDATE account_authority_outbox_events SET " + corruption); + fixture.dsl().execute("ALTER TABLE account_authority_outbox_events ENABLE TRIGGER USER"); + String expectedMessage = + corruption.startsWith("payload = ") + ? "Original checkpoint capture differs" + : "Account source event readback is inconsistent"; + assertThatThrownBy( + () -> + tx(fixture, () -> fixture.operations().claim(second.request(), second.capture()))) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage(expectedMessage); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) + .isEqualTo(1); + assertThat( + tx( + fixture, + () -> + fixture + .generations() + .read(AuthorityScope.account(seed.account().getAccountUuid())))) + .isEqualTo(current); + } + } + + @Test + void retainedReceiptCannotLeadRegressedCurrentAuthorityOrCheckpoint() { + for (String table : + List.of("account_authority_generations", "account_authority_outbox_streams")) { + Fixture fixture = fixture(null); + Seed seed = seed(fixture); + Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); + producerFixture(fixture, pending, false); + var committed = + tx( + fixture, + () -> + fixture + .operations() + .findByRequestId(pending.request().requestId()) + .orElseThrow()); + assertThat(committed.receipt()).isPresent(); + assertThat( + tx( + fixture, + () -> + fixture.fences().readSourceChange(pending.capture().sourceChange()).status())) + .isEqualTo("SOURCE_COMMITTED"); + fixture.dsl().execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); + fixture + .dsl() + .execute( + table.equals("account_authority_generations") + ? "UPDATE account_authority_generations SET generation = 1, source_version = 1" + : "UPDATE account_authority_outbox_streams SET last_sequence = 0"); + fixture.dsl().execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); + String expectedMessage = + table.equals("account_authority_generations") + ? "Account source snapshot is inconsistent" + : "Account authority outbox zero checkpoint has event evidence"; + Class expectedException = + table.equals("account_authority_generations") + ? IllegalArgumentException.class + : IllegalStateException.class; + assertThatThrownBy( + () -> + tx( + fixture, + () -> fixture.operations().findByRequestId(pending.request().requestId()))) + .isExactlyInstanceOf(expectedException) + .hasMessage(expectedMessage); + } + } + + @Test + void missingSecurityReceiptAndChangedCurrentPoststateCannotCommit() { + Fixture missing = fixture(null); + Seed seed = seed(missing); + Pending pending = pending(missing, seed, state(false), state(true), 0L, new byte[0]); + tx(missing, () -> missing.operations().claim(pending.request(), pending.capture())); + Event event = producerFixture(missing, pending, false); + var committed = + tx( + missing, + () -> + missing.operations().findByRequestId(pending.request().requestId()).orElseThrow()); + assertThat(committed.receipt()).isPresent(); + assertThat( + tx( + missing, + () -> missing.fences().readSourceChange(pending.capture().sourceChange()).status())) + .isEqualTo("SOURCE_COMMITTED"); + ScopeState current = tx(missing, () -> missing.generations().read(seed.source().scope())); + var checkpoint = tx(missing, () -> missing.outbox().readCheckpoint(event.outboxStreamKey())); + assertThat(sourceReader(missing).readCurrent(seed.account().getAccountUuid()).latestEvent()) + .contains(event); + + // Simulate a missing immutable receipt only after proving the original source mutation settled. + missing.dsl().execute("ALTER TABLE account_security_state_operations DISABLE TRIGGER USER"); + try { + assertThat( + missing + .dsl() + .execute( + "DELETE FROM account_security_state_operations WHERE request_id = ?", + pending.request().requestId())) + .isEqualTo(1); + } finally { + missing.dsl().execute("ALTER TABLE account_security_state_operations ENABLE TRIGGER USER"); + } + assertPostgresCheckViolation( + () -> + missing + .dsl() + .execute( + "UPDATE accounts SET email_verified = false WHERE id = ?", + seed.account().getId()), + "V79 security-state event has no exact committed Account operation receipt"); + assertThat(missing.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); + assertThat(missing.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isEqualTo(1); + assertThat(tx(missing, () -> missing.generations().read(seed.source().scope()))) + .isEqualTo(current); + assertThat(tx(missing, () -> missing.outbox().readCheckpoint(event.outboxStreamKey()))) + .isEqualTo(checkpoint); + assertThat( + Objects.requireNonNull( + missing + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + seed.account().getId()), + "Expected persisted Account row after missing-receipt rejection") + .get(0, Boolean.class)) + .isTrue(); + + Fixture changed = fixture(null); + Seed other = seed(changed); + Pending original = pending(changed, other, state(false), state(true), 0L, new byte[0]); + tx(changed, () -> changed.operations().claim(original.request(), original.capture())); + producerFixture(changed, original, false); + assertPostgresCheckViolation( + () -> + changed + .dsl() + .execute( + "UPDATE accounts SET email_verified = false WHERE id = ?", + other.account().getId()), + "V79 security-state receipt does not bind the exact original and current Account states"); + assertThat( + Objects.requireNonNull( + changed + .dsl() + .fetchOne( + "SELECT email_verified FROM accounts WHERE id = ?", + other.account().getId()), + "Expected persisted Account row after rejected poststate change") + .get(0, Boolean.class)) + .isTrue(); + tx( + changed, + () -> { + sourceReadback(changed) + .requireCurrentLatest( + new AccountRepository(changed.dsl()) + .findById(other.account().getId()) + .orElseThrow(), + changed.generations().read(other.source().scope())); + return null; + }); + } + + @Test + void v78ToV79MigrationPreservesRetainedUnenrolledAccountWithoutBackfill() { + Fixture fixture = fixture("73"); + String suffix = UUID.randomUUID().toString(); + Long accountId = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "INSERT INTO accounts (username, email, password_hash, role) " + + "VALUES (?, ?, ?, 'player') RETURNING id", + "retained-" + suffix, + suffix + "@example.test", + "retained-password-" + suffix)) + .get(0, Long.class); + UUID accountUuid = + Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT account_uuid FROM accounts WHERE id = ?", accountId)) + .get(0, UUID.class); + // This is the same historical raw-row fixture used by the Account retained-upgrade proof. + // Advance it to V78 before capturing the migration preimage; do not invent source or birth + // rows. + migrate(fixture.dataSource(), fixture.schema(), "78"); + var accountBefore = + fixture.dsl().fetch("SELECT * FROM accounts WHERE id = ?", accountId).intoMaps(); + var authorityBefore = + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .intoMaps(); + var sourceBefore = + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_source_records " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .intoMaps(); + var fenceBefore = + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid) + .intoMaps(); + var rolesBefore = + fixture + .dsl() + .fetch("SELECT * FROM account_global_role_sources WHERE account_uuid = ?", accountUuid) + .intoMaps(); + assertThat(authorityBefore).isEmpty(); + assertThat(sourceBefore).isEmpty(); + assertThat(fenceBefore).isEmpty(); + assertThat(rolesBefore).isEmpty(); + assertThat( + fixture + .dsl() + .resultQuery("SELECT to_regclass('account_platform_restriction_births')::TEXT") + .fetchOne(0, String.class)) + .isNull(); + + migrate(fixture.dataSource(), fixture.schema(), "79"); + assertThat(fixture.dsl().fetch("SELECT * FROM accounts WHERE id = ?", accountId).intoMaps()) + .isEqualTo(accountBefore); + assertThat( + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .intoMaps()) + .isEqualTo(authorityBefore); + assertThat( + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_source_records " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .intoMaps()) + .isEqualTo(sourceBefore); + assertThat( + fixture + .dsl() + .fetch( + "SELECT * FROM account_authority_issuance_fences WHERE account_uuid = ?", + accountUuid) + .intoMaps()) + .isEqualTo(fenceBefore); + assertThat( + fixture + .dsl() + .fetch( + "SELECT * FROM account_global_role_sources WHERE account_uuid = ?", accountUuid) + .intoMaps()) + .isEqualTo(rolesBefore); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); + assertThat(accountUuid).isNotNull(); + assertThat( + fixture + .dsl() + .resultQuery("SELECT to_regclass('account_platform_restriction_births')::TEXT") + .fetchOne(0, String.class)) + .isNull(); + } + + @Test + void v78ToV79MigrationPreservesPopulatedHistoricalAccountAuthorityWithoutBackfill() { + Fixture fixture = fixture("78"); + HistoricalAccount historical = seedHistoricalV78Account(fixture); + + var accountBefore = snapshotRows(fixture.dsl(), "accounts", "id"); + var generationsBefore = + snapshotRows( + fixture.dsl(), + "account_authority_generations", + "scope_kind, issuer_id NULLS FIRST, account_uuid NULLS FIRST, tenant_uuid NULLS FIRST"); + var sourcesBefore = + snapshotRows(fixture.dsl(), "account_authority_source_records", "outbox_stream_key"); + var fencesBefore = + snapshotRows(fixture.dsl(), "account_authority_issuance_fences", "account_uuid"); + var rolesBefore = snapshotRows(fixture.dsl(), "account_global_role_sources", "account_uuid"); + var checkpointsBefore = + snapshotRows(fixture.dsl(), "account_authority_outbox_streams", "outbox_stream_key"); + var historyBefore = snapshotRows(fixture.dsl(), "flyway_schema_history", "installed_rank"); + var historicalBaseline = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT account_row.id, account_row.account_uuid, " + + "account_row.account_uuid_source_numeric_id, account_row.account_uuid_provenance, " + + "account_row.account_repository_insert_transaction_id, " + + "generation_row.created_transaction_id, generation_row.generation, " + + "generation_row.source_version, source_row.initialization_transaction_id, " + + "source_row.initialization_provenance, source_row.account_source_numeric_id, " + + "source_row.account_repository_insert_transaction_id AS source_insert_transaction_id, " + + "source_row.baseline_generation, source_row.baseline_source_version, " + + "source_row.baseline_issuance_fence, source_row.current_generation, " + + "source_row.current_source_version, source_row.current_issuance_fence, " + + "source_row.current_issuance_fence_source_version, source_row.last_outbox_sequence, " + + "fence_row.issuance_fence, fence_row.source_version AS fence_source_version, " + + "stream_row.last_sequence, role_row.global_roles, " + + "role_row.global_role_source_version " + + "FROM accounts AS account_row " + + "JOIN account_authority_generations AS generation_row " + + "ON generation_row.scope_kind = 'ACCOUNT' " + + "AND generation_row.account_uuid = account_row.account_uuid " + + "JOIN account_authority_source_records AS source_row " + + "ON source_row.scope_kind = 'ACCOUNT' " + + "AND source_row.account_uuid = account_row.account_uuid " + + "JOIN account_authority_issuance_fences AS fence_row " + + "ON fence_row.account_uuid = account_row.account_uuid " + + "JOIN account_authority_outbox_streams AS stream_row " + + "ON stream_row.outbox_stream_key = source_row.outbox_stream_key " + + "JOIN account_global_role_sources AS role_row " + + "ON role_row.account_uuid = account_row.account_uuid " + + "WHERE account_row.id = ? AND account_row.account_uuid = ?", + historical.accountId(), + historical.accountUuid()), + "Expected complete historical Account birth/source readback"); + assertThat(accountBefore).hasSize(1); + assertThat(generationsBefore).isNotEmpty(); + assertThat(sourcesBefore).isNotEmpty(); + assertThat(fencesBefore).hasSize(1); + assertThat(rolesBefore).hasSize(1); + assertThat(checkpointsBefore).isNotEmpty(); + assertThat(historyBefore).isNotEmpty(); + assertThat(historicalBaseline.get("account_uuid", UUID.class)) + .isEqualTo(historical.accountUuid()); + assertThat(historicalBaseline.get("id", Long.class)).isEqualTo(historical.accountId()); + assertThat(historicalBaseline.get("account_uuid_source_numeric_id", Long.class)) + .isEqualTo(historical.accountId()); + assertThat(historicalBaseline.get("account_uuid_provenance", String.class)) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + Long insertTransactionId = + historicalBaseline.get("account_repository_insert_transaction_id", Long.class); + assertThat(insertTransactionId).isPositive(); + assertThat(historicalBaseline.get("created_transaction_id", Long.class)) + .isEqualTo(insertTransactionId); + assertThat(historicalBaseline.get("initialization_transaction_id", Long.class)) + .isEqualTo(insertTransactionId); + assertThat(historicalBaseline.get("source_insert_transaction_id", Long.class)) + .isEqualTo(insertTransactionId); + assertThat(historicalBaseline.get("initialization_provenance", String.class)) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + assertThat(historicalBaseline.get("account_source_numeric_id", Long.class)) + .isEqualTo(historical.accountId()); + assertThat(historicalBaseline.get("generation", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("source_version", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("baseline_generation", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("baseline_source_version", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("baseline_issuance_fence", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("current_generation", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("current_source_version", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("issuance_fence", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("fence_source_version", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("current_issuance_fence", Long.class)).isEqualTo(1L); + assertThat(historicalBaseline.get("current_issuance_fence_source_version", Long.class)) + .isEqualTo(1L); + assertThat(historicalBaseline.get("last_outbox_sequence", Long.class)).isZero(); + assertThat(historicalBaseline.get("last_sequence", Long.class)).isZero(); + assertThat(historicalBaseline.get("global_roles", String[].class)).isEmpty(); + assertThat(historicalBaseline.get("global_role_source_version", Long.class)).isEqualTo(1L); + var appliedV78 = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne("SELECT success FROM flyway_schema_history WHERE version = '78'"), + "Expected V78 Flyway history row before the V79 upgrade"); + assertThat(appliedV78.get("success", Boolean.class)).isTrue(); + assertThat( + fixture + .dsl() + .resultQuery("SELECT to_regclass('account_security_state_operations')::TEXT") + .fetchOne(0, String.class)) + .isNull(); + assertThat( + fixture + .dsl() + .resultQuery("SELECT to_regclass('account_platform_restriction_births')::TEXT") + .fetchOne(0, String.class)) + .isNull(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + + migrate(fixture.dataSource(), fixture.schema(), "79"); + + assertThat(snapshotRows(fixture.dsl(), "accounts", "id")).isEqualTo(accountBefore); + assertThat( + snapshotRows( + fixture.dsl(), + "account_authority_generations", + "scope_kind, issuer_id NULLS FIRST, account_uuid NULLS FIRST, tenant_uuid NULLS FIRST")) + .isEqualTo(generationsBefore); + assertThat(snapshotRows(fixture.dsl(), "account_authority_source_records", "outbox_stream_key")) + .isEqualTo(sourcesBefore); + assertThat(snapshotRows(fixture.dsl(), "account_authority_issuance_fences", "account_uuid")) + .isEqualTo(fencesBefore); + assertThat(snapshotRows(fixture.dsl(), "account_global_role_sources", "account_uuid")) + .isEqualTo(rolesBefore); + assertThat(snapshotRows(fixture.dsl(), "account_authority_outbox_streams", "outbox_stream_key")) + .isEqualTo(checkpointsBefore); + var historyAfter = snapshotRows(fixture.dsl(), "flyway_schema_history", "installed_rank"); + assertThat(historyAfter).hasSize(historyBefore.size() + 1); + assertThat(historyAfter.subList(0, historyBefore.size())).isEqualTo(historyBefore); + var appliedMigration = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT version, script, success FROM flyway_schema_history " + + "ORDER BY installed_rank DESC LIMIT 1"), + "Expected V79 Flyway history row"); + assertThat(appliedMigration.get("version", String.class)).isEqualTo("79"); + assertThat(appliedMigration.get("script", String.class)) + .isEqualTo("V79__account_security_state_operations.sql"); + assertThat(appliedMigration.get("success", Boolean.class)).isTrue(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); + assertThat( + fixture + .dsl() + .resultQuery("SELECT to_regclass('account_platform_restriction_births')::TEXT") + .fetchOne(0, String.class)) + .isNull(); + } + + private Event producerFixture(Fixture fixture, Pending pending, boolean lateFailure) { + return producerFixture(fixture, pending, lateFailure, true); + } + + private Event producerFixture( + Fixture fixture, Pending pending, boolean lateFailure, boolean retainReceipt) { + return tx( + fixture, + () -> { + // Fixture-only sole mutation writer. Storage itself never calls these operations. + if (!fixture.fences().sourceMutationPermitted(pending.capture().sourceChange())) + throw new IllegalStateException("Fixture source is not settled"); + var sources = + new AccountAuthoritySourceEvidenceRepository( + fixture.dsl(), fixture.generations(), fixture.outbox()); + var currentSource = + sources + .readCurrentIssuerAccountSources( + "firemud-account-service", pending.request().accountUuid()) + .account(); + var retained = pending.capture().sourceState(); + if (!currentSource.scope().equals(retained.scope()) + || currentSource.generation() != retained.generation() + || currentSource.sourceVersion() != retained.sourceVersion() + || !currentSource.issuanceFence().equals(retained.issuanceFence())) { + throw new IllegalStateException( + "Fixture retained source differs from actual owner readback"); + } + ScopeState advanced = + sources.prepareClosedAccountAdvance(pending.request().accountUuid(), currentSource); + fixture + .dsl() + .execute( + "UPDATE accounts SET email_verified = ?, login_auth_modes = ?, lifecycle_state = ? WHERE account_uuid = ?", + pending.request().desiredState().emailVerified(), + AccountLoginAuthModes.normalize( + String.join(",", pending.request().desiredState().loginAuthModes())), + pending + .request() + .desiredState() + .lifecycleState() + .toLowerCase(java.util.Locale.ROOT), + pending.request().accountUuid()); + Event event = + fixture + .outbox() + .append( + stream(pending.request().accountUuid()), + pending.request().requestId().toString(), + sequence -> { + var sealed = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + pending.request().requestId(), + pending.request().accountUuid(), + Long.toString(advanced.generation()), + Long.toString(advanced.sourceVersion()), + Long.toString(sequence), + pending.request().mutationKinds(), + pending.request().desiredState())); + return new EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + fixture.fences().markSourceCommitted(pending.capture().sourceChange()); + if (retainReceipt) fixture.operations().complete(pending.request(), event, advanced, 1L); + if (lateFailure) + throw new IllegalStateException("Late fixture failure after receipt completion"); + return event; + }); + } + + private Pending pending( + Fixture fixture, + Seed seed, + AccountState before, + AccountState after, + long checkpointSequence, + byte[] checkpointPayload) { + UUID requestId = UUID.randomUUID(); + UUID account = seed.account().getAccountUuid(); + var request = + new AccountSecurityStateMutationRequest( + requestId, + account, + correlation(account, requestId), + seed.source().generation(), + seed.source().sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(before, after), + after); + var draft = + new Capture( + seed.account().getId(), + seed.account().getAccountUuidProvenance(), + before, + seed.source(), + checkpointSequence, + checkpointPayload, + 1L, + null); + byte[] captureBytes = AccountSecurityStateOperationRepository.captureBytes(request, draft); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + Long.toString(seed.source().generation()), + Long.toString(seed.source().sourceVersion()), + stream(account), + Long.toString(checkpointSequence), + captureBytes); + var change = new SourceChange(UUID.randomUUID(), List.of(source), captureBytes); + var capture = + new Capture( + draft.accountId(), + draft.provenance(), + before, + seed.source(), + checkpointSequence, + checkpointPayload, + 1L, + change); + tx( + fixture, + () -> { + fixture.fences().requestSourceChange(change); + return null; + }); + return new Pending(request, capture); + } + + private AccountAuthoritySourceEventReadback sourceReadback(Fixture fixture) { + return new AccountAuthoritySourceEventReadback( + fixture.outbox(), + new AccountPasswordResetOperationRepository(fixture.dsl()), + new AccountLogoutAllOperationRepository(fixture.dsl()), + fixture.operations()); + } + + private AccountAuthoritySourceReader sourceReader(Fixture fixture) { + return new AccountAuthoritySourceReader( + new AccountRepository(fixture.dsl()), + fixture.generations(), + fixture.outbox(), + sourceReadback(fixture), + fixture.transaction().getTransactionManager()); + } + + private Fixture fixture(String version) { + String schema = "security_state_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + migrate(dataSource, schema, version); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + schema, + dataSource, + dsl, + new TransactionTemplate(new DataSourceTransactionManager(dataSource)), + new AccountAuthorityGenerationRepository(dsl), + new AccountAuthorityOutboxRepository(dsl), + new DraftAuthorizationFenceRepository(dsl), + new AccountSecurityStateOperationRepository(dsl)); + } + + private Seed seed(Fixture fixture) { + return tx( + fixture, + () -> { + Account account = new Account(); + String id = UUID.randomUUID().toString().substring(0, 12); + account.setUsername("security-" + id); + account.setEmail(id + "@example.test"); + account.setPasswordHash("synthetic-verifier"); + account = new AccountRepository(fixture.dsl()).save(account); + new AccountAuthoritySourceEvidenceRepository( + fixture.dsl(), fixture.generations(), fixture.outbox()) + .initializeIssuerIfAbsent("firemud-account-service"); + ScopeState source = + fixture.generations().read(AuthorityScope.account(account.getAccountUuid())); + return new Seed(account, source); + }); + } + + private void migrate(DriverManagerDataSource dataSource, String schema, String version) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (version != null) { + configuration.target(version); + } + configuration.load().migrate(); + } + + /** + * Stipulates a V78 historical Account birth using the storage sequence of the pre-V81 API. + * PostgreSQL generates the Account numeric identity and transaction provenance, and the installed + * identity and role triggers generate their paired values. The generation, fence, stream, and + * source inserts follow the V40 AccountRepository birth contract in this same transaction; this + * fixture asserts storage constraints only, not authenticated authority. + */ + private HistoricalAccount seedHistoricalV78Account(Fixture fixture) { + return tx( + fixture, + () -> { + UUID accountUuid = UUID.randomUUID(); + String suffix = UUID.randomUUID().toString(); + var accountRow = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "INSERT INTO accounts (account_uuid, account_uuid_provenance, username, " + + "email, password_hash, role, email_verified, login_auth_modes, " + + "lifecycle_state) " + + "VALUES (?, 'ACCOUNT_REPOSITORY_INSERT', ?, ?, ?, NULL, FALSE, " + + "'PASSWORD,EMAIL_OTP', 'active') " + + "RETURNING id, account_uuid, account_uuid_source_numeric_id, " + + "account_uuid_provenance, account_repository_insert_transaction_id", + accountUuid, + "historical-" + suffix, + suffix + "@example.test", + "historical-password-" + suffix), + "Expected V78 historical Account birth"); + Long accountId = + Objects.requireNonNull(accountRow.get("id", Long.class), "Expected Account id"); + String issuerId = "firemud-account-service"; + String issuerStreamKey = "account:auth-authority:v1:issuer/" + issuerId; + String accountStreamKey = "account:auth-authority:v1:account/" + accountUuid; + + fixture + .dsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, issuer_id, generation, source_version) " + + "VALUES ('ISSUER', ?, 1, 1)", + issuerId); + fixture + .dsl() + .execute( + "INSERT INTO account_authority_outbox_streams " + + "(outbox_stream_key, last_sequence) VALUES (?, 0)", + issuerStreamKey); + fixture + .dsl() + .execute( + "INSERT INTO account_authority_source_records " + + "(outbox_stream_key, scope_kind, issuer_id, account_uuid, " + + "baseline_generation, baseline_source_version, initialization_provenance, " + + "current_generation, current_source_version, last_outbox_sequence) " + + "VALUES (?, 'ISSUER', ?, NULL, 1, 1, 'ISSUER_SCOPE_INSERT', 1, 1, 0)", + issuerStreamKey, + issuerId); + + fixture + .dsl() + .execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) " + + "VALUES ('ACCOUNT', ?, 1, 1)", + accountUuid); + fixture + .dsl() + .execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", + accountUuid); + fixture + .dsl() + .execute( + "INSERT INTO account_authority_outbox_streams " + + "(outbox_stream_key, last_sequence) VALUES (?, 0)", + accountStreamKey); + int insertedSource = + fixture + .dsl() + .execute( + "INSERT INTO account_authority_source_records " + + "(outbox_stream_key, scope_kind, issuer_id, account_uuid, " + + "baseline_generation, baseline_source_version, baseline_issuance_fence, " + + "initialization_provenance, account_source_numeric_id, " + + "account_uuid_provenance, account_repository_insert_transaction_id, " + + "current_generation, current_source_version, current_issuance_fence, " + + "current_issuance_fence_source_version, last_outbox_sequence) " + + "SELECT ?, 'ACCOUNT', NULL, account_row.account_uuid, " + + "generation_row.generation, generation_row.source_version, " + + "fence_row.issuance_fence, account_row.account_uuid_provenance, " + + "account_row.account_uuid_source_numeric_id, " + + "account_row.account_uuid_provenance, " + + "account_row.account_repository_insert_transaction_id, " + + "generation_row.generation, generation_row.source_version, " + + "fence_row.issuance_fence, fence_row.source_version, " + + "stream_row.last_sequence " + + "FROM accounts AS account_row " + + "JOIN account_authority_generations AS generation_row " + + "ON generation_row.scope_kind = 'ACCOUNT' " + + "AND generation_row.account_uuid = account_row.account_uuid " + + "JOIN account_authority_issuance_fences AS fence_row " + + "ON fence_row.account_uuid = account_row.account_uuid " + + "JOIN account_authority_outbox_streams AS stream_row " + + "ON stream_row.outbox_stream_key = ? " + + "WHERE account_row.id = ? AND account_row.account_uuid = ?", + accountStreamKey, + accountStreamKey, + accountId, + accountUuid); + if (insertedSource != 1) { + throw new IllegalStateException("Historical Account source baseline was not inserted"); + } + return new HistoricalAccount(accountId, accountUuid); + }); + } + + private List> snapshotRows(DSLContext dsl, String table, String orderBy) { + return dsl.fetch( + "SELECT encode(convert_to(to_jsonb(retained_row)::TEXT, 'UTF8'), 'hex') " + + "AS row_bytes_hex, retained_row.xmin::TEXT AS xmin FROM " + + table + + " AS retained_row ORDER BY " + + orderBy) + .intoMaps(); + } + + private static T tx(Fixture fixture, Supplier work) { + return fixture.transaction().execute(status -> work.get()); + } + + private static void assertPostgresCheckViolation(Runnable operation, String expectedMessage) { + Throwable failure = catchThrowable(operation::run); + assertThat(failure).isInstanceOf(org.jooq.exception.DataAccessException.class); + Throwable cause = failure; + while (cause.getCause() != null) cause = cause.getCause(); + assertThat(cause) + .isExactlyInstanceOf(PSQLException.class) + .hasMessageContaining(expectedMessage); + assertThat(((PSQLException) cause).getSQLState()).isEqualTo("23514"); + } + + private static AccountState state(boolean verified) { + return new AccountState(verified, List.of("EMAIL_OTP", "PASSWORD"), List.of(), "ACTIVE"); + } + + private static String stream(Seed seed) { + return stream(seed.account().getAccountUuid()); + } + + private static String stream(UUID account) { + return "account:auth-authority:v1:account/" + account; + } + + private static byte[] correlation(UUID actor, UUID operation) { + return ("{\"actorAccountUuid\":\"" + + actor + + "\",\"ownerEvidenceDigest\":\"sha256:" + + "a".repeat(64) + + "\",\"ownerOperationId\":\"" + + operation + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transaction, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox, + DraftAuthorizationFenceRepository fences, + AccountSecurityStateOperationRepository operations) {} + + private record Seed(Account account, ScopeState source) {} + + private record HistoricalAccount(Long accountId, UUID accountUuid) {} + + private record Pending(AccountSecurityStateMutationRequest request, Capture capture) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java new file mode 100644 index 0000000000..fc0fd83b27 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java @@ -0,0 +1,105 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import org.junit.jupiter.api.Test; + +class AccountLogoutRequestDigestTest { + private static final UUID LOGOUT_ALL_ACCOUNT = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TOKEN_LOGOUT_ACCOUNT = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void accountLogoutAllMatchesFixedRequestDigestV1PreimageAndDigestVector() { + String tokenHash = "a".repeat(64); + + assertThat( + AccountLogoutRequestDigest.accountLogoutAllPreimageHex( + LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isEqualTo( + compactHex( + """ + 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131383a4143434f554e545f4c4f474f55545f414c4c31363a7375626a6563744163636f756e744964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d31313131313131313131313131323a746f6b656e50726f66696c65363a737472696e673131303a636f6e74726f6c2d756931383a70726573656e746564546f6b656e48617368363a737472696e673136343a61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161 + """)); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isEqualTo("78f999be5a5bdb0a5bc4517336ad6899b2383c8058b0bb8f76fe67eb67dea020"); + } + + @Test + void tokenLogoutMatchesFixedRequestDigestV1PreimageAndDigestVector() { + String tokenHash = "b".repeat(64); + + assertThat( + AccountLogoutRequestDigest.tokenLogoutPreimageHex( + TOKEN_LOGOUT_ACCOUNT, "player-bootstrap", tokenHash)) + .isEqualTo( + compactHex( + """ + 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131323a544f4b454e5f4c4f474f555431363a7375626a6563744163636f756e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231323a746f6b656e50726f66696c65363a737472696e673131363a706c617965722d626f6f747374726170393a746f6b656e48617368363a737472696e673136343a62626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262 + """)); + assertThat( + AccountLogoutRequestDigest.tokenLogout( + TOKEN_LOGOUT_ACCOUNT, "player-bootstrap", tokenHash)) + .isEqualTo("21c085ddf384d4ab3d32c04f37601e710240d11ffe1be64531ee780cf2fcdee0"); + } + + @Test + void eachClosedTupleFieldChangesTheDigest() { + String tokenHash = "a".repeat(64); + String original = + AccountLogoutRequestDigest.accountLogoutAll(LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash); + + assertThat(AccountLogoutRequestDigest.tokenLogout(LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + TOKEN_LOGOUT_ACCOUNT, "control-ui", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "player-bootstrap", tokenHash)) + .isNotEqualTo(original); + assertThat( + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "control-ui", "b".repeat(64))) + .isNotEqualTo(original); + } + + @Test + void rejectsUnsupportedProfilesNoncanonicalAccountIdentityAndMalformedTokenHashes() { + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "private-player-delegation", "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("token profile"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.accountLogoutAll( + new UUID(0L, 0L), "control-ui", "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil Account UUID"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.tokenLogout( + LOGOUT_ALL_ACCOUNT, "control-ui", "A".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase SHA-256 hex"); + assertThatThrownBy( + () -> + AccountLogoutRequestDigest.tokenLogout( + LOGOUT_ALL_ACCOUNT, "control-ui", "a".repeat(63))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lowercase SHA-256 hex"); + } + + private static String compactHex(String hex) { + return hex.replaceAll("\\s+", ""); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java new file mode 100644 index 0000000000..d1085cf5b3 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java @@ -0,0 +1,182 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateRequestDigest; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import org.junit.jupiter.api.Test; + +class AccountSecurityStateMutationRequestTest { + private static final UUID REQUEST = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final List KINDS = List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); + + @Test + void exactRequestFramesRetainCallerAndStateBytesAndFixedDigest() { + var request = + request( + REQUEST, ACCOUNT, caller(ACCOUNT, REQUEST, "a".repeat(64)), 1L, 1L, KINDS, state(true)); + ByteBuffer bytes = ByteBuffer.wrap(AccountSecurityStateRequestDigest.requestBytes(request)); + assertThat(readFrame(bytes)).isEqualTo("firemud/account/security-state/request/v1"); + assertThat(readFrame(bytes)).isEqualTo(REQUEST.toString()); + assertThat(readFrame(bytes)).isEqualTo(ACCOUNT.toString()); + assertThat(readFrame(bytes)) + .isEqualTo(new String(request.callerProofBinding(), StandardCharsets.UTF_8)); + assertThat(readFrame(bytes)).isEqualTo("1"); + assertThat(readFrame(bytes)).isEqualTo("1"); + assertThat(readFrame(bytes)).isEqualTo("1"); + assertThat(readFrame(bytes)).isEqualTo("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); + assertThat(readFrame(bytes)) + .isEqualTo( + "{\"emailVerified\":true,\"globalRoles\":[],\"lifecycleState\":\"ACTIVE\",\"loginAuthModes\":[\"EMAIL_OTP\",\"PASSWORD\"]}"); + assertThat(bytes.hasRemaining()).isFalse(); + assertThat(AccountSecurityStateRequestDigest.digest(request)) + .isEqualTo("604a354594c3a0b5f882224d44ad40bc8a5ce67c2afa704e6f470f79d0e8ee30"); + } + + @Test + void everyOriginalSemanticBindingChangesDigestIncludingCallerTargetStateAndKinds() { + var original = + request( + REQUEST, ACCOUNT, caller(ACCOUNT, REQUEST, "a".repeat(64)), 1L, 1L, KINDS, state(true)); + UUID other = UUID.fromString("33333333-3333-4333-8333-333333333333"); + for (var changed : + List.of( + request(other, ACCOUNT, original.callerProofBinding(), 1L, 1L, KINDS, state(true)), + request(REQUEST, other, original.callerProofBinding(), 1L, 1L, KINDS, state(true)), + request( + REQUEST, + ACCOUNT, + caller(other, REQUEST, "a".repeat(64)), + 1L, + 1L, + KINDS, + state(true)), + request( + REQUEST, + ACCOUNT, + caller(ACCOUNT, other, "a".repeat(64)), + 1L, + 1L, + KINDS, + state(true)), + request( + REQUEST, + ACCOUNT, + caller(ACCOUNT, REQUEST, "b".repeat(64)), + 1L, + 1L, + KINDS, + state(true)), + request(REQUEST, ACCOUNT, original.callerProofBinding(), 2L, 1L, KINDS, state(true)), + request(REQUEST, ACCOUNT, original.callerProofBinding(), 1L, 2L, KINDS, state(true)), + request(REQUEST, ACCOUNT, original.callerProofBinding(), 1L, 1L, KINDS, state(false)), + request( + REQUEST, + ACCOUNT, + original.callerProofBinding(), + 1L, + 1L, + List.of("LOGIN_AUTH_MODES_CHANGED"), + state(true)))) { + assertThat(AccountSecurityStateRequestDigest.digest(changed)) + .isNotEqualTo(AccountSecurityStateRequestDigest.digest(original)); + } + } + + @Test + void closedCorrelationRejectsAssertionsCredentialsNullsAndUnknownFields() { + byte[] original = caller(ACCOUNT, REQUEST, "a".repeat(64)); + for (String extra : List.of("password", "token", "otp", "authenticated", "globalRoles")) { + String value = new String(original, StandardCharsets.UTF_8); + byte[] changed = + (value.substring(0, value.length() - 1) + ",\"" + extra + "\":\"asserted\"}") + .getBytes(StandardCharsets.UTF_8); + assertThatThrownBy(() -> request(REQUEST, ACCOUNT, changed, 1L, 1L, KINDS, state(true))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + request( + REQUEST, + ACCOUNT, + "{}".getBytes(StandardCharsets.UTF_8), + 1L, + 1L, + KINDS, + state(true))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request(REQUEST, ACCOUNT, original, 0L, 1L, KINDS, state(true))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + request(REQUEST, ACCOUNT, original, 1L, 1L, List.of("PASSWORD_RESET"), state(true))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requestCopiesInputsAndStateHasOnlySharedCodecPolicyVocabulary() { + byte[] bytes = caller(ACCOUNT, REQUEST, "a".repeat(64)); + var request = request(REQUEST, ACCOUNT, bytes, 1L, 1L, KINDS, state(true)); + byte[] retained = request.callerProofBinding(); + bytes[0] = 0; + retained[0] = 0; + assertThat(request.callerProofBinding()[0]).isEqualTo((byte) '{'); + assertThatThrownBy(() -> request.mutationKinds().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + request( + REQUEST, + ACCOUNT, + request.callerProofBinding(), + 1L, + 1L, + KINDS, + new AccountState(true, List.of("PASSWORD"), List.of("admin"), "ACTIVE"))) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + AccountSecurityStateMutationRequest.parseCanonicalState( + request.canonicalDesiredState())) + .isEqualTo(request.desiredState()); + } + + private static AccountSecurityStateMutationRequest request( + UUID request, + UUID account, + byte[] caller, + long generation, + long version, + List kinds, + AccountState state) { + return new AccountSecurityStateMutationRequest( + request, account, caller, generation, version, kinds, state); + } + + private static AccountState state(boolean verified) { + return new AccountState(verified, List.of("EMAIL_OTP", "PASSWORD"), List.of(), "ACTIVE"); + } + + private static byte[] caller(UUID actor, UUID operation, String digest) { + return ("{\"actorAccountUuid\":\"" + + actor + + "\",\"ownerEvidenceDigest\":\"sha256:" + + digest + + "\",\"ownerOperationId\":\"" + + operation + + "\",\"schemaVersion\":\"account-security-state-caller-correlation/v1\"}") + .getBytes(StandardCharsets.UTF_8); + } + + private static String readFrame(ByteBuffer bytes) { + byte[] field = new byte[bytes.getInt()]; + bytes.get(field); + return new String(field, StandardCharsets.UTF_8); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java index 552b2b9195..303ae52eb2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java @@ -3,21 +3,184 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Map; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class AccountLogoutAllAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/" + + "account-auth-logout-all-event-v1-vectors.json"; private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; private static final String REQUEST_ID = "22222222-2222-4222-8222-222222222222"; private static final String STREAM = AccountLogoutAllAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + ACCOUNT_ID; private static final String LARGE_COUNTER = "9223372036854775807"; private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (InputStream stream = + AccountLogoutAllAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void fixedVectorsVerifySealAndArbitraryPrecisionCounters() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-logout-all-event-vectors/v1"); + + JsonNode validEvents = vectors.path("validEvents"); + assertThat(validEvents.isArray()).as("validEvents is an array").isTrue(); + assertThat(validEvents.size()).as("validEvents is nonempty").isPositive(); + for (JsonNode vector : validEvents) { + JsonNode wireEvent = vector.path("event"); + var verified = AccountLogoutAllAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.eventDigest()).isEqualTo(wireEvent.path("eventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo( + vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + + ObjectNode preimage = (ObjectNode) wireEvent.deepCopy(); + preimage.remove("eventDigest"); + Map preimageMap = JSON.convertValue(preimage, new TypeReference<>() {}); + var sealed = AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(sealed.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + var large = + AccountLogoutAllAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(1).path("event").toString()); + assertThat(large.outboxSequence()).isEqualTo("18446744073709551616000000000000000001"); + assertThat(large.accountAuthorityGeneration()) + .isEqualTo("92233720368547758081234567890123456789"); + assertThat(large.sourceVersion()).isEqualTo("90071992547409931234567890123456789"); + } + + @Test + void changedDeclaredFieldsCannotReuseTheOriginalDigest() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + + JsonNode mutations = vectors.path("changedDeclaredFieldMutations"); + assertThat(mutations.isArray()).as("changedDeclaredFieldMutations is an array").isTrue(); + assertThat(mutations.size()).as("changedDeclaredFieldMutations is nonempty").isPositive(); + for (JsonNode mutation : mutations) { + ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); + JsonNode changes = mutation.path("changes"); + changes + .fieldNames() + .forEachRemaining(field -> changedWire.set(field, changes.get(field).deepCopy())); + ObjectNode changedPreimage = (ObjectNode) changedWire.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + + var sealed = AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()) + .as(mutation.path("name").asText()) + .isNotEqualTo(originalDigest); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + } + + @Test + void canonicalPropertyReorderingPreservesTheFixedEvent() { + JsonNode vector = vectors.path("validEvents").get(0); + JsonNode event = vector.path("event"); + ObjectNode reordered = JSON.createObjectNode(); + JsonNode propertyOrder = vectors.path("canonicalReorderedPropertyOrder"); + assertThat(propertyOrder.isArray()).as("canonicalReorderedPropertyOrder is an array").isTrue(); + assertThat(propertyOrder.size()).as("canonicalReorderedPropertyOrder is nonempty").isPositive(); + for (JsonNode field : propertyOrder) { + String fieldName = field.asText(); + reordered.set(fieldName, event.path(fieldName).deepCopy()); + } + + var verified = AccountLogoutAllAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + @Test + void invalidMutationVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + JsonNode mutations = vectors.path("invalidMutations"); + assertThat(mutations.isArray()).as("invalidMutations is an array").isTrue(); + assertThat(mutations.size()).as("invalidMutations is nonempty").isPositive(); + for (JsonNode mutation : mutations) { + ObjectNode changed = (ObjectNode) baseline.deepCopy(); + applyMutation(changed, mutation); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + + if (!"/eventDigest".equals(mutation.path("path").asText())) { + ObjectNode changedPreimage = (ObjectNode) changed.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap)) + .as(mutation.path("name").asText() + " invalid preimage") + .isInstanceOf(IllegalArgumentException.class); + } + } + } + + @Test + void rejectsUppercaseRequestIdWhenEventIdentityBindingMatches() { + String uppercaseRequestId = "22222222-2222-4222-8222-22222222222A"; + ObjectNode changed = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + changed.put("requestId", uppercaseRequestId); + changed.put( + "eventId", AccountLogoutAllAuthorityEventV1Codec.EVENT_ID_PREFIX + uppercaseRequestId); + changed.remove("eventDigest"); + Map preimageMap = JSON.convertValue(changed, new TypeReference<>() {}); + + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.seal(preimageMap)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requestId") + .hasMessageContaining("canonical lowercase non-nil UUID"); + } + + private static void applyMutation(ObjectNode root, JsonNode mutation) { + String[] path = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < path.length - 1; index++) { + parent = parent.path(path[index]); + } + if (!(parent instanceof ObjectNode object)) { + throw new IllegalArgumentException("Mutation parent must be an object: " + mutation); + } + String field = path[path.length - 1]; + switch (mutation.path("op").asText()) { + case "add", "replace" -> object.set(field, mutation.path("value").deepCopy()); + case "remove" -> object.remove(field); + default -> throw new IllegalArgumentException("Unsupported mutation operation: " + mutation); + } + } @Test void sealsAndVerifiesRequestDerivedLogoutIdentityAndLargeCounters() throws Exception { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java index e4c64d4a54..39c330da6e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java @@ -3,20 +3,167 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Map; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class PasswordResetAuthorityEventV1CodecTest { + private static final String VECTOR_RESOURCE = + "/net/firedevops/firemud/common/account/authority/" + + "account-auth-password-reset-event-v1-vectors.json"; private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; private static final String STREAM = PasswordResetAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + ACCOUNT_ID; private static final String LARGE_COUNTER = "9223372036854775807"; private static final ObjectMapper JSON = new ObjectMapper(); + private static JsonNode vectors; + + @BeforeAll + static void loadVectors() throws IOException { + try (InputStream stream = + PasswordResetAuthorityEventV1CodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("Missing shared event vectors: " + VECTOR_RESOURCE); + } + vectors = JSON.readTree(stream); + } + } + + @Test + void fixedVectorsVerifySealAndArbitraryPrecisionCounters() throws Exception { + assertThat(vectors.path("schemaVersion").asText()) + .isEqualTo("account-auth-password-reset-event-vectors/v1"); + + JsonNode validEvents = vectors.path("validEvents"); + assertThat(validEvents.isArray()).as("validEvents is an array").isTrue(); + assertThat(validEvents.size()).as("validEvents is nonempty").isPositive(); + for (JsonNode vector : validEvents) { + JsonNode wireEvent = vector.path("event"); + var verified = PasswordResetAuthorityEventV1Codec.verify(wireEvent.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.eventDigest()).isEqualTo(wireEvent.path("eventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo( + vector.path("expectedCanonicalJson").asText().getBytes(StandardCharsets.UTF_8)); + assertThat(verified.canonicalJsonUtf8()) + .isEqualTo(Rfc8785CanonicalJson.canonicalizeUtf8(wireEvent.toString())); + + ObjectNode preimage = (ObjectNode) wireEvent.deepCopy(); + preimage.remove("eventDigest"); + Map preimageMap = JSON.convertValue(preimage, new TypeReference<>() {}); + var sealed = PasswordResetAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(sealed.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + var large = + PasswordResetAuthorityEventV1Codec.verify( + vectors.path("validEvents").get(1).path("event").toString()); + assertThat(large.outboxSequence()).isEqualTo("18446744073709551616000000000000000001"); + assertThat(large.accountAuthorityGeneration()) + .isEqualTo("92233720368547758081234567890123456789"); + assertThat(large.sourceVersion()).isEqualTo("90071992547409931234567890123456789"); + } + + @Test + void changedDeclaredFieldsCannotReuseTheOriginalDigest() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + String originalDigest = baseline.path("eventDigest").asText(); + + JsonNode mutations = vectors.path("changedDeclaredFieldMutations"); + assertThat(mutations.isArray()).as("changedDeclaredFieldMutations is an array").isTrue(); + assertThat(mutations.size()).as("changedDeclaredFieldMutations is nonempty").isPositive(); + for (JsonNode mutation : mutations) { + ObjectNode changedWire = (ObjectNode) baseline.deepCopy(); + JsonNode changes = mutation.path("changes"); + changes + .fieldNames() + .forEachRemaining(field -> changedWire.set(field, changes.get(field).deepCopy())); + ObjectNode changedPreimage = (ObjectNode) changedWire.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + + var sealed = PasswordResetAuthorityEventV1Codec.seal(preimageMap); + assertThat(sealed.eventDigest()) + .as(mutation.path("name").asText()) + .isNotEqualTo(originalDigest); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(changedWire.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + } + + @Test + void canonicalPropertyReorderingPreservesTheFixedEvent() { + JsonNode vector = vectors.path("validEvents").get(0); + JsonNode event = vector.path("event"); + ObjectNode reordered = JSON.createObjectNode(); + JsonNode propertyOrder = vectors.path("canonicalReorderedPropertyOrder"); + assertThat(propertyOrder.isArray()).as("canonicalReorderedPropertyOrder is an array").isTrue(); + assertThat(propertyOrder.size()).as("canonicalReorderedPropertyOrder is nonempty").isPositive(); + for (JsonNode field : propertyOrder) { + String fieldName = field.asText(); + reordered.set(fieldName, event.path(fieldName).deepCopy()); + } + + var verified = PasswordResetAuthorityEventV1Codec.verify(reordered.toString()); + assertThat(verified.eventDigest()).isEqualTo(vector.path("expectedEventDigest").asText()); + assertThat(verified.canonicalJson()).isEqualTo(vector.path("expectedCanonicalJson").asText()); + } + + @Test + void invalidMutationVectorsAreRejected() { + ObjectNode baseline = (ObjectNode) vectors.path("validEvents").get(0).path("event").deepCopy(); + JsonNode mutations = vectors.path("invalidMutations"); + assertThat(mutations.isArray()).as("invalidMutations is an array").isTrue(); + assertThat(mutations.size()).as("invalidMutations is nonempty").isPositive(); + for (JsonNode mutation : mutations) { + ObjectNode changed = (ObjectNode) baseline.deepCopy(); + applyMutation(changed, mutation); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(changed.toString())) + .as(mutation.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + + if (!"/eventDigest".equals(mutation.path("path").asText())) { + ObjectNode changedPreimage = (ObjectNode) changed.deepCopy(); + changedPreimage.remove("eventDigest"); + Map preimageMap = + JSON.convertValue(changedPreimage, new TypeReference<>() {}); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.seal(preimageMap)) + .as(mutation.path("name").asText() + " invalid preimage") + .isInstanceOf(IllegalArgumentException.class); + } + } + } + + private static void applyMutation(ObjectNode root, JsonNode mutation) { + String[] path = mutation.path("path").asText().substring(1).split("/"); + JsonNode parent = root; + for (int index = 0; index < path.length - 1; index++) { + parent = parent.path(path[index]); + } + if (!(parent instanceof ObjectNode object)) { + throw new IllegalArgumentException("Mutation parent must be an object: " + mutation); + } + String field = path[path.length - 1]; + switch (mutation.path("op").asText()) { + case "add", "replace" -> object.set(field, mutation.path("value").deepCopy()); + case "remove" -> object.remove(field); + default -> throw new IllegalArgumentException("Unsupported mutation operation: " + mutation); + } + } @Test void sealsAndVerifiesBoundPasswordResetEvidenceWithLargeStringCounters() throws Exception { diff --git a/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json new file mode 100644 index 0000000000..ca03aeb191 --- /dev/null +++ b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-logout-all-event-v1-vectors.json @@ -0,0 +1,103 @@ +{ + "schemaVersion": "account-auth-logout-all-event-vectors/v1", + "validEvents": [ + { + "name": "standard-account-logout-all-cutoff", + "expectedEventDigest": "sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"2\",\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"2\",\"outboxSequence\":\"1\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\"},\"eventDigest\":\"sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439\",\"eventId\":\"account-logout-all-event-v1:22222222-2222-4222-8222-222222222222\",\"eventType\":\"LOGOUT_ALL_COMMITTED\",\"outboxSequence\":\"1\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"schemaVersion\":\"account-auth-logout-all-event/v1\",\"sourceScope\":\"account/11111111-1111-4111-8111-111111111111\",\"sourceVersion\":\"2\"}", + "event": { + "schemaVersion": "account-auth-logout-all-event/v1", + "eventType": "LOGOUT_ALL_COMMITTED", + "eventId": "account-logout-all-event-v1:22222222-2222-4222-8222-222222222222", + "requestId": "22222222-2222-4222-8222-222222222222", + "accountId": "11111111-1111-4111-8111-111111111111", + "sourceScope": "account/11111111-1111-4111-8111-111111111111", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "1", + "accountAuthorityGeneration": "2", + "sourceVersion": "2", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "2", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "1" + }, + "eventDigest": "sha256:8bcd1a2c82b807a59f01cab599dfabc43d7b687fba80709ef9aa54590272f439" + } + }, + { + "name": "counters-above-javascript-safe-integer-and-signed-long", + "expectedEventDigest": "sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"accountId\":\"11111111-1111-4111-8111-111111111111\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\"},\"eventDigest\":\"sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7\",\"eventId\":\"account-logout-all-event-v1:22222222-2222-4222-8222-222222222222\",\"eventType\":\"LOGOUT_ALL_COMMITTED\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111\",\"requestId\":\"22222222-2222-4222-8222-222222222222\",\"schemaVersion\":\"account-auth-logout-all-event/v1\",\"sourceScope\":\"account/11111111-1111-4111-8111-111111111111\",\"sourceVersion\":\"90071992547409931234567890123456789\"}", + "event": { + "schemaVersion": "account-auth-logout-all-event/v1", + "eventType": "LOGOUT_ALL_COMMITTED", + "eventId": "account-logout-all-event-v1:22222222-2222-4222-8222-222222222222", + "requestId": "22222222-2222-4222-8222-222222222222", + "accountId": "11111111-1111-4111-8111-111111111111", + "sourceScope": "account/11111111-1111-4111-8111-111111111111", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "18446744073709551616000000000000000001", + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "sourceVersion": "90071992547409931234567890123456789", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "outboxSequence": "18446744073709551616000000000000000001" + }, + "eventDigest": "sha256:c5938750b1da3b163fdadc80913667430052797e91671f098189f86e120e44d7" + } + } + ], + "changedDeclaredFieldMutations": [ + {"name": "request-and-derived-event-identities", "changes": {"requestId": "33333333-3333-4333-8333-333333333333", "eventId": "account-logout-all-event-v1:33333333-3333-4333-8333-333333333333"}}, + {"name": "account-identity-and-derived-scope", "changes": {"accountId": "44444444-4444-4444-8444-444444444444", "sourceScope": "account/44444444-4444-4444-8444-444444444444", "outboxStreamKey": "account:auth-authority:v1:account/44444444-4444-4444-8444-444444444444", "accountSecurityCutoff": {"accountAuthorityGeneration": "2", "outboxStreamKey": "account:auth-authority:v1:account/44444444-4444-4444-8444-444444444444", "outboxSequence": "1"}}}, + {"name": "outbox-sequence-and-cutoff", "changes": {"outboxSequence": "3", "accountSecurityCutoff": {"accountAuthorityGeneration": "2", "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", "outboxSequence": "3"}}}, + {"name": "account-authority-generation-and-cutoff", "changes": {"accountAuthorityGeneration": "4", "accountSecurityCutoff": {"accountAuthorityGeneration": "4", "outboxStreamKey": "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", "outboxSequence": "1"}}}, + {"name": "source-version", "changes": {"sourceVersion": "3"}} + ], + "canonicalReorderedPropertyOrder": [ + "sourceVersion", "requestId", "outboxSequence", "outboxStreamKey", "eventType", + "eventId", "eventDigest", "accountId", "accountAuthorityGeneration", + "accountSecurityCutoff", "schemaVersion", "sourceScope" + ], + "invalidMutations": [ + {"name": "unsupported-schema", "op": "replace", "path": "/schemaVersion", "value": "account-auth-logout-all-event/v2"}, + {"name": "password-reset-schema-is-not-an-alias", "op": "replace", "path": "/schemaVersion", "value": "account-auth-password-reset-event/v1"}, + {"name": "unsupported-event-type", "op": "replace", "path": "/eventType", "value": "PASSWORD_RESET_COMMITTED"}, + {"name": "numeric-event-type", "op": "replace", "path": "/eventType", "value": 7}, + {"name": "missing-event-id", "op": "remove", "path": "/eventId"}, + {"name": "null-event-id", "op": "replace", "path": "/eventId", "value": null}, + {"name": "missing-request-id", "op": "remove", "path": "/requestId"}, + {"name": "nil-request-id", "op": "replace", "path": "/requestId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-request-id", "op": "replace", "path": "/requestId", "value": "22222222-2222-4222-8222-22222222222A"}, + {"name": "request-event-identity-mismatch", "op": "replace", "path": "/requestId", "value": "33333333-3333-4333-8333-333333333333"}, + {"name": "wrong-event-id-prefix", "op": "replace", "path": "/eventId", "value": "password-reset-event-v1:22222222-2222-4222-8222-222222222222"}, + {"name": "nil-account-id", "op": "replace", "path": "/accountId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-account-id", "op": "replace", "path": "/accountId", "value": "11111111-1111-4111-8111-11111111111A"}, + {"name": "numeric-account-id", "op": "replace", "path": "/accountId", "value": 111}, + {"name": "mismatched-source-scope", "op": "replace", "path": "/sourceScope", "value": "account/22222222-2222-4222-8222-222222222222"}, + {"name": "mismatched-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": "account:auth-authority:v1:account/22222222-2222-4222-8222-222222222222"}, + {"name": "numeric-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": 1}, + {"name": "zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "leading-zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "01"}, + {"name": "negative-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "-1"}, + {"name": "numeric-account-generation", "op": "replace", "path": "/accountAuthorityGeneration", "value": 2}, + {"name": "zero-source-version", "op": "replace", "path": "/sourceVersion", "value": "0"}, + {"name": "null-source-version", "op": "replace", "path": "/sourceVersion", "value": null}, + {"name": "null-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": null}, + {"name": "array-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": []}, + {"name": "missing-cutoff-sequence", "op": "remove", "path": "/accountSecurityCutoff/outboxSequence"}, + {"name": "extra-cutoff-field", "op": "add", "path": "/accountSecurityCutoff/issuanceFence", "value": "4"}, + {"name": "numeric-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": 2}, + {"name": "mismatched-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": "3"}, + {"name": "mismatched-cutoff-stream", "op": "replace", "path": "/accountSecurityCutoff/outboxStreamKey", "value": "account:auth-authority:v1:account/22222222-2222-4222-8222-222222222222"}, + {"name": "mismatched-cutoff-sequence", "op": "replace", "path": "/accountSecurityCutoff/outboxSequence", "value": "2"}, + {"name": "unknown-fence-field", "op": "add", "path": "/issuanceFence", "value": "9"}, + {"name": "forbidden-authority-tuple", "op": "add", "path": "/authorityTuple", "value": {}}, + {"name": "forbidden-presented-token-identity", "op": "add", "path": "/tokenHash", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "forbidden-recipient-tuple", "op": "add", "path": "/recipientAuthorityTuple", "value": {}}, + {"name": "missing-digest", "op": "remove", "path": "/eventDigest"}, + {"name": "malformed-digest", "op": "replace", "path": "/eventDigest", "value": "SHA256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "digest-mismatch", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +} diff --git a/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json new file mode 100644 index 0000000000..d564498b3c --- /dev/null +++ b/services/common-platform-core/src/test/resources/net/firedevops/firemud/common/account/authority/account-auth-password-reset-event-v1-vectors.json @@ -0,0 +1,95 @@ +{ + "schemaVersion": "account-auth-password-reset-event-vectors/v1", + "validEvents": [ + { + "name": "standard-password-reset-cutoff", + "expectedEventDigest": "sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"7\",\"accountId\":\"018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"7\",\"outboxSequence\":\"3\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\"},\"eventDigest\":\"sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07\",\"eventId\":\"password-reset-event-001\",\"eventType\":\"PASSWORD_RESET_COMMITTED\",\"outboxSequence\":\"3\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"requestId\":\"password-reset-request-001\",\"schemaVersion\":\"account-auth-password-reset-event/v1\",\"sourceScope\":\"account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"sourceVersion\":\"12\"}", + "event": { + "schemaVersion": "account-auth-password-reset-event/v1", + "eventType": "PASSWORD_RESET_COMMITTED", + "eventId": "password-reset-event-001", + "requestId": "password-reset-request-001", + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "3", + "accountAuthorityGeneration": "7", + "sourceVersion": "12", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "7", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "3" + }, + "eventDigest": "sha256:9d276449fcd7388ff4dee66f5d69f92c666e15c641ab0f21990104ac9b9bea07" + } + }, + { + "name": "counters-above-javascript-safe-integer-and-signed-long", + "expectedEventDigest": "sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65", + "expectedCanonicalJson": "{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"accountId\":\"018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"accountSecurityCutoff\":{\"accountAuthorityGeneration\":\"92233720368547758081234567890123456789\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\"},\"eventDigest\":\"sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65\",\"eventId\":\"password-reset-event-large-counters\",\"eventType\":\"PASSWORD_RESET_COMMITTED\",\"outboxSequence\":\"18446744073709551616000000000000000001\",\"outboxStreamKey\":\"account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"requestId\":\"password-reset-request-large-counters\",\"schemaVersion\":\"account-auth-password-reset-event/v1\",\"sourceScope\":\"account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a\",\"sourceVersion\":\"90071992547409931234567890123456789\"}", + "event": { + "schemaVersion": "account-auth-password-reset-event/v1", + "eventType": "PASSWORD_RESET_COMMITTED", + "eventId": "password-reset-event-large-counters", + "requestId": "password-reset-request-large-counters", + "accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "18446744073709551616000000000000000001", + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "sourceVersion": "90071992547409931234567890123456789", + "accountSecurityCutoff": { + "accountAuthorityGeneration": "92233720368547758081234567890123456789", + "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", + "outboxSequence": "18446744073709551616000000000000000001" + }, + "eventDigest": "sha256:2fef25b7ec2fc79dc95e07352e0477214835f09ee287d0233bd937488c8b2f65" + } + } + ], + "changedDeclaredFieldMutations": [ + {"name": "event-id", "changes": {"eventId": "password-reset-event-002"}}, + {"name": "request-id", "changes": {"requestId": "password-reset-request-002"}}, + {"name": "account-identity-and-derived-scope", "changes": {"accountId": "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", "sourceScope": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", "accountSecurityCutoff": {"accountAuthorityGeneration": "7", "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b", "outboxSequence": "3"}}}, + {"name": "outbox-sequence-and-cutoff", "changes": {"outboxSequence": "4", "accountSecurityCutoff": {"accountAuthorityGeneration": "7", "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", "outboxSequence": "4"}}}, + {"name": "account-authority-generation-and-cutoff", "changes": {"accountAuthorityGeneration": "8", "accountSecurityCutoff": {"accountAuthorityGeneration": "8", "outboxStreamKey": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a", "outboxSequence": "3"}}}, + {"name": "source-version", "changes": {"sourceVersion": "13"}} + ], + "canonicalReorderedPropertyOrder": [ + "sourceVersion", "requestId", "outboxSequence", "outboxStreamKey", "eventType", + "eventId", "eventDigest", "accountId", "accountAuthorityGeneration", + "accountSecurityCutoff", "schemaVersion", "sourceScope" + ], + "invalidMutations": [ + {"name": "unsupported-schema", "op": "replace", "path": "/schemaVersion", "value": "account-auth-password-reset-event/v2"}, + {"name": "unsupported-event-type", "op": "replace", "path": "/eventType", "value": "PASSWORD_RESET_REQUESTED"}, + {"name": "missing-required-event-id", "op": "remove", "path": "/eventId"}, + {"name": "empty-event-id", "op": "replace", "path": "/eventId", "value": ""}, + {"name": "missing-required-request-id", "op": "remove", "path": "/requestId"}, + {"name": "null-account-id", "op": "replace", "path": "/accountId", "value": null}, + {"name": "nil-account-id", "op": "replace", "path": "/accountId", "value": "00000000-0000-0000-0000-000000000000"}, + {"name": "uppercase-account-id", "op": "replace", "path": "/accountId", "value": "018F8F0A-1A6B-7B13-8D04-5F6E7D8C9B0A"}, + {"name": "mismatched-source-scope", "op": "replace", "path": "/sourceScope", "value": "account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "mismatched-stream-key", "op": "replace", "path": "/outboxStreamKey", "value": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "numeric-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": 3}, + {"name": "zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "0"}, + {"name": "leading-zero-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "03"}, + {"name": "negative-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "-3"}, + {"name": "exponent-outbox-sequence", "op": "replace", "path": "/outboxSequence", "value": "3e0"}, + {"name": "numeric-account-generation", "op": "replace", "path": "/accountAuthorityGeneration", "value": 7}, + {"name": "zero-source-version", "op": "replace", "path": "/sourceVersion", "value": "0"}, + {"name": "null-security-cutoff", "op": "replace", "path": "/accountSecurityCutoff", "value": null}, + {"name": "missing-cutoff-sequence", "op": "remove", "path": "/accountSecurityCutoff/outboxSequence"}, + {"name": "extra-cutoff-field", "op": "add", "path": "/accountSecurityCutoff/issuanceFence", "value": "4"}, + {"name": "mismatched-cutoff-generation", "op": "replace", "path": "/accountSecurityCutoff/accountAuthorityGeneration", "value": "8"}, + {"name": "mismatched-cutoff-stream", "op": "replace", "path": "/accountSecurityCutoff/outboxStreamKey", "value": "account:auth-authority:v1:account/018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0b"}, + {"name": "mismatched-cutoff-sequence", "op": "replace", "path": "/accountSecurityCutoff/outboxSequence", "value": "4"}, + {"name": "unknown-fence-field", "op": "add", "path": "/issuanceFence", "value": "9"}, + {"name": "forbidden-authority-tuple", "op": "add", "path": "/authorityTuple", "value": {}}, + {"name": "forbidden-credential-material", "op": "add", "path": "/passwordVerifier", "value": "secret"}, + {"name": "missing-digest", "op": "remove", "path": "/eventDigest"}, + {"name": "malformed-digest", "op": "replace", "path": "/eventDigest", "value": "SHA256:1111111111111111111111111111111111111111111111111111111111111111"}, + {"name": "digest-mismatch", "op": "replace", "path": "/eventDigest", "value": "sha256:1111111111111111111111111111111111111111111111111111111111111111"} + ] +}