From a8ec25148a3e905c111864ee33acb72351bdc052 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 15:20:32 +1300 Subject: [PATCH 01/12] Retain Account security-state receipts and exact encrypted issuance results --- .github/workflows/ci.yml | 39 + .../account-service/api-contracts.md | 4 +- .../account-service/runtime-and-data.md | 2 + .../player-access-and-session.md | 8 +- .../dto/AccountControlUiIssuanceRequest.java | 30 + ...AccountControlUiIssuanceRequestDigest.java | 42 + .../AccountSecurityStateMutationRequest.java | 173 ++++ .../AccountSecurityStateRequestDigest.java | 51 ++ .../AccountControlUiIssuanceOperation.java | 242 ++++++ ...tControlUiIssuanceOperationRepository.java | 478 +++++++++++ ...countSecurityStateOperationRepository.java | 658 ++++++++++++++ .../AccountAuthoritySourceEventReadback.java | 217 +++-- ...countMembershipAuthorityEventProducer.java | 5 +- .../service/impl/AccountServiceImpl.java | 5 +- ...V65__account_security_state_operations.sql | 371 ++++++++ .../V66__control_ui_issuance_operations.sql | 222 +++++ ...uanceOperationPostgresIntegrationTest.java | 537 ++++++++++++ ...ershipSnapshotPostgresIntegrationTest.java | 4 +- ...rojectionPostgresRedisIntegrationTest.java | 8 +- ...horityProducerPostgresIntegrationTest.java | 8 +- ...ftSourceChangePostgresIntegrationTest.java | 7 +- ...StateOperationPostgresIntegrationTest.java | 809 ++++++++++++++++++ ...otstrapServicePostgresIntegrationTest.java | 2 + ...horityProducerPostgresIntegrationTest.java | 2 + ...iCurrentSourcePostgresIntegrationTest.java | 4 +- ...countSecurityStateMutationRequestTest.java | 182 ++++ ...AccountControlUiIssuanceOperationTest.java | 108 +++ ...tSecurityStateOperationRepositoryTest.java | 48 ++ ...countAuthoritySourceEventReadbackTest.java | 71 +- ...ntLogoutAllAuthorityEventProducerTest.java | 5 +- ...thorityEventProducerCanonicalJoinTest.java | 3 + ...tMembershipAuthorityEventProducerTest.java | 15 + .../service/impl/AccountServiceImplTest.java | 6 + ...orityGrpcPostgresMtlsCrossServiceTest.java | 4 +- 34 files changed, 4269 insertions(+), 101 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountControlUiIssuanceRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountControlUiIssuanceRequestDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperation.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V65__account_security_state_operations.sql create mode 100644 services/account-service/src/main/resources/db/migration/V66__control_ui_issuance_operations.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2d53b7c16c..205dcf231b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2472,6 +2472,45 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.AccountPasswordResetDraftSourceChangePostgresIntegrationTest#sourceAbortedIsImmutableNoMutationTerminalDistinctFromSourceCommit()' \ account-service + - name: Capture Account security-state and control-ui PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-security-state-control-ui-postgresql-proof-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + services/account-service/build/test-results/integrationTest/TEST-*AccountSecurityStateOperationPostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountControlUiIssuanceOperationPostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Verify Account security-state and control-ui PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#originalCallerAndFamilyBindingsCannotBeChangedOnRetry()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#concurrentExactClaimsSerializeToOneOriginalRequest()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#exactExistingOutboxReceiptCompletesOnceAndHistoricalImagesSurviveLaterAdvance()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#lawfulPrivateFenceAdvanceKeepsLatestSourceEventAndOriginalReceiptUnchanged()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#lateReceiptFailureRollsBackEntireFixtureProducerButRetainsOriginalWaitingIntent()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#requestCaptureResultsDeletesAndTruncationRemainGuarded()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#substitutedEventStateCannotBecomeTheOriginalReceipt()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#corruptPositiveCheckpointMetadataAndPayloadDenyBeforeNewIntentOrSourceMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#retainedReceiptCannotLeadRegressedCurrentAuthorityOrCheckpoint()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#actualReaderDeniesUncommittedOperationAndChangedCurrentPoststate()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#forwardMigrationRetainsOriginalAccountAuthorityAndRoleImagesWithoutBackfill()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest#claimRequiresAnActiveWritableOwnerTransaction()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest#exactClaimsRecoverOriginalCaptureAndChangedAccountOrCaptureConflicts()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest#simultaneousExactClaimsAllocateOneOperationAndRetainTheFirstCapture()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest#abandonedPendingClaimCannotBeReportedCommittedWithoutExactEnvelope()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest#exactEncryptedResultSurvivesRestartRotationAndLaterTransactionRetry(Path)' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest#lateRollbackLeavesOriginalPendingCaptureAndNoEncryptedResult()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest#additiveV66MigrationPreservesV64ReceiptAndExistingV65Structure()' \ + account-service + - name: Verify Account generation projection PostgreSQL and Redis proof cases if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 40c5e68fe9..baf48894f5 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -220,7 +220,7 @@ The stored receipt and event must be read back exactly before success, including ### Account-Owned Account Source Readback -Account's owner-local source readback selects one exact canonical Account UUID, locks its persisted identity/credential row and Account source generation/issuance-fence rows in producer order, and holds those locks through the complete current and selected historical read. It does not enroll missing authority. The current snapshot binds the exact Account source scope, positive generation/source version, actual local issuance fence, derived stream and latest checkpoint/event. Sequence zero requires the original positive 1/1 source baseline and proved absence of committed stream history; event identity, digest and payload are absent at zero. A positive checkpoint must match the exact latest closed [password-reset](../../system-architecture-authentication.md#account-password-reset-source-event), [logout-all](../../system-architecture-authentication.md#account-logout-all-source-event), or [security-state](../../system-architecture-authentication.md#account-security-state-source-event) event and its immutable operation receipt. Security-state producer, receipt storage and current/historical reader integration remain unimplemented prerequisites; declaring its schema does not enable that path. Unsupported event types or contradictory source, receipt or checkpoint content fail closed. +Account's owner-local source readback selects one exact canonical Account UUID, locks its persisted identity/credential row and Account source generation/issuance-fence rows in producer order, and holds those locks through the complete current and selected historical read. It does not enroll missing authority. The current snapshot binds the exact Account source scope, positive generation/source version, actual local issuance fence, derived stream and latest checkpoint/event. Sequence zero requires the original positive 1/1 source baseline and proved absence of committed stream history; event identity, digest and payload are absent at zero. A positive checkpoint must match the exact latest closed [password-reset](../../system-architecture-authentication.md#account-password-reset-source-event), [logout-all](../../system-architecture-authentication.md#account-logout-all-source-event), or [security-state](../../system-architecture-authentication.md#account-security-state-source-event) event and its immutable operation receipt. Security-state receipt/readback does not itself implement the authenticated mutation producer or activate a runtime path; implementation and executed proof are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). Unsupported event types or contradictory source, receipt or checkpoint content fail closed. A historical selector is a positive outbox sequence in that exact Account stream. Readback returns the unchanged requested event together with the current source snapshot, validates its complete canonical payload/digest and immutable receipt binding, and rejects missing, cross-scope or ahead-of-current evidence. A later password reset does not erase the prior reset source event or make its old verifier current authority: historical source validation proves the original receipt, while password-reset operation recovery still requires its original current-password postcondition and deadline. Source readback cannot recover a superseded password-reset result, return credentials, supply recipient authorization, or substitute for the complete Account evidence bundle. The source snapshot carries no password verifier or private operation receipt. Authentication, transport, event delivery, projection consumption and live activation are separate proof obligations; an owner-local reader alone enables none of them. @@ -228,6 +228,8 @@ A historical selector is a positive outbox sequence in that exact Account stream The closed source payload and digest are owned by [Authentication's Account security-state source event](../../system-architecture-authentication.md#account-security-state-source-event). This is an Account-owned operation contract, not a new public mutation route or a permission grant. Its producer remains unimplemented at this boundary. Account claims a stable original operation UUID before changing state and retains the exact authenticated caller/workload binding, canonical Account UUID and independently verified numeric association, request-digest version and digest, expected source state, and complete credential-free before/after images in immutable operation evidence. A retry must reuse that original identity; a newly generated repository-save identity cannot recover an ambiguous earlier commit. Global roles must be read from the actual Account-owned grant/source under [ADR 0185](../../decisions/adr-0185-account-owned-global-role-administration-and-bootstrap.md), not inferred from `accounts.role`. The existing fresh-empty source reader proves only qualifying fresh empty authority; unsupported retained or mutated global-role sources remain denied until their owning source readback exists. +The private `firemud/account/security-state/request/v1` digest uses SHA-256 over unsigned 32-bit big-endian byte-length-framed fields in this exact order: domain, original request UUID, canonical Account UUID, canonical caller-correlation bytes, original expected Account generation, original expected source version, changed-family count, each sorted changed-family name, and canonical complete desired-state bytes. Counters and cardinality use canonical decimal strings. Caller correlation is a closed `account-security-state-caller-correlation/v1` object containing only that schema version, canonical non-nil `actorAccountUuid`, canonical non-nil `ownerOperationId`, and `ownerEvidenceDigest` (`sha256:` plus 64 lowercase hexadecimal digits). It identifies separately retained genuine owner authorization evidence; neither its shape nor its digest authenticates a caller. The mutation owner must verify the original evidence, exact caller/workload and current authorization independently. Do not include passwords, password verifiers, raw tokens or OTPs in this correlation or request preimage. + Under the existing Account owner transaction and lock order, the producer compares the exact before/after images and requires the event's changed-family set to equal every supported changed family, with no omissions, additions or duplicates. One operation changing several supported families still advances the Account generation/source version and applicable local issuance fence once and appends one source event/checkpoint. It commits the row/source changes, immutable request/result receipt and outbox evidence together; a failed claim, source comparison, counter overflow, append or readback rolls them all back. A password change must use the unchanged password-reset owner operation, event and receipt; generic password-hash comparison does not authorize or synthesize it. Unsupported mixed-password mutations are denied until that real owner operation is composed. Logout-all retains its separate operation and exact lifecycle retry semantics. The immutable committed receipt binds the original operation/caller/request digest, exact Account association, credential-free before/after images and detected family set to the committed event ID, complete canonical event bytes/digest, exact stream/sequence, generation/source version and actual private local fence result. SQL uniqueness and immutability protect the original operation identity and stream checkpoint. Before success, owner readback independently compares the complete claimed request/result and receipt, request-indexed and sequence-indexed outbox event, committed source/checkpoint and current owner state. Exact retry first reads and verifies the original receipt/event without another state update, generation/fence advance or append; changed caller, target, digest, state or family bindings conflict. A later owner advance preserves the original committed result and bytes. Historical validation proves the unchanged receipt/event and rejects history ahead of the current source; it does not demand that historical post-state remain current, return credentials, authorize the current caller or replace the separate complete Account evidence bundle. Current source readback must bind the latest supported event and receipt to the current same-snapshot owner state. Missing, contradictory or unsupported evidence fails closed. Codec vectors alone establish neither operation persistence nor producer, projection, authenticated handoff or runtime activation proof. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fe20fe506d..7a2e512c3e 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -241,6 +241,8 @@ Game Session orchestrates binding-refresh installation and reconciliation throug Ordinary `POST /auth/login` uses the crash-safe registry-backed issuance protocol in [ADR 0014](../../decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md#crash-safe-issuance-and-registry-projection). Its ingress and callers retain a stable high-entropy `requestId` for that issuance operation. This identifier belongs to durable operation identity, not an additional JWT claim, and the existing login response shape is unchanged. The semantic request digest identifies issuance semantics, not the supplied credential: Account must not retain a plaintext password, OTP, or fast credential digest to identify an exact retry. +The private semantic digest uses SHA-256 over unsigned 32-bit big-endian byte-length-framed UTF-8 fields in the fixed order `firemud/account/control-ui-issuance/request/v1`, `1`, `LOGIN_ISSUANCE`, canonical Account UUID, `control-ui` profile, and `control-ui` audience. The original request UUID remains the durable request key and a separate response-envelope binding. Credential flow, password, OTP and fresh recovery authentication are not semantic request fields. The original complete authority/fence capture is retained separately and is never replaced by a new retry capture. + The existing Account response-envelope ring uses a distinct `control-ui-response` AEAD key and versioned targetless operation binding. It binds the exact Account subject, operation and request identities, token profile and audience, semantic request digest, original committed token and response hashes, complete applicable authority/fence/generation evidence, and original expiry. It contains no invented tenant, connect scope, Gateway context, or private-delegation binding. A key for another envelope purpose cannot decrypt this response. Provisioning, rotation, authenticated materialization/readback, and evidence-based decrypt-only key retirement remain owned by [Environment and Secrets](../../infrastructure/environment-and-secrets-overview.md#account-ring-materializer-target-cluster-binding); local encryption does not satisfy those delivery gates. Every recovery authenticates a currently valid credential for the same Account at the required authentication strength, then proves the exact durable operation is `COMMITTED`, its original issued-token registry record is active and exact, current authority and issuance fences still match, and the original result remains unexpired. A valid password or newly valid eligible OTP may establish fresh authentication; a consumed or expired original OTP cannot. Historical authentication evidence alone is insufficient. Changed issuance semantics conflict under the retained request identity rather than causing a new issuance. 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 b931e8dd51..94ebee6ca5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,13 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The closed Account security-state codec and canonical generation-projection consumer now preserve the existing reset/logout schemas while validating the complete new payload and exact duplicate identity. Structural snapshot construction accepts that closed schema, but authenticated current/historical source readers still reject it without a real immutable operation receipt; no producer or permission is implied. The control-ui response envelope adds a distinct purpose/key and targetless original-operation, response, authority-capture, fence and expiry binding. Local combined checks/JAR/analyzers/docs pass with 249 common-platform and 1000 Account unit outcomes, including eleven new codec vectors and six control-ui crypto cases; all 404 Account integration cases skip without Docker. Eighty offline ring bootstrap/materializer cases pass. Stable authenticated source operations, receipt persistence/readback, actual ordinary control-ui issuance/registry/recovery and protected custody/live readiness remain required; no runtime activation follows. +Account's V65 candidate retains one immutable security-state request/capture and its exact committed event/result, with the original V57 source-change binding and independently verified Account UUID/numeric provenance. The existing current/historical source reader now requires that real receipt, complete closed event/checkpoint binding and actual current post-state; unsupported or uncommitted evidence remains denied. A lawful independent issuance-fence advance does not invalidate an unchanged latest source event or rewrite its original receipt. Reset/logout schemas and operation families remain separate. This adds receipt/readback composition, not the authenticated mutation producer, transport authorization, source enrollment or runtime activation; genuine owner caller evidence and atomic state/source/event production remain required under [Account's operation contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-security-state-operation-and-readback). + +The V66 targetless control-ui candidate retains canonical request correlation, the first original Account association and opaque authority/fence captures, and one exact purpose-bound encrypted result. First-writer claims serialize; committed retries cannot substitute response, token, key-purpose or capture bytes. The unregistered repository does not authenticate credentials, establish current authority, verify or write the active token registry, mint a JWT or release a credential. V66's additive fixture preserves a real V64 pending receipt and the V65 table structure; it does not directly exercise a nonempty V65 operation row. Actual ordinary control-ui issuance/authenticated exact recovery, registry/currentness composition and protected custody/live readiness remain open under [Account's recovery contract](../../architecture/microservices/account-service/runtime-and-data.md#exact-control-ui-issuance-recovery). The ring mount and denied runtime paths remain unchanged. + +The composed Account/Game Session/Common gate passes in 2m24s: checks, Account boot JAR/jOOQ, formatting, Checkstyle, SpotBugs, coverage, links and Markdown are clean. XML records 1009 Account and 249 Common unit outcomes without skips/failures/errors; Game Session records 2377 executed unit cases (17 skipped), 26 executed cross-service cases (57 skipped) and 18 executed integration cases (198 skipped), all clean. All 423 Account PostgreSQL cases compile but skip locally without Docker, including V65's twelve and V66's seven. The strict proof inspector rejects those skips as intended, and CI explicitly requires all nineteen methods and retains their raw XML. Actionlint passes. Configuration-cache storage is discarded for 83 protobuf problems; this is not cache-support, fresh-image, database, authenticated delivery or enabled player-flow proof. Earlier published codec/crypto proof comprised eleven closed-codec vectors, six control-ui crypto cases and eighty offline ring-tooling cases; it does not replace the new transaction execution gates. + +Exact parent `3b48b7493766acf80e616eb48dba604081131379` [CI37399537835](https://github.com/benhook1013/FireMUD/actions/runs/37399537835) executes ten World association cases with one failure and no skips, plus one passing preparation case. The remaining changed-binding case correctly reaches SQL denial but exposes a persistence exception instead of the typed domain conflict; the bounded translation correction must retain rollback and every binding guard. Account's job is cancelled after the V59 retained-source-change fixture invokes a current reader expecting V61 columns. Its raw XML is unavailable, so this run gives no Account case-count or execution credit. The owning parent corrections remain required; neither aggregate failure nor local child storage proof establishes activation. At exact published `9c9f01be79bc1696bd2ca5a2e707068603916602`, [CI37395254176](https://github.com/benhook1013/FireMUD/actions/runs/37395254176) executes all seven pending-reset source-change and seventeen logout-all PostgreSQL methods cleanly without skips. Verified merge `3a54423ebe6c956a05691c8eae37e223f7134d38` has exact source/parent and a source-identical tree. This closes the corrected schema-name and V59-to-V60 fixture execution gaps below. Account's separate V58-to-V59 retained-image fixture fails because it migrates past its named target into V61; the bounded correction pins V59 without dropping retained-row assertions. World separately fails six of ten association methods on immutable frozen-plan readback, while its one reserved-tenant preparation method passes. Aggregate CI is red, and the owning corrections still require corrected-state PostgreSQL execution. These storage results do not establish authenticated creator, release or lifecycle activation. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountControlUiIssuanceRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountControlUiIssuanceRequest.java new file mode 100644 index 0000000000..cbf1c25d8d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountControlUiIssuanceRequest.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; + +/** Credential-free semantic identity for one targetless control-UI login issuance. */ +public record AccountControlUiIssuanceRequest(String requestId, String accountUuid) { + + public static final String PROFILE = "control-ui"; + public static final String AUDIENCE = "control-ui"; + + public AccountControlUiIssuanceRequest { + requestId = canonicalUuid(requestId, "requestId"); + accountUuid = canonicalUuid(accountUuid, "accountUuid"); + } + + private static String canonicalUuid(String value, String field) { + Objects.requireNonNull(value, field); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) + || (parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L)) { + throw new IllegalArgumentException("Invalid " + field); + } + return value; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Invalid " + field, exception); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountControlUiIssuanceRequestDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountControlUiIssuanceRequestDigest.java new file mode 100644 index 0000000000..934ab75056 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountControlUiIssuanceRequestDigest.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Objects; + +/** Versioned semantic request framing; it deliberately accepts no credential material. */ +public final class AccountControlUiIssuanceRequestDigest { + public static final int VERSION = 1; + public static final String DOMAIN = "firemud/account/control-ui-issuance/request/v1"; + + private AccountControlUiIssuanceRequestDigest() {} + + public static byte[] canonicalBytes(AccountControlUiIssuanceRequest request) { + Objects.requireNonNull(request, "request"); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + frame(output, DOMAIN); + frame(output, Integer.toString(VERSION)); + frame(output, "LOGIN_ISSUANCE"); + frame(output, request.accountUuid()); + frame(output, AccountControlUiIssuanceRequest.PROFILE); + frame(output, AccountControlUiIssuanceRequest.AUDIENCE); + return output.toByteArray(); + } + + public static byte[] digest(AccountControlUiIssuanceRequest request) { + try { + return MessageDigest.getInstance("SHA-256").digest(canonicalBytes(request)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void frame(ByteArrayOutputStream output, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + output.writeBytes(bytes); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java new file mode 100644 index 0000000000..bb5f164754 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.accountservice.dto; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Immutable operation correlation only; this request does not establish caller authorization. */ +public record AccountSecurityStateMutationRequest( + UUID requestId, + UUID accountUuid, + byte[] callerProofBinding, + long expectedGeneration, + long expectedSourceVersion, + List mutationKinds, + AccountState desiredState) { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Set CALLER_FIELDS = + Set.of("schemaVersion", "actorAccountUuid", "ownerOperationId", "ownerEvidenceDigest"); + + public AccountSecurityStateMutationRequest { + requireUuid(requestId); + requireUuid(accountUuid); + if (expectedGeneration <= 0 || expectedSourceVersion <= 0) { + throw new IllegalArgumentException("Original positive source counters are required"); + } + callerProofBinding = canonicalCallerBinding(callerProofBinding); + mutationKinds = List.copyOf(Objects.requireNonNull(mutationKinds)); + Objects.requireNonNull(desiredState); + // The shared source codec owns the complete state and family vocabulary. + var validated = + AccountSecurityStateAuthorityEventV1Codec.seal( + eventPreimage(requestId, accountUuid, "1", "1", "1", mutationKinds, desiredState)); + desiredState = validated.accountState(); + mutationKinds = validated.mutationKinds(); + } + + @Override + public byte[] callerProofBinding() { + return callerProofBinding.clone(); + } + + @Override + public List mutationKinds() { + return List.copyOf(mutationKinds); + } + + public byte[] canonicalDesiredState() { + return canonicalState(desiredState); + } + + public static byte[] canonicalState(AccountState state) { + Objects.requireNonNull(state); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(state)); + } catch (IOException exception) { + throw new IllegalArgumentException("Account state cannot be canonicalized", exception); + } + } + + public static AccountState parseCanonicalState(byte[] bytes) { + try { + String text = new String(Objects.requireNonNull(bytes), StandardCharsets.UTF_8); + JsonNode node = JSON.readTree(text); + var validated = + AccountSecurityStateAuthorityEventV1Codec.seal( + eventPreimage( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "1", + "1", + "1", + List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED"), + JSON.convertValue(node, new TypeReference>() {}))); + if (!Arrays.equals(bytes, canonicalState(validated.accountState()))) { + throw new IllegalArgumentException("Stored Account state is not canonical"); + } + return validated.accountState(); + } catch (IOException exception) { + throw new IllegalArgumentException("Stored Account state is malformed", exception); + } + } + + public static Map eventPreimage( + UUID requestId, + UUID accountUuid, + String generation, + String sourceVersion, + String sequence, + List mutationKinds, + Object state) { + String stream = "account:auth-authority:v1:account/" + accountUuid; + return Map.ofEntries( + Map.entry("schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId.toString()), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + stream, + "outboxSequence", + sequence)), + Map.entry("mutationKinds", mutationKinds), + Map.entry("accountState", state)); + } + + private static byte[] canonicalCallerBinding(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > 16_384) { + throw new IllegalArgumentException("Bounded original caller/proof correlation is required"); + } + try { + String text = new String(bytes, StandardCharsets.UTF_8); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(text))) { + throw new IllegalArgumentException("Caller/proof correlation must be canonical JSON"); + } + JsonNode node = JSON.readTree(text); + Set fields = new java.util.HashSet<>(); + node.fieldNames().forEachRemaining(fields::add); + if (!node.isObject() || !fields.equals(CALLER_FIELDS)) { + throw new IllegalArgumentException( + "Caller correlation must contain exactly its identity fields"); + } + if (!"account-security-state-caller-correlation/v1" + .equals(node.path("schemaVersion").textValue())) { + throw new IllegalArgumentException("Unsupported caller correlation version"); + } + for (String field : List.of("actorAccountUuid", "ownerOperationId")) { + JsonNode id = node.get(field); + if (!id.isTextual() + || !id.textValue() + .matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + throw new IllegalArgumentException("Canonical correlation UUIDs are required"); + } + requireUuid(UUID.fromString(id.textValue())); + } + if (!node.get("ownerEvidenceDigest").isTextual() + || !node.get("ownerEvidenceDigest").textValue().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "Original owner evidence digest correlation is required"); + } + return bytes.clone(); + } catch (IOException exception) { + throw new IllegalArgumentException("Caller/proof correlation is malformed", exception); + } + } + + private static void requireUuid(UUID uuid) { + if (uuid == null || uuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException( + "Canonical non-nil operation and Account UUIDs are required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java new file mode 100644 index 0000000000..e779dddd2a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Exact versioned request/capture bytes; neither digest establishes caller authorization. */ +public final class AccountSecurityStateRequestDigest { + public static final String REQUEST_DOMAIN = "firemud/account/security-state/request/v1"; + + private AccountSecurityStateRequestDigest() {} + + public static byte[] requestBytes(AccountSecurityStateMutationRequest request) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + frame(bytes, REQUEST_DOMAIN); + frame(bytes, request.requestId().toString()); + frame(bytes, request.accountUuid().toString()); + frame(bytes, request.callerProofBinding()); + frame(bytes, Long.toString(request.expectedGeneration())); + frame(bytes, Long.toString(request.expectedSourceVersion())); + // Each kind has its own frame; cardinality is also an explicit frame. + frame(bytes, Integer.toString(request.mutationKinds().size())); + request.mutationKinds().forEach(kind -> frame(bytes, kind)); + frame(bytes, request.canonicalDesiredState()); + return bytes.toByteArray(); + } + + public static String digest(AccountSecurityStateMutationRequest request) { + return sha256(requestBytes(request)); + } + + public static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + public static void frame(ByteArrayOutputStream output, String text) { + frame(output, text.getBytes(StandardCharsets.UTF_8)); + } + + public static void frame(ByteArrayOutputStream output, byte[] value) { + output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); + output.writeBytes(value); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperation.java new file mode 100644 index 0000000000..1825ca4642 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperation.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequest; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.security.AccountControlUiResponseEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; + +/** Credential-free, immutable correlation row and optional encrypted original response. */ +public record AccountControlUiIssuanceOperation( + UUID operationId, + AccountControlUiIssuanceRequest request, + long accountId, + AccountIdentityProvenance accountProvenance, + byte[] requestDigest, + Lifecycle lifecycle, + OriginalCapture originalCapture, + CompletedResponse completedResponse, + Instant createdAt, + Instant updatedAt) { + + private static final int DIGEST_LENGTH = 32; + + public AccountControlUiIssuanceOperation { + requireNonNil(operationId, "operationId"); + Objects.requireNonNull(request, "request"); + if (accountId <= 0L) { + throw new IllegalArgumentException("Invalid Account numeric association"); + } + Objects.requireNonNull(accountProvenance, "accountProvenance"); + requestDigest = copyDigest(requestDigest, "requestDigest"); + Objects.requireNonNull(lifecycle, "lifecycle"); + Objects.requireNonNull(originalCapture, "originalCapture"); + if (originalCapture.accountId() != accountId + || originalCapture.accountProvenance() != accountProvenance) { + throw new IllegalArgumentException("Original capture Account association differs"); + } + Objects.requireNonNull(createdAt, "createdAt"); + Objects.requireNonNull(updatedAt, "updatedAt"); + if ((lifecycle == Lifecycle.PENDING) != (completedResponse == null)) { + throw new IllegalArgumentException("Operation lifecycle/result shape differs"); + } + if (completedResponse != null) { + requireCompletedBinding( + completedResponse, operationId, request, requestDigest, originalCapture); + } + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof AccountControlUiIssuanceOperation that)) return false; + return accountId == that.accountId + && operationId.equals(that.operationId) + && request.equals(that.request) + && accountProvenance == that.accountProvenance + && Arrays.equals(requestDigest, that.requestDigest) + && lifecycle == that.lifecycle + && originalCapture.equals(that.originalCapture) + && Objects.equals(completedResponse, that.completedResponse) + && createdAt.equals(that.createdAt) + && updatedAt.equals(that.updatedAt); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + operationId, + request, + accountId, + accountProvenance, + lifecycle, + originalCapture, + completedResponse, + createdAt, + updatedAt); + return 31 * result + Arrays.hashCode(requestDigest); + } + + @Override + public String toString() { + return "AccountControlUiIssuanceOperation{operationId=" + + operationId + + ", requestId=" + + request.requestId() + + ", lifecycle=" + + lifecycle + + ", originalEvidence=}"; + } + + private static void requireCompletedBinding( + CompletedResponse result, + UUID operationId, + AccountControlUiIssuanceRequest request, + byte[] requestDigest, + OriginalCapture capture) { + var binding = result.binding(); + if (!binding.accountId().equals(request.accountUuid()) + || !binding.operationId().equals(operationId.toString()) + || !binding.requestId().equals(request.requestId()) + || !MessageDigest.isEqual(binding.requestDigest(), requestDigest) + || !MessageDigest.isEqual( + binding.authorityCaptureDigest(), capture.authorityCaptureDigest()) + || !MessageDigest.isEqual(binding.issuanceFenceDigest(), capture.issuanceFenceDigest()) + || result.envelope().purpose() != AccountEnvelopePurpose.CONTROL_UI_RESPONSE) { + throw new IllegalArgumentException( + "Committed response does not match its original operation"); + } + } + + private static byte[] copyDigest(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length != DIGEST_LENGTH) { + throw new IllegalArgumentException("Invalid " + name); + } + return value.clone(); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be non-nil"); + } + } + + public enum Lifecycle { + PENDING, + COMMITTED + } + + /** + * Opaque complete original authority and issuance-fence bytes; digests establish identity only. + */ + public static final class OriginalCapture { + private static final int MAX_CAPTURE_BYTES = 1024 * 1024; + + private final long accountId; + private final AccountIdentityProvenance accountProvenance; + private final byte[] authorityCapture; + private final byte[] issuanceFenceCapture; + + public OriginalCapture( + long accountId, + AccountIdentityProvenance accountProvenance, + byte[] authorityCapture, + byte[] issuanceFenceCapture) { + if (accountId <= 0L) { + throw new IllegalArgumentException("Invalid Account numeric association"); + } + this.accountId = accountId; + this.accountProvenance = Objects.requireNonNull(accountProvenance, "accountProvenance"); + this.authorityCapture = copyCapture(authorityCapture, "authorityCapture"); + this.issuanceFenceCapture = copyCapture(issuanceFenceCapture, "issuanceFenceCapture"); + } + + public long accountId() { + return accountId; + } + + public AccountIdentityProvenance accountProvenance() { + return accountProvenance; + } + + public byte[] authorityCapture() { + return authorityCapture.clone(); + } + + public byte[] issuanceFenceCapture() { + return issuanceFenceCapture.clone(); + } + + public byte[] authorityCaptureDigest() { + return sha256(authorityCapture); + } + + public byte[] issuanceFenceDigest() { + return sha256(issuanceFenceCapture); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof OriginalCapture that)) return false; + return accountId == that.accountId + && accountProvenance == that.accountProvenance + && Arrays.equals(authorityCapture, that.authorityCapture) + && Arrays.equals(issuanceFenceCapture, that.issuanceFenceCapture); + } + + @Override + public int hashCode() { + int result = Objects.hash(accountId, accountProvenance); + result = 31 * result + Arrays.hashCode(authorityCapture); + result = 31 * result + Arrays.hashCode(issuanceFenceCapture); + return result; + } + + @Override + public String toString() { + return "OriginalCapture{evidence=}"; + } + + private static byte[] copyCapture(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length == 0 || value.length > MAX_CAPTURE_BYTES) { + throw new IllegalArgumentException("Invalid " + name); + } + return value.clone(); + } + } + + public record CompletedResponse( + AccountControlUiResponseEnvelopeBinding binding, AccountEncryptedEnvelope envelope) { + public CompletedResponse { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(envelope, "envelope"); + if (envelope.purpose() != AccountEnvelopePurpose.CONTROL_UI_RESPONSE) { + throw new IllegalArgumentException("Wrong encrypted response purpose"); + } + } + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java new file mode 100644 index 0000000000..529c3a7f31 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java @@ -0,0 +1,478 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequest; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequestDigest; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation.CompletedResponse; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation.Lifecycle; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation.OriginalCapture; +import net.firedevops.firemud.accountservice.security.AccountControlUiResponseEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Account-local first-writer correlation and exact encrypted-result storage. + * + *

This component does not authenticate credentials, establish authority/currentness, write or + * inspect the active token registry, or prove custody. Its opaque capture bytes identify the + * original supplied evidence only; callers must establish all applicable gates separately. + */ +public final class AccountControlUiIssuanceOperationRepository { + private static final String OPERATIONS = "account_control_ui_issuance_operations"; + private static final String ENVELOPES = "account_control_ui_issuance_response_envelopes"; + + private final DSLContext dsl; + + public AccountControlUiIssuanceOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Claims the stable request identity or recovers its original capture. An existing exact retry + * may omit a new capture; if it supplies one, it must byte-match the immutable first capture. + */ + public Claim claim( + AccountControlUiIssuanceRequest request, Optional proposedCapture) { + requireWritableOwnerTransaction(); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(proposedCapture, "proposedCapture"); + byte[] requestDigest = AccountControlUiIssuanceRequestDigest.digest(request); + AccountAssociation association = lockAccount(request.accountUuid()); + Optional existing = + readOperation(UUID.fromString(request.requestId()), true); + if (existing.isPresent()) { + AccountControlUiIssuanceOperation stored = existing.orElseThrow(); + requireRequestAndAssociation(stored, request, requestDigest, association); + proposedCapture.ifPresent( + capture -> { + if (!stored.originalCapture().equals(capture)) { + throw new OperationConflictException( + "Original control-UI authority/fence capture cannot be replaced"); + } + }); + return new Claim(false, stored); + } + + OriginalCapture capture = + proposedCapture.orElseThrow( + () -> new IllegalArgumentException("First control-UI claim requires original capture")); + requireCaptureAssociation(capture, association); + UUID proposedOperationId = UUID.randomUUID(); + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATIONS + + " (operation_id, request_id, account_uuid, account_id, account_provenance, " + + "profile, audience, request_digest_version, request_digest, " + + "authority_capture, authority_capture_digest, issuance_fence_capture, " + + "issuance_fence_digest, status) " + + "VALUES (?, ?, ?, ?, ?, 'control-ui', 'control-ui', ?, ?, ?, ?, ?, ?, 'PENDING') " + + "ON CONFLICT (request_id) DO NOTHING", + proposedOperationId, + UUID.fromString(request.requestId()), + UUID.fromString(request.accountUuid()), + association.accountId(), + association.provenance().name(), + AccountControlUiIssuanceRequestDigest.VERSION, + requestDigest, + capture.authorityCapture(), + capture.authorityCaptureDigest(), + capture.issuanceFenceCapture(), + capture.issuanceFenceDigest()); + if (inserted < 0 || inserted > 1) { + throw new IllegalStateException("Control-UI issuance claim result was ambiguous"); + } + + AccountControlUiIssuanceOperation stored = + readOperation(UUID.fromString(request.requestId()), true) + .orElseThrow( + () -> + new IllegalStateException( + "Control-UI issuance claim has no durable operation readback")); + requireRequestAndAssociation(stored, request, requestDigest, association); + if (inserted == 1 + && (!stored.operationId().equals(proposedOperationId) + || !stored.originalCapture().equals(capture))) { + throw new IllegalStateException("First control-UI claim readback differs from its proposal"); + } + return new Claim(inserted == 1, stored); + } + + /** Reads the exact original operation and encrypted response, if committed. */ + public Optional findByRequest( + AccountControlUiIssuanceRequest request) { + requireWritableOwnerTransaction(); + Objects.requireNonNull(request, "request"); + byte[] requestDigest = AccountControlUiIssuanceRequestDigest.digest(request); + AccountAssociation association = lockAccount(request.accountUuid()); + Optional stored = + readOperation(UUID.fromString(request.requestId()), false); + stored.ifPresent( + operation -> requireRequestAndAssociation(operation, request, requestDigest, association)); + return stored; + } + + /** + * Commits one exact original encrypted result. This does not mint, extend or validate a token; + * authenticated/currentness/registry checks must already have succeeded outside this store. + */ + public AccountControlUiIssuanceOperation complete( + Claim claim, + AccountControlUiResponseEnvelopeBinding binding, + AccountEncryptedEnvelope envelope) { + requireWritableOwnerTransaction(); + Objects.requireNonNull(claim, "claim"); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(envelope, "envelope"); + AccountControlUiIssuanceOperation claimed = claim.operation(); + AccountControlUiIssuanceRequest request = claimed.request(); + AccountAssociation association = lockAccount(request.accountUuid()); + AccountControlUiIssuanceOperation stored = + readOperation(UUID.fromString(request.requestId()), true) + .orElseThrow( + () -> new OperationConflictException("Original control-UI claim is missing")); + requireRequestAndAssociation( + stored, request, AccountControlUiIssuanceRequestDigest.digest(request), association); + if (!stored.operationId().equals(claimed.operationId()) + || !stored.originalCapture().equals(claimed.originalCapture())) { + throw new OperationConflictException("Control-UI claim no longer matches its original row"); + } + requireBinding(stored, binding, envelope); + CompletedResponse proposed = new CompletedResponse(binding, envelope); + if (stored.lifecycle() == Lifecycle.COMMITTED) { + if (!stored.completedResponse().equals(proposed)) { + throw new OperationConflictException( + "Committed control-UI result cannot be replaced or reminted"); + } + return stored; + } + + int updated = + dsl.execute( + "UPDATE " + + OPERATIONS + + " SET status = 'COMMITTED', token_hash = ?, response_digest = ?, " + + "issued_at = ?, expires_at = ? WHERE operation_id = ? AND request_id = ? " + + "AND status = 'PENDING'", + binding.tokenHash(), + binding.responseDigest(), + toOffsetDateTime(binding.issuedAt()), + toOffsetDateTime(binding.expiresAt()), + stored.operationId(), + UUID.fromString(request.requestId())); + if (updated != 1) { + throw new OperationConflictException("Control-UI operation did not transition exactly once"); + } + int envelopeInserted = + dsl.execute( + "INSERT INTO " + + ENVELOPES + + " (operation_id, request_id, account_uuid, account_id, account_provenance, " + + "profile, audience, request_digest_version, request_digest, token_hash, " + + "response_digest, authority_capture_digest, issuance_fence_digest, issued_at, " + + "expires_at, format_version, key_id, purpose, nonce, ciphertext) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + stored.operationId(), + UUID.fromString(request.requestId()), + UUID.fromString(request.accountUuid()), + stored.accountId(), + stored.accountProvenance().name(), + binding.profile(), + binding.audience(), + AccountControlUiIssuanceRequestDigest.VERSION, + binding.requestDigest(), + binding.tokenHash(), + binding.responseDigest(), + binding.authorityCaptureDigest(), + binding.issuanceFenceDigest(), + toOffsetDateTime(binding.issuedAt()), + toOffsetDateTime(binding.expiresAt()), + envelope.formatVersion(), + envelope.keyId(), + envelope.purpose().name(), + envelope.nonce(), + envelope.ciphertext()); + if (envelopeInserted != 1) { + throw new IllegalStateException("Control-UI encrypted response insert was ambiguous"); + } + + AccountControlUiIssuanceOperation readback = + readOperation(UUID.fromString(request.requestId()), true) + .orElseThrow( + () -> new IllegalStateException("Committed control-UI operation disappeared")); + if (!sameCommittedReadback(readback, stored, proposed)) { + throw new IllegalStateException("Committed control-UI operation/envelope readback differs"); + } + return readback; + } + + private static boolean sameCommittedReadback( + AccountControlUiIssuanceOperation readback, + AccountControlUiIssuanceOperation original, + CompletedResponse result) { + return readback.operationId().equals(original.operationId()) + && readback.request().equals(original.request()) + && readback.accountId() == original.accountId() + && readback.accountProvenance() == original.accountProvenance() + && MessageDigest.isEqual(readback.requestDigest(), original.requestDigest()) + && readback.lifecycle() == Lifecycle.COMMITTED + && readback.originalCapture().equals(original.originalCapture()) + && readback.completedResponse().equals(result) + && readback.createdAt().equals(original.createdAt()) + && !readback.updatedAt().isBefore(original.updatedAt()); + } + + private Optional readOperation( + UUID requestId, boolean forUpdate) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + OPERATIONS + + " WHERE request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + requestId); + if (row == null) return Optional.empty(); + + UUID operationId = row.get("operation_id", UUID.class); + UUID accountUuid = row.get("account_uuid", UUID.class); + String requestIdText = row.get("request_id", UUID.class).toString(); + AccountControlUiIssuanceRequest request = + new AccountControlUiIssuanceRequest(requestIdText, accountUuid.toString()); + if (!"control-ui".equals(row.get("profile", String.class)) + || !"control-ui".equals(row.get("audience", String.class)) + || row.get("request_digest_version", Short.class) + != AccountControlUiIssuanceRequestDigest.VERSION) { + throw new IllegalStateException("Stored control-UI request profile/version is invalid"); + } + byte[] requestDigest = row.get("request_digest", byte[].class); + if (!MessageDigest.isEqual( + requestDigest, AccountControlUiIssuanceRequestDigest.digest(request))) { + throw new IllegalStateException("Stored control-UI semantic request digest differs"); + } + long accountId = row.get("account_id", Long.class); + AccountIdentityProvenance provenance = + AccountIdentityProvenance.fromStorageValue(row.get("account_provenance", String.class)); + OriginalCapture capture = + new OriginalCapture( + accountId, + provenance, + row.get("authority_capture", byte[].class), + row.get("issuance_fence_capture", byte[].class)); + if (!MessageDigest.isEqual( + capture.authorityCaptureDigest(), row.get("authority_capture_digest", byte[].class)) + || !MessageDigest.isEqual( + capture.issuanceFenceDigest(), row.get("issuance_fence_digest", byte[].class))) { + throw new IllegalStateException("Stored original control-UI capture digest differs"); + } + + Lifecycle lifecycle = parseLifecycle(row.get("status", String.class)); + Optional completed = + readEnvelope(operationId, row, capture, request, requestDigest); + if ((lifecycle == Lifecycle.PENDING) != completed.isEmpty()) { + throw new IllegalStateException("Stored control-UI operation/envelope lifecycle differs"); + } + return Optional.of( + new AccountControlUiIssuanceOperation( + operationId, + request, + accountId, + provenance, + requestDigest, + lifecycle, + capture, + completed.orElse(null), + toInstant(row.get("created_at", OffsetDateTime.class)), + toInstant(row.get("updated_at", OffsetDateTime.class)))); + } + + private Optional readEnvelope( + UUID operationId, + Record operation, + OriginalCapture capture, + AccountControlUiIssuanceRequest request, + byte[] requestDigest) { + Record row = + dsl.fetchOne("SELECT * FROM " + ENVELOPES + " WHERE operation_id = ?", operationId); + if (row == null) return Optional.empty(); + try { + if (!operationId.equals(row.get("operation_id", UUID.class)) + || !operation.get("request_id", UUID.class).equals(row.get("request_id", UUID.class)) + || !operation.get("account_uuid", UUID.class).equals(row.get("account_uuid", UUID.class)) + || !operation.get("account_id", Long.class).equals(row.get("account_id", Long.class)) + || !operation + .get("account_provenance", String.class) + .equals(row.get("account_provenance", String.class)) + || !"control-ui".equals(row.get("profile", String.class)) + || !"control-ui".equals(row.get("audience", String.class)) + || row.get("request_digest_version", Short.class) + != AccountControlUiIssuanceRequestDigest.VERSION + || !MessageDigest.isEqual(requestDigest, row.get("request_digest", byte[].class)) + || !MessageDigest.isEqual( + capture.authorityCaptureDigest(), row.get("authority_capture_digest", byte[].class)) + || !MessageDigest.isEqual( + capture.issuanceFenceDigest(), row.get("issuance_fence_digest", byte[].class))) { + throw new IllegalStateException("Stored control-UI envelope index binding differs"); + } + AccountControlUiResponseEnvelopeBinding binding = + new AccountControlUiResponseEnvelopeBinding( + row.get("account_uuid", UUID.class).toString(), + operationId.toString(), + row.get("request_id", UUID.class).toString(), + row.get("request_digest", byte[].class), + row.get("token_hash", String.class), + row.get("response_digest", byte[].class), + row.get("authority_capture_digest", byte[].class), + row.get("issuance_fence_digest", byte[].class), + toInstant(row.get("issued_at", OffsetDateTime.class)), + toInstant(row.get("expires_at", OffsetDateTime.class))); + AccountControlUiResponseEnvelopeBinding operationBinding = + new AccountControlUiResponseEnvelopeBinding( + operation.get("account_uuid", UUID.class).toString(), + operationId.toString(), + operation.get("request_id", UUID.class).toString(), + operation.get("request_digest", byte[].class), + operation.get("token_hash", String.class), + operation.get("response_digest", byte[].class), + capture.authorityCaptureDigest(), + capture.issuanceFenceDigest(), + toInstant(operation.get("issued_at", OffsetDateTime.class)), + toInstant(operation.get("expires_at", OffsetDateTime.class))); + if (!binding.equals(operationBinding) + || !binding.requestId().equals(request.requestId()) + || !binding.accountId().equals(request.accountUuid())) { + throw new IllegalStateException("Stored control-UI original response binding differs"); + } + AccountEncryptedEnvelope envelope = + new AccountEncryptedEnvelope( + row.get("format_version", Short.class), + row.get("key_id", String.class), + AccountEnvelopePurpose.valueOf(row.get("purpose", String.class)), + row.get("nonce", byte[].class), + row.get("ciphertext", byte[].class)); + return Optional.of(new CompletedResponse(binding, envelope)); + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException) throw failure; + throw new IllegalStateException("Stored control-UI encrypted response is malformed"); + } + } + + private static void requireBinding( + AccountControlUiIssuanceOperation operation, + AccountControlUiResponseEnvelopeBinding binding, + AccountEncryptedEnvelope envelope) { + if (!binding.accountId().equals(operation.request().accountUuid()) + || !binding.operationId().equals(operation.operationId().toString()) + || !binding.requestId().equals(operation.request().requestId()) + || !MessageDigest.isEqual(binding.requestDigest(), operation.requestDigest()) + || !MessageDigest.isEqual( + binding.authorityCaptureDigest(), operation.originalCapture().authorityCaptureDigest()) + || !MessageDigest.isEqual( + binding.issuanceFenceDigest(), operation.originalCapture().issuanceFenceDigest()) + || !AccountControlUiIssuanceRequest.PROFILE.equals(binding.profile()) + || !AccountControlUiIssuanceRequest.AUDIENCE.equals(binding.audience()) + || envelope.purpose() != AccountEnvelopePurpose.CONTROL_UI_RESPONSE) { + throw new OperationConflictException( + "Encrypted control-UI response does not match the exact original operation binding"); + } + } + + private AccountAssociation lockAccount(String accountUuid) { + Record row = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_source_numeric_id, account_uuid_provenance " + + "FROM accounts WHERE account_uuid = ? FOR UPDATE", + UUID.fromString(accountUuid)); + if (row == null) { + throw new OperationConflictException("Canonical Account association does not exist"); + } + Long id = row.get("id", Long.class); + Long sourceNumericId = row.get("account_uuid_source_numeric_id", Long.class); + UUID uuid = row.get("account_uuid", UUID.class); + AccountIdentityProvenance provenance = + AccountIdentityProvenance.fromStorageValue( + row.get("account_uuid_provenance", String.class)); + if (id == null + || id <= 0L + || !id.equals(sourceNumericId) + || !uuid.toString().equals(accountUuid)) { + throw new OperationConflictException( + "Canonical Account numeric association is contradictory"); + } + return new AccountAssociation(id, uuid, provenance); + } + + private static void requireRequestAndAssociation( + AccountControlUiIssuanceOperation operation, + AccountControlUiIssuanceRequest request, + byte[] digest, + AccountAssociation association) { + if (!operation.request().equals(request) + || !MessageDigest.isEqual(operation.requestDigest(), digest) + || operation.accountId() != association.accountId() + || operation.accountProvenance() != association.provenance() + || !operation.request().accountUuid().equals(association.accountUuid().toString())) { + throw new OperationConflictException( + "Control-UI request identity or Account association was reused with changed semantics"); + } + } + + private static void requireCaptureAssociation( + OriginalCapture capture, AccountAssociation association) { + if (capture.accountId() != association.accountId() + || capture.accountProvenance() != association.provenance()) { + throw new OperationConflictException( + "Original control-UI capture has a changed Account association"); + } + } + + private static Lifecycle parseLifecycle(String value) { + try { + return Lifecycle.valueOf(value); + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored control-UI operation lifecycle is invalid"); + } + } + + private static Instant toInstant(OffsetDateTime value) { + if (value == null) throw new IllegalStateException("Stored control-UI result time is missing"); + return value.toInstant(); + } + + private static OffsetDateTime toOffsetDateTime(Instant value) { + return OffsetDateTime.ofInstant(value, ZoneOffset.UTC); + } + + private static void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Control-UI issuance storage requires a writable caller-owned Account transaction"); + } + } + + private record AccountAssociation( + long accountId, UUID accountUuid, AccountIdentityProvenance provenance) {} + + /** First writer retains one operation UUID; exact retries return its original capture/result. */ + public record Claim(boolean created, AccountControlUiIssuanceOperation operation) { + public Claim { + Objects.requireNonNull(operation, "operation"); + } + } + + public static final class OperationConflictException extends IllegalStateException { + public OperationConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java new file mode 100644 index 0000000000..df81c33d7c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java @@ -0,0 +1,658 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateRequestDigest; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account-local immutable operation storage. Caller bytes are correlation only. This class neither + * authorizes a mutation nor updates Account/source/outbox or settles V57. Real owner evidence, + * exact workload/caller authentication and commit currentness must be proved separately; a digest + * cannot replace a retained owner receipt. Data access is not producer activation. + */ +@Repository +public class AccountSecurityStateOperationRepository { + private static final String TABLE = "account_security_state_operations"; + private final DSLContext dsl; + private final AccountAuthorityGenerationRepository generations; + private final AccountAuthorityOutboxRepository outbox; + + @SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "Spring proxies require a non-final repository; constructor only validates internal DSL collaborators, acquires no resources and publishes no partial instance.") + public AccountSecurityStateOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + generations = new AccountAuthorityGenerationRepository(dsl); + outbox = new AccountAuthorityOutboxRepository(dsl); + } + + /** Locks identity, then recovers the original request before comparing any new capture. */ + public Claim claim(AccountSecurityStateMutationRequest request, Capture capture) { + requireTransaction(); + Objects.requireNonNull(request); + Objects.requireNonNull(capture); + lockAssociation(capture.accountId(), request.accountUuid(), capture.provenance()); + Optional prior = readForUpdate(request.requestId()); + if (prior.isPresent()) { + Operation original = prior.orElseThrow(); + requireRequest(original, request); + if (capture.accountId() != original.capture().accountId() + || capture.provenance() != original.capture().provenance()) { + throw new OperationConflictException("Original Account association changed"); + } + if (original.receipt().isEmpty()) requireSourceChange(original.capture(), false); + return new Claim(false, original); + } + requireCapture(request, capture); + increment(request.expectedGeneration()); + increment(request.expectedSourceVersion()); + increment(capture.sourceState().issuanceFence().value()); + increment(capture.sourceState().issuanceFence().sourceVersion()); + increment(capture.checkpointSequence()); + if (request.mutationKinds().contains("GLOBAL_ROLE_CHANGED")) + increment(capture.globalRoleSourceVersion()); + ScopeState current = generations.read(AuthorityScope.account(request.accountUuid())); + if (!current.equals(capture.sourceState()) + || !readCurrentState(request.accountUuid(), capture.globalRoleSourceVersion()) + .equals(capture.beforeState())) { + throw new IllegalStateException("Original source/state capture is not current"); + } + requireCheckpoint(capture, request.accountUuid()); + requireSourceChange(capture, false); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, account_id, account_uuid, account_provenance, " + + "caller_proof_binding, request_payload, request_digest, expected_generation, " + + "expected_source_version, expected_fence, expected_fence_source_version, " + + "checkpoint_sequence, checkpoint_payload, global_role_source_version, before_state, " + + "after_state, mutation_kinds, source_change_id, source_change_binding, capture_payload, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'WAITING') " + + "ON CONFLICT (request_id) DO NOTHING", + request.requestId(), + capture.accountId(), + request.accountUuid(), + capture.provenance().name(), + request.callerProofBinding(), + AccountSecurityStateRequestDigest.requestBytes(request), + AccountSecurityStateRequestDigest.digest(request), + request.expectedGeneration(), + request.expectedSourceVersion(), + capture.sourceState().issuanceFence().value(), + capture.sourceState().issuanceFence().sourceVersion(), + capture.checkpointSequence(), + capture.checkpointPayload(), + capture.globalRoleSourceVersion(), + AccountSecurityStateMutationRequest.canonicalState(capture.beforeState()), + request.canonicalDesiredState(), + request.mutationKinds().toArray(String[]::new), + capture.sourceChange().changeId(), + capture.sourceChange().canonicalBytes(), + captureBytes(request, capture)); + Operation stored = readForUpdate(request.requestId()).orElseThrow(); + requireRequest(stored, request); + if (inserted == 1 + && !Arrays.equals( + captureBytes(request, capture), captureBytes(request, stored.capture()))) { + throw new IllegalStateException("Original operation capture readback differs"); + } + return new Claim(inserted == 1, stored); + } + + /** Returns immutable current or historical operation evidence without applying a mutation. */ + public Optional findByRequestId(UUID requestId) { + requireTransaction(); + Objects.requireNonNull(requestId); + Record identity = + dsl.fetchOne( + "SELECT account_id, account_uuid, account_provenance FROM " + + TABLE + + " WHERE request_id = ?", + requestId); + if (identity == null) return Optional.empty(); + lockAssociation( + identity.get("account_id", Long.class), + identity.get("account_uuid", UUID.class), + AccountIdentityProvenance.fromStorageValue( + identity.get("account_provenance", String.class))); + Optional stored = readForUpdate(requestId); + stored + .filter(operation -> operation.receipt().isEmpty()) + .ifPresent(operation -> requireSourceChange(operation.capture(), false)); + return stored; + } + + /** Proves actual current poststate, separately from immutable historical receipt validation. */ + public void requireCurrentPostState(Operation operation, ScopeState current) { + requireTransaction(); + Objects.requireNonNull(operation); + Receipt receipt = + operation + .receipt() + .orElseThrow( + () -> new IllegalStateException("Committed security-state receipt is required")); + var request = operation.request(); + lockAssociation( + operation.capture().accountId(), request.accountUuid(), operation.capture().provenance()); + Operation stored = findByRequestId(request.requestId()).orElseThrow(); + requireRequest(stored, request); + if (!stored.receipt().orElseThrow().event().equals(receipt.event()) + || current == null + || !receipt.sourceState().scope().equals(current.scope()) + || receipt.sourceState().generation() != current.generation() + || receipt.sourceState().sourceVersion() != current.sourceVersion() + || !generations.read(AuthorityScope.account(request.accountUuid())).equals(current) + || !readCurrentState(request.accountUuid(), receipt.globalRoleSourceVersion()) + .equals(request.desiredState())) { + throw new IllegalStateException( + "Latest security-state actual Account/role/source poststate differs"); + } + var checkpoint = outbox.readCheckpoint(streamKey(request.accountUuid())).orElseThrow(); + if (checkpoint.outboxSequence() != receipt.event().outboxSequence() + || !checkpoint.sourceEventId().equals(receipt.event().eventId()) + || !checkpoint.sourceEventDigest().equals(receipt.event().eventDigest())) { + throw new IllegalStateException("Latest security-state complete checkpoint differs"); + } + } + + /** Records only an existing producer-committed event and V57 completion in this transaction. */ + public Operation complete( + AccountSecurityStateMutationRequest request, + Event event, + ScopeState result, + long resultGlobalRoleSourceVersion) { + requireTransaction(); + Record identity = + dsl.fetchOne( + "SELECT account_id, account_provenance FROM " + TABLE + " WHERE request_id = ?", + request.requestId()); + if (identity == null) + throw new IllegalStateException("Original security-state request is missing"); + lockAssociation( + identity.get("account_id", Long.class), + request.accountUuid(), + AccountIdentityProvenance.fromStorageValue( + identity.get("account_provenance", String.class))); + Operation original = readForUpdate(request.requestId()).orElseThrow(); + requireRequest(original, request); + if (original.receipt().isPresent()) { + Receipt committed = original.receipt().orElseThrow(); + if (!committed.event().equals(event) + || !committed.sourceState().equals(result) + || committed.globalRoleSourceVersion() != resultGlobalRoleSourceVersion) { + throw new OperationConflictException("Committed receipt was supplied with changed results"); + } + return original; + } + requireResult(original, event, result, resultGlobalRoleSourceVersion); + requireSourceChange(original.capture(), true); + if (!generations.read(AuthorityScope.account(request.accountUuid())).equals(result) + || !readCurrentState(request.accountUuid(), resultGlobalRoleSourceVersion) + .equals(request.desiredState())) { + throw new IllegalStateException("Committed producer state readback differs"); + } + var checkpoint = outbox.readCheckpoint(event.outboxStreamKey()).orElseThrow(); + if (checkpoint.outboxSequence() != event.outboxSequence() + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new IllegalStateException("Committed source checkpoint readback differs"); + } + int updated = + dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'COMMITTED', event_sequence = ?, event_id = ?, " + + "event_digest = ?, event_payload = ?, result_generation = ?, result_source_version = ?, " + + "result_fence = ?, result_fence_source_version = ?, result_global_role_source_version = ? " + + "WHERE request_id = ? AND status = 'WAITING'", + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.payload(), + result.generation(), + result.sourceVersion(), + result.issuanceFence().value(), + result.issuanceFence().sourceVersion(), + resultGlobalRoleSourceVersion, + request.requestId()); + if (updated != 1) throw new IllegalStateException("Operation did not commit exactly once"); + Operation stored = readForUpdate(request.requestId()).orElseThrow(); + requireRequest(stored, request); + if (!stored.receipt().orElseThrow().event().equals(event)) { + throw new IllegalStateException("Committed operation event readback differs"); + } + return stored; + } + + private Optional readForUpdate(UUID requestId) { + Record row = + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", requestId); + if (row == null) return Optional.empty(); + UUID accountUuid = row.get("account_uuid", UUID.class); + var request = + new AccountSecurityStateMutationRequest( + requestId, + accountUuid, + row.get("caller_proof_binding", byte[].class), + row.get("expected_generation", Long.class), + row.get("expected_source_version", Long.class), + List.of(row.get("mutation_kinds", String[].class)), + AccountSecurityStateMutationRequest.parseCanonicalState( + row.get("after_state", byte[].class))); + if (!Arrays.equals( + AccountSecurityStateRequestDigest.requestBytes(request), + row.get("request_payload", byte[].class)) + || !AccountSecurityStateRequestDigest.digest(request) + .equals(row.get("request_digest", String.class))) { + throw new IllegalStateException("Stored original request digest/bytes differ"); + } + ScopeState expected = + new ScopeState( + AuthorityScope.account(accountUuid), + request.expectedGeneration(), + request.expectedSourceVersion(), + new AccountAuthorityGenerationRepository.IssuanceFence( + accountUuid, + row.get("expected_fence", Long.class), + row.get("expected_fence_source_version", Long.class))); + Capture capture = + new Capture( + row.get("account_id", Long.class), + AccountIdentityProvenance.fromStorageValue(row.get("account_provenance", String.class)), + AccountSecurityStateMutationRequest.parseCanonicalState( + row.get("before_state", byte[].class)), + expected, + row.get("checkpoint_sequence", Long.class), + row.get("checkpoint_payload", byte[].class), + row.get("global_role_source_version", Long.class), + SourceChange.fromStored(row.get("source_change_binding", byte[].class))); + requireCapture(request, capture); + if (!capture.sourceChange().changeId().equals(row.get("source_change_id", UUID.class)) + || !Arrays.equals( + captureBytes(request, capture), row.get("capture_payload", byte[].class))) { + throw new IllegalStateException("Stored original source capture differs"); + } + String status = row.get("status", String.class); + Optional receipt = Optional.empty(); + if ("COMMITTED".equals(status)) { + Event event = + new Event( + streamKey(accountUuid), + requestId.toString(), + row.get("event_sequence", Long.class), + row.get("event_id", String.class), + row.get("event_digest", String.class), + row.get("event_payload", byte[].class)); + ScopeState result = + new ScopeState( + AuthorityScope.account(accountUuid), + row.get("result_generation", Long.class), + row.get("result_source_version", Long.class), + new AccountAuthorityGenerationRepository.IssuanceFence( + accountUuid, + row.get("result_fence", Long.class), + row.get("result_fence_source_version", Long.class))); + receipt = + Optional.of( + new Receipt(event, result, row.get("result_global_role_source_version", Long.class))); + } else if (!"WAITING".equals(status)) { + throw new IllegalStateException("Unsupported operation state"); + } + Operation operation = new Operation(request, capture, receipt); + if (receipt.isPresent()) { + requireResult( + operation, + receipt.orElseThrow().event(), + receipt.orElseThrow().sourceState(), + receipt.orElseThrow().globalRoleSourceVersion()); + requireSourceChange(capture, true); + requireReceiptNotAhead(operation); + } + return Optional.of(operation); + } + + private void requireResult( + Operation operation, Event event, ScopeState result, long roleSourceVersion) { + if (event == null || result == null || result.issuanceFence() == null) { + throw new IllegalStateException("Complete Account source receipt is required"); + } + var request = operation.request(); + var capture = operation.capture(); + var verified = + AccountSecurityStateAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + if (!Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + || !request.accountUuid().toString().equals(verified.accountId()) + || !request.requestId().toString().equals(verified.requestId()) + || !request.requestId().toString().equals(event.requestId()) + || !streamKey(request.accountUuid()).equals(event.outboxStreamKey()) + || !event.outboxStreamKey().equals(verified.outboxStreamKey()) + || !event.eventId().equals(verified.eventId()) + || !event.eventDigest().equals(verified.eventDigest()) + || !Long.toString(event.outboxSequence()).equals(verified.outboxSequence()) + || event.outboxSequence() != increment(capture.checkpointSequence()) + || !result.scope().equals(capture.sourceState().scope()) + || result.generation() != increment(request.expectedGeneration()) + || result.sourceVersion() != increment(request.expectedSourceVersion()) + || !Long.toString(result.generation()).equals(verified.accountAuthorityGeneration()) + || !Long.toString(result.sourceVersion()).equals(verified.sourceVersion()) + || !request.accountUuid().equals(result.issuanceFence().accountId()) + || result.issuanceFence().value() + != increment(capture.sourceState().issuanceFence().value()) + || result.issuanceFence().sourceVersion() + != increment(capture.sourceState().issuanceFence().sourceVersion()) + || roleSourceVersion + != (request.mutationKinds().contains("GLOBAL_ROLE_CHANGED") + ? increment(capture.globalRoleSourceVersion()) + : capture.globalRoleSourceVersion()) + || !verified.accountState().equals(request.desiredState()) + || !verified.mutationKinds().equals(request.mutationKinds())) { + throw new IllegalStateException("Source receipt differs from the original operation/result"); + } + Event byRequest = outbox.findEvent(event.outboxStreamKey(), event.requestId()).orElseThrow(); + Event bySequence = + outbox.findEvent(event.outboxStreamKey(), event.outboxSequence()).orElseThrow(); + if (!event.equals(byRequest) || !event.equals(bySequence)) { + throw new IllegalStateException("Canonical outbox receipt readback differs"); + } + } + + private void requireCapture(AccountSecurityStateMutationRequest request, Capture capture) { + Objects.requireNonNull(capture.sourceChange(), "Original V57 source change is required"); + if (!capture.sourceState().scope().equals(AuthorityScope.account(request.accountUuid())) + || capture.sourceState().generation() != request.expectedGeneration() + || capture.sourceState().sourceVersion() != request.expectedSourceVersion() + || !request.accountUuid().equals(capture.sourceState().issuanceFence().accountId()) + || !detectedKinds(capture.beforeState(), request.desiredState()) + .equals(request.mutationKinds())) { + throw new IllegalArgumentException( + "Original state/source/family capture differs from request"); + } + // Passwords are intentionally absent; their real owner operation is outside this journal. + boolean accountSource = false; + boolean roleSource = false; + for (var source : capture.sourceChange().sources()) { + if (!request.accountUuid().toString().equals(source.scopeId())) { + throw new IllegalArgumentException("Source participation targets another Account"); + } + if (source.kind() == SourceKind.ACCOUNT) { + accountSource = true; + if (!Long.toString(request.expectedGeneration()).equals(source.generation()) + || !Long.toString(request.expectedSourceVersion()).equals(source.sourceVersion()) + || !streamKey(request.accountUuid()).equals(source.checkpointStream()) + || !Long.toString(capture.checkpointSequence()).equals(source.checkpointSequence()) + || !Arrays.equals(captureBytes(request, capture), source.evidence())) { + throw new IllegalArgumentException("Exact Account source participation is required"); + } + } else if (source.kind() == SourceKind.GLOBAL_ROLES) { + roleSource = true; + if (!Long.toString(capture.globalRoleSourceVersion()).equals(source.sourceVersion()) + || source.generation() != null + || source.checkpointStream() != null + || !Arrays.equals(captureBytes(request, capture), source.evidence())) { + throw new IllegalArgumentException("Independent role-source version differs"); + } + } else { + throw new IllegalArgumentException("Unrelated source participation is unsupported"); + } + } + if (!accountSource + || roleSource != request.mutationKinds().contains("GLOBAL_ROLE_CHANGED") + || !Arrays.equals(captureBytes(request, capture), capture.sourceChange().mutation())) { + throw new IllegalArgumentException("Complete exact source-change binding is required"); + } + } + + public static List detectedKinds(AccountState before, AccountState after) { + List kinds = new ArrayList<>(); + if (before.emailVerified() != after.emailVerified()) + kinds.add("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); + if (!before.globalRoles().equals(after.globalRoles())) kinds.add("GLOBAL_ROLE_CHANGED"); + if (!before.lifecycleState().equals(after.lifecycleState())) + kinds.add("LIFECYCLE_STATE_CHANGED"); + if (!before.loginAuthModes().equals(after.loginAuthModes())) + kinds.add("LOGIN_AUTH_MODES_CHANGED"); + return List.copyOf(kinds); + } + + public static byte[] captureBytes(AccountSecurityStateMutationRequest request, Capture capture) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + AccountSecurityStateRequestDigest.frame(bytes, "firemud/account/security-state/capture/v1"); + AccountSecurityStateRequestDigest.frame( + bytes, AccountSecurityStateRequestDigest.requestBytes(request)); + AccountSecurityStateRequestDigest.frame(bytes, Long.toString(capture.accountId())); + AccountSecurityStateRequestDigest.frame(bytes, capture.provenance().name()); + AccountSecurityStateRequestDigest.frame( + bytes, AccountSecurityStateMutationRequest.canonicalState(capture.beforeState())); + AccountSecurityStateRequestDigest.frame( + bytes, Long.toString(capture.sourceState().issuanceFence().value())); + AccountSecurityStateRequestDigest.frame( + bytes, Long.toString(capture.sourceState().issuanceFence().sourceVersion())); + AccountSecurityStateRequestDigest.frame(bytes, Long.toString(capture.checkpointSequence())); + AccountSecurityStateRequestDigest.frame(bytes, capture.checkpointPayload()); + AccountSecurityStateRequestDigest.frame( + bytes, Long.toString(capture.globalRoleSourceVersion())); + return bytes.toByteArray(); + } + + private void requireCheckpoint(Capture capture, UUID accountUuid) { + var checkpoint = outbox.readCheckpoint(streamKey(accountUuid)); + if (capture.checkpointSequence() == 0) { + Record history = + dsl.fetchOne( + "SELECT count(*)::integer AS count FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + streamKey(accountUuid)); + if (history == null) { + throw new IllegalStateException("Original Account source history count is missing"); + } + Integer count = history.get("count", Integer.class); + if (capture.sourceState().generation() != 1 + || capture.sourceState().sourceVersion() != 1 + || checkpoint.isPresent() + || count == null + || count != 0 + || capture.checkpointPayload().length != 0) { + throw new IllegalStateException("Original sequence-zero baseline is not proved"); + } + } else { + Event latest = + outbox.findEvent(streamKey(accountUuid), capture.checkpointSequence()).orElseThrow(); + if (checkpoint.orElseThrow().outboxSequence() != capture.checkpointSequence() + || !checkpoint.orElseThrow().sourceEventId().equals(latest.eventId()) + || !checkpoint.orElseThrow().sourceEventDigest().equals(latest.eventDigest()) + || !latest.equals( + outbox.findEvent(streamKey(accountUuid), latest.requestId()).orElseThrow()) + || !Arrays.equals(capture.checkpointPayload(), latest.payload())) { + throw new IllegalStateException("Original checkpoint capture differs"); + } + // Structural closed-schema verification only; this does not prove caller authorization. + new AccountSourceSnapshot( + accountUuid, + capture.sourceState(), + streamKey(accountUuid), + capture.checkpointSequence(), + Optional.of(latest)); + } + } + + private void requireReceiptNotAhead(Operation operation) { + Receipt retained = operation.receipt().orElseThrow(); + UUID accountUuid = operation.request().accountUuid(); + ScopeState current = generations.read(AuthorityScope.account(accountUuid)); + var checkpoint = outbox.readCheckpoint(streamKey(accountUuid)).orElseThrow(); + Event latest = + outbox.findEvent(streamKey(accountUuid), checkpoint.outboxSequence()).orElseThrow(); + AccountSourceSnapshot snapshot = + new AccountSourceSnapshot( + accountUuid, + current, + streamKey(accountUuid), + checkpoint.outboxSequence(), + Optional.of(latest)); + new AccountSourceEventReadback(snapshot, retained.event()); + Record role = + dsl.fetchOne( + "SELECT global_role_source_version FROM account_global_role_sources WHERE account_uuid = ? FOR SHARE", + accountUuid); + Long roleVersion = role == null ? null : role.get("global_role_source_version", Long.class); + if (retained.sourceState().issuanceFence().value() > current.issuanceFence().value() + || retained.sourceState().issuanceFence().sourceVersion() + > current.issuanceFence().sourceVersion() + || roleVersion == null + || retained.globalRoleSourceVersion() > roleVersion) { + throw new IllegalStateException("Retained receipt is ahead of present Account authority"); + } + } + + private void requireSourceChange(Capture capture, boolean committed) { + Record source = + dsl.fetchOne( + "SELECT binding, status FROM account_draft_authorization_source_changes WHERE change_id = ? FOR SHARE", + capture.sourceChange().changeId()); + if (source == null + || !Arrays.equals( + capture.sourceChange().canonicalBytes(), source.get("binding", byte[].class)) + || !(committed ? "SOURCE_COMMITTED" : "WAITING") + .equals(source.get("status", String.class))) { + throw new IllegalStateException("Original V57 source-change evidence/status differs"); + } + } + + private void lockAssociation( + long numericId, UUID accountUuid, AccountIdentityProvenance provenance) { + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_source_numeric_id, account_uuid_provenance FROM accounts WHERE id = ? FOR UPDATE", + numericId); + if (account == null + || !accountUuid.equals(account.get("account_uuid", UUID.class)) + || !Long.valueOf(numericId) + .equals(account.get("account_uuid_source_numeric_id", Long.class)) + || !provenance.name().equals(account.get("account_uuid_provenance", String.class))) { + throw new IllegalStateException("Persisted numeric/UUID/provenance association differs"); + } + } + + private AccountState readCurrentState(UUID accountUuid, long roleVersion) { + Record row = + dsl.fetchOne( + "SELECT a.email_verified, a.login_auth_modes, a.lifecycle_state, r.global_roles, r.global_role_source_version FROM accounts a JOIN account_global_role_sources r ON r.account_uuid = a.account_uuid WHERE a.account_uuid = ? FOR SHARE OF a, r", + accountUuid); + if (row == null + || !Long.valueOf(roleVersion).equals(row.get("global_role_source_version", Long.class))) { + throw new IllegalStateException( + "Current independently versioned global-role source is unavailable"); + } + var state = + new AccountState( + Boolean.TRUE.equals(row.get("email_verified", Boolean.class)), + AccountLoginAuthModes.read(row.get("login_auth_modes", String.class)).stream() + .map(Enum::name) + .sorted() + .toList(), + Arrays.stream(row.get("global_roles", String[].class)).sorted().toList(), + row.get("lifecycle_state", String.class).toUpperCase(java.util.Locale.ROOT)); + return AccountSecurityStateMutationRequest.parseCanonicalState( + AccountSecurityStateMutationRequest.canonicalState(state)); + } + + private static void requireRequest( + Operation original, AccountSecurityStateMutationRequest request) { + if (!Arrays.equals( + AccountSecurityStateRequestDigest.requestBytes(original.request()), + AccountSecurityStateRequestDigest.requestBytes(request))) { + throw new OperationConflictException( + "Request ID was reused with changed original caller/state binding"); + } + } + + private static long increment(long value) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account source counter overflow", overflow); + } + } + + private static String streamKey(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account owner transaction is required"); + } + } + + public record Capture( + long accountId, + AccountIdentityProvenance provenance, + AccountState beforeState, + ScopeState sourceState, + long checkpointSequence, + byte[] checkpointPayload, + long globalRoleSourceVersion, + SourceChange sourceChange) { + public Capture { + if (accountId <= 0 + || checkpointSequence < 0 + || globalRoleSourceVersion <= 0 + || provenance == null + || beforeState == null + || sourceState == null + || sourceState.issuanceFence() == null + || checkpointPayload == null) + throw new IllegalArgumentException("Complete original capture is required"); + checkpointPayload = checkpointPayload.clone(); + beforeState = + AccountSecurityStateMutationRequest.parseCanonicalState( + AccountSecurityStateMutationRequest.canonicalState(beforeState)); + // A temporary null change is permitted solely while constructing its non-circular capture + // bytes. + } + + @Override + public byte[] checkpointPayload() { + return checkpointPayload.clone(); + } + } + + public record Receipt(Event event, ScopeState sourceState, long globalRoleSourceVersion) {} + + public record Operation( + AccountSecurityStateMutationRequest request, Capture capture, Optional receipt) {} + + public record Claim(boolean claimed, Operation operation) {} + + public static final class OperationConflictException extends IllegalStateException { + public OperationConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java index 48e3d68de8..670e19cd9c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java @@ -28,6 +28,7 @@ import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; @@ -35,8 +36,8 @@ import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; /** - * Narrow validator for the two closed Account account-scope source-event schemas currently emitted. - * It does not authenticate a caller or turn source evidence into recipient authority. + * Narrow receipt validator for the three closed Account account-scope source-event schemas. It does + * not authenticate a caller or turn source evidence into recipient authority. */ public final class AccountAuthoritySourceEventReadback { private static final ObjectMapper SNAPSHOT_JSON = @@ -56,11 +57,13 @@ public final class AccountAuthoritySourceEventReadback { private final AccountAuthorityOutboxRepository outboxRepository; private final AccountPasswordResetOperationRepository passwordResetRepository; private final AccountLogoutAllOperationRepository logoutAllRepository; + private final AccountSecurityStateOperationRepository securityStateRepository; public AccountAuthoritySourceEventReadback( AccountAuthorityOutboxRepository outboxRepository, AccountPasswordResetOperationRepository passwordResetRepository, - AccountLogoutAllOperationRepository logoutAllRepository) { + AccountLogoutAllOperationRepository logoutAllRepository, + AccountSecurityStateOperationRepository securityStateRepository) { this.outboxRepository = Objects.requireNonNull(outboxRepository, "Account authority outbox repository is required"); this.passwordResetRepository = @@ -68,6 +71,9 @@ public AccountAuthoritySourceEventReadback( passwordResetRepository, "Password-reset operation repository is required"); this.logoutAllRepository = Objects.requireNonNull(logoutAllRepository, "Logout-all operation repository is required"); + this.securityStateRepository = + Objects.requireNonNull( + securityStateRepository, "Security-state operation repository is required"); } /** @@ -124,6 +130,8 @@ public LatestSourceSnapshot requireCurrentLatest(Account account, ScopeState cur new IllegalStateException( "Latest Account password-reset event has no immutable operation receipt")); requirePasswordResetReceipt(account, receipt, latestEvent, verified, current); + } else if (verified.securityState().isPresent()) { + requireSecurityStateReceipt(account, latestEvent, verified, current, true); } else { UUID requestId = parseLogoutAllRequestId(verified.requestId()); LogoutAllReceipt receipt = @@ -186,6 +194,10 @@ public void requireRetainedEvent(Account account, Event event, ScopeState curren return; } + if (verified.securityState().isPresent()) { + requireSecurityStateReceipt(account, event, verified, current, false); + return; + } UUID requestId = parseLogoutAllRequestId(verified.requestId()); LogoutAllReceipt receipt = logoutAllRepository @@ -204,6 +216,41 @@ private long currentSourceSequence(Account account) { .orElse(0L); } + private void requireSecurityStateReceipt( + Account account, + Event event, + VerifiedSourceEvent verified, + ScopeState current, + boolean latest) { + var operation = + securityStateRepository + .findByRequestId(UUID.fromString(verified.requestId())) + .orElseThrow( + () -> + new IllegalStateException( + "Account security-state event has no immutable operation receipt")); + var receipt = + operation + .receipt() + .orElseThrow( + () -> + new IllegalStateException("Account security-state operation is not COMMITTED")); + if (!operation.request().accountUuid().equals(account.getAccountUuid()) + || operation.capture().accountId() != account.getId() + || operation.capture().provenance() != account.getAccountUuidProvenance() + || !receipt.event().equals(event)) { + throw new IllegalStateException("Account security-state operation association/event differs"); + } + requireReceiptNotAhead( + receipt.sourceState().generation(), + receipt.sourceState().sourceVersion(), + receipt.sourceState().issuanceFence().value(), + receipt.sourceState().issuanceFence().sourceVersion(), + current, + "Security-state"); + if (latest) securityStateRepository.requireCurrentPostState(operation, current); + } + private void requirePasswordResetReceipt( Account account, PasswordResetReceipt receipt, @@ -321,49 +368,85 @@ private UUID parseLogoutAllRequestId(String requestIdText) { } private static VerifiedSourceEvent verifyEvent(Event event, UUID accountUuid) { - if (event == null) { - throw new IllegalStateException("Account source event is missing"); - } + if (event == null) throw new IllegalStateException("Account source event is missing"); String payload = new String(event.payload(), StandardCharsets.UTF_8); try { - PasswordResetAuthorityEvent reset = PasswordResetAuthorityEventV1Codec.verify(payload); - if (!MessageDigest.isEqual(event.payload(), reset.canonicalJsonUtf8()) - || !event.outboxStreamKey().equals(reset.outboxStreamKey()) - || !event.requestId().equals(reset.requestId()) - || !event.eventId().equals(reset.eventId()) - || !event.eventDigest().equals(reset.eventDigest()) - || !accountUuid.toString().equals(reset.accountId()) - || !Long.toString(event.outboxSequence()).equals(reset.outboxSequence())) { - throw new IllegalStateException("Account password-reset event readback is inconsistent"); + JsonNode tree = SNAPSHOT_JSON.readTree(payload); + if (tree == null || !tree.isObject() || !tree.path("schemaVersion").isTextual()) { + throw new IllegalStateException("Account source event schema is missing"); } - return VerifiedSourceEvent.passwordReset(reset); - } catch (IllegalArgumentException resetFailure) { - try { - AccountLogoutAllAuthorityEvent logout = - AccountLogoutAllAuthorityEventV1Codec.verify(payload); - if (!MessageDigest.isEqual(event.payload(), logout.canonicalJsonUtf8()) - || !event.outboxStreamKey().equals(logout.outboxStreamKey()) - || !event.requestId().equals(logout.requestId()) - || !event.eventId().equals(logout.eventId()) - || !event.eventDigest().equals(logout.eventDigest()) - || !accountUuid.toString().equals(logout.accountId()) - || !Long.toString(event.outboxSequence()).equals(logout.outboxSequence())) { - throw new IllegalStateException("Account logout-all event readback is inconsistent"); + return switch (tree.path("schemaVersion").textValue()) { + case PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION -> { + var reset = PasswordResetAuthorityEventV1Codec.verify(payload); + requireEventBinding( + event, + accountUuid, + reset.accountId(), + reset.requestId(), + reset.eventId(), + reset.eventDigest(), + reset.outboxStreamKey(), + reset.outboxSequence(), + reset.canonicalJsonUtf8()); + yield VerifiedSourceEvent.passwordReset(reset); } - return VerifiedSourceEvent.logoutAll(logout); - } catch (IllegalArgumentException logoutFailure) { - logoutFailure.addSuppressed(resetFailure); - throw new IllegalStateException( - "Account source event is not a valid declared password-reset or logout-all event", - logoutFailure); - } + case AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION -> { + var logout = AccountLogoutAllAuthorityEventV1Codec.verify(payload); + requireEventBinding( + event, + accountUuid, + logout.accountId(), + logout.requestId(), + logout.eventId(), + logout.eventDigest(), + logout.outboxStreamKey(), + logout.outboxSequence(), + logout.canonicalJsonUtf8()); + yield VerifiedSourceEvent.logoutAll(logout); + } + case AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION -> { + var security = AccountSecurityStateAuthorityEventV1Codec.verify(payload); + requireEventBinding( + event, + accountUuid, + security.accountId(), + security.requestId(), + security.eventId(), + security.eventDigest(), + security.outboxStreamKey(), + security.outboxSequence(), + security.canonicalJsonUtf8()); + yield VerifiedSourceEvent.securityState(security); + } + default -> throw new IllegalStateException("Account source event schema is unsupported"); + }; + } catch (IOException | IllegalArgumentException invalid) { + throw new IllegalStateException("Account source event is invalid", invalid); } } - /** - * Checks structural source-result invariants, without proving an immutable operation receipt. - * Security-state evidence remains unsupported by the owner current/historical receipt readers. - */ + private static void requireEventBinding( + Event event, + UUID accountUuid, + String accountId, + String requestId, + String eventId, + String digest, + String stream, + String sequence, + byte[] canonical) { + if (!MessageDigest.isEqual(event.payload(), canonical) + || !accountUuid.toString().equals(accountId) + || !event.requestId().equals(requestId) + || !event.eventId().equals(eventId) + || !event.eventDigest().equals(digest) + || !event.outboxStreamKey().equals(stream) + || !Long.toString(event.outboxSequence()).equals(sequence)) { + throw new IllegalStateException("Account source event readback is inconsistent"); + } + } + + /** Structural binding only; owner receipt proof is checked separately. */ static void requireEventMatchesSnapshot( Event event, UUID accountUuid, ScopeState current, boolean mustBeCurrentLatest) { if (accountUuid == null @@ -391,42 +474,8 @@ static void requireEventMatchesSnapshot( } private static SnapshotCounters verifySnapshotEvent(Event event, UUID accountUuid) { - if (event == null) { - throw new IllegalStateException("Account source event is missing"); - } - String payload = new String(event.payload(), StandardCharsets.UTF_8); - final JsonNode tree; - try { - tree = SNAPSHOT_JSON.readTree(payload); - } catch (IOException exception) { - throw new IllegalStateException("Account source event snapshot JSON is malformed", exception); - } - if (tree == null || !tree.isObject() || !tree.path("schemaVersion").isTextual()) { - throw new IllegalStateException("Account source event snapshot schema is missing"); - } - if (!AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION.equals( - tree.path("schemaVersion").textValue())) { - VerifiedSourceEvent original = verifyEvent(event, accountUuid); - return new SnapshotCounters(original.accountAuthorityGeneration(), original.sourceVersion()); - } - final AccountSecurityStateAuthorityEventV1Codec.AccountSecurityStateAuthorityEvent security; - try { - security = AccountSecurityStateAuthorityEventV1Codec.verify(payload); - } catch (IllegalArgumentException exception) { - throw new IllegalStateException( - "Account security-state snapshot event is invalid", exception); - } - if (!MessageDigest.isEqual(event.payload(), security.canonicalJsonUtf8()) - || !event.outboxStreamKey().equals(security.outboxStreamKey()) - || !event.requestId().equals(security.requestId()) - || !event.eventId().equals(security.eventId()) - || !event.eventDigest().equals(security.eventDigest()) - || !accountUuid.toString().equals(security.accountId()) - || !Long.toString(event.outboxSequence()).equals(security.outboxSequence())) { - throw new IllegalStateException( - "Account security-state snapshot event readback is inconsistent"); - } - return new SnapshotCounters(security.accountAuthorityGeneration(), security.sourceVersion()); + VerifiedSourceEvent verified = verifyEvent(event, accountUuid); + return new SnapshotCounters(verified.accountAuthorityGeneration(), verified.sourceVersion()); } private record SnapshotCounters(String accountAuthorityGeneration, String sourceVersion) {} @@ -546,13 +595,16 @@ private record VerifiedSourceEvent( String requestId, String accountAuthorityGeneration, String sourceVersion, - Optional passwordReset) { + Optional passwordReset, + Optional + securityState) { private static VerifiedSourceEvent passwordReset(PasswordResetAuthorityEvent event) { return new VerifiedSourceEvent( event.requestId(), event.accountAuthorityGeneration(), event.sourceVersion(), - Optional.of(event)); + Optional.of(event), + Optional.empty()); } private static VerifiedSourceEvent logoutAll(AccountLogoutAllAuthorityEvent event) { @@ -560,7 +612,18 @@ private static VerifiedSourceEvent logoutAll(AccountLogoutAllAuthorityEvent even event.requestId(), event.accountAuthorityGeneration(), event.sourceVersion(), + Optional.empty(), Optional.empty()); } + + private static VerifiedSourceEvent securityState( + AccountSecurityStateAuthorityEventV1Codec.AccountSecurityStateAuthorityEvent event) { + return new VerifiedSourceEvent( + event.requestId(), + event.accountAuthorityGeneration(), + event.sourceVersion(), + Optional.empty(), + Optional.of(event)); + } } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 6454766381..eeedc10e00 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -112,6 +112,8 @@ public AccountMembershipAuthorityEventProducer( AccountAuthorityOutboxRepository authorityOutboxRepository, AccountPasswordResetOperationRepository passwordResetOperationRepository, AccountLogoutAllOperationRepository logoutAllOperationRepository, + net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository + securityStateOperationRepository, AccountMembershipTransitionReceiptRepository transitionReceiptRepository, AccountTenantMembershipRepository membershipRepository, AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository, @@ -128,7 +130,8 @@ public AccountMembershipAuthorityEventProducer( new AccountAuthoritySourceEventReadback( authorityOutboxRepository, passwordResetOperationRepository, - logoutAllOperationRepository); + logoutAllOperationRepository, + securityStateOperationRepository); this.transitionReceiptRepository = transitionReceiptRepository; this.membershipRepository = membershipRepository; this.roleSnapshotRepository = roleSnapshotRepository; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 019a383e93..ce5e797102 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -196,6 +196,8 @@ public AccountServiceImpl( AccountAuthorityOutboxRepository accountAuthorityOutboxRepository, AccountPasswordResetOperationRepository passwordResetOperationRepository, AccountLogoutAllOperationRepository logoutAllOperationRepository, + net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository + securityStateOperationRepository, AccountAuditOutboxRepository accountAuditOutboxRepository, AccountConnectScopeRepository accountConnectScopeRepository, AccountJoinOperationRepository accountJoinOperationRepository, @@ -231,7 +233,8 @@ public AccountServiceImpl( new AccountAuthoritySourceEventReadback( accountAuthorityOutboxRepository, passwordResetOperationRepository, - logoutAllOperationRepository); + logoutAllOperationRepository, + securityStateOperationRepository); this.accountAuditOutboxRepository = accountAuditOutboxRepository; this.accountConnectScopeRepository = accountConnectScopeRepository; this.accountJoinOperationRepository = accountJoinOperationRepository; diff --git a/services/account-service/src/main/resources/db/migration/V65__account_security_state_operations.sql b/services/account-service/src/main/resources/db/migration/V65__account_security_state_operations.sql new file mode 100644 index 0000000000..74864eee4b --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V65__account_security_state_operations.sql @@ -0,0 +1,371 @@ +-- Correlation/receipt storage only. No source writer, authorization grant, or retained-row backfill. +CREATE TABLE account_security_state_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'), + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL, + account_provenance VARCHAR(40) NOT NULL, + caller_proof_binding BYTEA NOT NULL CHECK (octet_length(caller_proof_binding) BETWEEN 1 AND 16384), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0), + request_digest VARCHAR(64) NOT NULL CHECK (request_digest ~ '^[0-9a-f]{64}$'), + expected_generation BIGINT NOT NULL CHECK (expected_generation > 0), + expected_source_version BIGINT NOT NULL CHECK (expected_source_version > 0), + expected_fence BIGINT NOT NULL CHECK (expected_fence > 0), + expected_fence_source_version BIGINT NOT NULL CHECK (expected_fence_source_version > 0), + checkpoint_sequence BIGINT NOT NULL CHECK (checkpoint_sequence >= 0), + checkpoint_payload BYTEA NOT NULL, + global_role_source_version BIGINT NOT NULL CHECK (global_role_source_version > 0), + before_state BYTEA NOT NULL, + after_state BYTEA NOT NULL, + mutation_kinds TEXT[] NOT NULL CHECK (cardinality(mutation_kinds) BETWEEN 1 AND 4), + source_change_id UUID NOT NULL UNIQUE REFERENCES account_draft_authorization_source_changes(change_id), + source_change_binding BYTEA NOT NULL CHECK (octet_length(source_change_binding) > 0), + capture_payload BYTEA NOT NULL CHECK (octet_length(capture_payload) > 0), + status VARCHAR(12) NOT NULL CHECK (status IN ('WAITING', 'COMMITTED')), + event_sequence BIGINT CHECK (event_sequence > 0), + event_id VARCHAR(128), + event_digest VARCHAR(71), + event_payload BYTEA, + result_generation BIGINT CHECK (result_generation > 0), + result_source_version BIGINT CHECK (result_source_version > 0), + result_fence BIGINT CHECK (result_fence > 0), + result_fence_source_version BIGINT CHECK (result_fence_source_version > 0), + result_global_role_source_version BIGINT CHECK (result_global_role_source_version > 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + FOREIGN KEY (account_uuid, account_id, account_provenance) + REFERENCES accounts(account_uuid, account_uuid_source_numeric_id, account_uuid_provenance) + ON DELETE RESTRICT, + CONSTRAINT account_security_state_result_shape CHECK ( + (status = 'WAITING' AND event_sequence IS NULL AND event_id IS NULL AND event_digest IS NULL + AND event_payload IS NULL AND result_generation IS NULL AND result_source_version IS NULL + AND result_fence IS NULL AND result_fence_source_version IS NULL + AND result_global_role_source_version IS NULL AND committed_at IS NULL) + OR (status = 'COMMITTED' AND event_sequence IS NOT NULL AND event_id IS NOT NULL + AND event_digest IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$' AND event_payload IS NOT NULL + AND result_generation IS NOT NULL AND result_source_version IS NOT NULL + AND result_fence IS NOT NULL AND result_fence_source_version IS NOT NULL + AND result_global_role_source_version IS NOT NULL AND committed_at IS NOT NULL)) +); + +CREATE UNIQUE INDEX account_security_state_event_checkpoint_unique + ON account_security_state_operations(account_uuid, event_sequence) WHERE event_sequence IS NOT NULL; + +-- [jooq ignore start] +CREATE FUNCTION account_security_state_frame(value BYTEA) +RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT int4send(octet_length(value)) || value; +$$; + +CREATE FUNCTION account_security_state_canonical_state(value BYTEA) +RETURNS TEXT LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + state JSONB := convert_from(value, 'UTF8')::JSONB; + modes TEXT[]; + roles TEXT[]; + canonical TEXT; +BEGIN + IF jsonb_typeof(state) <> 'object' + OR (SELECT array_agg(k ORDER BY k) FROM jsonb_object_keys(state) k) + <> ARRAY['emailVerified','globalRoles','lifecycleState','loginAuthModes'] + OR jsonb_typeof(state->'emailVerified') <> 'boolean' + OR jsonb_typeof(state->'loginAuthModes') <> 'array' + OR jsonb_typeof(state->'globalRoles') <> 'array' + OR jsonb_typeof(state->'lifecycleState') <> 'string' + OR state->>'lifecycleState' NOT IN ('ACTIVE','SECURITY_LOCKED','DEACTIVATED_PENDING_DELETE','DELETED') THEN + RAISE EXCEPTION 'Unsupported security-state representation' USING ERRCODE = '23514'; + END IF; + SELECT COALESCE(array_agg(v ORDER BY ordinal), ARRAY[]::TEXT[]) INTO modes + FROM jsonb_array_elements_text(state->'loginAuthModes') WITH ORDINALITY AS t(v, ordinal); + SELECT COALESCE(array_agg(v ORDER BY ordinal), ARRAY[]::TEXT[]) INTO roles + FROM jsonb_array_elements_text(state->'globalRoles') WITH ORDINALITY AS t(v, ordinal); + IF cardinality(modes) = 0 OR NOT modes <@ ARRAY['EMAIL_OTP','PASSWORD']::TEXT[] + OR modes <> (SELECT array_agg(DISTINCT v ORDER BY v) FROM unnest(modes) v) + OR NOT roles <@ ARRAY['billingAdmin','platformAdmin','support']::TEXT[] + OR roles <> (SELECT COALESCE(array_agg(DISTINCT v ORDER BY v), ARRAY[]::TEXT[]) FROM unnest(roles) v) THEN + RAISE EXCEPTION 'Unsupported security-state arrays' USING ERRCODE = '23514'; + END IF; + canonical := '{"emailVerified":' || (state->'emailVerified')::TEXT + || ',"globalRoles":' || replace((state->'globalRoles')::TEXT, ', ', ',') + || ',"lifecycleState":"' || (state->>'lifecycleState') || '"' + || ',"loginAuthModes":' || replace((state->'loginAuthModes')::TEXT, ', ', ',') || '}'; + IF value IS DISTINCT FROM convert_to(canonical, 'UTF8') THEN + RAISE EXCEPTION 'Security-state bytes must be complete canonical JSON' USING ERRCODE = '23514'; + END IF; + RETURN canonical; +END; +$$; + +CREATE FUNCTION account_security_state_operation_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + before_json JSONB; + after_json JSONB; + kinds TEXT[] := ARRAY[]::TEXT[]; + request_bytes BYTEA; + capture_bytes BYTEA; + account_source_bytes BYTEA; + role_source_bytes BYTEA; + change_bytes BYTEA; + kind TEXT; + source_row RECORD; + account_row RECORD; + role_row RECORD; + authority_row RECORD; + fence_row RECORD; + outbox_row RECORD; + stream_row RECORD; + key TEXT; + preimage TEXT; + expected_digest TEXT; + expected_wire TEXT; + caller_json JSONB; + canonical_caller TEXT; + checkpoint_json JSONB; + checkpoint_text TEXT; + checkpoint_preimage TEXT; +BEGIN + IF TG_OP = 'UPDATE' THEN + IF OLD.status <> 'WAITING' OR NEW.status <> 'COMMITTED' + OR (to_jsonb(NEW) - ARRAY['status','event_sequence','event_id','event_digest','event_payload', + 'result_generation','result_source_version','result_fence','result_fence_source_version', + 'result_global_role_source_version','committed_at']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status','event_sequence','event_id','event_digest','event_payload', + 'result_generation','result_source_version','result_fence','result_fence_source_version', + 'result_global_role_source_version','committed_at']) THEN + RAISE EXCEPTION 'Original security-state request/capture and committed results are immutable' + USING ERRCODE = '23514'; + END IF; + NEW.committed_at := CURRENT_TIMESTAMP; + ELSIF NEW.status <> 'WAITING' THEN + RAISE EXCEPTION 'Security-state operation must start WAITING' USING ERRCODE = '23514'; + END IF; + before_json := account_security_state_canonical_state(NEW.before_state)::JSONB; + after_json := account_security_state_canonical_state(NEW.after_state)::JSONB; + caller_json := convert_from(NEW.caller_proof_binding,'UTF8')::JSONB; + IF jsonb_typeof(caller_json) <> 'object' + OR (SELECT array_agg(k ORDER BY k) FROM jsonb_object_keys(caller_json) k) + <> ARRAY['actorAccountUuid','ownerEvidenceDigest','ownerOperationId','schemaVersion'] + OR caller_json->>'schemaVersion' <> 'account-security-state-caller-correlation/v1' + OR jsonb_typeof(caller_json->'actorAccountUuid') <> 'string' + OR jsonb_typeof(caller_json->'ownerOperationId') <> 'string' + OR jsonb_typeof(caller_json->'ownerEvidenceDigest') <> 'string' + OR jsonb_typeof(caller_json->'schemaVersion') <> 'string' + OR caller_json->>'actorAccountUuid' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR caller_json->>'ownerOperationId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR caller_json->>'actorAccountUuid' = '00000000-0000-0000-0000-000000000000' + OR caller_json->>'ownerOperationId' = '00000000-0000-0000-0000-000000000000' + OR caller_json->>'ownerEvidenceDigest' !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Unsupported original caller correlation shape' USING ERRCODE = '23514'; + END IF; + canonical_caller := '{"actorAccountUuid":"' || (caller_json->>'actorAccountUuid') + || '","ownerEvidenceDigest":"' || (caller_json->>'ownerEvidenceDigest') + || '","ownerOperationId":"' || (caller_json->>'ownerOperationId') + || '","schemaVersion":"account-security-state-caller-correlation/v1"}'; + IF NEW.caller_proof_binding IS DISTINCT FROM convert_to(canonical_caller,'UTF8') THEN + RAISE EXCEPTION 'Original caller correlation bytes must be canonical' USING ERRCODE = '23514'; + END IF; + IF before_json->'emailVerified' <> after_json->'emailVerified' THEN + kinds := array_append(kinds, 'EMAIL_LOGIN_ELIGIBILITY_CHANGED'); + END IF; + IF before_json->'globalRoles' <> after_json->'globalRoles' THEN + kinds := array_append(kinds, 'GLOBAL_ROLE_CHANGED'); + END IF; + IF before_json->'lifecycleState' <> after_json->'lifecycleState' THEN + kinds := array_append(kinds, 'LIFECYCLE_STATE_CHANGED'); + END IF; + IF before_json->'loginAuthModes' <> after_json->'loginAuthModes' THEN + kinds := array_append(kinds, 'LOGIN_AUTH_MODES_CHANGED'); + END IF; + IF kinds <> NEW.mutation_kinds OR cardinality(kinds) = 0 THEN + RAISE EXCEPTION 'Complete changed-family set differs from state images' USING ERRCODE = '23514'; + END IF; + request_bytes := account_security_state_frame(convert_to('firemud/account/security-state/request/v1','UTF8')) + || account_security_state_frame(convert_to(NEW.request_id::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.account_uuid::TEXT,'UTF8')) + || account_security_state_frame(NEW.caller_proof_binding) + || account_security_state_frame(convert_to(NEW.expected_generation::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.expected_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to(cardinality(kinds)::TEXT,'UTF8')); + FOREACH kind IN ARRAY kinds LOOP + request_bytes := request_bytes || account_security_state_frame(convert_to(kind,'UTF8')); + END LOOP; + request_bytes := request_bytes || account_security_state_frame(NEW.after_state); + capture_bytes := account_security_state_frame(convert_to('firemud/account/security-state/capture/v1','UTF8')) + || account_security_state_frame(request_bytes) + || account_security_state_frame(convert_to(NEW.account_id::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.account_provenance,'UTF8')) + || account_security_state_frame(NEW.before_state) + || account_security_state_frame(convert_to(NEW.expected_fence::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.expected_fence_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.checkpoint_sequence::TEXT,'UTF8')) + || account_security_state_frame(NEW.checkpoint_payload) + || account_security_state_frame(convert_to(NEW.global_role_source_version::TEXT,'UTF8')); + IF request_bytes <> NEW.request_payload OR encode(sha256(request_bytes),'hex') <> NEW.request_digest + OR capture_bytes <> NEW.capture_payload THEN + RAISE EXCEPTION 'Security-state request/capture bytes or digest differ' USING ERRCODE = '23514'; + END IF; + -- Reuse the exact V57 framing; correlation cannot substitute a different source vector. + key := 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT; + account_source_bytes := account_security_state_frame(convert_to('account-draft-source-evidence/v1','UTF8')) + || account_security_state_frame(convert_to('ACCOUNT','UTF8')) + || account_security_state_frame(convert_to(NEW.account_uuid::TEXT,'UTF8')) + || account_security_state_frame(convert_to('PRESENT','UTF8')) + || account_security_state_frame(convert_to(NEW.expected_generation::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.expected_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to('PRESENT','UTF8')) + || account_security_state_frame(convert_to(key,'UTF8')) + || account_security_state_frame(convert_to(NEW.checkpoint_sequence::TEXT,'UTF8')) + || account_security_state_frame(capture_bytes); + change_bytes := account_security_state_frame(convert_to('account-draft-source-change/v1','UTF8')) + || account_security_state_frame(convert_to(NEW.source_change_id::TEXT,'UTF8')) + || account_security_state_frame(convert_to(CASE WHEN 'GLOBAL_ROLE_CHANGED' = ANY(kinds) THEN '2' ELSE '1' END,'UTF8')) + || account_security_state_frame(account_source_bytes); + IF 'GLOBAL_ROLE_CHANGED' = ANY(kinds) THEN + role_source_bytes := account_security_state_frame(convert_to('account-draft-source-evidence/v1','UTF8')) + || account_security_state_frame(convert_to('GLOBAL_ROLES','UTF8')) + || account_security_state_frame(convert_to(NEW.account_uuid::TEXT,'UTF8')) + || account_security_state_frame(convert_to('ABSENT','UTF8')) + || account_security_state_frame(convert_to(NEW.global_role_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to('ABSENT','UTF8')) + || account_security_state_frame(capture_bytes); + change_bytes := change_bytes || account_security_state_frame(role_source_bytes); + END IF; + change_bytes := change_bytes || account_security_state_frame(capture_bytes); + IF change_bytes <> NEW.source_change_binding THEN + RAISE EXCEPTION 'Security-state exact V57 participation binding differs' USING ERRCODE = '23514'; + END IF; + SELECT * INTO account_row FROM accounts WHERE id = NEW.account_id FOR UPDATE; + IF NOT FOUND OR account_row.account_uuid <> NEW.account_uuid + OR account_row.account_uuid_source_numeric_id <> NEW.account_id + OR account_row.account_uuid_provenance <> NEW.account_provenance THEN + RAISE EXCEPTION 'Security-state Account association differs' USING ERRCODE = '23514'; + END IF; + SELECT * INTO source_row FROM account_draft_authorization_source_changes + WHERE change_id = NEW.source_change_id FOR SHARE; + IF NOT FOUND OR source_row.binding <> NEW.source_change_binding + OR source_row.status <> CASE WHEN TG_OP = 'INSERT' THEN 'WAITING' ELSE 'SOURCE_COMMITTED' END THEN + RAISE EXCEPTION 'Security-state V57 source change differs' USING ERRCODE = '23514'; + END IF; + SELECT * INTO authority_row FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid FOR SHARE; + SELECT * INTO fence_row FROM account_authority_issuance_fences WHERE account_uuid = NEW.account_uuid FOR SHARE; + SELECT * INTO role_row FROM account_global_role_sources WHERE account_uuid = NEW.account_uuid FOR SHARE; + IF authority_row IS NULL OR fence_row IS NULL OR role_row IS NULL THEN + RAISE EXCEPTION 'Security-state current source evidence is missing' USING ERRCODE = '23514'; + END IF; + key := 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT; + IF TG_OP = 'INSERT' THEN + IF NEW.expected_generation = 9223372036854775807 OR NEW.expected_source_version = 9223372036854775807 + OR NEW.expected_fence = 9223372036854775807 OR NEW.expected_fence_source_version = 9223372036854775807 + OR NEW.checkpoint_sequence = 9223372036854775807 + OR ('GLOBAL_ROLE_CHANGED' = ANY(kinds) AND NEW.global_role_source_version = 9223372036854775807) THEN + RAISE EXCEPTION 'Account source counter overflow' USING ERRCODE = '23514'; + END IF; + IF authority_row.generation <> NEW.expected_generation OR authority_row.source_version <> NEW.expected_source_version + OR fence_row.issuance_fence <> NEW.expected_fence OR fence_row.source_version <> NEW.expected_fence_source_version + OR role_row.global_role_source_version <> NEW.global_role_source_version THEN + RAISE EXCEPTION 'Security-state original source capture is stale' USING ERRCODE = '23514'; + END IF; + IF NEW.checkpoint_sequence = 0 THEN + IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1 OR octet_length(NEW.checkpoint_payload) <> 0 + OR EXISTS (SELECT 1 FROM account_authority_outbox_events WHERE outbox_stream_key = key) + OR EXISTS (SELECT 1 FROM account_authority_outbox_streams WHERE outbox_stream_key = key) THEN + RAISE EXCEPTION 'Security-state pristine baseline is not proved' USING ERRCODE = '23514'; + END IF; + ELSE + SELECT * INTO stream_row FROM account_authority_outbox_streams WHERE outbox_stream_key = key; + SELECT * INTO outbox_row FROM account_authority_outbox_events + WHERE outbox_stream_key = key AND outbox_sequence = NEW.checkpoint_sequence; + IF stream_row IS NULL OR outbox_row IS NULL OR stream_row.last_sequence <> NEW.checkpoint_sequence + OR outbox_row.payload <> NEW.checkpoint_payload THEN + RAISE EXCEPTION 'Security-state original checkpoint differs' USING ERRCODE = '23514'; + END IF; + checkpoint_text := convert_from(NEW.checkpoint_payload,'UTF8'); + checkpoint_json := checkpoint_text::JSONB; + checkpoint_preimage := replace(checkpoint_text, + '"eventDigest":"' || outbox_row.event_digest || '",', ''); + IF COALESCE(checkpoint_json->>'schemaVersion','') NOT IN ('account-auth-password-reset-event/v1', + 'account-auth-logout-all-event/v1', 'account-auth-account-security-state-event/v1') + OR checkpoint_json->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR checkpoint_json->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT + OR checkpoint_json->>'outboxStreamKey' IS DISTINCT FROM key + OR checkpoint_json->>'outboxSequence' IS DISTINCT FROM NEW.checkpoint_sequence::TEXT + OR checkpoint_json->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.expected_generation::TEXT + OR checkpoint_json->>'sourceVersion' IS DISTINCT FROM NEW.expected_source_version::TEXT + OR checkpoint_json->>'requestId' IS DISTINCT FROM outbox_row.request_id + OR checkpoint_json->>'eventId' IS DISTINCT FROM outbox_row.event_id + OR checkpoint_json->>'eventDigest' IS DISTINCT FROM outbox_row.event_digest + OR checkpoint_json->'accountSecurityCutoff'->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.expected_generation::TEXT + OR checkpoint_json->'accountSecurityCutoff'->>'outboxStreamKey' IS DISTINCT FROM key + OR checkpoint_json->'accountSecurityCutoff'->>'outboxSequence' IS DISTINCT FROM NEW.checkpoint_sequence::TEXT + OR outbox_row.event_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(checkpoint_preimage,'UTF8')),'hex') + OR checkpoint_preimage = checkpoint_text THEN + RAISE EXCEPTION 'Security-state checkpoint identity/counters/digest differ' USING ERRCODE = '23514'; + END IF; + END IF; + ELSE + IF NEW.result_generation::NUMERIC <> NEW.expected_generation::NUMERIC + 1 + OR NEW.result_source_version::NUMERIC <> NEW.expected_source_version::NUMERIC + 1 + OR NEW.result_fence::NUMERIC <> NEW.expected_fence::NUMERIC + 1 + OR NEW.result_fence_source_version::NUMERIC <> NEW.expected_fence_source_version::NUMERIC + 1 + OR NEW.event_sequence::NUMERIC <> NEW.checkpoint_sequence::NUMERIC + 1 + OR NEW.result_global_role_source_version::NUMERIC <> NEW.global_role_source_version::NUMERIC + + CASE WHEN 'GLOBAL_ROLE_CHANGED' = ANY(kinds) THEN 1 ELSE 0 END + OR authority_row.generation <> NEW.result_generation OR authority_row.source_version <> NEW.result_source_version + OR fence_row.issuance_fence <> NEW.result_fence OR fence_row.source_version <> NEW.result_fence_source_version + OR role_row.global_role_source_version <> NEW.result_global_role_source_version THEN + RAISE EXCEPTION 'Security-state producer result counters differ' USING ERRCODE = '23514'; + END IF; + SELECT * INTO outbox_row FROM account_authority_outbox_events + WHERE outbox_stream_key = key AND request_id = NEW.request_id::TEXT; + SELECT * INTO stream_row FROM account_authority_outbox_streams WHERE outbox_stream_key = key; + IF outbox_row IS NULL OR stream_row IS NULL OR outbox_row.outbox_sequence <> NEW.event_sequence + OR outbox_row.event_id <> NEW.event_id OR outbox_row.event_digest <> NEW.event_digest + OR outbox_row.payload <> NEW.event_payload OR stream_row.last_sequence <> NEW.event_sequence THEN + RAISE EXCEPTION 'Security-state exact outbox receipt differs' USING ERRCODE = '23514'; + END IF; + preimage := '{"accountAuthorityGeneration":"' || NEW.result_generation::TEXT + || '","accountId":"' || NEW.account_uuid::TEXT + || '","accountSecurityCutoff":{"accountAuthorityGeneration":"' || NEW.result_generation::TEXT + || '","outboxSequence":"' || NEW.event_sequence::TEXT || '","outboxStreamKey":"' || key + || '"},"accountState":' || convert_from(NEW.after_state,'UTF8') + || ',"eventId":"account-security-state-event-v1:' || NEW.request_id::TEXT + || '","eventType":"ACCOUNT_SECURITY_STATE_CHANGED","mutationKinds":' + || replace(to_jsonb(kinds)::TEXT, ', ', ',') + || ',"outboxSequence":"' || NEW.event_sequence::TEXT || '","outboxStreamKey":"' || key + || '","requestId":"' || NEW.request_id::TEXT + || '","schemaVersion":"account-auth-account-security-state-event/v1","sourceScope":"account/' + || NEW.account_uuid::TEXT || '","sourceVersion":"' || NEW.result_source_version::TEXT || '"}'; + expected_digest := 'sha256:' || encode(sha256(convert_to(preimage,'UTF8')),'hex'); + expected_wire := replace(preimage, ',"eventId":', ',"eventDigest":"' || expected_digest || '","eventId":'); + IF NEW.event_digest IS DISTINCT FROM expected_digest OR NEW.event_payload IS DISTINCT FROM convert_to(expected_wire,'UTF8') THEN + RAISE EXCEPTION 'Security-state canonical event/digest differs' USING ERRCODE = '23514'; + END IF; + before_json := after_json; + END IF; + IF (before_json->'emailVerified')::BOOLEAN IS DISTINCT FROM account_row.email_verified + OR before_json->>'lifecycleState' IS DISTINCT FROM upper(account_row.lifecycle_state) + OR before_json->'globalRoles' IS DISTINCT FROM to_jsonb(role_row.global_roles) + OR before_json->'loginAuthModes' IS DISTINCT FROM (SELECT jsonb_agg(v ORDER BY v) + FROM unnest(string_to_array(account_row.login_auth_modes, ',')) v) THEN + RAISE EXCEPTION 'Security-state exact owner-state readback differs' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_security_state_operation_guard BEFORE INSERT OR UPDATE + ON account_security_state_operations FOR EACH ROW EXECUTE FUNCTION account_security_state_operation_guard(); + +CREATE FUNCTION account_security_state_retention_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Security-state operation evidence must be retained' USING ERRCODE = '23514'; + RETURN OLD; +END; +$$; +CREATE TRIGGER account_security_state_delete_denied BEFORE DELETE ON account_security_state_operations + FOR EACH ROW EXECUTE FUNCTION account_security_state_retention_guard(); +CREATE TRIGGER account_security_state_truncate_denied BEFORE TRUNCATE ON account_security_state_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_security_state_retention_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V66__control_ui_issuance_operations.sql b/services/account-service/src/main/resources/db/migration/V66__control_ui_issuance_operations.sql new file mode 100644 index 0000000000..8978e95c99 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V66__control_ui_issuance_operations.sql @@ -0,0 +1,222 @@ +-- Durable targetless control-UI issuance correlation and exact encrypted-result retention. +-- This is not authentication, active-token-registry proof, or authority-currentness proof. +CREATE TABLE account_control_ui_issuance_operations ( + operation_id UUID PRIMARY KEY CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'), + request_id UUID NOT NULL UNIQUE CHECK (request_id <> '00000000-0000-0000-0000-000000000000'), + account_uuid UUID NOT NULL CHECK (account_uuid <> '00000000-0000-0000-0000-000000000000'), + account_id BIGINT NOT NULL, + account_provenance VARCHAR(40) NOT NULL, + profile VARCHAR(32) NOT NULL CHECK (profile = 'control-ui'), + audience VARCHAR(32) NOT NULL CHECK (audience = 'control-ui'), + request_digest_version SMALLINT NOT NULL CHECK (request_digest_version = 1), + request_digest BYTEA NOT NULL CHECK (octet_length(request_digest) = 32), + authority_capture BYTEA NOT NULL CHECK (octet_length(authority_capture) BETWEEN 1 AND 1048576), + authority_capture_digest BYTEA NOT NULL CHECK (octet_length(authority_capture_digest) = 32), + issuance_fence_capture BYTEA NOT NULL CHECK (octet_length(issuance_fence_capture) BETWEEN 1 AND 1048576), + issuance_fence_digest BYTEA NOT NULL CHECK (octet_length(issuance_fence_digest) = 32), + status VARCHAR(12) NOT NULL CHECK (status IN ('PENDING', 'COMMITTED')), + token_hash VARCHAR(64), + response_digest BYTEA, + issued_at TIMESTAMPTZ, + expires_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_control_ui_issuance_account_binding_fk + FOREIGN KEY (account_uuid, account_id, account_provenance) + REFERENCES accounts (account_uuid, account_uuid_source_numeric_id, account_uuid_provenance) + ON DELETE RESTRICT, + CONSTRAINT account_control_ui_issuance_result_shape CHECK ( + (status = 'PENDING' + AND token_hash IS NULL AND response_digest IS NULL + AND issued_at IS NULL AND expires_at IS NULL) + OR (status = 'COMMITTED' + AND token_hash IS NOT NULL AND token_hash ~ '^[0-9a-f]{64}$' + AND response_digest IS NOT NULL + AND octet_length(response_digest) = 32 + AND issued_at IS NOT NULL AND expires_at IS NOT NULL + AND issued_at > CAST('1970-01-01 00:00:00+00' AS TIMESTAMP WITH TIME ZONE) + AND expires_at > issued_at + AND date_trunc('second', issued_at) = issued_at + AND date_trunc('second', expires_at) = expires_at)) +); + +CREATE TABLE account_control_ui_issuance_response_envelopes ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL, + account_uuid UUID NOT NULL, + account_id BIGINT NOT NULL, + account_provenance VARCHAR(40) NOT NULL, + profile VARCHAR(32) NOT NULL CHECK (profile = 'control-ui'), + audience VARCHAR(32) NOT NULL CHECK (audience = 'control-ui'), + request_digest_version SMALLINT NOT NULL CHECK (request_digest_version = 1), + request_digest BYTEA NOT NULL CHECK (octet_length(request_digest) = 32), + token_hash VARCHAR(64) NOT NULL CHECK (token_hash ~ '^[0-9a-f]{64}$'), + response_digest BYTEA NOT NULL CHECK (octet_length(response_digest) = 32), + authority_capture_digest BYTEA NOT NULL CHECK (octet_length(authority_capture_digest) = 32), + issuance_fence_digest BYTEA NOT NULL CHECK (octet_length(issuance_fence_digest) = 32), + issued_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + format_version SMALLINT NOT NULL CHECK (format_version = 1), + key_id VARCHAR(64) NOT NULL CHECK (key_id ~ '^[A-Za-z0-9_-]{1,64}$'), + purpose VARCHAR(32) NOT NULL CHECK (purpose = 'CONTROL_UI_RESPONSE'), + nonce BYTEA NOT NULL CHECK (octet_length(nonce) = 12), + ciphertext BYTEA NOT NULL CHECK (octet_length(ciphertext) BETWEEN 16 AND 65552), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_control_ui_issuance_envelope_operation_fk + FOREIGN KEY (operation_id) + REFERENCES account_control_ui_issuance_operations (operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_control_ui_issuance_envelope_identity_check CHECK ( + request_id <> '00000000-0000-0000-0000-000000000000' + AND account_uuid <> '00000000-0000-0000-0000-000000000000' + AND account_id > 0 + AND issued_at > CAST('1970-01-01 00:00:00+00' AS TIMESTAMP WITH TIME ZONE) + AND expires_at > issued_at + AND date_trunc('second', issued_at) = issued_at + AND date_trunc('second', expires_at) = expires_at) +); + +CREATE INDEX account_control_ui_issuance_account_idx + ON account_control_ui_issuance_operations (account_uuid, created_at, operation_id); + +-- [jooq ignore start] +CREATE FUNCTION account_control_ui_issuance_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.status <> 'PENDING' + OR NEW.token_hash IS NOT NULL OR NEW.response_digest IS NOT NULL + OR NEW.issued_at IS NOT NULL OR NEW.expires_at IS NOT NULL THEN + RAISE EXCEPTION 'Control-UI issuance must begin without a committed result' + USING ERRCODE = '23514', CONSTRAINT = 'account_control_ui_issuance_initial_state'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_control_ui_issuance_update_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.status <> 'PENDING' OR NEW.status <> 'COMMITTED' + OR (to_jsonb(NEW) - ARRAY['status','token_hash','response_digest','issued_at','expires_at','updated_at']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['status','token_hash','response_digest','issued_at','expires_at','updated_at']) THEN + RAISE EXCEPTION 'Original control-UI issuance request and capture are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_control_ui_issuance_identity_immutable'; + END IF; + NEW.updated_at := CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_control_ui_issuance_envelope_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + operation account_control_ui_issuance_operations%ROWTYPE; +BEGIN + SELECT * INTO operation FROM account_control_ui_issuance_operations + WHERE operation_id = NEW.operation_id; + IF NOT FOUND OR operation.status <> 'COMMITTED' + OR operation.request_id IS DISTINCT FROM NEW.request_id + OR operation.account_uuid IS DISTINCT FROM NEW.account_uuid + OR operation.account_id IS DISTINCT FROM NEW.account_id + OR operation.account_provenance IS DISTINCT FROM NEW.account_provenance + OR operation.profile IS DISTINCT FROM NEW.profile + OR operation.audience IS DISTINCT FROM NEW.audience + OR operation.request_digest_version IS DISTINCT FROM NEW.request_digest_version + OR operation.request_digest IS DISTINCT FROM NEW.request_digest + OR operation.token_hash IS DISTINCT FROM NEW.token_hash + OR operation.response_digest IS DISTINCT FROM NEW.response_digest + OR operation.authority_capture_digest IS DISTINCT FROM NEW.authority_capture_digest + OR operation.issuance_fence_digest IS DISTINCT FROM NEW.issuance_fence_digest + OR operation.issued_at IS DISTINCT FROM NEW.issued_at + OR operation.expires_at IS DISTINCT FROM NEW.expires_at THEN + RAISE EXCEPTION 'Control-UI envelope does not match its committed operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_control_ui_issuance_envelope_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_control_ui_issuance_envelope_update_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-UI response envelope is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_control_ui_issuance_envelope_immutable'; + RETURN OLD; +END; +$$; + +CREATE FUNCTION account_control_ui_issuance_no_delete() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-UI issuance recovery evidence cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_control_ui_issuance_no_delete'; + RETURN OLD; +END; +$$; + +CREATE FUNCTION account_control_ui_issuance_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-UI issuance recovery evidence cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_control_ui_issuance_no_truncate'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_control_ui_issuance_terminal_envelope_check() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.status = 'COMMITTED' AND NOT EXISTS ( + SELECT 1 FROM account_control_ui_issuance_response_envelopes envelope + WHERE envelope.operation_id = NEW.operation_id + AND envelope.request_id = NEW.request_id + AND envelope.account_uuid = NEW.account_uuid + AND envelope.account_id = NEW.account_id + AND envelope.account_provenance = NEW.account_provenance + AND envelope.profile = NEW.profile AND envelope.audience = NEW.audience + AND envelope.request_digest_version = NEW.request_digest_version + AND envelope.request_digest = NEW.request_digest + AND envelope.token_hash = NEW.token_hash + AND envelope.response_digest = NEW.response_digest + AND envelope.authority_capture_digest = NEW.authority_capture_digest + AND envelope.issuance_fence_digest = NEW.issuance_fence_digest + AND envelope.issued_at = NEW.issued_at AND envelope.expires_at = NEW.expires_at + AND envelope.purpose = 'CONTROL_UI_RESPONSE' + ) THEN + RAISE EXCEPTION 'Committed control-UI issuance requires its exact encrypted envelope' + USING ERRCODE = '23514', CONSTRAINT = 'account_control_ui_issuance_envelope_required'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_control_ui_issuance_insert_guard_trigger + BEFORE INSERT ON account_control_ui_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_insert_guard(); +CREATE TRIGGER account_control_ui_issuance_update_guard_trigger + BEFORE UPDATE ON account_control_ui_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_update_guard(); +CREATE TRIGGER account_control_ui_issuance_envelope_insert_guard_trigger + BEFORE INSERT ON account_control_ui_issuance_response_envelopes + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_envelope_insert_guard(); +CREATE TRIGGER account_control_ui_issuance_envelope_update_guard_trigger + BEFORE UPDATE ON account_control_ui_issuance_response_envelopes + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_envelope_update_guard(); +CREATE TRIGGER account_control_ui_issuance_operation_no_delete_trigger + BEFORE DELETE ON account_control_ui_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_no_delete(); +CREATE TRIGGER account_control_ui_issuance_envelope_no_delete_trigger + BEFORE DELETE ON account_control_ui_issuance_response_envelopes + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_no_delete(); +CREATE TRIGGER account_control_ui_issuance_operation_no_truncate_trigger + BEFORE TRUNCATE ON account_control_ui_issuance_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_issuance_no_truncate(); +CREATE TRIGGER account_control_ui_issuance_envelope_no_truncate_trigger + BEFORE TRUNCATE ON account_control_ui_issuance_response_envelopes + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_issuance_no_truncate(); +CREATE TRIGGER account_control_ui_issuance_terminal_envelope_check_trigger + AFTER INSERT OR UPDATE ON account_control_ui_issuance_operations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_terminal_envelope_check(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java new file mode 100644 index 0000000000..0a48f456f4 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java @@ -0,0 +1,537 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequest; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation.OriginalCapture; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperationRepository; +import net.firedevops.firemud.accountservice.security.AccountControlUiResponseEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class AccountControlUiIssuanceOperationPostgresIntegrationTest { + private static final List RING_PURPOSES = + List.of("bare-login", "connect-token", "pending-reset", "control-ui-response"); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void claimRequiresAnActiveWritableOwnerTransaction() { + TestContext context = newTestContext(); + AccountControlUiIssuanceRequest request = request(context.account().uuid()); + + assertThatThrownBy( + () -> context.repository().claim(request, Optional.of(capture(context.account())))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable caller-owned Account transaction"); + } + + @Test + void exactClaimsRecoverOriginalCaptureAndChangedAccountOrCaptureConflicts() { + TestContext context = newTestContext(); + AccountControlUiIssuanceRequest request = request(context.account().uuid()); + OriginalCapture originalCapture = capture(context.account()); + + var first = + inTransaction( + context.transaction(), + () -> context.repository().claim(request, Optional.of(originalCapture))); + var retry = + inTransaction( + context.transaction(), () -> context.repository().claim(request, Optional.empty())); + + assertThat(first.created()).isTrue(); + assertThat(retry.created()).isFalse(); + assertThat(retry.operation().operationId()).isEqualTo(first.operation().operationId()); + assertThat(retry.operation().lifecycle()) + .isEqualTo(AccountControlUiIssuanceOperation.Lifecycle.PENDING); + assertThat(retry.operation().originalCapture()).isEqualTo(originalCapture); + + AccountControlUiIssuanceRequest changedAccount = + new AccountControlUiIssuanceRequest( + request.requestId(), insertAccount(context.dsl()).uuid().toString()); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().claim(changedAccount, Optional.empty()))) + .isInstanceOf(AccountControlUiIssuanceOperationRepository.OperationConflictException.class); + + OriginalCapture changedCapture = + new OriginalCapture( + originalCapture.accountId(), + originalCapture.accountProvenance(), + "changed authority capture".getBytes(StandardCharsets.UTF_8), + originalCapture.issuanceFenceCapture()); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().claim(request, Optional.of(changedCapture)))) + .isInstanceOf(AccountControlUiIssuanceOperationRepository.OperationConflictException.class); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().findByRequest(request).orElseThrow())) + .isEqualTo(first.operation()); + } + + @Test + void simultaneousExactClaimsAllocateOneOperationAndRetainTheFirstCapture() throws Exception { + TestContext context = newTestContext(); + AccountControlUiIssuanceRequest request = request(context.account().uuid()); + OriginalCapture originalCapture = capture(context.account()); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Callable attempt = + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Control-UI claim race did not start"); + } + return inTransaction( + context.transaction(), + () -> context.repository().claim(request, Optional.of(originalCapture))); + }; + Future first = executor.submit(attempt); + Future second = executor.submit(attempt); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + List claims = + List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); + assertThat(claims) + .extracting(AccountControlUiIssuanceOperationRepository.Claim::created) + .containsExactlyInAnyOrder(true, false); + assertThat(claims) + .extracting(claim -> claim.operation().operationId()) + .containsOnly(claims.get(0).operation().operationId()); + assertThat(claims) + .extracting(claim -> claim.operation().originalCapture()) + .containsOnly(originalCapture); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void abandonedPendingClaimCannotBeReportedCommittedWithoutExactEnvelope() { + TestContext context = newTestContext(); + AccountControlUiIssuanceRequest request = request(context.account().uuid()); + var claim = + inTransaction( + context.transaction(), + () -> context.repository().claim(request, Optional.of(capture(context.account())))); + + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .dsl() + .execute( + "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED' " + + "WHERE operation_id = ?", + claim.operation().operationId()))) + .isInstanceOf(RuntimeException.class); + AccountControlUiIssuanceOperation stored = + inTransaction( + context.transaction(), () -> context.repository().findByRequest(request).orElseThrow()); + assertThat(stored.lifecycle()).isEqualTo(AccountControlUiIssuanceOperation.Lifecycle.PENDING); + assertThat(stored.completedResponse()).isNull(); + Record envelopeCount = + inTransaction( + context.transaction(), + () -> + context + .dsl() + .fetchOne( + "SELECT count(*) AS envelope_count " + + "FROM account_control_ui_issuance_response_envelopes " + + "WHERE operation_id = ?", + claim.operation().operationId())); + assertThat( + Objects.requireNonNull( + envelopeCount, "Pending encrypted-envelope count query returned no row") + .get("envelope_count", Long.class)) + .isZero(); + } + + @Test + void exactEncryptedResultSurvivesRestartRotationAndLaterTransactionRetry(@TempDir Path temp) + throws Exception { + TestContext context = newTestContext(); + AccountControlUiIssuanceRequest request = request(context.account().uuid()); + var claim = + inTransaction( + context.transaction(), + () -> context.repository().claim(request, Optional.of(capture(context.account())))); + byte[] exactResponse = + "{\"accountId\":\"" + .concat(request.accountUuid()) + .concat("\",\"token\":\"synthetic-original-token\"}") + .getBytes(StandardCharsets.UTF_8); + String tokenHash = hex(sha256("synthetic-original-token".getBytes(StandardCharsets.UTF_8))); + OriginalCapture originalCapture = claim.operation().originalCapture(); + AccountControlUiResponseEnvelopeBinding binding = + new AccountControlUiResponseEnvelopeBinding( + request.accountUuid(), + claim.operation().operationId().toString(), + request.requestId(), + claim.operation().requestDigest(), + tokenHash, + sha256(exactResponse), + originalCapture.authorityCaptureDigest(), + originalCapture.issuanceFenceDigest(), + Instant.parse("2030-05-06T07:08:09Z"), + Instant.parse("2030-05-06T08:08:09Z")); + Path manifest = temp.resolve("account-ring.v1"); + writeManifest(manifest, "k1", 1, 0); + AccountEncryptedEnvelope envelope = + new AccountEnvelopeCrypto(manifest).encryptControlUiResponse(binding, exactResponse); + + AccountControlUiIssuanceOperation completed = + inTransaction( + context.transaction(), () -> context.repository().complete(claim, binding, envelope)); + AccountControlUiIssuanceOperation exactReadback = + inTransaction( + context.transaction(), () -> context.repository().findByRequest(request).orElseThrow()); + assertThat(completed).isEqualTo(exactReadback); + assertThat(exactReadback.lifecycle()) + .isEqualTo(AccountControlUiIssuanceOperation.Lifecycle.COMMITTED); + assertThat(exactReadback.originalCapture()).isEqualTo(originalCapture); + assertThat(exactReadback.completedResponse().binding()).isEqualTo(binding); + assertThat(exactReadback.completedResponse().envelope()).isEqualTo(envelope); + + writeManifest(manifest, "k2", 2, 1); + byte[] recovered = + new AccountEnvelopeCrypto(manifest) + .decryptControlUiResponse(exactReadback.completedResponse().envelope(), binding); + assertThat(recovered).containsExactly(exactResponse); + assertThat(exactReadback.completedResponse().envelope().nonce()) + .containsExactly(envelope.nonce()); + assertThat(exactReadback.completedResponse().envelope().ciphertext()) + .containsExactly(envelope.ciphertext()); + + AccountControlUiIssuanceOperation replayedCommit = + inTransaction( + context.transaction(), () -> context.repository().complete(claim, binding, envelope)); + assertThat(replayedCommit).isEqualTo(exactReadback); + String storedWire = + inTransaction( + context.transaction(), + () -> + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT to_jsonb(operation_row)::text || to_jsonb(envelope_row)::text AS wire " + + "FROM account_control_ui_issuance_operations operation_row " + + "JOIN account_control_ui_issuance_response_envelopes envelope_row " + + "USING (operation_id) WHERE operation_row.operation_id = ?", + claim.operation().operationId()), + "Committed operation/envelope wire query returned no row") + .get("wire", String.class)); + assertThat(storedWire) + .doesNotContain( + "synthetic-original-token", new String(exactResponse, StandardCharsets.UTF_8)); + + var changedBinding = + new AccountControlUiResponseEnvelopeBinding( + binding.accountId(), + binding.operationId(), + binding.requestId(), + binding.requestDigest(), + "ff".repeat(32), + binding.responseDigest(), + binding.authorityCaptureDigest(), + binding.issuanceFenceDigest(), + binding.issuedAt(), + binding.expiresAt()); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> context.repository().complete(claim, changedBinding, envelope))) + .isInstanceOf(AccountControlUiIssuanceOperationRepository.OperationConflictException.class); + } + + @Test + void lateRollbackLeavesOriginalPendingCaptureAndNoEncryptedResult() throws Exception { + TestContext context = newTestContext(); + AccountControlUiIssuanceRequest request = request(context.account().uuid()); + var claim = + inTransaction( + context.transaction(), + () -> context.repository().claim(request, Optional.of(capture(context.account())))); + byte[] response = + "synthetic response held only by this fixture".getBytes(StandardCharsets.UTF_8); + AccountControlUiResponseEnvelopeBinding binding = binding(claim.operation(), response); + AccountEncryptedEnvelope envelope = + new AccountEncryptedEnvelope( + AccountEncryptedEnvelope.CURRENT_FORMAT_VERSION, + "test-key", + AccountEnvelopePurpose.CONTROL_UI_RESPONSE, + new byte[AccountEncryptedEnvelope.NONCE_LENGTH_BYTES], + new byte[AccountEncryptedEnvelope.AUTHENTICATION_TAG_LENGTH_BYTES]); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> { + context.repository().complete(claim, binding, envelope); + throw new IllegalStateException("synthetic late owner rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synthetic late owner rollback"); + AccountControlUiIssuanceOperation stored = + inTransaction( + context.transaction(), () -> context.repository().findByRequest(request).orElseThrow()); + assertThat(stored.lifecycle()).isEqualTo(AccountControlUiIssuanceOperation.Lifecycle.PENDING); + assertThat(stored.originalCapture()).isEqualTo(claim.operation().originalCapture()); + assertThat(stored.completedResponse()).isNull(); + } + + @Test + void additiveV66MigrationPreservesV64ReceiptAndExistingV65Structure() { + TestContext context = newTestContext(); + Record receipt = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT request_id, source_snapshot_payload, status " + + "FROM account_tenant_creation_bootstrap_operations WHERE request_id = ?", + context.retainedV64RequestId()), + "Retained V64 receipt lookup returned no row"); + assertThat(receipt).isNotNull(); + assertThat(receipt.get("status", String.class)).isEqualTo("IN_PROGRESS"); + assertThat(receipt.get("source_snapshot_payload", byte[].class)) + .containsExactly("retained-v64-source-snapshot".getBytes(StandardCharsets.UTF_8)); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(*) AS table_count FROM information_schema.tables " + + "WHERE table_schema = current_schema() " + + "AND table_name = 'account_security_state_operations'"), + "V65 security-state table existence query returned no row") + .get("table_count", Long.class)) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(*) AS operation_count FROM account_security_state_operations"), + "V65 security-state operation count query returned no row") + .get("operation_count", Long.class)) + .isZero(); + } + + private TestContext newTestContext() { + String schema = "account_control_ui_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target(MigrationVersion.fromVersion("65")) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + AccountSeed account = insertAccount(dsl); + UUID retainedRequestId = UUID.randomUUID(); + insertV64PendingReceipt(dsl, account, retainedRequestId); + + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + return new TestContext( + dsl, + new AccountControlUiIssuanceOperationRepository(dsl), + new TransactionTemplate(new DataSourceTransactionManager(dataSource)), + account, + retainedRequestId); + } + + private static AccountSeed insertAccount(DSLContext dsl) { + String unique = UUID.randomUUID().toString().replace("-", ""); + Record row = + dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) " + + "RETURNING id, account_uuid, account_uuid_provenance", + "ctrlui_" + unique.substring(0, 12), + unique + "@example.test", + "test-password-hash"); + if (row == null) throw new IllegalStateException("Account fixture was not inserted"); + return new AccountSeed( + row.get("id", Long.class), + row.get("account_uuid", UUID.class), + AccountIdentityProvenance.fromStorageValue( + row.get("account_uuid_provenance", String.class))); + } + + private static void insertV64PendingReceipt(DSLContext dsl, AccountSeed account, UUID requestId) { + UUID tenant = UUID.randomUUID(); + UUID creationRequest = UUID.randomUUID(); + UUID creationOperation = UUID.randomUUID(); + String digest = "sha256:" + "a".repeat(64); + int inserted = + dsl.execute( + "INSERT INTO account_tenant_creation_bootstrap_operations " + + "(request_id, schema_version, initiating_account_uuid, tenant_uuid, " + + "creation_request_id, creation_operation_id, account_authorization_operation_id, " + + "account_authorization_digest, creator_evidence_digest, creator_evidence_payload, " + + "source_snapshot_payload, source_snapshot_digest, request_payload, request_digest, " + + "baseline_membership_version, baseline_membership_authority_generation, " + + "baseline_event_sequence, status) " + + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 0, 'IN_PROGRESS')", + requestId, + account.uuid(), + tenant, + creationRequest, + creationOperation, + requestId, + digest, + digest, + "retained-v64-creator-evidence".getBytes(StandardCharsets.UTF_8), + "retained-v64-source-snapshot".getBytes(StandardCharsets.UTF_8), + digest, + "retained-v64-request".getBytes(StandardCharsets.UTF_8), + digest); + if (inserted != 1) throw new IllegalStateException("V64 retention fixture was not inserted"); + } + + private static AccountControlUiIssuanceRequest request(UUID account) { + return new AccountControlUiIssuanceRequest(UUID.randomUUID().toString(), account.toString()); + } + + private static OriginalCapture capture(AccountSeed account) { + return new OriginalCapture( + account.id(), + account.provenance(), + "fixture-authority-capture-bytes".getBytes(StandardCharsets.UTF_8), + "fixture-issuance-fence-capture-bytes".getBytes(StandardCharsets.UTF_8)); + } + + private static AccountControlUiResponseEnvelopeBinding binding( + AccountControlUiIssuanceOperation operation, byte[] response) { + return new AccountControlUiResponseEnvelopeBinding( + operation.request().accountUuid(), + operation.operationId().toString(), + operation.request().requestId(), + operation.requestDigest(), + hex(sha256("synthetic-token".getBytes(StandardCharsets.UTF_8))), + sha256(response), + operation.originalCapture().authorityCaptureDigest(), + operation.originalCapture().issuanceFenceDigest(), + Instant.parse("2030-05-06T07:08:09Z"), + Instant.parse("2030-05-06T08:08:09Z")); + } + + private static void writeManifest(Path path, String activeKeyId, int activeSeed, int retainedSeed) + throws Exception { + List lines = new ArrayList<>(); + lines.add("version=1"); + lines.add("activeKeyId=" + activeKeyId); + for (String purpose : RING_PURPOSES) { + if (retainedSeed > 0) lines.add(keyLine("k1", purpose, retainedSeed)); + } + for (String purpose : RING_PURPOSES) lines.add(keyLine(activeKeyId, purpose, activeSeed)); + Files.writeString(path, String.join("\n", lines) + "\n", StandardCharsets.US_ASCII); + } + + private static String keyLine(String keyId, String purpose, int seed) { + byte[] key = new byte[32]; + java.util.Arrays.fill(key, (byte) (seed * 32 + RING_PURPOSES.indexOf(purpose) + 1)); + return "key:" + + keyId + + ":" + + purpose + + "=" + + Base64.getUrlEncoder().withoutPadding().encodeToString(key); + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (Exception exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String hex(byte[] bytes) { + return java.util.HexFormat.of().formatHex(bytes); + } + + private T inTransaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private record AccountSeed(long id, UUID uuid, AccountIdentityProvenance provenance) {} + + private record TestContext( + DSLContext dsl, + AccountControlUiIssuanceOperationRepository repository, + TransactionTemplate transaction, + AccountSeed account, + UUID retainedV64RequestId) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java index 6584998545..b89a56757a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCurrentAuthorityMembershipSnapshotPostgresIntegrationTest.java @@ -2562,7 +2562,9 @@ private AccountLogoutAllAuthorityEventProducer logoutProducer() { new AccountAuthoritySourceEventReadback( authorityOutboxRepository, passwordResetOperationRepository, - logoutAllOperationRepository), + logoutAllOperationRepository, + new net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository(dsl)), dsl, transactionManager); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountGenerationProjectionPostgresRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountGenerationProjectionPostgresRedisIntegrationTest.java index 6876a5b674..2429560c54 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountGenerationProjectionPostgresRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountGenerationProjectionPostgresRedisIntegrationTest.java @@ -661,7 +661,11 @@ private AccountAuthoritySourceReader sourceReader(Fixture fixture) { private AccountAuthoritySourceEventReadback sourceReadback(Fixture fixture) { return new AccountAuthoritySourceEventReadback( - fixture.outbox(), fixture.resetOperations(), fixture.logoutOperations()); + fixture.outbox(), + fixture.resetOperations(), + fixture.logoutOperations(), + new net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository(fixture.transactionDsl())); } private RedisAccountGenerationProjectionStore store(AccountAuthoritySourceReader reader) { @@ -695,6 +699,8 @@ private void reset(Fixture fixture, String rawToken, String password) { fixture.outbox(), fixture.resetOperations(), fixture.logoutOperations(), + new net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository(fixture.transactionDsl()), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java index a7e0146701..809d5cf44f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java @@ -1547,7 +1547,11 @@ private AccountLogoutAllAuthorityEventProducer producer( private AccountAuthoritySourceEventReadback sourceReadback( Fixture fixture, AccountAuthorityOutboxRepository outbox) { return new AccountAuthoritySourceEventReadback( - outbox, fixture.passwordResetOperations(), fixture.logoutOperations()); + outbox, + fixture.passwordResetOperations(), + fixture.logoutOperations(), + new net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository(fixture.transactionDsl())); } private void reset(Fixture fixture, Seed seed, String password) { @@ -1562,6 +1566,8 @@ private void reset(Fixture fixture, String rawToken, String password) { fixture.outbox(), fixture.passwordResetOperations(), fixture.logoutOperations(), + new net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository(fixture.transactionDsl()), null, null, null, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountPasswordResetDraftSourceChangePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountPasswordResetDraftSourceChangePostgresIntegrationTest.java index 5be8ddd2f3..f261c93d6c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountPasswordResetDraftSourceChangePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountPasswordResetDraftSourceChangePostgresIntegrationTest.java @@ -446,7 +446,12 @@ private Fixture newFixture() throws Exception { AccountPasswordResetDraftSourceChangeRepository pendingResets = new AccountPasswordResetDraftSourceChangeRepository(transactionDsl); AccountAuthoritySourceEventReadback sourceReadback = - new AccountAuthoritySourceEventReadback(outbox, operations, logoutAll); + new AccountAuthoritySourceEventReadback( + outbox, + operations, + logoutAll, + new net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository(transactionDsl)); Path manifest = temporaryDirectory.resolve(UUID.randomUUID() + ".manifest.v1"); writeKeyRing(manifest); return new Fixture( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java new file mode 100644 index 0000000000..0bd92f5110 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -0,0 +1,809 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.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.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +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.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.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 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.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<>("postgres:16-alpine"); + + @Test + void pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation() { + Fixture fixture = fixture("65"); + Seed seed = seed(fixture); + 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 originalCallerAndFamilyBindingsCannotBeChangedOnRetry() { + Fixture fixture = fixture("65"); + 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("65"); + 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("65"); + 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); + 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 lawfulPrivateFenceAdvanceKeepsLatestSourceEventAndOriginalReceiptUnchanged() { + Fixture fixture = fixture("65"); + 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()); + ScopeState advanced = + tx( + fixture, + () -> { + new AccountRepository(fixture.dsl()) + .findByIdForUpdate(seed.account().getId()) + .orElseThrow(); + var source = fixture.generations().read(seed.source().scope()); + // Fixture-only private-fence CAS follows the existing guarded counters, without a + // source advance. + assertThat( + 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())) + .isEqualTo(1); + return fixture.generations().read(seed.source().scope()); + }); + var snapshot = sourceReader(fixture).readCurrent(seed.account().getAccountUuid()); + assertThat(snapshot.latestEvent()).contains(event); + assertThat(snapshot.sourceState()).isEqualTo(advanced); + assertThat(advanced.generation()) + .isEqualTo(original.receipt().orElseThrow().sourceState().generation()); + assertThat(advanced.sourceVersion()) + .isEqualTo(original.receipt().orElseThrow().sourceState().sourceVersion()); + assertThat(advanced.issuanceFence().value()) + .isEqualTo(original.receipt().orElseThrow().sourceState().issuanceFence().value() + 1); + 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("65"); + 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 V57 source-change row after rollback") + .get(0, String.class)) + .isEqualTo("WAITING"); + } + + @Test + void requestCaptureResultsDeletesAndTruncationRemainGuarded() { + Fixture fixture = fixture("65"); + 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("65"); + 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("65"); + 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); + 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"); + assertThatThrownBy( + () -> + tx(fixture, () -> fixture.operations().claim(second.request(), second.capture()))) + .isInstanceOf(RuntimeException.class); + 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("65"); + 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); + 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"); + assertThatThrownBy( + () -> + tx( + fixture, + () -> fixture.operations().findByRequestId(pending.request().requestId()))) + .isInstanceOf(RuntimeException.class); + } + } + + @Test + void actualReaderDeniesUncommittedOperationAndChangedCurrentPoststate() { + Fixture missing = fixture("65"); + 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, false); + assertThatThrownBy( + () -> + tx( + missing, + () -> + sourceReadback(missing) + .requireCurrentLatest( + new AccountRepository(missing.dsl()) + .findById(seed.account().getId()) + .orElseThrow(), + missing.generations().read(seed.source().scope())))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + tx( + missing, + () -> { + sourceReadback(missing) + .requireRetainedEvent( + new AccountRepository(missing.dsl()) + .findById(seed.account().getId()) + .orElseThrow(), + event, + missing.generations().read(seed.source().scope())); + return null; + })) + .isInstanceOf(IllegalStateException.class); + + Fixture changed = fixture("65"); + 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); + // Deliberately change current state without its lawful producer to test fail-closed readback. + changed + .dsl() + .execute( + "UPDATE accounts SET email_verified = false WHERE id = ?", other.account().getId()); + assertThatThrownBy( + () -> + tx( + changed, + () -> + sourceReadback(changed) + .requireCurrentLatest( + new AccountRepository(changed.dsl()) + .findById(other.account().getId()) + .orElseThrow(), + changed.generations().read(other.source().scope())))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("poststate differs"); + } + + @Test + void forwardMigrationRetainsOriginalAccountAuthorityAndRoleImagesWithoutBackfill() { + Fixture fixture = fixture("64"); + Seed seed = seed(fixture); + var before = + fixture + .dsl() + .fetch( + "SELECT account_uuid, account_uuid_source_numeric_id, account_uuid_provenance, email_verified, login_auth_modes, lifecycle_state, password_hash FROM accounts"); + var authority = fixture.dsl().fetch("SELECT * FROM account_authority_generations"); + var roles = fixture.dsl().fetch("SELECT * FROM account_global_role_sources"); + migrate(fixture.dataSource(), fixture.schema(), "65"); + assertThat( + fixture + .dsl() + .fetch( + "SELECT account_uuid, account_uuid_source_numeric_id, account_uuid_provenance, email_verified, login_auth_modes, lifecycle_state, password_hash FROM accounts")) + .isEqualTo(before); + assertThat(fixture.dsl().fetch("SELECT * FROM account_authority_generations")) + .isEqualTo(authority); + assertThat(fixture.dsl().fetch("SELECT * FROM account_global_role_sources")).isEqualTo(roles); + assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); + assertThat(seed.account().getAccountUuid()).isNotNull(); + } + + 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"); + fixture + .dsl() + .execute( + "UPDATE accounts SET email_verified = ?, login_auth_modes = ?, lifecycle_state = ? WHERE account_uuid = ?", + pending.request().desiredState().emailVerified(), + String.join(",", pending.request().desiredState().loginAuthModes()), + pending + .request() + .desiredState() + .lifecycleState() + .toLowerCase(java.util.Locale.ROOT), + pending.request().accountUuid()); + ScopeState advanced = + fixture + .generations() + .advance( + pending.capture().sourceState(), + pending.capture().sourceState().issuanceFence()); + 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); + ScopeState source = + fixture.generations().initialize(AuthorityScope.account(account.getAccountUuid())); + return new Seed(account, source); + }); + } + + private void migrate(DriverManagerDataSource dataSource, String schema, String version) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(version) + .load() + .migrate(); + } + + private static T tx(Fixture fixture, Supplier work) { + return fixture.transaction().execute(status -> work.get()); + } + + 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 Pending(AccountSecurityStateMutationRequest request, Capture capture) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java index cccccc11da..77b2f64bb9 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java @@ -451,6 +451,8 @@ private static Fixture fixture(boolean failAfterAudit) { outbox, passwordResets, logoutAll, + new net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository(txDsl), transitionReceipts, memberships, roles, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java index 0475c5bb0e..6ca05dc562 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -370,6 +370,8 @@ private AccountServiceImpl newService( fixture.outbox(), operations, fixture.logoutAllOperations(), + new net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository(fixture.transactionDsl()), null, // audit outbox null, // connect scopes null, // join operations diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java index 1da0e8e19d..c815ba9f65 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java @@ -218,7 +218,9 @@ private static Fixture fixture(boolean enrollAuthority) { new AccountAuthoritySourceEventReadback( outbox, new AccountPasswordResetOperationRepository(dsl), - new AccountLogoutAllOperationRepository(dsl)); + new AccountLogoutAllOperationRepository(dsl), + new net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository(dsl)); var source = new AccountControlUiCurrentSourceRepository( dsl, 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/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationTest.java new file mode 100644 index 0000000000..300811771e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationTest.java @@ -0,0 +1,108 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.List; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequest; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequestDigest; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation; +import org.junit.jupiter.api.Test; + +class AccountControlUiIssuanceOperationTest { + private static final String REQUEST = "11111111-1111-4111-8111-111111111111"; + private static final String OTHER_REQUEST = "22222222-2222-4222-8222-222222222222"; + private static final String ACCOUNT = "33333333-3333-4333-8333-333333333333"; + private static final String OTHER_ACCOUNT = "44444444-4444-4444-8444-444444444444"; + + @Test + void semanticDigestHasClosedCredentialFreeVersionedTargetlessFrame() throws Exception { + var request = new AccountControlUiIssuanceRequest(REQUEST, ACCOUNT); + ByteBuffer frames = + ByteBuffer.wrap(AccountControlUiIssuanceRequestDigest.canonicalBytes(request)); + assertThat(readFrame(frames)).isEqualTo("firemud/account/control-ui-issuance/request/v1"); + assertThat(readFrame(frames)).isEqualTo("1"); + assertThat(readFrame(frames)).isEqualTo("LOGIN_ISSUANCE"); + assertThat(readFrame(frames)).isEqualTo(ACCOUNT); + assertThat(readFrame(frames)).isEqualTo("control-ui"); + assertThat(readFrame(frames)).isEqualTo("control-ui"); + assertThat(frames.hasRemaining()).isFalse(); + assertThat(AccountControlUiIssuanceRequest.class.getRecordComponents()) + .extracting(java.lang.reflect.RecordComponent::getName) + .containsExactly("requestId", "accountUuid"); + assertThat(AccountControlUiIssuanceRequestDigest.digest(request)) + .containsExactly( + MessageDigest.getInstance("SHA-256") + .digest(AccountControlUiIssuanceRequestDigest.canonicalBytes(request))); + assertThat( + AccountControlUiIssuanceRequestDigest.digest( + new AccountControlUiIssuanceRequest(OTHER_REQUEST, ACCOUNT))) + .containsExactly(AccountControlUiIssuanceRequestDigest.digest(request)); + assertThat( + AccountControlUiIssuanceRequestDigest.digest( + new AccountControlUiIssuanceRequest(REQUEST, OTHER_ACCOUNT))) + .isNotEqualTo(AccountControlUiIssuanceRequestDigest.digest(request)); + } + + @Test + void requestRequiresCanonicalNonNilUuidStrings() { + for (String invalid : + List.of( + "00000000-0000-0000-0000-000000000000", + "11111111-1111-4111-8111-11111111111", + "11111111-1111-4111-8111-111111111111 ", + "11111111-1111-4111-8111-11111111111A")) { + assertThatThrownBy(() -> new AccountControlUiIssuanceRequest(invalid, ACCOUNT)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new AccountControlUiIssuanceRequest(REQUEST, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void originalCaptureCopiesAndRedactsCompleteEvidenceBytes() { + byte[] authority = "complete authority capture bytes".getBytes(StandardCharsets.UTF_8); + byte[] fence = "complete issuance fence bytes".getBytes(StandardCharsets.UTF_8); + var capture = + new AccountControlUiIssuanceOperation.OriginalCapture( + 73L, AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, authority, fence); + byte[] expectedAuthorityDigest = capture.authorityCaptureDigest(); + byte[] expectedFenceDigest = capture.issuanceFenceDigest(); + authority[0] = 0; + fence[0] = 0; + byte[] returnedAuthority = capture.authorityCapture(); + byte[] returnedFence = capture.issuanceFenceCapture(); + returnedAuthority[0] = 0; + returnedFence[0] = 0; + + assertThat(capture.authorityCapture()) + .containsExactly("complete authority capture bytes".getBytes(StandardCharsets.UTF_8)); + assertThat(capture.issuanceFenceCapture()) + .containsExactly("complete issuance fence bytes".getBytes(StandardCharsets.UTF_8)); + assertThat(capture.authorityCaptureDigest()).containsExactly(expectedAuthorityDigest); + assertThat(capture.issuanceFenceDigest()).containsExactly(expectedFenceDigest); + assertThat(capture.toString()).doesNotContain("complete authority", "complete issuance"); + assertThat(capture) + .isEqualTo( + new AccountControlUiIssuanceOperation.OriginalCapture( + 73L, + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, + "complete authority capture bytes".getBytes(StandardCharsets.UTF_8), + "complete issuance fence bytes".getBytes(StandardCharsets.UTF_8))); + assertThatThrownBy( + () -> + new AccountControlUiIssuanceOperation.OriginalCapture( + 73L, AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, new byte[0], fence)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static String readFrame(ByteBuffer bytes) { + byte[] value = new byte[bytes.getInt()]; + bytes.get(value); + return new String(value, StandardCharsets.UTF_8); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java new file mode 100644 index 0000000000..38bb559393 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepositoryTest.java @@ -0,0 +1,48 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class AccountSecurityStateOperationRepositoryTest { + @Test + void storageDeniesOutsideWritableOwnerTransactionBeforeDataAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountSecurityStateOperationRepository(dsl); + assertThatThrownBy(() -> repository.findByRequestId(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + verifyNoInteractions(dsl); + assertThat( + repository + .getClass() + .isAnnotationPresent(org.springframework.stereotype.Repository.class)) + .isTrue(); + assertThat( + repository.getClass().isAnnotationPresent(org.springframework.stereotype.Service.class)) + .isFalse(); + } + + @Test + void detectorExactlyCoversIndependentCredentialFreeChangedFamilies() { + var before = new AccountState(false, List.of("PASSWORD"), List.of(), "ACTIVE"); + var after = + new AccountState( + true, List.of("EMAIL_OTP", "PASSWORD"), List.of("support"), "SECURITY_LOCKED"); + assertThat(AccountSecurityStateOperationRepository.detectedKinds(before, after)) + .containsExactly( + "EMAIL_LOGIN_ELIGIBILITY_CHANGED", + "GLOBAL_ROLE_CHANGED", + "LIFECYCLE_STATE_CHANGED", + "LOGIN_AUTH_MODES_CHANGED"); + assertThat(AccountSecurityStateOperationRepository.detectedKinds(before, before)).isEmpty(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java index b90ecc152f..c534bc66fa 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java @@ -50,7 +50,13 @@ void sequenceZeroRequiresTheOriginalPositiveBaselineAndNoCheckpoint() { mock(AccountPasswordResetOperationRepository.class); AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); AccountAuthoritySourceEventReadback readback = - new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); when(outbox.readCheckpoint("account:auth-authority:v1:account/" + ACCOUNT_UUID)) .thenReturn(Optional.empty()); boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); @@ -81,7 +87,10 @@ void sequenceZeroNeverRepairsAProgressedSourceWithoutHistory() { new AccountAuthoritySourceEventReadback( outbox, mock(AccountPasswordResetOperationRepository.class), - mock(AccountLogoutAllOperationRepository.class)); + mock(AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); when(outbox.readCheckpoint("account:auth-authority:v1:account/" + ACCOUNT_UUID)) .thenReturn(Optional.empty()); boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive(); @@ -112,7 +121,13 @@ void presentCheckpointIsContradictoryAtPristineBaselineAndSingleCounterProgressi mock(AccountPasswordResetOperationRepository.class); AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); AccountAuthoritySourceEventReadback readback = - new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; when(outbox.readCheckpoint(streamKey)) .thenReturn( @@ -139,7 +154,13 @@ void retainedPasswordResetUsesImmutableReceiptWithoutMakingItsVerifierCurrent() mock(AccountPasswordResetOperationRepository.class); AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); AccountAuthoritySourceEventReadback readback = - new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); Account account = account(); account.setPasswordHash("a-later-password-verifier"); Event retained = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "a".repeat(64)); @@ -164,7 +185,13 @@ void latestPasswordResetStillRequiresItsRecordedVerifierToBeCurrent() { mock(AccountPasswordResetOperationRepository.class); AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); AccountAuthoritySourceEventReadback readback = - new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); Account account = account(); account.setPasswordHash("a-later-password-verifier"); Event latest = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "b".repeat(64)); @@ -188,7 +215,13 @@ void retainedLogoutAllEventRequiresItsExactImmutableReceipt() { mock(AccountPasswordResetOperationRepository.class); AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); AccountAuthoritySourceEventReadback readback = - new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); Event retained = logoutAllEvent( ACCOUNT_UUID, UUID.fromString("a980fa44-619e-4ca4-8ad6-75b0538a66a3"), 1L, 2L, 2L); @@ -212,7 +245,13 @@ void retainedReadRejectsChangedEventBytesAndMissingReceipts() { mock(AccountPasswordResetOperationRepository.class); AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); AccountAuthoritySourceEventReadback readback = - new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); Event valid = passwordResetEvent(ACCOUNT_UUID, 1L, 2L, 2L, "e".repeat(64)); String streamKey = "account:auth-authority:v1:account/" + ACCOUNT_UUID; when(outbox.readCheckpoint(streamKey)) @@ -234,7 +273,7 @@ void retainedReadRejectsChangedEventBytesAndMissingReceipts() { readback.requireRetainedEvent( account(), changedBytes, accountState(3L, 3L, 8L, 7L))) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("not a valid declared"); + .hasMessageContaining("Account source event is invalid"); Event changedDigest = new Event( @@ -264,7 +303,7 @@ void retainedReadRejectsChangedEventBytesAndMissingReceipts() { readback.requireRetainedEvent( account(), unsupportedSchema, accountState(3L, 3L, 8L, 7L))) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("not a valid declared"); + .hasMessageContaining("schema is missing"); Event wrongAccount = passwordResetEvent( @@ -393,13 +432,19 @@ void structuralSecurityStateCountersRequireCurrentEqualityAndRetainedNotAhead() } @Test - void structurallyValidSecurityStateCannotPassOwnerCurrentOrHistoricalReceiptReadback() { + void structurallyValidSecurityStateWithoutReceiptCannotPassOwnerReadback() { AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); AccountPasswordResetOperationRepository resets = mock(AccountPasswordResetOperationRepository.class); AccountLogoutAllOperationRepository logouts = mock(AccountLogoutAllOperationRepository.class); AccountAuthoritySourceEventReadback readback = - new AccountAuthoritySourceEventReadback(outbox, resets, logouts); + new AccountAuthoritySourceEventReadback( + outbox, + resets, + logouts, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); Event event = securityStateEvent(ACCOUNT_UUID, 1L, "2", "2"); assertThat(structuralSnapshot(event, 2L, 2L).latestEvent()).contains(event); when(outbox.readCheckpoint(event.outboxStreamKey())) @@ -410,11 +455,11 @@ void structurallyValidSecurityStateCannotPassOwnerCurrentOrHistoricalReceiptRead assertThatThrownBy(() -> readback.requireCurrentLatest(account(), accountState(2L, 2L, 2L, 2L))) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("not a valid declared password-reset or logout-all event"); + .hasMessageContaining("no immutable operation receipt"); assertThatThrownBy( () -> readback.requireRetainedEvent(account(), event, accountState(3L, 3L, 3L, 3L))) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("not a valid declared password-reset or logout-all event"); + .hasMessageContaining("no immutable operation receipt"); verifyNoInteractions(resets, logouts); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java index 09409b7abf..f606083083 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java @@ -182,7 +182,10 @@ private AccountLogoutAllAuthorityEventProducer newProducer(Collaborators collabo new AccountAuthoritySourceEventReadback( collaborators.outboxRepository(), collaborators.passwordResetRepository(), - collaborators.logoutAllRepository()); + collaborators.logoutAllRepository(), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class)); return new AccountLogoutAllAuthorityEventProducer( collaborators.accountRepository(), collaborators.generationRepository(), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index 2789c0f1a0..56251944f1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -113,6 +113,9 @@ private AccountMembershipAuthorityEventProducer producer() { authorityOutbox, mock(AccountPasswordResetOperationRepository.class), mock(AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), transitionReceipts, memberships, roleSnapshots, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java index 8cdeff464f..f24f08185b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerTest.java @@ -53,6 +53,9 @@ void inactiveMembershipSnapshotRequiresOwnerTransactionBeforeRepositoryReads() { outboxRepository, mock(AccountPasswordResetOperationRepository.class), mock(AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), receiptRepository, membershipRepository, rolesRepository, @@ -106,6 +109,9 @@ void freshSnapshotRequiresOwnerTransactionBeforeRepositoryReads() { mock(AccountAuthorityOutboxRepository.class), mock(AccountPasswordResetOperationRepository.class), mock(AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), mock(AccountMembershipTransitionReceiptRepository.class), mock(AccountTenantMembershipRepository.class), mock(AccountTenantMembershipRoleSnapshotRepository.class), @@ -145,6 +151,9 @@ void canonicalRuntimeSnapshotRequiresOwnerTransactionBeforeIdentityReads() { mock(AccountAuthorityOutboxRepository.class), mock(AccountPasswordResetOperationRepository.class), mock(AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), mock(AccountMembershipTransitionReceiptRepository.class), mock(AccountTenantMembershipRepository.class), mock(AccountTenantMembershipRoleSnapshotRepository.class), @@ -198,6 +207,9 @@ void existingPositiveSnapshotRequiresOwnerTransactionBeforeIdentityReads() { authorityOutboxRepository, mock(AccountPasswordResetOperationRepository.class), mock(AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), transitionReceiptRepository, membershipRepository, roleSnapshotRepository, @@ -259,6 +271,9 @@ void existingRuntimeSnapshotRequiresOwnerTransactionBeforeIdentityReads() { authorityOutboxRepository, mock(AccountPasswordResetOperationRepository.class), mock(AccountLogoutAllOperationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), transitionReceiptRepository, membershipRepository, roleSnapshotRepository, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 2d5088adbf..e635fcf2fc 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -280,6 +280,9 @@ void setup() { accountAuthorityOutboxRepository, passwordResetOperationRepository, logoutAllOperationRepository, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, @@ -3158,6 +3161,9 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { accountAuthorityOutboxRepository, passwordResetOperationRepository, logoutAllOperationRepository, + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), accountAuditOutboxRepository, accountConnectScopeRepository, accountJoinOperationRepository, diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.java index 5aa4d9677e..78edad8393 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/AccountMembershipAuthorityGrpcPostgresMtlsCrossServiceTest.java @@ -1285,7 +1285,9 @@ private AccountLogoutAllAuthorityEventProducer logoutProducer() { new AccountAuthoritySourceEventReadback( authorityOutboxRepository, passwordResetOperationRepository, - logoutAllOperationRepository), + logoutAllOperationRepository, + new net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository(dsl)), dsl, transactionManager); } From f03919b6dbbd0ef691bacd561b1abf36c72095eb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 15:32:15 +1300 Subject: [PATCH 02/12] docs: record nonblocking shared git housekeeping warning --- design/project-management/ai-observations.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 67d089e0e0..1323135db6 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -450,3 +450,8 @@ Entry format: - `2026-10-06`: A terminal CI failure may contain no acquired test runner - Context: exact #3007 source `a6f10921` Validation run 37369680372 ended after about 45 minutes without an Account or World matrix job, raw XML or artifacts. The detector's check annotation explicitly reports that the hosted runner was not acquired despite multiple attempts; its steps are empty. - Expected pattern: inspect terminal job annotations before attributing an aggregate failure to code. Record zero execution credit and the concrete runner-acquisition failure, retain local skipped-test limits, and continue independent implementation. A failed or cancelled detector is neither a database failure nor successful proof. + +- `2026-10-06`: Successful commits can coexist with failed background Git housekeeping + - Context: commits and normal parent merges in the Unit 1B worktrees succeeded, but Git reported an earlier `gc.log` failure and excessive unreachable loose objects, then disabled automatic cleanup. The shared repository's root cause and object-retention needs are not established. + - Expected pattern: distinguish successful publication from housekeeping health. Do not delete the warning log or run destructive object pruning as an implementation workaround; preserve unmerged branches, worktrees and unpublished objects until separately authorized maintenance establishes safe retention. + - Outcome: commit/push and byte-exact patch-preservation checks succeeded. Housekeeping remains a nonblocking maintenance concern; no cleanup or pruning was attempted. From 7ed82198ff87410d26bf0d1971b1b9897a591aee Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 16:11:39 +1300 Subject: [PATCH 03/12] Bind control-ui observations to exact issuer history in one snapshot --- .github/workflows/ci.yml | 10 ++ .../account-service/api-contracts.md | 8 ++ .../game-design-service/api-contracts.md | 2 + design/project-management/ai-observations.md | 4 + .../player-access-and-session.md | 4 + ...countControlUiCurrentSourceRepository.java | 30 +++- .../AccountIssuerAuthorityEventProducer.java | 18 +++ ...iCurrentSourcePostgresIntegrationTest.java | 130 +++++++++++++++++- ...countIssuerAuthorityEventProducerTest.java | 24 ++++ 9 files changed, 220 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 205dcf231b..c081abae09 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2480,6 +2480,7 @@ jobs: path: | services/account-service/build/test-results/integrationTest/TEST-*AccountSecurityStateOperationPostgresIntegrationTest.xml services/account-service/build/test-results/integrationTest/TEST-*AccountControlUiIssuanceOperationPostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountControlUiCurrentSourcePostgresIntegrationTest.xml if-no-files-found: warn retention-days: 7 @@ -2490,6 +2491,7 @@ jobs: --strict \ --require-suite integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest \ --require-suite integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#originalCallerAndFamilyBindingsCannotBeChangedOnRetry()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#concurrentExactClaimsSerializeToOneOriginalRequest()' \ @@ -2509,6 +2511,14 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest#exactEncryptedResultSurvivesRestartRotationAndLaterTransactionRetry(Path)' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest#lateRollbackLeavesOriginalPendingCaptureAndNoEncryptedResult()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest#additiveV66MigrationPreservesV64ReceiptAndExistingV65Structure()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#currentFreshSourceIsObservedAtOneOwnerTransactionWithoutEnrollmentOrMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#currentIssuerAdvanceRetainsItsCompleteExactEventAndCheckpointInTheSameObservation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#matchingAdvancedCountersWithoutTheirIssuerEventCannotProduceObservation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#matchingCountersAndCheckpointCannotHideContradictoryIssuerEventDigest()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#missingAuthorityFailsWithoutInventingAnInitialGeneration()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#absentOwnerTransactionAndReadOnlyTransactionCannotProduceObservation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#committedIssuerAdvanceRejectsThePriorExactSignedAndActiveRecord()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#concurrentIssuerAdvanceSerializesOnTheObservationCompositeFence()' \ account-service - name: Verify Account generation projection PostgreSQL and Redis proof cases diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index baf48894f5..b58ff0f5cf 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -28,6 +28,14 @@ For each committed role or creator-bootstrap change, Account revalidates the exa An exact retry may return only the immutable result of the original operation after its identity, digest, expected source, and committed owner readback match. It does not reauthorize a new mutation or create reusable authority. Changed actor, target, tenant, operation kind, or expected source conflicts; stale or contradictory source state and unavailable or incomplete authorization/readback fail closed. Concrete route, request, and event details proceed under this approved authority boundary and must be specified and proved before mutation is enabled; this contract adds no public Account route or wire encoding. +### Versionless Tenant-Creation Authorization + +The closed `CREATE_TENANT` operation family binds the verified initiating Account, Game Design-reserved canonical tenant UUID, exact creation operation/request and digest, and every applicable current Account source. Its two exact participants are Game Design's tenant creation and Account's first-administrator bootstrap, declared from inception. This family has no Version, Draft or World participant; a dummy Version or an existing authored-Draft fence cannot substitute for it. The distinct [Game Design reservation](../game-design-service/api-contracts.md#fresh-tenant-creation-initiator-qualification) is non-authoritative preparation and supplies neither creator content nor any role, membership or admission permission. + +Game Design commits the completed creation and creator qualification atomically, binding the same original authorization UUID and digest. At its own bootstrap commit, Account authenticates exact committed Game Design creation/qualification readback and revalidates the current actor, target and applicable sources. Each participant's definitive commit or abort readback binds the complete original operation and outcome. Account's authorization/source ordering remains unresolved until both exact outcomes settle; source-change races and uncertain outcomes retain the fence. No usable administrator, content or admission capability is exposed before its required positive outcomes are proved. No database transaction is held across owner RPCs, and neither expiry nor an absent result proves an abort. + +Recovery reads the original immutable results and never remints permission or reopens a settled authorization. If an earlier creation authorization finalized without covering bootstrap, it is historical provenance only: bootstrap requires a separately fresh, currently authorized operation. The original creation and qualification remain unchanged. Concrete producer, authenticated transport, automatic recovery and source-change concurrency proof remain required before this family can be used; [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md) tracks those implementation gates. + ### Account-Owned Hosted Terms and Creator Party Account is the sole target authority for the identified hosted Creator Party, operator/legal-party and terms-version catalog, and acceptance/currentness evidence under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md). Acceptance is an explicit party-level decision for an identified operator and hosted-terms scope; tenant roles, billing ownership, payment, caller-supplied fields, or a copied Game Design flag do not establish party, signer, or acceptance authority. Organization and other unsupported party/signer paths remain disabled until their target contract is implemented and reviewed. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 5a74e440d4..db6ab99316 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -126,6 +126,8 @@ The focused proof boundary is an owner database producer/readback test that veri The original `FreshTenantCreationEvidence/v1` and both creation digests above establish tenant identity, not creator authority. Preserve their exact bytes and digests. A fresh creator-qualified operation additionally records a distinct `FreshTenantCreatorEvidence/v1`: the complete original creation evidence, canonical initiating Account UUID, exact Account-owned creation-authorization operation UUID and digest, and its own qualification digest. Game Design stores both evidence classes atomically with the newly issued tenant; an unqualified existing operation cannot acquire a creator qualification afterward. Changed creator, authorization identity/digest or original creation input conflicts before mutation. Exact retries independently read back the original source and qualification. Private source keys remain provenance, never Account identity or permission. +Normal protected creation uses Account's [versionless tenant-creation authorization](../account-service/api-contracts.md#versionless-tenant-creation-authorization), which covers Game Design creation and Account bootstrap from inception. Before that authorization, Game Design may durably reserve its own canonical tenant UUID in a separate, explicitly non-authoritative preparation record. Reservation creates no game/content row, creator qualification, published tenant or administrator/admission authority. The completed creation-plus-qualification contract above remains atomic; its operation must not become a durably committed `PENDING` creation. A successful creator qualification preserves the original Account authorization UUID/digest and the reserved target exactly. Game Design's definitive commit/abort readback participates in that Account ordering; an unresolved creation is not permission to release a source fence or expose content. + The qualification digest uses the same strict UTF-8 decimal-byte-length framing as the original creation digests. Its fixed-order segments are `game-design-tenant-creator-qualification/v1`, qualification schema version `1`, original creation schema version, namespace, creation-request UUID, original operation UUID, original request digest, canonical tenant UUID, positive decimal source game row ID, exact source tenant key, provenance kind, original evidence digest, initiating Account UUID, Account authorization operation UUID and Account authorization digest. All fields are mandatory; a valid digest binds evidence but does not authenticate its producer or authorize a creator. `TenantIdentityService.ResolveFreshTenantCreatorQualification` is a separate Account-only, same-namespace verified-mTLS read. Its closed request binds a distinct canonical `read_request_id`, the original creation request and expected request/evidence digests, the initiating Account, authorization operation/digest and expected qualification digest. Its closed response echoes the read identity and returns the complete unchanged creation evidence and distinct qualification. The receiver rejects unknown fields and authenticated forwarded caller context before owner access, compares every requested binding and both recomputed digests, and denies missing or contradictory qualification. The Account consumer authenticates Game Design and repeats those complete checks. Only this exact method is exempted from JWT interception; the workload guard remains mandatory. Existing source-only creation and authored-world source reads retain their contracts. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 1323135db6..d56fb8fac6 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -455,3 +455,7 @@ Entry format: - Context: commits and normal parent merges in the Unit 1B worktrees succeeded, but Git reported an earlier `gc.log` failure and excessive unreachable loose objects, then disabled automatic cleanup. The shared repository's root cause and object-retention needs are not established. - Expected pattern: distinguish successful publication from housekeeping health. Do not delete the warning log or run destructive object pruning as an implementation workaround; preserve unmerged branches, worktrees and unpublished objects until separately authorized maintenance establishes safe retention. - Outcome: commit/push and byte-exact patch-preservation checks succeeded. Housekeeping remains a nonblocking maintenance concern; no cleanup or pruning was attempted. + +- `2026-10-06`: JSON string escaping is not shell argument quoting + - Context: a controller job revision passed Markdown via a JSON-quoted shell argument; Bash evaluated backtick spans and preserved literal newline escapes, corrupting the saved brief despite a successful controller result. The observed substitutions were non-existent commit-name commands; no repository code or secret was read by them. + - Outcome: the next guarded revision restored the complete intended brief using shell-safe single-argument quoting, and exact readback matched the original text. Use a body file/stdin or shell-safe quoting for multiline controller input; a successful write alone does not prove content preservation. 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 94ebee6ca5..34dce4aeaa 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -4,6 +4,10 @@ This is a non-normative implementation tracker for player access and session. Canonical target-state authentication, admission, session, and reconnection contracts remain authoritative in [design/architecture](../../architecture/README.md) and the linked design sources below; this tracker owns current implementation status, proof evidence, gaps, and handoffs, and does not redefine those contracts. +The unregistered unscoped control-ui currentness component now reads the existing issuer's complete immutable event/checkpoint through the issuer owner in the same writable Account snapshot as Account state, the private issuance fence and explicit fresh-empty global-role source. It locks issuer before recipient rows and rejects matching counters with missing or contradictory history; reads never enroll sources. Three additional PostgreSQL definitions cover positive retained issuer evidence, row-only advancement and a contradictory event digest; eight total source-observation methods are required by strict CI. The Account full check, boot JAR, formatting, Checkstyle, SpotBugs, links and Markdown pass in 1m24s (71 tasks: 19 executed, 52 up-to-date), with 1010 clean unit cases. All 426 PostgreSQL cases, including these eight, compile and skip locally without Docker. Twenty-five CI classifier/contract cases and actionlint pass after extending the strict raw-XML requirement from nineteen to twenty-seven methods. Configuration-cache storage is discarded for eighteen protobuf problems. This remains a non-authorizing source observation, not real credential authentication, a complete bundle, current Coordination projection, signer/registry proof or a released credential; exact-source PostgreSQL execution, fresh-image and activation proof remain open. + +The approved [versionless tenant-creation family](../../architecture/microservices/account-service/api-contracts.md#versionless-tenant-creation-authorization) still requires its protected Account producer, Game Design non-authoritative UUID reservation, source-writer participation, automatic two-owner outcome recovery and commit-time bootstrap authorization. Existing Version/Draft plus World storage is not that family. Creator/bootstrap fixtures and stored qualification alone do not establish these capabilities; normal creation and administrator/content exposure stay denied until the owner and concurrency proof is complete. + ## Current Status Account's V65 candidate retains one immutable security-state request/capture and its exact committed event/result, with the original V57 source-change binding and independently verified Account UUID/numeric provenance. The existing current/historical source reader now requires that real receipt, complete closed event/checkpoint binding and actual current post-state; unsupported or uncommitted evidence remains denied. A lawful independent issuance-fence advance does not invalidate an unchanged latest source event or rewrite its original receipt. Reset/logout schemas and operation families remain separate. This adds receipt/readback composition, not the authenticated mutation producer, transport authorization, source enrollment or runtime activation; genuine owner caller evidence and atomic state/source/event production remain required under [Account's operation contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-security-state-operation-and-readback). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java index 8ce4da5e70..2ef33ce9f6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java @@ -14,6 +14,8 @@ import net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourceRepository.FreshEmptySource; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiTokenChecks.InspectedToken; import net.firedevops.firemud.common.security.AccountJwtExactValues; import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; @@ -26,9 +28,9 @@ * Existing-only source observations for the genuinely unscoped fresh-creator control-ui cut. * *

All observations use the same locked Account transaction. The result is not a complete - * account-auth-evidence-bundle/v1 and never authorizes creator registration: issuer event/source - * provenance, current Coordination projections, durable token issuance and signer-generation - * retention remain separate prerequisites. Reads cannot enroll missing authority or roles. + * account-auth-evidence-bundle/v1 and never authorizes creator registration: current Coordination + * projections, durable token issuance and signer-generation retention remain separate + * prerequisites. Reads cannot enroll missing authority or roles. */ public final class AccountControlUiCurrentSourceRepository { private static final JsonMapper JSON = JsonMapper.builder().build(); @@ -37,6 +39,7 @@ public final class AccountControlUiCurrentSourceRepository { private final AccountGlobalRoleSourceRepository globalRoles; private final AccountAuthorityGenerationRepository generations; private final AccountAuthoritySourceEventReadback accountSource; + private final AccountIssuerAuthorityEventProducer issuerSource; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -46,12 +49,14 @@ public AccountControlUiCurrentSourceRepository( AccountRepository accounts, AccountGlobalRoleSourceRepository globalRoles, AccountAuthorityGenerationRepository generations, - AccountAuthoritySourceEventReadback accountSource) { + AccountAuthoritySourceEventReadback accountSource, + AccountIssuerAuthorityEventProducer issuerSource) { this.dsl = Objects.requireNonNull(dsl); this.accounts = Objects.requireNonNull(accounts); this.globalRoles = Objects.requireNonNull(globalRoles); this.generations = Objects.requireNonNull(generations); this.accountSource = Objects.requireNonNull(accountSource); + this.issuerSource = Objects.requireNonNull(issuerSource); } /** @@ -71,6 +76,10 @@ public CurrentSourceObservation inspectUnscopedCurrent(InspectedToken candidate) || (claims.containsKey("globalRoles") && !List.of().equals(claims.get("globalRoles")))) { throw invalid(); } + // Lock issuer first, preserving the composite source-writer lock order. Both issuer history + // and recipient evidence remain fenced until this same Account transaction finishes. + IssuerAuthoritySnapshot issuer = + issuerSource.readCurrentInAccountSnapshot(ControlUiJwtProfileValidator.ISSUER); FreshEmptySource roles = globalRoles.readFreshEmptySourceForUpdate(candidate.accountId()); Account account = accounts @@ -86,6 +95,10 @@ public CurrentSourceObservation inspectUnscopedCurrent(InspectedToken candidate) CompositeSnapshot current = generations.readCompositeSnapshot( ControlUiJwtProfileValidator.ISSUER, candidate.accountId(), List.of(), List.of()); + if (issuer.issuerAuthGeneration() != current.issuer().generation() + || issuer.sourceVersion() != current.issuer().sourceVersion()) { + throw invalid(); + } var latest = accountSource.requireCurrentLatest(account, current.account()); String stream = "account:auth-authority:v1:account/" + candidate.accountId(); if (latest.outboxSequence() == 0L) { @@ -133,7 +146,7 @@ public CurrentSourceObservation inspectUnscopedCurrent(InspectedToken candidate) "issuanceFenceSourceVersion", current.issuanceFence().sourceVersion()); requireEqual(expectedVersions, candidate.registryRecord().get("authoritySourceVersions")); return new CurrentSourceObservation( - candidate.accountId(), current, source, roles.globalRoleSourceVersion()); + candidate.accountId(), current, issuer, source, roles.globalRoleSourceVersion()); } private static void requireEqual(Object left, Object right) { @@ -150,16 +163,19 @@ private static IllegalStateException invalid() { public static final class CurrentSourceObservation { private final UUID accountId; private final CompositeSnapshot authority; + private final IssuerAuthoritySnapshot issuerSource; private final AccountSourceSnapshot accountSource; private final long globalRoleSourceVersion; private CurrentSourceObservation( UUID accountId, CompositeSnapshot authority, + IssuerAuthoritySnapshot issuerSource, AccountSourceSnapshot accountSource, long globalRoleSourceVersion) { this.accountId = accountId; this.authority = authority; + this.issuerSource = issuerSource; this.accountSource = accountSource; this.globalRoleSourceVersion = globalRoleSourceVersion; } @@ -176,6 +192,10 @@ public AccountSourceSnapshot accountSource() { return accountSource; } + public IssuerAuthoritySnapshot issuerSource() { + return issuerSource; + } + public long globalRoleSourceVersion() { return globalRoleSourceVersion; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java index 56eca9cb6c..b8e2a82767 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducer.java @@ -144,6 +144,24 @@ public IssuerAuthoritySnapshot readCurrent(String requestedIssuerId) { return snapshot; } + /** + * Reads existing issuer state and its exact history in the caller's writable Account snapshot. + * + *

This owner-local composition boundary acquires the same issuer row fence as {@link + * #readCurrent(String)}, but never creates a separate transaction or enrolls missing authority. + * Callers must acquire this issuer fence before locking recipient Account source rows. The + * returned source evidence is not recipient authorization or an issuance result. + */ + public IssuerAuthoritySnapshot readCurrentInAccountSnapshot(String requestedIssuerId) { + requireExactIssuer(requestedIssuerId); + requireActiveOwnerTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Issuer snapshot access requires a writable Account transaction"); + } + return readCurrentInTransaction(); + } + /** * Reads one exact retained immutable event together with the current source and checkpoint * evidence that bounds it, all while holding the issuer source row lock. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java index c815ba9f65..4c8b3bb24f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java @@ -21,7 +21,9 @@ import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiTokenChecks.InspectedToken; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; @@ -60,6 +62,9 @@ void currentFreshSourceIsObservedAtOneOwnerTransactionWithoutEnrollmentOrMutatio assertThat(observation).isNotNull(); assertThat(observation.accountId()).isEqualTo(fixture.accountId()); assertThat(observation.authority().issuer().generation()).isEqualTo(1L); + assertThat(observation.issuerSource().issuerAuthGeneration()).isEqualTo(1L); + assertThat(observation.issuerSource().outboxSequence()).isZero(); + assertThat(observation.issuerSource().latestEvent()).isEmpty(); assertThat(observation.accountSource().sourceState().generation()).isEqualTo(1L); assertThat(observation.globalRoleSourceVersion()).isEqualTo(1L); assertThat(observation.toString()).contains("non-authorizing"); @@ -68,6 +73,93 @@ void currentFreshSourceIsObservedAtOneOwnerTransactionWithoutEnrollmentOrMutatio assertThat(count(fixture.dsl(), "account_global_role_sources")).isEqualTo(1L); } + @Test + void currentIssuerAdvanceRetainsItsCompleteExactEventAndCheckpointInTheSameObservation() + throws Exception { + Fixture fixture = fixture(true); + var event = fixture.issuer().advance(ISSUER, UUID.randomUUID(), 1L, 1L); + var currentCandidate = candidate(fixture.accountId(), 2L); + var observation = + fixture.tx().execute(status -> fixture.source().inspectUnscopedCurrent(currentCandidate)); + assertThat(observation).isNotNull(); + assertThat(observation.issuerSource().issuerAuthGeneration()).isEqualTo(2L); + assertThat(observation.issuerSource().sourceVersion()).isEqualTo(2L); + assertThat(observation.issuerSource().outboxSequence()).isEqualTo(1L); + var retained = observation.issuerSource().latestEvent().orElseThrow(); + assertThat(retained.canonicalJsonUtf8()).isEqualTo(event.canonicalJsonUtf8()); + assertThat(retained.eventId()).isEqualTo(event.eventId()); + assertThat(retained.eventDigest()).isEqualTo(event.eventDigest()); + assertThat(observation.accountSource().outboxSequence()).isZero(); + } + + @Test + void matchingAdvancedCountersWithoutTheirIssuerEventCannotProduceObservation() throws Exception { + Fixture fixture = fixture(true); + fixture + .tx() + .execute( + status -> + fixture + .generations() + .advance(fixture.generations().read(AuthorityScope.issuer(ISSUER)), null)); + var matchingCounters = candidate(fixture.accountId(), 2L); + assertThatThrownBy( + () -> + fixture + .tx() + .execute(status -> fixture.source().inspectUnscopedCurrent(matchingCounters))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("sequence-zero"); + assertThat(count(fixture.dsl(), "account_authority_outbox_events")).isZero(); + } + + @Test + void matchingCountersAndCheckpointCannotHideContradictoryIssuerEventDigest() throws Exception { + Fixture fixture = fixture(true); + UUID request = UUID.randomUUID(); + fixture + .tx() + .executeWithoutResult( + status -> { + fixture + .generations() + .advance(fixture.generations().read(AuthorityScope.issuer(ISSUER)), null); + var event = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", + IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "account-issuer-authority-event-v1:" + request), + Map.entry("requestId", request.toString()), + Map.entry("issuerId", ISSUER), + Map.entry("sourceScope", "issuer/" + ISSUER), + Map.entry( + "outboxStreamKey", "account:auth-authority:v1:issuer/" + ISSUER), + Map.entry("outboxSequence", "1"), + Map.entry("issuerAuthGeneration", "2"), + Map.entry("sourceVersion", "2"))); + fixture + .outbox() + .append( + event.outboxStreamKey(), + request.toString(), + event.eventId(), + "f".repeat(64), + event.canonicalJsonUtf8()); + }); + var matchingCounters = candidate(fixture.accountId(), 2L); + assertThatThrownBy( + () -> + fixture + .tx() + .execute(status -> fixture.source().inspectUnscopedCurrent(matchingCounters))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("contradict"); + assertThat(count(fixture.dsl(), "account_authority_outbox_events")).isEqualTo(1L); + } + @Test void missingAuthorityFailsWithoutInventingAnInitialGeneration() throws Exception { Fixture fixture = fixture(false); @@ -166,17 +258,35 @@ void concurrentIssuerAdvanceSerializesOnTheObservationCompositeFence() throws Ex } private static InspectedToken candidate(UUID accountId) throws Exception { + return candidate(accountId, 1L); + } + + private static InspectedToken candidate(UUID accountId, long issuerVersion) throws Exception { var crypto = new AccountControlUiTokenFixture( Clock.fixed(AccountControlUiTokenFixture.NOW, ZoneOffset.UTC)); var claims = crypto.claims(accountId); + @SuppressWarnings("unchecked") + var tuple = new java.util.LinkedHashMap<>((Map) claims.get("authorityTuple")); + tuple.put("issuerAuthGeneration", Long.toString(issuerVersion)); + claims.put("authorityTuple", tuple); String token = crypto.sign(claims); + var registry = crypto.registry(token, claims); + registry.put( + "authoritySourceVersions", + Map.of( + "issuerSourceVersion", + issuerVersion, + "accountSourceVersion", + 1L, + "issuanceFenceSourceVersion", + 1L)); return crypto .checks() .inspect( "fresh-creator-candidate", token, - AccountControlUiTokenFixture.canonical(crypto.registry(token, claims)), + AccountControlUiTokenFixture.canonical(registry), AccountControlUiTokenFixture.unscopedShape()); } @@ -193,7 +303,7 @@ private static Fixture fixture(boolean enrollAuthority) { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") - .target(MigrationVersion.fromVersion("55")) + .target(MigrationVersion.fromVersion("65")) .load() .migrate(); DSLContext dsl = @@ -214,6 +324,13 @@ private static Fixture fixture(boolean enrollAuthority) { return generations.initialize(AuthorityScope.account(account.getAccountUuid())); }); var outbox = new AccountAuthorityOutboxRepository(dsl); + var issuer = + new AccountIssuerAuthorityEventProducer( + ISSUER, + generations, + outbox, + dsl, + java.util.Objects.requireNonNull(tx.getTransactionManager())); var readback = new AccountAuthoritySourceEventReadback( outbox, @@ -227,8 +344,9 @@ private static Fixture fixture(boolean enrollAuthority) { accounts, new AccountGlobalRoleSourceRepository(dsl, dataSource), generations, - readback); - return new Fixture(dsl, tx, account.getAccountUuid(), generations, source); + readback, + issuer); + return new Fixture(dsl, tx, account.getAccountUuid(), generations, source, issuer, outbox); } private static Long count(DSLContext dsl, String table) { @@ -253,5 +371,7 @@ private record Fixture( TransactionTemplate tx, UUID accountId, AccountAuthorityGenerationRepository generations, - AccountControlUiCurrentSourceRepository source) {} + AccountControlUiCurrentSourceRepository source, + AccountIssuerAuthorityEventProducer issuer, + AccountAuthorityOutboxRepository outbox) {} } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java index dfcf6b54d1..77346ee5bc 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountIssuerAuthorityEventProducerTest.java @@ -154,6 +154,30 @@ void sequenceZeroSnapshotContainsOnlyProvenBaselineAndEmptyEventOptional() { assertThat(snapshot.outboxSequence()).isZero(); } + @Test + void composedSnapshotRequiresExactIssuerAndWritableOwnerTransactionBeforePersistence() { + Collaborators collaborators = new Collaborators(); + var producer = newProducer(ISSUER_ID, collaborators); + assertThatThrownBy(() -> producer.readCurrentInAccountSnapshot(OTHER_ISSUER_ID)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> producer.readCurrentInAccountSnapshot(ISSUER_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Account owner transaction"); + boolean active = TransactionSynchronizationManager.isActualTransactionActive(); + boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> producer.readCurrentInAccountSnapshot(ISSUER_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable Account transaction"); + collaborators.verifyUnused(); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly); + TransactionSynchronizationManager.setActualTransactionActive(active); + } + } + @Test void sequenceZeroSnapshotRejectsWrongIssuerStreamAndUnprovenCounters() { assertThatThrownBy( From e057e1f873753fe7141a53a1e65f2c9f214b1d38 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 17:30:36 +1300 Subject: [PATCH 04/12] Complete versionless tenant creation ordering and repair PostgreSQL guards --- .github/workflows/ci.yml | 26 +- .../player-access-and-session.md | 8 +- .../DraftAuthorizationFenceRepository.java | 4 +- ...nantCreationAuthorizationFenceBinding.java | 317 ++++++++++ ...tCreationAuthorizationFenceRepository.java | 357 +++++++++++ ...V65__account_security_state_operations.sql | 4 +- ...__tenant_creation_authorization_fences.sql | 166 +++++ ...horityProducerPostgresIntegrationTest.java | 25 +- ...StateOperationPostgresIntegrationTest.java | 24 +- ...horityProducerPostgresIntegrationTest.java | 36 +- ...iCurrentSourcePostgresIntegrationTest.java | 2 +- ...orizationFencePostgresIntegrationTest.java | 575 ++++++++++++++++++ ...CreationAuthorizationFenceBindingTest.java | 152 +++++ 13 files changed, 1670 insertions(+), 26 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V67__tenant_creation_authorization_fences.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceBindingTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 443136392d..c23c01d8c8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2521,6 +2521,30 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#concurrentIssuerAdvanceSerializesOnTheObservationCompositeFence()' \ account-service + - name: Capture Account versionless tenant-creation PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-tenant-creation-fence-postgresql-proof-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: services/account-service/build/test-results/integrationTest/TEST-*TenantCreationAuthorizationFencePostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Verify Account versionless tenant-creation PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFencePostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFencePostgresIntegrationTest#revokeFirstRetainsBothFamilyFencesUntilExactAborts()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFencePostgresIntegrationTest#commitFirstRequiresBothExactOutcomesAndMixedVectorDoesNotQualifySuccess()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFencePostgresIntegrationTest#contradictoryRevokeOutcomeNeverReleasesSourceOrdering()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFencePostgresIntegrationTest#exactRetryAndDatabaseGuardsPreserveBindingAndFinalizedResults()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFencePostgresIntegrationTest#lateFailureRollsBackSourceTransitionWithOwnersRemainingImmutable()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFencePostgresIntegrationTest#sharedSourceLocksSerializeBothCompetingInterleavings()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFencePostgresIntegrationTest#migrationRetainsV66AndDraftImagesAndOriginalDraftBindingBytes()' \ + account-service + - name: Verify Account generation projection PostgreSQL and Redis proof cases if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | @@ -2621,7 +2645,7 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#sameRequestUuidAcrossExactIssuersHasDistinctPersistedSourceChangeIdentities()' \ --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#failedIssuerAdvanceRetainsOriginalPendingCaptureForExactRetry()' \ --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#issuerPendingCaptureRetainsIndependentCountersCheckpointAndExactPositiveEventBytes()' \ - --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#v59PreservesV58HistoryAndExactKeysBeforeV61ProducerInteractionsWithFullMultibyteIssuer()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerAuthorityProducerPostgresIntegrationTest#v59PreservesV58HistoryAndExactKeysBeforeV67ProducerInteractionsWithFullMultibyteIssuer()' \ account-service - name: Verify Account tenant Draft source ordering PostgreSQL proof cases 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 feb93cf8ff..3d38ed28a4 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -4,12 +4,16 @@ This is a non-normative implementation tracker for player access and session. Canonical target-state authentication, admission, session, and reconnection contracts remain authoritative in [design/architecture](../../architecture/README.md) and the linked design sources below; this tracker owns current implementation status, proof evidence, gaps, and handoffs, and does not redefine those contracts. +## Current Status + +The versionless `CREATE_TENANT` candidate adds V67 and an immutable exact-operation/source-ordering repository for Game Design creation and Account first-admin bootstrap. It shares the existing V57 source locks and journal with Draft work; both exact definitive owner outcomes are required before source mutation or no-mutation abort may settle. Three unit cases execute; seven PostgreSQL cases specify both competing source-order interleavings, mixed and contradictory outcomes, rollback, exact retry, database immutability and V66/Draft row preservation. These fixtures stipulate authentication and owner readbacks: the repository does not authenticate the creator, authorize either owner, create a tenant or enable bootstrap. The protected producer and automatic two-owner recovery remain open. + +At exact `3bdc63340b760313cfeefe7b442bc876fcd1977a`, [CI37408149747](https://github.com/benhook1013/FireMUD/actions/runs/37408149747) fails Account and Game Session startup on V65's PL/pgSQL `CASE` expression in a trigger `IF`, with SQLSTATE `42601`. The Account report records fifteen cases and eleven startup failures; the required V65/V66/current-source suites supply no raw execution XML. The correction parenthesizes the affected conditional expressions without removing any guard, including the same pattern in new V67. Historical issuer and logout fixture seeds retain their declared V58→V59 and V59→V60 table-image boundaries; only current-engine interactions advance to V67. The corrected local Account check, jOOQ, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass in 1m48s (72 tasks: 20 executed), with 1013 clean unit cases. All 433 PostgreSQL cases, including the seven new ones, compile but skip without Docker. Corrected exact-source PostgreSQL execution remains required; the aggregate run also has separate TCP Proxy and Game Logic failures. This is neither database execution nor activation proof. + The unregistered unscoped control-ui currentness component now reads the existing issuer's complete immutable event/checkpoint through the issuer owner in the same writable Account snapshot as Account state, the private issuance fence and explicit fresh-empty global-role source. It locks issuer before recipient rows and rejects matching counters with missing or contradictory history; reads never enroll sources. Three additional PostgreSQL definitions cover positive retained issuer evidence, row-only advancement and a contradictory event digest; eight total source-observation methods are required by strict CI. The Account full check, boot JAR, formatting, Checkstyle, SpotBugs, links and Markdown pass in 1m24s (71 tasks: 19 executed, 52 up-to-date), with 1010 clean unit cases. All 426 PostgreSQL cases, including these eight, compile and skip locally without Docker. Twenty-five CI classifier/contract cases and actionlint pass after extending the strict raw-XML requirement from nineteen to twenty-seven methods. Configuration-cache storage is discarded for eighteen protobuf problems. This remains a non-authorizing source observation, not real credential authentication, a complete bundle, current Coordination projection, signer/registry proof or a released credential; exact-source PostgreSQL execution, fresh-image and activation proof remain open. The approved [versionless tenant-creation family](../../architecture/microservices/account-service/api-contracts.md#versionless-tenant-creation-authorization) still requires its protected Account producer, Game Design non-authoritative UUID reservation, source-writer participation, automatic two-owner outcome recovery and commit-time bootstrap authorization. Existing Version/Draft plus World storage is not that family. Creator/bootstrap fixtures and stored qualification alone do not establish these capabilities; normal creation and administrator/content exposure stay denied until the owner and concurrency proof is complete. -## Current Status - Account's V65 candidate retains one immutable security-state request/capture and its exact committed event/result, with the original V57 source-change binding and independently verified Account UUID/numeric provenance. The existing current/historical source reader now requires that real receipt, complete closed event/checkpoint binding and actual current post-state; unsupported or uncommitted evidence remains denied. A lawful independent issuance-fence advance does not invalidate an unchanged latest source event or rewrite its original receipt. Reset/logout schemas and operation families remain separate. This adds receipt/readback composition, not the authenticated mutation producer, transport authorization, source enrollment or runtime activation; genuine owner caller evidence and atomic state/source/event production remain required under [Account's operation contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-security-state-operation-and-readback). The V66 targetless control-ui candidate retains canonical request correlation, the first original Account association and opaque authority/fence captures, and one exact purpose-bound encrypted result. First-writer claims serialize; committed retries cannot substitute response, token, key-purpose or capture bytes. The unregistered repository does not authenticate credentials, establish current authority, verify or write the active token registry, mint a JWT or release a credential. V66's additive fixture preserves a real V64 pending receipt and the V65 table structure; it does not directly exercise a nonempty V65 operation row. Actual ordinary control-ui issuance/authenticated exact recovery, registry/currentness composition and protected custody/live readiness remain open under [Account's recovery contract](../../architecture/microservices/account-service/runtime-and-data.md#exact-control-ui-issuance-recovery). The ring mount and denied runtime paths remain unchanged. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index ba50e2416d..7a480bbf6c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.Owner; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.OwnerReadback; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceRepository; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -277,6 +278,7 @@ public boolean requestSourceChange(SourceChange change) { operation); } } + new TenantCreationAuthorizationFenceRepository(dsl).revokeAffected(change.sources()); return allAffectedSettled(change.sources()); } @@ -544,7 +546,7 @@ private boolean allAffectedSettled(List sources) { return false; } } - return true; + return new TenantCreationAuthorizationFenceRepository(dsl).allAffectedSettled(sources); } private Settlement settlement(UUID operation, Ordering ordering) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceBinding.java new file mode 100644 index 0000000000..69998f9802 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceBinding.java @@ -0,0 +1,317 @@ +package net.firedevops.firemud.accountservice.tenantcreation; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; + +/** + * Closed versionless CREATE_TENANT correlation. Supplied actor, original authorization capture and + * source bytes require authenticated, current owner producers; storage cannot establish them. The + * capture is immutable evidence for this fresh operation, not finalized participant outcomes. An + * already-finalized creation authorization is provenance only and cannot authorize bootstrap. There + * is no Draft, Version, World participant or reusable authorization in this family. + */ +public record TenantCreationAuthorizationFenceBinding( + UUID operationId, + UUID requestId, + UUID fenceId, + UUID actorAccountId, + UUID tenantId, + UUID creationOperationId, + String targetNamespace, + String sourceGameTenantKey, + String name, + String description, + String creationRequestDigest, + byte[] originalAuthorizationCapture, + List sources) { + public static final String SCHEMA = "account-create-tenant-authorization-fence/v1"; + + public TenantCreationAuthorizationFenceBinding { + for (UUID id : + List.of(operationId, requestId, fenceId, actorAccountId, tenantId, creationOperationId)) { + requireUuid(id); + } + for (String value : List.of(targetNamespace, sourceGameTenantKey, name)) { + text(value); + } + if (!targetNamespace.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new IllegalArgumentException("Canonical target namespace required"); + } + if (description != null) { + GameTenantCreationDigest.utf8ByteLength(description); + if (description.indexOf('\0') >= 0) { + throw new IllegalArgumentException("NUL in creation description"); + } + } + if (sourceGameTenantKey.codePointCount(0, sourceGameTenantKey.length()) > 36 + || name.codePointCount(0, name.length()) > 100 + || (description != null && description.codePointCount(0, description.length()) > 255) + || !GameTenantCreationDigest.requestDigest( + targetNamespace, requestId, sourceGameTenantKey, name, description) + .equals(creationRequestDigest)) { + throw new IllegalArgumentException("Exact Game Design creation request digest required"); + } + originalAuthorizationCapture = bytes(originalAuthorizationCapture); + sources = + Objects.requireNonNull(sources).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Distinct applicable current Account sources required"); + } + } + + @Override + public byte[] originalAuthorizationCapture() { + return originalAuthorizationCapture.clone(); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (String value : + List.of( + SCHEMA, + "CREATE_TENANT", + operationId.toString(), + requestId.toString(), + fenceId.toString(), + actorAccountId.toString(), + tenantId.toString(), + creationOperationId.toString(), + targetNamespace, + sourceGameTenantKey, + name)) { + frame(out, value); + } + frame(out, description == null ? "ABSENT" : "PRESENT"); + if (description != null) { + frame(out, description); + } + frame(out, creationRequestDigest); + frame(out, originalAuthorizationCapture); + frame(out, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + frame(out, source.canonicalBytes()); + } + // Exact participants from inception, with their distinct owner-local operation identities. + frame(out, "GAME_DESIGN"); + frame(out, creationOperationId.toString()); + frame(out, "ACCOUNT"); + frame(out, operationId.toString()); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + /** Recover only the fresh operation's original evidence, never finalized participant outcomes. */ + public static TenantCreationAuthorizationFenceBinding fromStored(byte[] stored) { + Reader reader = new Reader(stored); + reader.expect(SCHEMA); + reader.expect("CREATE_TENANT"); + UUID operation = UUID.fromString(reader.text()); + UUID request = UUID.fromString(reader.text()); + UUID fence = UUID.fromString(reader.text()); + UUID actor = UUID.fromString(reader.text()); + UUID tenant = UUID.fromString(reader.text()); + UUID creation = UUID.fromString(reader.text()); + String namespace = reader.text(); + String key = reader.text(); + String name = reader.text(); + String presence = reader.text(); + if (!"ABSENT".equals(presence) && !"PRESENT".equals(presence)) { + throw new IllegalArgumentException("Invalid creation description presence"); + } + String description = "PRESENT".equals(presence) ? reader.text() : null; + String digest = reader.text(); + byte[] authorization = reader.bytes(); + String count = reader.text(); + if (!count.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical source count required"); + } + int size; + try { + size = Integer.parseInt(count); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Source count out of range", invalid); + } + if (size > reader.input.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Incomplete stored source vector"); + } + List sources = new ArrayList<>(); + for (int i = 0; i < size; i++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + reader.expect("GAME_DESIGN"); + reader.expect(creation.toString()); + reader.expect("ACCOUNT"); + reader.expect(operation.toString()); + var binding = + new TenantCreationAuthorizationFenceBinding( + operation, + request, + fence, + actor, + tenant, + creation, + namespace, + key, + name, + description, + digest, + authorization, + sources); + if (reader.input.hasRemaining() || !Arrays.equals(stored, binding.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored CREATE_TENANT binding"); + } + return binding; + } + + public enum Owner { + GAME_DESIGN, + ACCOUNT + } + + public enum Outcome { + COMMITTED, + DEFINITIVELY_ABORTED + } + + /** + * Definitive exact readback, never timeout/absence; future authenticated verifier supplies it. + */ + public record OwnerReadback( + Owner owner, Outcome outcome, UUID ownerOperationId, byte[] fullBinding, byte[] result) { + public OwnerReadback { + Objects.requireNonNull(owner); + Objects.requireNonNull(outcome); + requireUuid(ownerOperationId); + fullBinding = bytes(fullBinding); + result = bytes(result); + } + + @Override + public byte[] fullBinding() { + return fullBinding.clone(); + } + + @Override + public byte[] result() { + return result.clone(); + } + + public void requireBinding(TenantCreationAuthorizationFenceBinding binding) { + UUID expected = + owner == Owner.GAME_DESIGN ? binding.creationOperationId() : binding.operationId(); + if (!expected.equals(ownerOperationId) + || !Arrays.equals(fullBinding, binding.canonicalBytes())) { + throw new IllegalArgumentException( + "Owner readback differs from exact CREATE_TENANT binding"); + } + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (String value : + List.of( + "account-create-tenant-owner-readback/v1", + owner.name(), + outcome.name(), + ownerOperationId.toString())) { + frame(out, value); + } + frame(out, fullBinding); + frame(out, result); + return out.toByteArray(); + } + } + + private static void requireUuid(UUID id) { + if (id == null || id.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Non-nil UUID required"); + } + } + + private static void text(String value) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) { + throw new IllegalArgumentException("Nonempty canonical text required"); + } + GameTenantCreationDigest.utf8ByteLength(value); + } + + private static byte[] bytes(byte[] value) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException("Exact bytes required"); + } + return value.clone(); + } + + private static void frame(ByteArrayOutputStream out, String value) { + frame(out, value.getBytes(StandardCharsets.UTF_8)); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + try { + DataOutputStream data = new DataOutputStream(out); + data.writeInt(value.length); + data.write(value); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static final class Reader { + private final ByteBuffer input; + + private Reader(byte[] stored) { + input = ByteBuffer.wrap(TenantCreationAuthorizationFenceBinding.bytes(stored)); + } + + private byte[] bytes() { + if (input.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("Truncated CREATE_TENANT frame"); + } + int length = input.getInt(); + if (length < 0 || length > input.remaining()) { + throw new IllegalArgumentException("Invalid CREATE_TENANT frame size"); + } + byte[] value = new byte[length]; + input.get(value); + return value; + } + + private String text() { + byte[] value = bytes(); + String decoded = new String(value, StandardCharsets.UTF_8); + if (!Arrays.equals(value, decoded.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Invalid UTF-8 creation frame"); + } + return decoded; + } + + private void expect(String value) { + if (!value.equals(text())) { + throw new IllegalArgumentException("Unexpected closed CREATE_TENANT field"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceRepository.java new file mode 100644 index 0000000000..f02ad539fb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceRepository.java @@ -0,0 +1,357 @@ +package net.firedevops.firemud.accountservice.tenantcreation; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceBinding.OwnerReadback; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired CREATE_TENANT durable ordering/readback storage. Callers first authenticate and lock/ + * revalidate every real applicable source, then acquire the same sorted participation locks used by + * Draft and source mutations. Do not retain any lock across RPC. Correlation is not authority; an + * exact replay recovers the original authorization capture, never reopens owner permission. + */ +public final class TenantCreationAuthorizationFenceRepository { + private static final String FENCES = "account_tenant_creation_authorization_fences"; + private static final String SOURCES = "account_tenant_creation_authorization_sources"; + private static final String READBACKS = "account_tenant_creation_authorization_readbacks"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "DSLContext is an internal caller-transaction persistence collaborator.") + public TenantCreationAuthorizationFenceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public record FenceSnapshot( + Ordering ordering, byte[] binding, OffsetDateTime reservedAt, OffsetDateTime orderedAt) { + public FenceSnapshot { + binding = binding.clone(); + } + + @Override + public byte[] binding() { + return binding.clone(); + } + } + + public record OwnerResultSnapshot(Outcome outcome, byte[] readback, OffsetDateTime recordedAt) { + public OwnerResultSnapshot { + readback = readback.clone(); + } + + @Override + public byte[] readback() { + return readback.clone(); + } + } + + public FenceSnapshot reserve(TenantCreationAuthorizationFenceBinding binding) { + requireTransaction(); + lockSources(binding.sources()); + Record row = readOperation(binding.operationId()); + if (row != null) { + return snapshot(requireExact(row, binding)); + } + if (hasWaitingChange(binding.sources())) { + throw new IllegalStateException("Applicable authority source change is waiting"); + } + dsl.execute( + "INSERT INTO " + + FENCES + + " (operation_id, request_id, fence_id, actor_account_id, tenant_id, creation_operation_id," + + " creation_request_digest, binding, ordering) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'RESERVED')", + binding.operationId(), + binding.requestId(), + binding.fenceId(), + binding.actorAccountId(), + binding.tenantId(), + binding.creationOperationId(), + binding.creationRequestDigest(), + binding.canonicalBytes()); + for (SourceEvidence source : binding.sources()) { + dsl.execute( + "INSERT INTO " + + SOURCES + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + source.key(), + source.canonicalBytes()); + } + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** Caller must revalidate real current source state before claiming this irrevocable order. */ + public FenceSnapshot claimCommitOrder(TenantCreationAuthorizationFenceBinding binding) { + requireTransaction(); + lockSources(binding.sources()); + Record row = requireExact(readOperation(binding.operationId()), binding); + Ordering ordering = Ordering.valueOf(row.get("ordering", String.class)); + if (ordering == Ordering.COMMIT_ORDER) { + return snapshot(row); + } + if (ordering == Ordering.REVOKE_ORDER || hasWaitingChange(binding.sources())) { + throw new IllegalStateException("Revocation precedes this tenant creation"); + } + dsl.execute( + "UPDATE " + + FENCES + + " SET ordering = 'COMMIT_ORDER', ordered_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND ordering = 'RESERVED'", + binding.operationId()); + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** Original exact source correlation only; not a fresh permission or owner dispatch gate. */ + public FenceSnapshot read(TenantCreationAuthorizationFenceBinding binding) { + requireTransaction(); + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** Read-only recovery of original provenance; absence is UNKNOWN and never no-commit proof. */ + public Optional readOriginalBinding(UUID operationId) { + requireTransaction(); + Record row = readOperation(operationId); + if (row == null) { + return Optional.empty(); + } + var binding = + TenantCreationAuthorizationFenceBinding.fromStored(row.get("binding", byte[].class)); + if (!operationId.equals(binding.operationId())) { + throw new IllegalStateException("Stored CREATE_TENANT operation identity differs"); + } + requireExact(row, binding); + return Optional.of(binding); + } + + public void recordOwnerReadback( + TenantCreationAuthorizationFenceBinding binding, OwnerReadback readback) { + requireTransaction(); + readback.requireBinding(binding); + Record row = requireExact(readOperation(binding.operationId()), binding); + if (Ordering.RESERVED.name().equals(row.get("ordering", String.class))) { + throw new IllegalStateException("Reservation alone cannot produce owner terminal evidence"); + } + Record prior = + dsl.fetchOne( + "SELECT readback FROM " + READBACKS + " WHERE operation_id = ? AND owner = ?", + binding.operationId(), + readback.owner().name()); + if (prior != null) { + if (!Arrays.equals(prior.get("readback", byte[].class), readback.canonicalBytes())) { + throw new IllegalArgumentException("Changed owner terminal evidence"); + } + return; + } + dsl.execute( + "INSERT INTO " + + READBACKS + + " (operation_id, owner, owner_operation_id, outcome, readback, owner_result) VALUES (?, ?, ?, ?, ?, ?)", + binding.operationId(), + readback.owner().name(), + readback.ownerOperationId(), + readback.outcome().name(), + readback.canonicalBytes(), + readback.result()); + } + + public Optional readOwnerResult( + TenantCreationAuthorizationFenceBinding binding, Owner owner) { + requireTransaction(); + requireExact(readOperation(binding.operationId()), binding); + Record row = + dsl.fetchOne( + "SELECT outcome, readback, recorded_at FROM " + + READBACKS + + " WHERE operation_id = ? AND owner = ?", + binding.operationId(), + owner.name()); + return row == null + ? Optional.empty() + : Optional.of( + new OwnerResultSnapshot( + Outcome.valueOf(row.get("outcome", String.class)), + row.get("readback", byte[].class), + row.get("recorded_at", OffsetDateTime.class))); + } + + public Settlement readSettlement(TenantCreationAuthorizationFenceBinding binding) { + requireTransaction(); + Record row = requireExact(readOperation(binding.operationId()), binding); + return settlement(binding.operationId(), Ordering.valueOf(row.get("ordering", String.class))); + } + + /** + * Existing source-change engine calls this under its shared sorted source locks, after locking + * affected Draft operations. Commit order remains fixed; reserved creation is revoked forever. + */ + public void revokeAffected(List sources) { + requireTransaction(); + lockSources(sources); + for (UUID operation : affectedOperations(sources)) { + Record row = readOperation(operation); + if (Ordering.RESERVED.name().equals(row.get("ordering", String.class))) { + dsl.execute( + "UPDATE " + + FENCES + + " SET ordering = 'REVOKE_ORDER', ordered_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND ordering = 'RESERVED'", + operation); + } + } + } + + /** Settlement is source-order release only. Mixed outcomes cannot qualify usable tenant state. */ + public boolean allAffectedSettled(List sources) { + requireTransaction(); + lockSources(sources); + for (UUID operation : affectedOperations(sources)) { + Record row = readOperation(operation); + if (settlement(operation, Ordering.valueOf(row.get("ordering", String.class))) + == Settlement.PENDING) { + return false; + } + } + return true; + } + + private Settlement settlement(UUID operation, Ordering ordering) { + if (ordering == Ordering.RESERVED) { + return Settlement.PENDING; + } + List outcomes = + dsl.fetch("SELECT outcome FROM " + READBACKS + " WHERE operation_id = ?", operation) + .getValues("outcome", String.class); + if (outcomes.size() != 2) { + return Settlement.PENDING; + } + if (ordering == Ordering.REVOKE_ORDER) { + return outcomes.stream().allMatch(Outcome.DEFINITIVELY_ABORTED.name()::equals) + ? Settlement.FAILED_NONPUBLICATION + : Settlement.PENDING; + } + return outcomes.stream().allMatch(Outcome.COMMITTED.name()::equals) + ? Settlement.COMMITTED + : Settlement.FAILED_NONPUBLICATION; + } + + private List affectedOperations(List sources) { + return sources.stream() + .flatMap( + source -> + dsl + .fetch( + "SELECT operation_id FROM " + SOURCES + " WHERE source_key = ?", + source.key()) + .getValues("operation_id", UUID.class) + .stream()) + .distinct() + .sorted(Comparator.comparing(UUID::toString)) + .toList(); + } + + private void lockSources(List sources) { + for (String key : sources.stream().map(SourceEvidence::key).distinct().sorted().toList()) { + dsl.execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT DO NOTHING", + key); + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + key); + } + } + + private boolean hasWaitingChange(List sources) { + for (SourceEvidence source : sources) { + if (!dsl.fetch( + "SELECT c.change_id FROM account_draft_authorization_source_changes c" + + " JOIN account_draft_authorization_changed_scopes s ON s.change_id = c.change_id" + + " WHERE s.source_key = ? AND c.status = 'WAITING'", + source.key()) + .isEmpty()) { + return true; + } + } + return false; + } + + private Record readOperation(UUID operation) { + return dsl.fetchOne( + "SELECT * FROM " + FENCES + " WHERE operation_id = ? FOR UPDATE", operation); + } + + private Record requireExact(Record row, TenantCreationAuthorizationFenceBinding binding) { + if (row == null + || !Arrays.equals(row.get("binding", byte[].class), binding.canonicalBytes()) + || !binding.requestId().equals(row.get("request_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class)) + || !binding.actorAccountId().equals(row.get("actor_account_id", UUID.class)) + || !binding.tenantId().equals(row.get("tenant_id", UUID.class)) + || !binding.creationOperationId().equals(row.get("creation_operation_id", UUID.class)) + || !binding + .creationRequestDigest() + .equals(row.get("creation_request_digest", String.class))) { + throw new IllegalArgumentException("Absent or changed immutable CREATE_TENANT operation"); + } + List rows = + dsl.fetch( + "SELECT source_key, source_evidence FROM " + + SOURCES + + " WHERE operation_id = ? ORDER BY source_key", + binding.operationId()); + // Java canonical key ordering is independent of the database collation. + rows = + rows.stream().sorted(Comparator.comparing(r -> r.get("source_key", String.class))).toList(); + if (rows.size() != binding.sources().size()) { + throw new IllegalStateException("Incomplete creation source participation"); + } + for (int i = 0; i < rows.size(); i++) { + SourceEvidence source = binding.sources().get(i); + if (!source.key().equals(rows.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), rows.get(i).get("source_evidence", byte[].class))) { + throw new IllegalStateException("Source participation differs from exact creation binding"); + } + } + return row; + } + + private FenceSnapshot snapshot(Record row) { + return new FenceSnapshot( + Ordering.valueOf(row.get("ordering", String.class)), + row.get("binding", byte[].class), + row.get("reserved_at", OffsetDateTime.class), + row.get("ordered_at", OffsetDateTime.class)); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable caller Account transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Transaction-bound writable READ_COMMITTED connection required"); + } + }); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V65__account_security_state_operations.sql b/services/account-service/src/main/resources/db/migration/V65__account_security_state_operations.sql index 74864eee4b..dcdc4111f8 100644 --- a/services/account-service/src/main/resources/db/migration/V65__account_security_state_operations.sql +++ b/services/account-service/src/main/resources/db/migration/V65__account_security_state_operations.sql @@ -243,7 +243,7 @@ BEGIN SELECT * INTO source_row FROM account_draft_authorization_source_changes WHERE change_id = NEW.source_change_id FOR SHARE; IF NOT FOUND OR source_row.binding <> NEW.source_change_binding - OR source_row.status <> CASE WHEN TG_OP = 'INSERT' THEN 'WAITING' ELSE 'SOURCE_COMMITTED' END THEN + OR source_row.status <> (CASE WHEN TG_OP = 'INSERT' THEN 'WAITING' ELSE 'SOURCE_COMMITTED' END) THEN RAISE EXCEPTION 'Security-state V57 source change differs' USING ERRCODE = '23514'; END IF; SELECT * INTO authority_row FROM account_authority_generations @@ -310,7 +310,7 @@ BEGIN OR NEW.result_fence_source_version::NUMERIC <> NEW.expected_fence_source_version::NUMERIC + 1 OR NEW.event_sequence::NUMERIC <> NEW.checkpoint_sequence::NUMERIC + 1 OR NEW.result_global_role_source_version::NUMERIC <> NEW.global_role_source_version::NUMERIC - + CASE WHEN 'GLOBAL_ROLE_CHANGED' = ANY(kinds) THEN 1 ELSE 0 END + + (CASE WHEN 'GLOBAL_ROLE_CHANGED' = ANY(kinds) THEN 1 ELSE 0 END) OR authority_row.generation <> NEW.result_generation OR authority_row.source_version <> NEW.result_source_version OR fence_row.issuance_fence <> NEW.result_fence OR fence_row.source_version <> NEW.result_fence_source_version OR role_row.global_role_source_version <> NEW.result_global_role_source_version THEN diff --git a/services/account-service/src/main/resources/db/migration/V67__tenant_creation_authorization_fences.sql b/services/account-service/src/main/resources/db/migration/V67__tenant_creation_authorization_fences.sql new file mode 100644 index 0000000000..65d1c89501 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V67__tenant_creation_authorization_fences.sql @@ -0,0 +1,166 @@ +-- Versionless CREATE_TENANT storage only. No authenticated producer or owner is enabled. +-- Source participation uses V57's existing locks and source-change journal, not a second engine. +CREATE TABLE account_tenant_creation_authorization_fences ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + fence_id UUID NOT NULL UNIQUE, + actor_account_id UUID NOT NULL, + tenant_id UUID NOT NULL UNIQUE, + creation_operation_id UUID NOT NULL UNIQUE, + creation_request_digest VARCHAR(71) NOT NULL + CHECK (creation_request_digest ~ '^sha256:[0-9a-f]{64}$'), + binding BYTEA NOT NULL CHECK (octet_length(binding) > 0), + ordering VARCHAR(20) NOT NULL CHECK (ordering IN ('RESERVED', 'COMMIT_ORDER', 'REVOKE_ORDER')), + reserved_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + ordered_at TIMESTAMPTZ, + CHECK ((ordering = 'RESERVED') = (ordered_at IS NULL)), + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000' + AND request_id <> '00000000-0000-0000-0000-000000000000' + AND fence_id <> '00000000-0000-0000-0000-000000000000' + AND actor_account_id <> '00000000-0000-0000-0000-000000000000' + AND tenant_id <> '00000000-0000-0000-0000-000000000000' + AND creation_operation_id <> '00000000-0000-0000-0000-000000000000') +); + +CREATE TABLE account_tenant_creation_authorization_sources ( + operation_id UUID NOT NULL REFERENCES account_tenant_creation_authorization_fences(operation_id), + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_tenant_creation_authorization_sources_by_scope + ON account_tenant_creation_authorization_sources(source_key, operation_id); + +CREATE TABLE account_tenant_creation_authorization_readbacks ( + operation_id UUID NOT NULL REFERENCES account_tenant_creation_authorization_fences(operation_id), + owner VARCHAR(16) NOT NULL CHECK (owner IN ('GAME_DESIGN', 'ACCOUNT')), + owner_operation_id UUID NOT NULL, + outcome VARCHAR(24) NOT NULL CHECK (outcome IN ('COMMITTED', 'DEFINITIVELY_ABORTED')), + readback BYTEA NOT NULL CHECK (octet_length(readback) > 0), + owner_result BYTEA NOT NULL CHECK (octet_length(owner_result) > 0), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (operation_id, owner) +); + +-- [jooq ignore start] +CREATE FUNCTION account_tenant_creation_authorization_frame(value BYTEA) +RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT int4send(octet_length(value)) || value; +$$; + +CREATE FUNCTION account_tenant_creation_authorization_order_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'CREATE_TENANT ordering cannot be deleted' USING ERRCODE = '23514'; + ELSIF TG_OP = 'INSERT' THEN + IF NEW.ordering <> 'RESERVED' OR NEW.ordered_at IS NOT NULL THEN + RAISE EXCEPTION 'CREATE_TENANT must begin reserved' USING ERRCODE = '23514'; + END IF; + ELSIF OLD.ordering <> 'RESERVED' + OR NEW.ordering NOT IN ('COMMIT_ORDER', 'REVOKE_ORDER') OR NEW.ordered_at IS NULL + OR (to_jsonb(NEW) - ARRAY['ordering','ordered_at']) IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['ordering','ordered_at']) THEN + RAISE EXCEPTION 'CREATE_TENANT binding and finalized order are immutable' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_creation_authorization_insert_phase_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + fence account_tenant_creation_authorization_fences%ROWTYPE; + expected_readback BYTEA; +BEGIN + SELECT * INTO fence FROM account_tenant_creation_authorization_fences + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF TG_TABLE_NAME = 'account_tenant_creation_authorization_sources' THEN + IF fence.ordering IS DISTINCT FROM 'RESERVED' THEN + RAISE EXCEPTION 'Ordered CREATE_TENANT cannot acquire sources' USING ERRCODE = '23514'; + END IF; + ELSE + IF fence.ordering IS NULL OR fence.ordering = 'RESERVED' + OR NEW.owner_operation_id IS DISTINCT FROM (CASE + WHEN NEW.owner = 'GAME_DESIGN' THEN fence.creation_operation_id + ELSE fence.operation_id END) THEN + RAISE EXCEPTION 'Exact ordered CREATE_TENANT owner operation required' USING ERRCODE = '23514'; + END IF; + expected_readback := + account_tenant_creation_authorization_frame(convert_to('account-create-tenant-owner-readback/v1', 'UTF8')) + || account_tenant_creation_authorization_frame(convert_to(NEW.owner, 'UTF8')) + || account_tenant_creation_authorization_frame(convert_to(NEW.outcome, 'UTF8')) + || account_tenant_creation_authorization_frame(convert_to(NEW.owner_operation_id::TEXT, 'UTF8')) + || account_tenant_creation_authorization_frame(fence.binding) + || account_tenant_creation_authorization_frame(NEW.owner_result); + IF NEW.readback IS DISTINCT FROM expected_readback THEN + RAISE EXCEPTION 'CREATE_TENANT readback must bind the original exact fence and outcome' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_creation_authorization_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'CREATE_TENANT evidence cannot be truncated' USING ERRCODE = '23514'; + RETURN NULL; +END; +$$; + +-- Compose with V61's unchanged Draft settlement/terminal guard. Both commit and no-mutation +-- abort retain their WAITING state until all affected CREATE_TENANT owners settle exactly. +CREATE FUNCTION account_tenant_creation_authorization_source_transition_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_tenant_creation_authorization_sources source USING (source_key) + JOIN account_tenant_creation_authorization_fences fence USING (operation_id) + WHERE changed.change_id = OLD.change_id + AND NOT ((fence.ordering = 'REVOKE_ORDER' AND ( + SELECT count(*) FROM account_tenant_creation_authorization_readbacks readback + WHERE readback.operation_id = fence.operation_id + AND readback.outcome = 'DEFINITIVELY_ABORTED' + ) = 2) OR (fence.ordering = 'COMMIT_ORDER' AND ( + SELECT count(*) FROM account_tenant_creation_authorization_readbacks readback + WHERE readback.operation_id = fence.operation_id + ) = 2)) + ) THEN + RAISE EXCEPTION 'Both exact CREATE_TENANT outcomes required before source transition' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_tenant_creation_authorization_order_guard_trigger + BEFORE INSERT OR UPDATE OR DELETE ON account_tenant_creation_authorization_fences + FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_authorization_order_guard(); +CREATE TRIGGER account_tenant_creation_authorization_sources_phase_trigger + BEFORE INSERT ON account_tenant_creation_authorization_sources + FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_authorization_insert_phase_guard(); +CREATE TRIGGER account_tenant_creation_authorization_readbacks_phase_trigger + BEFORE INSERT ON account_tenant_creation_authorization_readbacks + FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_authorization_insert_phase_guard(); +CREATE TRIGGER account_tenant_creation_authorization_sources_immutable_trigger + BEFORE UPDATE OR DELETE ON account_tenant_creation_authorization_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_tenant_creation_authorization_readbacks_immutable_trigger + BEFORE UPDATE OR DELETE ON account_tenant_creation_authorization_readbacks + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_tenant_creation_authorization_fences_no_truncate_trigger + BEFORE TRUNCATE ON account_tenant_creation_authorization_fences + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_creation_authorization_no_truncate(); +CREATE TRIGGER account_tenant_creation_authorization_sources_no_truncate_trigger + BEFORE TRUNCATE ON account_tenant_creation_authorization_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_creation_authorization_no_truncate(); +CREATE TRIGGER account_tenant_creation_authorization_readbacks_no_truncate_trigger + BEFORE TRUNCATE ON account_tenant_creation_authorization_readbacks + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_creation_authorization_no_truncate(); +CREATE TRIGGER account_tenant_creation_authorization_source_transition_trigger + BEFORE UPDATE ON account_draft_authorization_source_changes + FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_authorization_source_transition_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java index 809d5cf44f..f4e0b2b668 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java @@ -1343,7 +1343,23 @@ private void seedSyntheticDraftHistory(Fixture fixture, Seed seed) { () -> { fences.reserve(binding); fences.claimCommitOrder(binding); - fences.requestSourceChange(change); + // Canonical synthetic V59 fixture SQL preserves the declared historical boundary; + // the current source-change engine requires V67 and must not run on this old schema. + fixture + .transactionDsl() + .execute( + "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status)" + + " VALUES (?, ?, 'WAITING')", + change.changeId(), + change.canonicalBytes()); + for (SourceEvidence source : change.sources()) { + fixture + .transactionDsl() + .execute( + "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", + change.changeId(), + source.key()); + } return null; }); syntheticOwnerReadback(fixture, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {61}); @@ -1351,7 +1367,12 @@ private void seedSyntheticDraftHistory(Fixture fixture, Seed seed) { transaction( fixture.transaction(), () -> { - fences.markSourceCommitted(change); + fixture + .transactionDsl() + .execute( + "UPDATE account_draft_authorization_source_changes SET status = 'SOURCE_COMMITTED'," + + " committed_at = CURRENT_TIMESTAMP WHERE change_id = ?", + change.changeId()); return null; }); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java index 0bd92f5110..79e271773e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -54,7 +54,7 @@ class AccountSecurityStateOperationPostgresIntegrationTest { @Test void pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation() { - Fixture fixture = fixture("65"); + Fixture fixture = fixture("67"); Seed seed = seed(fixture); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); var first = tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); @@ -91,7 +91,7 @@ void pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation() { @Test void originalCallerAndFamilyBindingsCannotBeChangedOnRetry() { - Fixture fixture = fixture("65"); + Fixture fixture = fixture("67"); 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())); @@ -127,7 +127,7 @@ void originalCallerAndFamilyBindingsCannotBeChangedOnRetry() { @Test void concurrentExactClaimsSerializeToOneOriginalRequest() throws Exception { - Fixture fixture = fixture("65"); + Fixture fixture = fixture("67"); Seed seed = seed(fixture); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); CountDownLatch ready = new CountDownLatch(2); @@ -167,7 +167,7 @@ void concurrentExactClaimsSerializeToOneOriginalRequest() throws Exception { @Test void exactExistingOutboxReceiptCompletesOnceAndHistoricalImagesSurviveLaterAdvance() { - Fixture fixture = fixture("65"); + Fixture fixture = fixture("67"); 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())); @@ -231,7 +231,7 @@ void exactExistingOutboxReceiptCompletesOnceAndHistoricalImagesSurviveLaterAdvan @Test void lawfulPrivateFenceAdvanceKeepsLatestSourceEventAndOriginalReceiptUnchanged() { - Fixture fixture = fixture("65"); + Fixture fixture = fixture("67"); 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())); @@ -297,7 +297,7 @@ void lawfulPrivateFenceAdvanceKeepsLatestSourceEventAndOriginalReceiptUnchanged( @Test void lateReceiptFailureRollsBackEntireFixtureProducerButRetainsOriginalWaitingIntent() { - Fixture fixture = fixture("65"); + Fixture fixture = fixture("67"); 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())); @@ -346,7 +346,7 @@ void lateReceiptFailureRollsBackEntireFixtureProducerButRetainsOriginalWaitingIn @Test void requestCaptureResultsDeletesAndTruncationRemainGuarded() { - Fixture fixture = fixture("65"); + Fixture fixture = fixture("67"); 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())); @@ -372,7 +372,7 @@ void requestCaptureResultsDeletesAndTruncationRemainGuarded() { @Test void substitutedEventStateCannotBecomeTheOriginalReceipt() { - Fixture fixture = fixture("65"); + Fixture fixture = fixture("67"); 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())); @@ -429,7 +429,7 @@ void corruptPositiveCheckpointMetadataAndPayloadDenyBeforeNewIntentOrSourceMutat "request_id = 'substituted'", "event_digest = 'sha256:' || repeat('b',64)", "payload = convert_to('{}','UTF8')")) { - Fixture fixture = fixture("65"); + Fixture fixture = fixture("67"); 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())); @@ -474,7 +474,7 @@ void corruptPositiveCheckpointMetadataAndPayloadDenyBeforeNewIntentOrSourceMutat void retainedReceiptCannotLeadRegressedCurrentAuthorityOrCheckpoint() { for (String table : List.of("account_authority_generations", "account_authority_outbox_streams")) { - Fixture fixture = fixture("65"); + Fixture fixture = fixture("67"); 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())); @@ -498,7 +498,7 @@ void retainedReceiptCannotLeadRegressedCurrentAuthorityOrCheckpoint() { @Test void actualReaderDeniesUncommittedOperationAndChangedCurrentPoststate() { - Fixture missing = fixture("65"); + Fixture missing = fixture("67"); 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())); @@ -531,7 +531,7 @@ void actualReaderDeniesUncommittedOperationAndChangedCurrentPoststate() { })) .isInstanceOf(IllegalStateException.class); - Fixture changed = fixture("65"); + Fixture changed = fixture("67"); 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())); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java index 01f78af1eb..11a9b544bd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java @@ -359,7 +359,7 @@ void issuerPendingCaptureRetainsIndependentCountersCheckpointAndExactPositiveEve } @Test - void v59PreservesV58HistoryAndExactKeysBeforeV61ProducerInteractionsWithFullMultibyteIssuer() { + void v59PreservesV58HistoryAndExactKeysBeforeV67ProducerInteractionsWithFullMultibyteIssuer() { Fixture fixture = newFixture("58"); seedIssuer(fixture); UUID oldRequest = UUID.randomUUID(); @@ -379,7 +379,33 @@ void v59PreservesV58HistoryAndExactKeysBeforeV61ProducerInteractionsWithFullMult transaction(fixture.transaction(), () -> fences.reserve(oldBinding)); SourceChange oldChange = new SourceChange(UUID.randomUUID(), oldBinding.sources(), new byte[] {9}); - transaction(fixture.transaction(), () -> fences.requestSourceChange(oldChange)); + // Canonical synthetic V58 history, not a current-engine call against an obsolete schema. + transaction( + fixture.transaction(), + () -> { + fixture + .transactionDsl() + .execute( + "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status)" + + " VALUES (?, ?, 'WAITING')", + oldChange.changeId(), + oldChange.canonicalBytes()); + for (var source : oldChange.sources()) { + fixture + .transactionDsl() + .execute( + "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", + oldChange.changeId(), + source.key()); + } + fixture + .transactionDsl() + .execute( + "UPDATE account_draft_authorization_fences SET ordering = 'REVOKE_ORDER'," + + " ordered_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + oldBinding.operationId()); + return null; + }); String oldEvents = fixture .setupDsl() @@ -476,15 +502,15 @@ void v59PreservesV58HistoryAndExactKeysBeforeV61ProducerInteractionsWithFullMult assertThat(SourceChange.fromStored(retainedBinding).canonicalBytes()) .containsExactly(oldChange.canonicalBytes()); - // V59's retained-data proof is complete above. Current producer readback uses aborted_at, - // which first exists after V61, so run interactions only after advancing this private schema. + // V59's retained-data proof is complete above. Current source ordering also consumes the + // distinct CREATE_TENANT family, so advance to V67 before current producer interactions. Flyway.configure() .dataSource(dataSource) .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") - .target("61") + .target("67") .load() .migrate(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java index 4c8b3bb24f..6ffed179bd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java @@ -303,7 +303,7 @@ private static Fixture fixture(boolean enrollAuthority) { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") - .target(MigrationVersion.fromVersion("65")) + .target(MigrationVersion.fromVersion("67")) .load() .migrate(); DSLContext dsl = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java new file mode 100644 index 0000000000..60f4fead12 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java @@ -0,0 +1,575 @@ +package integration.net.firedevops.firemud.accountservice.tenantcreation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +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.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChangeAbortReason; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Synthetic original authorization captures and definitive readbacks stipulate absent authenticated + * producers. These tests prove component ordering only, never real authorization, atomic Game + * Design qualification, Account bootstrap, admission or runtime activation. + */ +@Testcontainers(disabledWithoutDocker = true) +class TenantCreationAuthorizationFencePostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void revokeFirstRetainsBothFamilyFencesUntilExactAborts() { + Context c = context("67"); + var b = binding(); + var draft = draft(b.sources().getFirst()); + var change = new SourceChange(UUID.randomUUID(), b.sources(), new byte[] {7}); + tx( + c, + () -> { + c.creation.reserve(b); + c.draft.reserve(draft); + return null; + }); + assertThat(tx(c, () -> c.draft.requestSourceChange(change))).isFalse(); + assertThat(tx(c, () -> c.creation.read(b).ordering())).isEqualTo(Ordering.REVOKE_ORDER); + assertThat(tx(c, () -> c.draft.read(draft).ordering())).isEqualTo(Ordering.REVOKE_ORDER); + assertThatThrownBy(() -> tx(c, () -> c.creation.claimCommitOrder(b))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> tx(c, () -> c.creation.reserve(bindingWithSources(b.sources())))) + .isInstanceOf(IllegalStateException.class); + assertThat(tx(c, () -> c.creation.readOwnerResult(b, Owner.GAME_DESIGN))).isEmpty(); + owner(c, b, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + owner(c, b, Owner.ACCOUNT, Outcome.DEFINITIVELY_ABORTED); + assertThat(tx(c, () -> c.draft.sourceMutationPermitted(change))).isFalse(); + draftOwners(c, draft); + assertThat(tx(c, () -> c.draft.sourceMutationPermitted(change))).isTrue(); + tx( + c, + () -> { + c.draft.markSourceCommitted(change); + return null; + }); + assertThat(tx(c, () -> c.creation.reserve(b).ordering())).isEqualTo(Ordering.REVOKE_ORDER); + assertThatThrownBy(() -> tx(c, () -> c.creation.claimCommitOrder(b))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void commitFirstRequiresBothExactOutcomesAndMixedVectorDoesNotQualifySuccess() { + Context c = context("67"); + var b = binding(); + var change = new SourceChange(UUID.randomUUID(), b.sources(), new byte[] {8}); + tx( + c, + () -> { + c.creation.reserve(b); + return c.creation.claimCommitOrder(b); + }); + assertThat(tx(c, () -> c.draft.requestSourceChange(change))).isFalse(); + owner(c, b, Owner.GAME_DESIGN, Outcome.COMMITTED); + assertThat(tx(c, () -> c.creation.readSettlement(b))).isEqualTo(Settlement.PENDING); + assertThat(tx(c, () -> c.draft.sourceAbortPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + tx( + c, + () -> { + c.draft.markSourceCommitted(change); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + tx( + c, + () -> + c.dsl.execute( + "UPDATE account_draft_authorization_source_changes SET status = 'SOURCE_ABORTED'," + + " aborted_at = CURRENT_TIMESTAMP, abort_reason = 'DEFINITIVE_ABORT' WHERE change_id = ?", + change.changeId()))) + .isInstanceOf(DataAccessException.class); + owner(c, b, Owner.ACCOUNT, Outcome.DEFINITIVELY_ABORTED); + assertThat(tx(c, () -> c.creation.readSettlement(b))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat(tx(c, () -> c.draft.sourceAbortPermitted(change))).isTrue(); + tx( + c, + () -> { + c.draft.markSourceAborted(change, SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + }); + assertThat( + tx(c, () -> c.creation.readOwnerResult(b, Owner.GAME_DESIGN)).orElseThrow().outcome()) + .isEqualTo(Outcome.COMMITTED); + } + + @Test + void contradictoryRevokeOutcomeNeverReleasesSourceOrdering() { + Context c = context("67"); + var b = binding(); + var change = new SourceChange(UUID.randomUUID(), b.sources(), new byte[] {9}); + tx(c, () -> c.creation.reserve(b)); + assertThat(tx(c, () -> c.draft.requestSourceChange(change))).isFalse(); + owner(c, b, Owner.GAME_DESIGN, Outcome.COMMITTED); + owner(c, b, Owner.ACCOUNT, Outcome.DEFINITIVELY_ABORTED); + assertThat(tx(c, () -> c.creation.readSettlement(b))).isEqualTo(Settlement.PENDING); + assertThat(tx(c, () -> c.draft.sourceMutationPermitted(change))).isFalse(); + assertThat(tx(c, () -> c.draft.sourceAbortPermitted(change))).isFalse(); + } + + @Test + void exactRetryAndDatabaseGuardsPreserveBindingAndFinalizedResults() { + Context c = context("67"); + var b = binding(); + tx(c, () -> c.creation.reserve(b)); + assertThatThrownBy(() -> owner(c, b, Owner.ACCOUNT, Outcome.COMMITTED)) + .isInstanceOf(IllegalStateException.class); + tx(c, () -> c.creation.claimCommitOrder(b)); + owner(c, b, Owner.ACCOUNT, Outcome.COMMITTED); + owner(c, b, Owner.GAME_DESIGN, Outcome.COMMITTED); + owner(c, b, Owner.GAME_DESIGN, Outcome.COMMITTED); + assertThat(tx(c, () -> c.creation.readSettlement(b))).isEqualTo(Settlement.COMMITTED); + assertThat(tx(c, () -> c.creation.claimCommitOrder(b).binding())) + .containsExactly(b.canonicalBytes()); + assertThat( + tx(c, () -> c.creation.readOriginalBinding(b.operationId())) + .orElseThrow() + .canonicalBytes()) + .containsExactly(b.canonicalBytes()); + var changedActor = copy(b, UUID.randomUUID(), b.originalAuthorizationCapture()); + assertThatThrownBy(() -> tx(c, () -> c.creation.reserve(changedActor))) + .isInstanceOf(IllegalArgumentException.class); + var changedProvenance = copy(b, b.actorAccountId(), new byte[] {99}); + assertThatThrownBy(() -> tx(c, () -> c.creation.read(changedProvenance))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> owner(c, b, Owner.ACCOUNT, Outcome.DEFINITIVELY_ABORTED)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + tx( + c, + () -> { + c.creation.recordOwnerReadback( + b, + new OwnerReadback( + Owner.ACCOUNT, + Outcome.COMMITTED, + b.creationOperationId(), + b.canonicalBytes(), + new byte[] {1})); + return null; + })) + .isInstanceOf(IllegalArgumentException.class); + for (String sql : + List.of( + "UPDATE account_tenant_creation_authorization_fences SET actor_account_id = '" + + UUID.randomUUID() + + "'", + "UPDATE account_tenant_creation_authorization_readbacks SET outcome = 'DEFINITIVELY_ABORTED'", + "DELETE FROM account_tenant_creation_authorization_sources", + "TRUNCATE account_tenant_creation_authorization_readbacks")) { + assertThatThrownBy(() -> tx(c, () -> c.dsl.execute(sql))) + .isInstanceOf(DataAccessException.class); + } + } + + @Test + void lateFailureRollsBackSourceTransitionWithOwnersRemainingImmutable() { + Context c = context("67"); + var b = binding(); + var change = new SourceChange(UUID.randomUUID(), b.sources(), new byte[] {10}); + tx( + c, + () -> { + c.creation.reserve(b); + return c.creation.claimCommitOrder(b); + }); + tx(c, () -> c.draft.requestSourceChange(change)); + owner(c, b, Owner.GAME_DESIGN, Outcome.COMMITTED); + owner(c, b, Owner.ACCOUNT, Outcome.COMMITTED); + assertThatThrownBy( + () -> + tx( + c, + () -> { + c.draft.markSourceCommitted(change); + throw new IllegalStateException("synthetic late owner-transaction failure"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat(tx(c, () -> c.draft.readSourceChange(change).status())).isEqualTo("WAITING"); + assertThat(tx(c, () -> c.creation.readSettlement(b))).isEqualTo(Settlement.COMMITTED); + tx( + c, + () -> { + c.draft.markSourceCommitted(change); + return null; + }); + } + + @Test + void sharedSourceLocksSerializeBothCompetingInterleavings() throws Exception { + for (boolean commitFirst : List.of(true, false)) { + Context c = context("67"); + var b = binding(); + var change = new SourceChange(UUID.randomUUID(), b.sources(), new byte[] {11}); + tx(c, () -> c.creation.reserve(b)); + CountDownLatch held = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch followerStarted = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var first = + executor.submit( + () -> + tx( + c, + () -> { + if (commitFirst) c.creation.claimCommitOrder(b); + else c.draft.requestSourceChange(change); + held.countDown(); + await(release); + return null; + })); + assertThat(held.await(10, TimeUnit.SECONDS)).isTrue(); + var second = + executor.submit( + () -> { + followerStarted.countDown(); + if (commitFirst) return tx(c, () -> c.draft.requestSourceChange(change)); + assertThatThrownBy(() -> tx(c, () -> c.creation.claimCommitOrder(b))) + .isInstanceOf(IllegalStateException.class); + return false; + }); + assertThat(followerStarted.await(10, TimeUnit.SECONDS)).isTrue(); + release.countDown(); + first.get(10, TimeUnit.SECONDS); + assertThat(second.get(10, TimeUnit.SECONDS)).isFalse(); + } finally { + release.countDown(); + } + assertThat(tx(c, () -> c.creation.read(b).ordering())) + .isEqualTo(commitFirst ? Ordering.COMMIT_ORDER : Ordering.REVOKE_ORDER); + assertThat(tx(c, () -> c.draft.sourceMutationPermitted(change))).isFalse(); + } + } + + @Test + void migrationRetainsV66AndDraftImagesAndOriginalDraftBindingBytes() { + Context c = context("66"); + var b = binding(); + var draft = draft(b.sources().getFirst()); + // These existing Draft-only methods do not call the common source-change/settlement engine. + // Keep V66's populated image intact before migrating; current source interactions require V67. + tx( + c, + () -> { + c.draft.reserve(draft); + c.draft.claimCommitOrder(draft); + return null; + }); + draftOwners(c, draft); + tx( + c, + () -> { + Record account = + c.dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash)" + + " VALUES (?, ?, 'synthetic-password-verifier') RETURNING id, account_uuid, account_uuid_provenance", + "retained", + "retained@example.test"); + if (account == null) { + throw new IllegalStateException("Retained Account fixture insert returned no row"); + } + UUID operation = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + c.dsl.execute( + "INSERT INTO account_control_ui_issuance_operations" + + " (operation_id, request_id, account_uuid, account_id, account_provenance, profile, audience," + + " request_digest_version, request_digest, authority_capture, authority_capture_digest," + + " issuance_fence_capture, issuance_fence_digest, status)" + + " VALUES (?, ?, ?, ?, ?, 'control-ui', 'control-ui', 1, ?, ?, ?, ?, ?, 'PENDING')", + operation, + request, + account.get("account_uuid", UUID.class), + account.get("id", Long.class), + account.get("account_uuid_provenance", String.class), + new byte[32], + new byte[] {21}, + new byte[32], + new byte[] {22}, + new byte[32]); + c.dsl.execute( + "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', token_hash = ?," + + " response_digest = ?, issued_at = '2030-01-01T00:00:00Z', expires_at = '2030-01-01T00:10:00Z'" + + " WHERE operation_id = ?", + "a".repeat(64), + new byte[32], + operation); + c.dsl.execute( + "INSERT INTO account_control_ui_issuance_response_envelopes" + + " (operation_id, request_id, account_uuid, account_id, account_provenance, profile, audience," + + " request_digest_version, request_digest, token_hash, response_digest, authority_capture_digest," + + " issuance_fence_digest, issued_at, expires_at, format_version, key_id, purpose, nonce, ciphertext)" + + " SELECT operation_id, request_id, account_uuid, account_id, account_provenance, profile, audience," + + " request_digest_version, request_digest, token_hash, response_digest, authority_capture_digest," + + " issuance_fence_digest, issued_at, expires_at, 1, 'fixture', 'CONTROL_UI_RESPONSE', ?, ?" + + " FROM account_control_ui_issuance_operations WHERE operation_id = ?", + new byte[12], + new byte[16], + operation); + return null; + }); + Map> images = retainedImages(c); + migration(c.source, c.schema, "67").migrate(); + assertThat(retainedImages(c)).isEqualTo(images); + assertThat(tx(c, () -> c.draft.read(draft).binding())).containsExactly(draft.canonicalBytes()); + assertThat(tx(c, () -> c.draft.readSettlement(draft))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + tx(c, () -> c.creation.reserve(b)); + assertThat(retainedImages(c).get("account_control_ui_issuance_operations")) + .isEqualTo(images.get("account_control_ui_issuance_operations")); + } + + private Map> retainedImages(Context c) { + Map> images = new LinkedHashMap<>(); + for (String table : + List.of( + "account_control_ui_issuance_operations", + "account_control_ui_issuance_response_envelopes", + "account_draft_authorization_fences", + "account_draft_authorization_sources", + "account_draft_authorization_owner_readbacks", + "account_draft_authorization_source_locks", + "account_draft_authorization_source_changes", + "account_draft_authorization_changed_scopes")) { + images.put( + table, + tx( + c, + () -> + c.dsl + .fetch( + "SELECT to_jsonb(t)::text AS image FROM " + + table + + " t ORDER BY to_jsonb(t)::text") + .getValues("image", String.class))); + } + return images; + } + + private void owner( + Context c, TenantCreationAuthorizationFenceBinding b, Owner owner, Outcome outcome) { + tx( + c, + () -> { + c.creation.recordOwnerReadback( + b, + new OwnerReadback( + owner, + outcome, + owner == Owner.GAME_DESIGN ? b.creationOperationId() : b.operationId(), + b.canonicalBytes(), + new byte[] {(byte) owner.ordinal(), (byte) outcome.ordinal()})); + return null; + }); + } + + private void draftOwners(Context c, DraftAuthorizationFenceBinding b) { + for (var owner : DraftAuthorizationFenceBinding.Owner.values()) { + tx( + c, + () -> { + c.draft.recordOwnerReadback( + b, + new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED, + b.operationId(), + b.commitId(), + b.fenceId(), + b.inputDigest(), + b.canonicalBytes(), + new byte[] {12})); + return null; + }); + } + } + + private TenantCreationAuthorizationFenceBinding binding() { + UUID actor = UUID.randomUUID(); + return bindingWithSources( + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + "fixture-stream/" + actor, + "0", + new byte[] {1}))); + } + + private TenantCreationAuthorizationFenceBinding bindingWithSources(List sources) { + UUID request = UUID.randomUUID(); + return new TenantCreationAuthorizationFenceBinding( + UUID.randomUUID(), + request, + UUID.randomUUID(), + UUID.fromString(sources.getFirst().scopeId()), + UUID.randomUUID(), + UUID.randomUUID(), + "firemud", + "fixture-key", + "Fixture", + null, + GameTenantCreationDigest.requestDigest("firemud", request, "fixture-key", "Fixture", null), + new byte[] {2}, + sources); + } + + private TenantCreationAuthorizationFenceBinding copy( + TenantCreationAuthorizationFenceBinding b, UUID actor, byte[] provenance) { + return new TenantCreationAuthorizationFenceBinding( + b.operationId(), + b.requestId(), + b.fenceId(), + actor, + b.tenantId(), + b.creationOperationId(), + b.targetNamespace(), + b.sourceGameTenantKey(), + b.name(), + b.description(), + b.creationRequestDigest(), + provenance, + b.sources()); + } + + private DraftAuthorizationFenceBinding draft(SourceEvidence source) { + var complete = + DraftCommitBinding.create( + new TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "fixture", 2, "fixture", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "fixture-base", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "fixture-payload")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "fixture", + "aggregate", + "fixture", + "1"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + UUID.fromString(source.scopeId()), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "1", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of(source)); + } + + private Context context(String target) { + String schema = "creation_fence_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + migration(source, schema, target).migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context( + source, + schema, + dsl, + new DraftAuthorizationFenceRepository(dsl), + new TenantCreationAuthorizationFenceRepository(dsl), + transaction); + } + + private Flyway migration(DriverManagerDataSource source, String schema, String target) { + return Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(target) + .load(); + } + + private T tx(Context c, Supplier work) { + return c.transaction.execute(status -> work.get()); + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("Fixture coordination timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private record Context( + DriverManagerDataSource source, + String schema, + DSLContext dsl, + DraftAuthorizationFenceRepository draft, + TenantCreationAuthorizationFenceRepository creation, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceBindingTest.java new file mode 100644 index 0000000000..2e6e1e7998 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFenceBindingTest.java @@ -0,0 +1,152 @@ +package unit.net.firedevops.firemud.accountservice.tenantcreation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceBinding; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +/** Synthetic correlation fixtures do not authenticate actors, current sources or owner results. */ +class TenantCreationAuthorizationFenceBindingTest { + @Test + void closedVersionlessFamilyPinsBothOwnersAndOriginalProvenance() { + var binding = binding(); + String framed = new String(binding.canonicalBytes(), StandardCharsets.UTF_8); + assertThat(framed) + .contains("CREATE_TENANT", "GAME_DESIGN", "ACCOUNT") + .doesNotContain("WORLD", "DRAFT", "versionId"); + byte[] original = binding.canonicalBytes(); + assertThat(TenantCreationAuthorizationFenceBinding.fromStored(original).canonicalBytes()) + .containsExactly(original); + binding.originalAuthorizationCapture()[0] = 99; + binding.sources().getFirst().evidence()[0] = 98; + assertThat(binding.canonicalBytes()).containsExactly(original); + assertThatThrownBy(() -> binding.sources().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + TenantCreationAuthorizationFenceBinding.fromStored( + java.util.Arrays.copyOf(original, original.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + TenantCreationAuthorizationFenceBinding.fromStored( + java.util.Arrays.copyOf(original, original.length + 1))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void ownerOperationAndFullBindingAreExactEvenWhenResultIsUnchanged() { + var binding = binding(); + new OwnerReadback( + Owner.GAME_DESIGN, + Outcome.COMMITTED, + binding.creationOperationId(), + binding.canonicalBytes(), + new byte[] {1}) + .requireBinding(binding); + new OwnerReadback( + Owner.ACCOUNT, + Outcome.DEFINITIVELY_ABORTED, + binding.operationId(), + binding.canonicalBytes(), + new byte[] {2}) + .requireBinding(binding); + assertThatThrownBy( + () -> + new OwnerReadback( + Owner.ACCOUNT, + Outcome.COMMITTED, + binding.creationOperationId(), + binding.canonicalBytes(), + new byte[] {1}) + .requireBinding(binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new OwnerReadback( + Owner.GAME_DESIGN, + Outcome.COMMITTED, + binding.creationOperationId(), + new byte[] {1}, + new byte[] {1}) + .requireBinding(binding)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requestDigestAndSourcesCannotBeOmittedOrAliased() { + var b = binding(); + assertThatThrownBy( + () -> + new TenantCreationAuthorizationFenceBinding( + b.operationId(), + b.requestId(), + b.fenceId(), + b.actorAccountId(), + b.tenantId(), + b.creationOperationId(), + b.targetNamespace(), + b.sourceGameTenantKey(), + "changed", + b.description(), + b.creationRequestDigest(), + b.originalAuthorizationCapture(), + b.sources())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new TenantCreationAuthorizationFenceBinding( + b.operationId(), + b.requestId(), + b.fenceId(), + b.actorAccountId(), + b.tenantId(), + b.creationOperationId(), + b.targetNamespace(), + b.sourceGameTenantKey(), + b.name(), + b.description(), + b.creationRequestDigest(), + b.originalAuthorizationCapture(), + List.of())) + .isInstanceOf(IllegalArgumentException.class); + } + + private TenantCreationAuthorizationFenceBinding binding() { + UUID actor = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + var source = + new SourceEvidence( + SourceKind.ACCOUNT, + actor.toString(), + "922337203685477580812345", + "922337203685477580912345", + "fixture-stream", + "0", + new byte[] {3}); + return new TenantCreationAuthorizationFenceBinding( + UUID.randomUUID(), + request, + UUID.randomUUID(), + actor, + UUID.randomUUID(), + UUID.randomUUID(), + "firemud", + "key", + "Name", + null, + GameTenantCreationDigest.requestDigest("firemud", request, "key", "Name", null), + new byte[] {4}, + List.of(source)); + } +} From c459bfd672d99fcd6858011caaf08c954bda2629 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 17:52:46 +1300 Subject: [PATCH 05/12] fix(account): use deferred constraint trigger for control-ui envelope --- .../V66__control_ui_issuance_operations.sql | 2 +- ...uanceOperationPostgresIntegrationTest.java | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/main/resources/db/migration/V66__control_ui_issuance_operations.sql b/services/account-service/src/main/resources/db/migration/V66__control_ui_issuance_operations.sql index 8978e95c99..dcfe281111 100644 --- a/services/account-service/src/main/resources/db/migration/V66__control_ui_issuance_operations.sql +++ b/services/account-service/src/main/resources/db/migration/V66__control_ui_issuance_operations.sql @@ -215,7 +215,7 @@ CREATE TRIGGER account_control_ui_issuance_operation_no_truncate_trigger CREATE TRIGGER account_control_ui_issuance_envelope_no_truncate_trigger BEFORE TRUNCATE ON account_control_ui_issuance_response_envelopes FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_issuance_no_truncate(); -CREATE TRIGGER account_control_ui_issuance_terminal_envelope_check_trigger +CREATE CONSTRAINT TRIGGER account_control_ui_issuance_terminal_envelope_check_trigger AFTER INSERT OR UPDATE ON account_control_ui_issuance_operations DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_terminal_envelope_check(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java index 0a48f456f4..372f507417 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java @@ -177,6 +177,33 @@ void abandonedPendingClaimCannotBeReportedCommittedWithoutExactEnvelope() { + "WHERE operation_id = ?", claim.operation().operationId()))) .isInstanceOf(RuntimeException.class); + // A structurally complete terminal row must still fail at commit without its envelope. + // This reaches the deferred constraint rather than only the immediate result-shape check. + AccountControlUiResponseEnvelopeBinding missingEnvelopeBinding = + binding( + claim.operation(), + "synthetic missing-envelope result".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .dsl() + .execute( + "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', " + + "token_hash = ?, response_digest = ?, issued_at = ?, expires_at = ? " + + "WHERE operation_id = ?", + missingEnvelopeBinding.tokenHash(), + missingEnvelopeBinding.responseDigest(), + java.time.OffsetDateTime.ofInstant( + missingEnvelopeBinding.issuedAt(), java.time.ZoneOffset.UTC), + java.time.OffsetDateTime.ofInstant( + missingEnvelopeBinding.expiresAt(), java.time.ZoneOffset.UTC), + claim.operation().operationId()))) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining( + "Committed control-UI issuance requires its exact encrypted envelope"); AccountControlUiIssuanceOperation stored = inTransaction( context.transaction(), () -> context.repository().findByRequest(request).orElseThrow()); From 2a60451b8e0b396b2049000faebffdeba5831c23 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 18:22:16 +1300 Subject: [PATCH 06/12] Account: bind fresh control-ui credentials and correct exact SQL recovery proof --- .github/workflows/ci.yml | 24 + .../account-service/runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 4 + ...AccountPlatformAuthCacheConfiguration.java | 26 + .../PlatformAuthRateLimitProperties.java | 259 +++++++ ...ontrolUiCredentialOperationRepository.java | 153 ++++ ...tControlUiIssuanceOperationRepository.java | 6 +- .../service/CredentialAttemptSource.java | 55 ++ .../service/PlatformAuthBucketStore.java | 10 + ...AccountControlUiAuthenticationRequest.java | 44 ++ .../AccountControlUiTokenChecks.java | 17 +- .../exception/AuthenticationException.java | 19 +- .../impl/AccountPlatformAuthAbuseLimiter.java | 284 +++++++ .../service/impl/AccountServiceImpl.java | 163 ++++ .../impl/PlatformAuthCacheRedisClient.java | 186 +++++ .../impl/RedisPlatformAuthBucketStore.java | 55 ++ .../src/main/resources/application.yml | 26 + ..._ui_credential_authentication_attempts.sql | 59 ++ .../redis/platform_auth_rate_limit_bucket.lua | 59 ++ ...AuthenticationPostgresIntegrationTest.java | 716 ++++++++++++++++++ ...uanceOperationPostgresIntegrationTest.java | 3 +- ...StateOperationPostgresIntegrationTest.java | 4 +- .../AccountControlUiTokenFixture.java | 2 + ...formAuthRateLimitRedisIntegrationTest.java | 92 +++ ...olUiCredentialOperationRepositoryTest.java | 210 +++++ .../service/CredentialAttemptSourceTest.java | 58 ++ .../AccountControlUiTokenChecksTest.java | 111 +++ .../AccountControlUiTokenFixture.java | 2 + .../AccountPlatformAuthAbuseLimiterTest.java | 373 +++++++++ .../service/impl/AccountServiceImplTest.java | 310 ++++++++ .../ratelimit/RateLimitSubjectHash.java | 363 +++++++++ .../ratelimit/RateLimitSubjectHashTest.java | 181 +++++ 33 files changed, 3869 insertions(+), 12 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPlatformAuthCacheConfiguration.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PlatformAuthRateLimitProperties.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCredentialOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CredentialAttemptSource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/PlatformAuthBucketStore.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiAuthenticationRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlatformAuthAbuseLimiter.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PlatformAuthCacheRedisClient.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RedisPlatformAuthBucketStore.java create mode 100644 services/account-service/src/main/resources/db/migration/V68__control_ui_credential_authentication_attempts.sql create mode 100644 services/account-service/src/main/resources/redis/platform_auth_rate_limit_bucket.lua create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/PlatformAuthRateLimitRedisIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountControlUiCredentialOperationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/CredentialAttemptSourceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlatformAuthAbuseLimiterTest.java create mode 100644 services/common-data-runtime/src/main/java/net/firedevops/firemud/common/ratelimit/RateLimitSubjectHash.java create mode 100644 services/common-data-runtime/src/test/java/net/firedevops/firemud/common/ratelimit/RateLimitSubjectHashTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c23c01d8c8..f43743bf5e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2545,6 +2545,30 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.tenantcreation.TenantCreationAuthorizationFencePostgresIntegrationTest#migrationRetainsV66AndDraftImagesAndOriginalDraftBindingBytes()' \ account-service + - name: Capture Account control-ui credential evidence PostgreSQL proof results + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-control-ui-credential-postgresql-proof-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: services/account-service/build/test-results/integrationTest/TEST-*AccountControlUiCredentialAuthenticationPostgresIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Verify Account control-ui credential evidence PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest#v67ToV68UpgradePreservesNonemptyPendingCommittedAndEncryptedOriginalImages()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest#exactPasswordAndOtpEvidenceBindOriginalOperationAndFreshRecoveryRemainsSeparate()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest#wrongAccountRequestDigestAndMissingOriginalDenyWithoutCredentialEvidence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest#recoveryLifecycleAndExactLiveChallengePredicatesDenyWithoutConsumption()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest#lateEvidenceInsertFailureRollsBackMatchingOtpConsumptionAndOriginalOperation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest#simultaneousMatchedOtpClaimsBlockOnOriginalOperationAndConsumeOnlyOnce()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest#credentialEvidenceRejectsUpdateDeleteAndTruncateAndPreservesExactStoredRows()' \ + account-service + - name: Verify Account generation projection PostgreSQL and Redis proof cases if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 7a2e512c3e..2fdee85555 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -249,7 +249,7 @@ Every recovery authenticates a currently valid credential for the same Account a Only after those checks may Account return the original encrypted response bytes. It never remints a token, extends expiry, resets issuance time, relabels a delegation token, or treats recovery as tenant/gameplay admission. Missing custody or currentness, wrong key/purpose/binding, conflicting operation evidence, and revoked or expired registry state fail closed. Confidential response retention is bounded by its documented recovery horizon, no later than original token expiry; immutable non-secret operation evidence and the existing safe key-retirement proof remain separate. -The unmerged creator-route components do not yet implement this producer or recovery path. Lost-response/restart, fresh-credential exact recovery, consumed-OTP denial, cross-Account and conflicting-request denial, expiry/revocation/currentness, and wrong-key/purpose/binding proof remain required before activation; detailed implementation status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). +The unmerged creator-route components do not yet implement complete issuance or original-response recovery. Fresh credential evidence alone cannot authorize either result release or creator mutation. Lost-response/restart, fresh-credential exact recovery, consumed-OTP denial, cross-Account and conflicting-request denial, expiry/revocation/currentness, and wrong-key/purpose/binding proof remain required before activation; detailed implementation status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). ## Membership and Entitlement Authority diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index d56fb8fac6..ebe9337fac 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -459,3 +459,8 @@ Entry format: - `2026-10-06`: JSON string escaping is not shell argument quoting - Context: a controller job revision passed Markdown via a JSON-quoted shell argument; Bash evaluated backtick spans and preserved literal newline escapes, corrupting the saved brief despite a successful controller result. The observed substitutions were non-existent commit-name commands; no repository code or secret was read by them. - Outcome: the next guarded revision restored the complete intended brief using shell-safe single-argument quoting, and exact readback matched the original text. Use a body file/stdin or shell-safe quoting for multiline controller input; a successful write alone does not prove content preservation. + +- `2026-10-06`: Implementation handoffs are not review findings + - Context: Document erroneously passed an implementation completion note as a rejected finding when completing controller attempt `gd-versionless-creation-reservation-r1-20261006`. The helper found no independent obligation, but the resulting record displays one finding. A second completion without that note is rejected because imported content is immutable. + - Expected pattern: complete a zero-finding helper with no `--finding-json`; record its implementation output and limits in the job, not as a fabricated finding. Read back counts immediately. Do not edit SQLite directly to conceal a mistake. + - Outcome: Document reported the exact erroneous attempt and correction-command gap to Overseer in controller message `6d42f60d-c5b5-4e75-ace6-f1449287267e`. The actual discovery count is zero; an audited controller correction remains pending. 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 3d38ed28a4..84a2a3a159 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The targetless control-ui credential component uses the existing Account password/OTP verifier and trusted first-party credential-attempt limiter, then records fresh credential evidence against an existing V66 operation. V68 retains that immutable evidence and atomically consumes only the exact eligible OTP challenge; it introduces no second issuance owner, plaintext credential, token or authority capture. Initial attempts require the original pending operation; response-recovery attempts require its unexpired committed result and authenticate again. Seven PostgreSQL definitions cover nonempty V67-to-V68 preservation, binding and lifecycle denial, exact challenge predicates, late-insert rollback, database-observed competing claims and immutability. Their original captures and verifier results are stipulated repository fixtures, not complete authenticated issuance. The closed control-ui inspection now requires the canonical capture `sourceFence`, independently of source versions and issuance fence, with exact large-decimal and incomplete-reference rejection tests. The composed five-module check, three service boot JARs, Account and Game Design jOOQ, formatting, Checkstyle, SpotBugs, links and Markdown pass in 1m45s (160 tasks: 21 executed). Account has 1054 clean unit outcomes; Common Platform Core 253 and Common Data Runtime 16 are clean reused results. Game Design has 542 executed unit cases and one object-store skip; World has 346 clean unit outcomes. All 714 integration cases skip without Docker (Account 443, Game Design 145 and World 126), including the seven new credential cases. The later physical Account reservation-client proof is outside this validated snapshot. The actual original capture producer, signer and pending/active registry composition, complete currentness, protected ring delivery and original-response release remain open. This component is not exposed as an enabled login route and does not grant creator or gameplay authority; executed PostgreSQL and activation evidence remain required. + +At published `c459bfd672d99fcd6858011caaf08c954bda2629`, V66 uses a PostgreSQL constraint trigger for its deferred exact-envelope requirement. The prior exact `e057e1f873753fe7141a53a1e65f2c9f214b1d38` [CI37414054058](https://github.com/benhook1013/FireMUD/actions/runs/37414054058) failed migration on the ordinary trigger's unsupported `DEFERRABLE` syntax: fifteen Account cases were reported, eleven failed startup, and the thirty-four required V65/V66/current-source/creation-order cases supplied no execution XML. Corrected-source [CI37415795444](https://github.com/benhook1013/FireMUD/actions/runs/37415795444) executes the twenty-seven V65/V66/current-source methods with zero skips: seventeen pass and ten fail. All eight current-source cases pass. The seven tenant-creation cases pass without skips according to their exact selector step and HTML report; standalone raw XML for that suite is unavailable. V66's additive migration succeeds, but its completion repository binds timestamps as varchar, and the missing-envelope negative also fails on that type mismatch before the deferred commit guard. Seven V65 failures come from the fixture storing event-array order instead of the canonical login-mode database representation. The correction adds explicit timestamp casts and uses the existing login-mode storage serializer without changing event digests, database guards or immutable readback. Its prepared V68 challenge queries use explicit timestamp-without-zone casts as well. Corrected PostgreSQL execution, genuine missing-envelope commit rejection and activation remain unproved; the aggregate run is separate from these executed component results. + The versionless `CREATE_TENANT` candidate adds V67 and an immutable exact-operation/source-ordering repository for Game Design creation and Account first-admin bootstrap. It shares the existing V57 source locks and journal with Draft work; both exact definitive owner outcomes are required before source mutation or no-mutation abort may settle. Three unit cases execute; seven PostgreSQL cases specify both competing source-order interleavings, mixed and contradictory outcomes, rollback, exact retry, database immutability and V66/Draft row preservation. These fixtures stipulate authentication and owner readbacks: the repository does not authenticate the creator, authorize either owner, create a tenant or enable bootstrap. The protected producer and automatic two-owner recovery remain open. At exact `3bdc63340b760313cfeefe7b442bc876fcd1977a`, [CI37408149747](https://github.com/benhook1013/FireMUD/actions/runs/37408149747) fails Account and Game Session startup on V65's PL/pgSQL `CASE` expression in a trigger `IF`, with SQLSTATE `42601`. The Account report records fifteen cases and eleven startup failures; the required V65/V66/current-source suites supply no raw execution XML. The correction parenthesizes the affected conditional expressions without removing any guard, including the same pattern in new V67. Historical issuer and logout fixture seeds retain their declared V58→V59 and V59→V60 table-image boundaries; only current-engine interactions advance to V67. The corrected local Account check, jOOQ, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass in 1m48s (72 tasks: 20 executed), with 1013 clean unit cases. All 433 PostgreSQL cases, including the seven new ones, compile but skip without Docker. Corrected exact-source PostgreSQL execution remains required; the aggregate run also has separate TCP Proxy and Game Logic failures. This is neither database execution nor activation proof. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPlatformAuthCacheConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPlatformAuthCacheConfiguration.java new file mode 100644 index 0000000000..a3144a2f12 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPlatformAuthCacheConfiguration.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.accountservice.config; + +import net.firedevops.firemud.accountservice.service.PlatformAuthBucketStore; +import net.firedevops.firemud.accountservice.service.impl.PlatformAuthCacheRedisClient; +import net.firedevops.firemud.accountservice.service.impl.RedisPlatformAuthBucketStore; +import net.firedevops.firemud.common.config.RedisProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** Wires Account's isolated credential-abuse Cache Redis client without replacing Coord Redis. */ +@Configuration +@EnableConfigurationProperties(PlatformAuthRateLimitProperties.class) +public class AccountPlatformAuthCacheConfiguration { + @Bean(destroyMethod = "close") + public PlatformAuthCacheRedisClient platformAuthCacheRedisClient( + PlatformAuthRateLimitProperties properties, RedisProperties coordinationRedis) { + return new PlatformAuthCacheRedisClient(properties.getCacheRedis(), coordinationRedis); + } + + @Bean + public PlatformAuthBucketStore platformAuthBucketStore( + PlatformAuthCacheRedisClient cacheRedisClient) { + return new RedisPlatformAuthBucketStore(cacheRedisClient); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PlatformAuthRateLimitProperties.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PlatformAuthRateLimitProperties.java new file mode 100644 index 0000000000..35bc9f9f4c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PlatformAuthRateLimitProperties.java @@ -0,0 +1,259 @@ +package net.firedevops.firemud.accountservice.config; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Base64; +import net.firedevops.firemud.common.ratelimit.RateLimitSubjectHash; +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** Account-owned platform-auth abuse-control settings and its separate Cache Redis role. */ +@ConfigurationProperties(prefix = "firemud.account.platform-auth-abuse") +public class PlatformAuthRateLimitProperties { + private CacheRedis cacheRedis = new CacheRedis(); + private String hmacKeyId = ""; + private String hmacKeyBase64 = ""; + private int subjectWindowSeconds = 300; + private int globalWindowSeconds = 60; + private int globalAdmissionsPerWindow = 1000; + private int sourceAttemptsPerWindow = 60; + private int candidateAttemptsPerWindow = 20; + private int sourceFailuresPerWindow = 20; + private int candidateFailuresPerWindow = 5; + private int sourceRetryBaseSeconds = 5; + private int candidateRetryBaseSeconds = 15; + private int globalRetryBaseSeconds = 5; + private int maxRetrySeconds = 300; + private long maxCounterValue = 1_000_000L; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Spring binds this mutable nested configuration before owner bean creation.") + public CacheRedis getCacheRedis() { + return cacheRedis; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Spring supplies the nested configuration through its property binder.") + public void setCacheRedis(CacheRedis cacheRedis) { + this.cacheRedis = cacheRedis; + } + + public String getHmacKeyId() { + return hmacKeyId; + } + + public void setHmacKeyId(String hmacKeyId) { + this.hmacKeyId = hmacKeyId; + } + + public String getHmacKeyBase64() { + return hmacKeyBase64; + } + + public void setHmacKeyBase64(String hmacKeyBase64) { + this.hmacKeyBase64 = hmacKeyBase64; + } + + public int getSubjectWindowSeconds() { + return subjectWindowSeconds; + } + + public void setSubjectWindowSeconds(int subjectWindowSeconds) { + this.subjectWindowSeconds = subjectWindowSeconds; + } + + public int getGlobalWindowSeconds() { + return globalWindowSeconds; + } + + public void setGlobalWindowSeconds(int globalWindowSeconds) { + this.globalWindowSeconds = globalWindowSeconds; + } + + public int getGlobalAdmissionsPerWindow() { + return globalAdmissionsPerWindow; + } + + public void setGlobalAdmissionsPerWindow(int globalAdmissionsPerWindow) { + this.globalAdmissionsPerWindow = globalAdmissionsPerWindow; + } + + public int getSourceAttemptsPerWindow() { + return sourceAttemptsPerWindow; + } + + public void setSourceAttemptsPerWindow(int sourceAttemptsPerWindow) { + this.sourceAttemptsPerWindow = sourceAttemptsPerWindow; + } + + public int getCandidateAttemptsPerWindow() { + return candidateAttemptsPerWindow; + } + + public void setCandidateAttemptsPerWindow(int candidateAttemptsPerWindow) { + this.candidateAttemptsPerWindow = candidateAttemptsPerWindow; + } + + public int getSourceFailuresPerWindow() { + return sourceFailuresPerWindow; + } + + public void setSourceFailuresPerWindow(int sourceFailuresPerWindow) { + this.sourceFailuresPerWindow = sourceFailuresPerWindow; + } + + public int getCandidateFailuresPerWindow() { + return candidateFailuresPerWindow; + } + + public void setCandidateFailuresPerWindow(int candidateFailuresPerWindow) { + this.candidateFailuresPerWindow = candidateFailuresPerWindow; + } + + public int getSourceRetryBaseSeconds() { + return sourceRetryBaseSeconds; + } + + public void setSourceRetryBaseSeconds(int sourceRetryBaseSeconds) { + this.sourceRetryBaseSeconds = sourceRetryBaseSeconds; + } + + public int getCandidateRetryBaseSeconds() { + return candidateRetryBaseSeconds; + } + + public void setCandidateRetryBaseSeconds(int candidateRetryBaseSeconds) { + this.candidateRetryBaseSeconds = candidateRetryBaseSeconds; + } + + public int getGlobalRetryBaseSeconds() { + return globalRetryBaseSeconds; + } + + public void setGlobalRetryBaseSeconds(int globalRetryBaseSeconds) { + this.globalRetryBaseSeconds = globalRetryBaseSeconds; + } + + public int getMaxRetrySeconds() { + return maxRetrySeconds; + } + + public void setMaxRetrySeconds(int maxRetrySeconds) { + this.maxRetrySeconds = maxRetrySeconds; + } + + public long getMaxCounterValue() { + return maxCounterValue; + } + + public void setMaxCounterValue(long maxCounterValue) { + this.maxCounterValue = maxCounterValue; + } + + public RateLimitSubjectHash.HmacKey activeHmacKey() { + if (hmacKeyId == null + || hmacKeyId.isBlank() + || hmacKeyBase64 == null + || hmacKeyBase64.isBlank()) { + throw new IllegalStateException("platform-auth rate-limit HMAC key is not configured"); + } + try { + return new RateLimitSubjectHash.HmacKey(hmacKeyId, Base64.getDecoder().decode(hmacKeyBase64)); + } catch (IllegalArgumentException ex) { + throw new IllegalStateException("platform-auth rate-limit HMAC key is invalid", ex); + } + } + + public static class CacheRedis { + private String url = ""; + private String host = "redis-cache"; + private int port = 6379; + private int database; + private int commandTimeoutMillis = 1_000; + private String username = ""; + private String password = ""; + private boolean useSsl; + private boolean startTls; + private boolean verifyPeer = true; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public int getDatabase() { + return database; + } + + public void setDatabase(int database) { + this.database = database; + } + + public int getCommandTimeoutMillis() { + return commandTimeoutMillis; + } + + public void setCommandTimeoutMillis(int commandTimeoutMillis) { + this.commandTimeoutMillis = commandTimeoutMillis; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public boolean isUseSsl() { + return useSsl; + } + + public void setUseSsl(boolean useSsl) { + this.useSsl = useSsl; + } + + public boolean isStartTls() { + return startTls; + } + + public void setStartTls(boolean startTls) { + this.startTls = startTls; + } + + public boolean isVerifyPeer() { + return verifyPeer; + } + + public void setVerifyPeer(boolean verifyPeer) { + this.verifyPeer = verifyPeer; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCredentialOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCredentialOperationRepository.java new file mode 100644 index 0000000000..c1b07bfdf4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCredentialOperationRepository.java @@ -0,0 +1,153 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequest; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequestDigest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiAuthenticationRequest.Purpose; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Records fresh credential evidence against an existing V66 issuance, without creating an issuance + * operation, capturing authority, signing, committing or activating a token. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The Account DSL collaborator remains internal.") +public class AccountControlUiCredentialOperationRepository { + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Null rejection acquires no resources or secret state in this Spring bean.") + public AccountControlUiCredentialOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** + * Called only after the Account owner has verified the current credential under its Account and + * challenge locks. Single-use challenge deletion and immutable evidence commit atomically. + */ + @Transactional(propagation = Propagation.MANDATORY) + public RecordedAttempt recordVerifiedCredential( + UUID requestId, + Account account, + Purpose purpose, + Optional matchedChallenge) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Control-UI credential recording requires an owner transaction"); + } + Objects.requireNonNull(account); + Objects.requireNonNull(purpose); + Objects.requireNonNull(matchedChallenge); + AccountControlUiIssuanceRequest request = + new AccountControlUiIssuanceRequest( + requestId.toString(), account.getAccountUuid().toString()); + Record operation = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE request_id = ? FOR UPDATE", + requestId); + if (operation == null + || !requestId.equals(operation.get("request_id", UUID.class)) + || !account.getAccountUuid().equals(operation.get("account_uuid", UUID.class)) + || !account.getId().equals(operation.get("account_id", Long.class)) + || !account + .getAccountUuidProvenance() + .name() + .equals(operation.get("account_provenance", String.class)) + || !"control-ui".equals(operation.get("profile", String.class)) + || !"control-ui".equals(operation.get("audience", String.class)) + || !Integer.valueOf(1).equals(operation.get("request_digest_version", Integer.class)) + || operation.get("request_digest", byte[].class) == null + || !MessageDigest.isEqual( + AccountControlUiIssuanceRequestDigest.digest(request), + operation.get("request_digest", byte[].class))) { + throw new CredentialOperationConflictException(); + } + String lifecycle = operation.get("status", String.class); + if ((purpose == Purpose.INITIAL_ISSUANCE && !"PENDING".equals(lifecycle)) + || (purpose == Purpose.EXACT_RESPONSE_RECOVERY + && (!"COMMITTED".equals(lifecycle) + || operation.get("expires_at", OffsetDateTime.class) == null + || !operation + .get("expires_at", OffsetDateTime.class) + .toInstant() + .isAfter(java.time.Instant.now())))) { + throw new CredentialOperationConflictException(); + } + Long challengeId = null; + if (matchedChallenge.isPresent()) { + AccountEmailLoginChallenge challenge = matchedChallenge.orElseThrow(); + if (challenge.getId() == null + || challenge.getId() <= 0L + || !account.getId().equals(challenge.getAccountId())) { + throw new CredentialOperationConflictException(); + } + Record consumed = + dsl.fetchOne( + "DELETE FROM account_email_login_challenge WHERE id = ? AND account_id = ? " + + "AND code_hash = ? AND expires_at > CAST(? AS timestamp) " + + "AND invalid_attempt_count < 5 RETURNING id", + challenge.getId(), + account.getId(), + challenge.getCodeHash(), + LocalDateTime.now()); + if (consumed == null || !challenge.getId().equals(consumed.get("id", Long.class))) { + throw new CredentialOperationConflictException(); + } + challengeId = challenge.getId(); + } + UUID operationId = operation.get("operation_id", UUID.class); + UUID attemptId = UUID.randomUUID(); + String method = challengeId == null ? "PASSWORD" : "EMAIL_OTP"; + Record inserted = + dsl.fetchOne( + "INSERT INTO account_control_ui_credential_authentication_attempts " + + "(attempt_id, operation_id, request_id, account_uuid, account_id, account_provenance, " + + "purpose, authentication_method, consumed_challenge_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING attempt_id, operation_id, authenticated_at", + attemptId, + operationId, + requestId, + account.getAccountUuid(), + account.getId(), + account.getAccountUuidProvenance().name(), + purpose.name(), + method, + challengeId); + if (inserted == null + || !attemptId.equals(inserted.get("attempt_id", UUID.class)) + || !operationId.equals(inserted.get("operation_id", UUID.class))) { + throw new IllegalStateException("Control-UI credential evidence readback failed"); + } + return new RecordedAttempt( + attemptId, + operationId, + method, + inserted.get("authenticated_at", OffsetDateTime.class).toInstant()); + } + + public record RecordedAttempt( + UUID attemptId, UUID operationId, String method, java.time.Instant authenticatedAt) {} + + public static final class CredentialOperationConflictException extends RuntimeException { + public CredentialOperationConflictException() { + super("Fresh credential does not bind the exact original control-UI operation"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java index 529c3a7f31..b4657c1db6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java @@ -162,7 +162,8 @@ public AccountControlUiIssuanceOperation complete( "UPDATE " + OPERATIONS + " SET status = 'COMMITTED', token_hash = ?, response_digest = ?, " - + "issued_at = ?, expires_at = ? WHERE operation_id = ? AND request_id = ? " + + "issued_at = CAST(? AS timestamptz), expires_at = CAST(? AS timestamptz) " + + "WHERE operation_id = ? AND request_id = ? " + "AND status = 'PENDING'", binding.tokenHash(), binding.responseDigest(), @@ -181,7 +182,8 @@ public AccountControlUiIssuanceOperation complete( + "profile, audience, request_digest_version, request_digest, token_hash, " + "response_digest, authority_capture_digest, issuance_fence_digest, issued_at, " + "expires_at, format_version, key_id, purpose, nonce, ciphertext) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS timestamptz), " + + "CAST(? AS timestamptz), ?, ?, ?, ?, ?)", stored.operationId(), UUID.fromString(request.requestId()), UUID.fromString(request.accountUuid()), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CredentialAttemptSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CredentialAttemptSource.java new file mode 100644 index 0000000000..78b60f4f14 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CredentialAttemptSource.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.ratelimit.RateLimitSubjectHash; + +/** Trusted, server-derived network context for one Account credential attempt. */ +public final class CredentialAttemptSource { + public enum ConnectionMode { + FIRST_PARTY_WEB, + TRUSTED_TCP_PROXY + } + + private final byte[] canonicalClientAddress; + private final ConnectionMode connectionMode; + + public CredentialAttemptSource(String canonicalClientIp, ConnectionMode connectionMode) { + if (!RateLimitSubjectHash.isCanonicalClientAddressLiteral(canonicalClientIp)) { + throw new IllegalArgumentException("credential source must be a canonical IP literal"); + } + this.canonicalClientAddress = + RateLimitSubjectHash.canonicalClientAddressBytes(canonicalClientIp); + this.connectionMode = Objects.requireNonNull(connectionMode, "connectionMode must not be null"); + } + + public byte[] canonicalClientAddress() { + return canonicalClientAddress.clone(); + } + + public ConnectionMode connectionMode() { + return connectionMode; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof CredentialAttemptSource that)) { + return false; + } + return connectionMode == that.connectionMode + && Arrays.equals(canonicalClientAddress, that.canonicalClientAddress); + } + + @Override + public int hashCode() { + return 31 * Arrays.hashCode(canonicalClientAddress) + connectionMode.hashCode(); + } + + @Override + public String toString() { + return "CredentialAttemptSource[clientAddress=redacted, connectionMode=" + connectionMode + "]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/PlatformAuthBucketStore.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/PlatformAuthBucketStore.java new file mode 100644 index 0000000000..30d88517c1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/PlatformAuthBucketStore.java @@ -0,0 +1,10 @@ +package net.firedevops.firemud.accountservice.service; + +import java.time.Duration; + +/** Atomic operations on one opaque platform-auth cache bucket at a time. */ +public interface PlatformAuthBucketStore { + long increment(String key, String collisionFingerprint, Duration ttl, long maximumValue); + + long count(String key, String collisionFingerprint); +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiAuthenticationRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiAuthenticationRequest.java new file mode 100644 index 0000000000..0986aee3fa --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiAuthenticationRequest.java @@ -0,0 +1,44 @@ +package net.firedevops.firemud.accountservice.service.controlui; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.CredentialAttemptSource; + +/** A fresh credential attempt for one existing targetless control-UI issuance operation. */ +public record AccountControlUiAuthenticationRequest( + UUID requestId, + String accountIdentifier, + String credential, + Purpose purpose, + CredentialAttemptSource credentialAttemptSource) { + + public AccountControlUiAuthenticationRequest { + Objects.requireNonNull(requestId, "requestId"); + if (requestId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("requestId must be non-nil"); + } + Objects.requireNonNull(purpose, "purpose"); + if (accountIdentifier == null + || accountIdentifier.isBlank() + || accountIdentifier.length() > 320) { + throw new IllegalArgumentException("Account identifier is required and bounded"); + } + if (credential == null || credential.isEmpty() || credential.length() > 100) { + throw new IllegalArgumentException("Credential is required and bounded"); + } + } + + public enum Purpose { + INITIAL_ISSUANCE, + EXACT_RESPONSE_RECOVERY + } + + @Override + public String toString() { + return "AccountControlUiAuthenticationRequest[requestId=" + + requestId + + ", purpose=" + + purpose + + ", credential=, identifier=]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecks.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecks.java index 84cc2f5016..e120510037 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecks.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecks.java @@ -202,18 +202,25 @@ private static void requireSourceReferences(Map record) { Map bundle = object(record.get("authEvidenceBundle")); if (!bundle .keySet() - .equals(Set.of("bundleVersion", "sourceVersion", "linearization", "canonicalSha256"))) { + .equals( + Set.of( + "bundleVersion", + "sourceVersion", + "sourceFence", + "linearization", + "canonicalSha256"))) { throw invalid(); } - for (String field : List.of("bundleVersion", "sourceVersion", "linearization")) { + for (String field : List.of("bundleVersion", "sourceVersion", "sourceFence", "linearization")) { requirePositiveDecimal(bundle.get(field)); } if (!(bundle.get("canonicalSha256") instanceof String digest) || !digest.matches("[0-9a-f]{64}")) throw invalid(); if (!"1".equals(bundle.get("bundleVersion"))) throw invalid(); - // The bundle sourceVersion identifies its durable evidence capture. It is independent of - // each authority source counter; equality with the actual bundle and its exact source - // versions/checkpoints belongs to the missing owner-readback/currentness gate. + // sourceVersion identifies the durable capture and sourceFence fences its commit/readback. + // Both remain independent of issuanceFence and each authority source counter; equality with + // the actual complete capture reference and its exact source versions/checkpoints belongs to + // the missing owner-readback/currentness gate. Structural validity is not authorization. } private static Map object(Object value) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/exception/AuthenticationException.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/exception/AuthenticationException.java index f292102e97..9b2fe657f5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/exception/AuthenticationException.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/exception/AuthenticationException.java @@ -3,18 +3,33 @@ /** Signals a login failure that should be surfaced to callers via explicit error codes. */ public final class AuthenticationException extends RuntimeException { private final String code; + private final int retryAfterSeconds; public AuthenticationException(String code, String message) { - super(message); - this.code = code; + this(code, message, null, 0); } public AuthenticationException(String code, String message, Throwable cause) { + this(code, message, cause, 0); + } + + public AuthenticationException(String code, String message, int retryAfterSeconds) { + this(code, message, null, retryAfterSeconds); + } + + private AuthenticationException( + String code, String message, Throwable cause, int retryAfterSeconds) { super(message, cause); this.code = code; + this.retryAfterSeconds = Math.min(3600, Math.max(0, retryAfterSeconds)); } public String getCode() { return code; } + + /** Optional bounded whole-second retry guidance for neutral temporary throttles. */ + public int getRetryAfterSeconds() { + return retryAfterSeconds; + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlatformAuthAbuseLimiter.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlatformAuthAbuseLimiter.java new file mode 100644 index 0000000000..886449ef37 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlatformAuthAbuseLimiter.java @@ -0,0 +1,284 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import net.firedevops.firemud.accountservice.config.PlatformAuthRateLimitProperties; +import net.firedevops.firemud.accountservice.service.CredentialAttemptSource; +import net.firedevops.firemud.accountservice.service.PlatformAuthBucketStore; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.ratelimit.RateLimitSubjectHash; +import net.firedevops.firemud.common.ratelimit.RateLimitSubjectHash.Digest; +import net.firedevops.firemud.common.ratelimit.RateLimitSubjectHash.HmacKey; +import net.firedevops.firemud.common.ratelimit.RateLimitSubjectHash.PlatformAuthPolicy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** Central, Account-owned graduated throttle for pre-tenant credential attempts. */ +@Service +public final class AccountPlatformAuthAbuseLimiter { + private static final String RETRY_LATER = "AUTH_RETRY_LATER"; + private static final String UNAVAILABLE = "AUTH_ABUSE_CONTROL_UNAVAILABLE"; + + private final PlatformAuthRateLimitProperties properties; + private final PlatformAuthBucketStore buckets; + private final Clock clock; + + @Autowired + public AccountPlatformAuthAbuseLimiter( + PlatformAuthRateLimitProperties properties, PlatformAuthBucketStore buckets) { + this(properties, buckets, Clock.systemUTC()); + } + + AccountPlatformAuthAbuseLimiter( + PlatformAuthRateLimitProperties properties, PlatformAuthBucketStore buckets, Clock clock) { + this.properties = Objects.requireNonNull(properties, "properties must not be null"); + this.buckets = Objects.requireNonNull(buckets, "buckets must not be null"); + this.clock = Objects.requireNonNull(clock, "clock must not be null"); + } + + /** Accounts for one credential attempt before account lookup, hashing, OTP, or mutation work. */ + public AttemptPermit begin(CredentialAttemptSource source) { + Objects.requireNonNull(source, "source must not be null"); + HmacKey key = activeKey(); + try { + Window globalWindow = window(clock.instant(), properties.getGlobalWindowSeconds()); + Bucket global = bucket(key, PlatformAuthPolicy.GLOBAL_PRESSURE, new byte[0], globalWindow); + long globalCount = + buckets.increment( + global.key(), + global.digest().collisionFingerprint(), + globalWindow.ttl(), + properties.getMaxCounterValue()); + if (globalCount > properties.getGlobalAdmissionsPerWindow()) { + throw retry( + globalCount, + properties.getGlobalAdmissionsPerWindow(), + properties.getGlobalRetryBaseSeconds(), + globalWindow); + } + + byte[] sourceBytes = source.canonicalClientAddress(); + Window subjectWindow = window(clock.instant(), properties.getSubjectWindowSeconds()); + Bucket sourceAttempts = + bucket(key, PlatformAuthPolicy.SOURCE_ATTEMPT, sourceBytes, subjectWindow); + long attemptCount = + buckets.increment( + sourceAttempts.key(), + sourceAttempts.digest().collisionFingerprint(), + subjectWindow.ttl(), + properties.getMaxCounterValue()); + enforce( + attemptCount, + properties.getSourceAttemptsPerWindow(), + properties.getSourceRetryBaseSeconds(), + subjectWindow); + + Bucket sourceFailures = + bucket(key, PlatformAuthPolicy.SOURCE_FAILURE, sourceBytes, subjectWindow); + long failureCount = + buckets.count(sourceFailures.key(), sourceFailures.digest().collisionFingerprint()); + enforceFailureThreshold( + failureCount, + properties.getSourceFailuresPerWindow(), + properties.getSourceRetryBaseSeconds(), + subjectWindow); + return new AttemptPermit(key, sourceBytes); + } catch (AuthenticationException expected) { + throw expected; + } catch (RuntimeException unavailable) { + throw unavailable(unavailable); + } + } + + /** Applies account-candidate admission to Account's normalized submitted selector. */ + public void admitCandidate(AttemptPermit permit, byte[] canonicalCandidateIdentity) { + Objects.requireNonNull(permit, "permit must not be null"); + Objects.requireNonNull(canonicalCandidateIdentity, "candidate identity must not be null"); + try { + Window candidateWindow = window(clock.instant(), properties.getSubjectWindowSeconds()); + Bucket candidateAttempts = + bucket( + permit.key, + PlatformAuthPolicy.CANDIDATE_ATTEMPT, + canonicalCandidateIdentity, + candidateWindow); + long attemptCount = + buckets.increment( + candidateAttempts.key(), + candidateAttempts.digest().collisionFingerprint(), + candidateWindow.ttl(), + properties.getMaxCounterValue()); + enforce( + attemptCount, + properties.getCandidateAttemptsPerWindow(), + properties.getCandidateRetryBaseSeconds(), + candidateWindow); + + Bucket candidateFailures = + bucket( + permit.key, + PlatformAuthPolicy.CANDIDATE_FAILURE, + canonicalCandidateIdentity, + candidateWindow); + long failureCount = + buckets.count(candidateFailures.key(), candidateFailures.digest().collisionFingerprint()); + enforceFailureThreshold( + failureCount, + properties.getCandidateFailuresPerWindow(), + properties.getCandidateRetryBaseSeconds(), + candidateWindow); + } catch (AuthenticationException expected) { + throw expected; + } catch (RuntimeException unavailable) { + throw unavailable(unavailable); + } + } + + /** Records only credential rejection, using separate single-bucket atomic Redis mutations. */ + public void recordFailure(AttemptPermit permit, byte[] canonicalCandidateIdentity) { + Objects.requireNonNull(permit, "permit must not be null"); + Objects.requireNonNull(canonicalCandidateIdentity, "candidate identity must not be null"); + try { + Window failureWindow = window(clock.instant(), properties.getSubjectWindowSeconds()); + Bucket sourceFailures = + bucket(permit.key, PlatformAuthPolicy.SOURCE_FAILURE, permit.sourceBytes, failureWindow); + buckets.increment( + sourceFailures.key(), + sourceFailures.digest().collisionFingerprint(), + failureWindow.ttl(), + properties.getMaxCounterValue()); + + Bucket candidateFailures = + bucket( + permit.key, + PlatformAuthPolicy.CANDIDATE_FAILURE, + canonicalCandidateIdentity, + failureWindow); + buckets.increment( + candidateFailures.key(), + candidateFailures.digest().collisionFingerprint(), + failureWindow.ttl(), + properties.getMaxCounterValue()); + } catch (RuntimeException unavailable) { + throw unavailable(unavailable); + } + } + + /** + * Encodes Account's already-normalized submitted selector as UTF-8. Account does not resolve + * aliases to a stored identity here; different normalized selectors are not claimed to converge. + */ + public static byte[] candidateIdentity(String canonicalIdentity) { + if (canonicalIdentity == null || canonicalIdentity.isBlank()) { + throw new IllegalArgumentException("candidate identity must not be blank"); + } + byte[] bytes = canonicalIdentity.getBytes(StandardCharsets.UTF_8); + if (bytes.length > 512) { + throw new IllegalArgumentException("candidate identity exceeds the bounded size"); + } + return bytes; + } + + private HmacKey activeKey() { + try { + validateBounds(); + return properties.activeHmacKey(); + } catch (RuntimeException unavailable) { + throw unavailable(unavailable); + } + } + + private void validateBounds() { + if (properties.getSubjectWindowSeconds() < 1 + || properties.getSubjectWindowSeconds() > 3600 + || properties.getGlobalWindowSeconds() < 1 + || properties.getGlobalWindowSeconds() > 3600 + || properties.getGlobalAdmissionsPerWindow() < 1 + || properties.getSourceAttemptsPerWindow() < 1 + || properties.getCandidateAttemptsPerWindow() < 1 + || properties.getSourceFailuresPerWindow() < 1 + || properties.getCandidateFailuresPerWindow() < 1 + || properties.getSourceRetryBaseSeconds() < 1 + || properties.getCandidateRetryBaseSeconds() < 1 + || properties.getGlobalRetryBaseSeconds() < 1 + || properties.getMaxRetrySeconds() < 1 + || properties.getMaxRetrySeconds() > 3600 + || properties.getMaxCounterValue() + <= Math.max( + properties.getGlobalAdmissionsPerWindow(), + Math.max( + properties.getSourceAttemptsPerWindow(), + Math.max( + properties.getCandidateAttemptsPerWindow(), + Math.max( + properties.getSourceFailuresPerWindow(), + properties.getCandidateFailuresPerWindow())))) + || properties.getMaxCounterValue() < 1 + || properties.getMaxCounterValue() > 1_000_000L) { + throw new IllegalStateException("platform-auth rate-limit bounds are invalid"); + } + } + + private Bucket bucket(HmacKey key, PlatformAuthPolicy policy, byte[] identity, Window window) { + Digest digest = RateLimitSubjectHash.platformAuthSubject(key, policy, identity); + return new Bucket(RateLimitSubjectHash.platformAuthBucketKey(digest, window.number()), digest); + } + + private Window window(Instant now, int windowSeconds) { + long epochSecond = now.getEpochSecond(); + long number = Math.floorDiv(epochSecond, windowSeconds); + long remainingMillis = + Math.max(1L, ((number + 1L) * windowSeconds * 1000L) - now.toEpochMilli()); + return new Window(number, Duration.ofMillis(remainingMillis)); + } + + private void enforce(long count, int threshold, int baseRetrySeconds, Window window) { + if (count > threshold) { + throw retry(count, threshold, baseRetrySeconds, window); + } + } + + private void enforceFailureThreshold( + long count, int threshold, int baseRetrySeconds, Window window) { + if (count >= threshold) { + throw retry(count, threshold, baseRetrySeconds, window); + } + } + + private AuthenticationException retry(long count, int threshold, int base, Window window) { + long excess = Math.max(1L, count - threshold); + long scaled = Math.min((long) base * excess, properties.getMaxRetrySeconds()); + long remainingSeconds = Math.max(1L, (window.ttl().toMillis() + 999L) / 1000L); + int retryAfter = (int) Math.max(1L, Math.min(scaled, remainingSeconds)); + return new AuthenticationException( + RETRY_LATER, "Authentication temporarily unavailable; retry later.", retryAfter); + } + + private AuthenticationException unavailable(RuntimeException cause) { + return new AuthenticationException( + UNAVAILABLE, "Shared authentication abuse control is unavailable.", cause); + } + + /** Opaque per-call state pins HMAC key/window across a concurrent rotation boundary. */ + public static final class AttemptPermit { + private final HmacKey key; + private final byte[] sourceBytes; + + private AttemptPermit(HmacKey key, byte[] sourceBytes) { + this.key = key; + this.sourceBytes = sourceBytes.clone(); + } + + @Override + public String toString() { + return "AttemptPermit[keyId=" + key.keyId() + ", source=redacted, window=redacted]"; + } + } + + private record Bucket(String key, Digest digest) {} + + private record Window(long number, Duration ttl) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index ce5e797102..a9af80a7cc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -18,6 +18,7 @@ import java.util.HashMap; import java.util.HexFormat; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -78,6 +79,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCredentialOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation; @@ -99,8 +101,10 @@ import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.CredentialAttemptSource; import net.firedevops.firemud.accountservice.service.EmailService; import net.firedevops.firemud.accountservice.service.NotificationService; +import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiAuthenticationRequest; import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; @@ -117,6 +121,7 @@ import org.jooq.exception.IntegrityConstraintViolationException; import org.jooq.exception.MappingException; import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; @@ -186,6 +191,9 @@ public class AccountServiceImpl implements AccountService { private final JwtUtil jwtUtil; private final net.firedevops.firemud.accountservice.service.session.SessionService sessionService; private final TransactionTemplate joinTransactionTemplate; + private final TransactionTemplate controlUiAuthenticationTransaction; + private AccountPlatformAuthAbuseLimiter controlUiCredentialLimiter; + private AccountControlUiCredentialOperationRepository controlUiCredentialOperations; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -265,8 +273,163 @@ public AccountServiceImpl( this.joinTransactionTemplate = new TransactionTemplate(transactionManager); this.joinTransactionTemplate.setPropagationBehavior( TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.controlUiAuthenticationTransaction = new TransactionTemplate(transactionManager); + this.controlUiAuthenticationTransaction.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.controlUiAuthenticationTransaction.setIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** Uses the real shared credential limiter and V66-bound credential evidence owner. */ + @Autowired + public void configureControlUiAuthentication( + AccountPlatformAuthAbuseLimiter limiter, + AccountControlUiCredentialOperationRepository operations) { + this.controlUiCredentialLimiter = Objects.requireNonNull(limiter); + this.controlUiCredentialOperations = Objects.requireNonNull(operations); + } + + /** + * Fresh authentication only. The original operation must already exist with its actual source + * capture. No JWT, registry record, authorization principal or issuance completion is created. + * Every retry, including COMMITTED result recovery, verifies the current credential again. + */ + public ControlUiCredentialAuthentication authenticateControlUiOperation( + AccountControlUiAuthenticationRequest request) { + Objects.requireNonNull(request); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Control-UI credential admission requires no ambient transaction"); + } + CredentialAttemptSource source = request.credentialAttemptSource(); + if (source == null + || source.connectionMode() != CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB + || controlUiCredentialLimiter == null + || controlUiCredentialOperations == null) { + throw new AuthenticationException( + "AUTH_ABUSE_CONTROL_UNAVAILABLE", + "Trusted credential source and shared abuse control are required"); + } + var permit = controlUiCredentialLimiter.begin(source); + byte[] candidateIdentity = + AccountPlatformAuthAbuseLimiter.candidateIdentity( + request.accountIdentifier().trim().toLowerCase(Locale.ROOT)); + controlUiCredentialLimiter.admitCandidate(permit, candidateIdentity); + ControlUiPreparation prepared = + controlUiAuthenticationTransaction.execute( + status -> { + PrimaryAuthentication authentication; + try { + Account selected = + findAccountForAuthentication(request.accountIdentifier()) + .orElseThrow(this::invalidCredentials); + requireAuthenticationPersistedIdentity(selected); + // Follow the source-writer issuer/account/fence lock order before recipient/OTP + // rows. + var sourceSnapshot = + Objects.requireNonNull( + accountAuthorityGenerationRepository.readCompositeSnapshot( + ACCOUNT_JWT_ISSUER, selected.getAccountUuid(), List.of(), List.of())); + if (!AuthorityScope.issuer(ACCOUNT_JWT_ISSUER) + .equals(sourceSnapshot.issuer().scope()) + || !AuthorityScope.account(selected.getAccountUuid()) + .equals(sourceSnapshot.account().scope()) + || !selected.getAccountUuid().equals(sourceSnapshot.issuanceFence().accountId()) + || !sourceSnapshot + .issuanceFence() + .equals(sourceSnapshot.account().issuanceFence()) + || !sourceSnapshot.tenants().isEmpty() + || !sourceSnapshot.memberships().isEmpty()) { + throw new IllegalStateException( + "Control-UI current Account source snapshot differs"); + } + Account current = + accountRepository + .findByAccountUuidForUpdate(selected.getAccountUuid()) + .orElseThrow(this::invalidCredentials); + requireAuthenticationPersistedIdentity(current); + if (!selected.getId().equals(current.getId())) throw invalidCredentials(); + authentication = authenticateAccountIdentity(current, request.credential(), true); + } catch (AuthenticationException rejected) { + // Commit the existing verifier's failed OTP counters before shared failure + // accounting. + return new ControlUiPreparation(null, rejected); + } + var recorded = + controlUiCredentialOperations.recordVerifiedCredential( + request.requestId(), + authentication.account(), + request.purpose(), + authentication.emailLoginChallenge()); + return new ControlUiPreparation( + new ControlUiCredentialAuthentication( + authentication.account().getAccountUuid(), + request.requestId(), + request.purpose(), + recorded), + null); + }); + if (prepared == null) + throw new IllegalStateException("Control-UI credential transaction returned no result"); + if (prepared.rejection() != null) { + if (AuthenticationErrorCodes.INVALID_CREDENTIALS.equals(prepared.rejection().getCode())) { + controlUiCredentialLimiter.recordFailure(permit, candidateIdentity); + } + throw prepared.rejection(); + } + return Objects.requireNonNull(prepared.authentication()); } + /** Owner-minted fresh credential metadata, not token/source currentness or creator permission. */ + public static final class ControlUiCredentialAuthentication { + private final UUID accountId; + private final UUID requestId; + private final AccountControlUiAuthenticationRequest.Purpose purpose; + private final AccountControlUiCredentialOperationRepository.RecordedAttempt attempt; + + private ControlUiCredentialAuthentication( + UUID accountId, + UUID requestId, + AccountControlUiAuthenticationRequest.Purpose purpose, + AccountControlUiCredentialOperationRepository.RecordedAttempt attempt) { + this.accountId = accountId; + this.requestId = requestId; + this.purpose = purpose; + this.attempt = attempt; + } + + public UUID accountId() { + return accountId; + } + + public UUID requestId() { + return requestId; + } + + public UUID operationId() { + return attempt.operationId(); + } + + public UUID authenticationAttemptId() { + return attempt.attemptId(); + } + + public String authenticationMethod() { + return attempt.method(); + } + + public Instant authenticatedAt() { + return attempt.authenticatedAt(); + } + + public AccountControlUiAuthenticationRequest.Purpose purpose() { + return purpose; + } + } + + private record ControlUiPreparation( + ControlUiCredentialAuthentication authentication, AuthenticationException rejection) {} + @Override @Transactional @Timed(value = "account.create") diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PlatformAuthCacheRedisClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PlatformAuthCacheRedisClient.java new file mode 100644 index 0000000000..5c9ba13000 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PlatformAuthCacheRedisClient.java @@ -0,0 +1,186 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.lettuce.core.SslVerifyMode; +import io.lettuce.core.resource.ClientResources; +import io.lettuce.core.resource.DefaultClientResources; +import java.net.URI; +import java.time.Duration; +import java.util.Locale; +import net.firedevops.firemud.accountservice.config.PlatformAuthRateLimitProperties; +import net.firedevops.firemud.common.config.RedisProperties; +import org.springframework.data.redis.connection.RedisPassword; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.StringRedisTemplate; + +/** Private Cache Redis client; it deliberately is not a Spring RedisConnectionFactory bean. */ +public final class PlatformAuthCacheRedisClient implements AutoCloseable { + private final ClientResources clientResources; + private final LettuceConnectionFactory connectionFactory; + private final StringRedisTemplate template; + + public PlatformAuthCacheRedisClient( + PlatformAuthRateLimitProperties.CacheRedis cacheProperties, + RedisProperties coordinationProperties) { + Endpoint cache = resolve(cacheProperties); + if (sameConfiguredEndpoint(cache.host(), cache.port(), coordinationProperties)) { + throw new IllegalStateException( + "Account platform-auth Cache Redis must use a distinct endpoint from Coordination Redis"); + } + + RedisStandaloneConfiguration standalone = + new RedisStandaloneConfiguration(cache.host(), cache.port()); + standalone.setDatabase(cache.database()); + if (!cache.username().isBlank()) { + standalone.setUsername(cache.username()); + } + if (!cache.password().isBlank()) { + standalone.setPassword(RedisPassword.of(cache.password())); + } + + clientResources = DefaultClientResources.create(); + LettuceClientConfiguration.LettuceClientConfigurationBuilder clientBuilder = + LettuceClientConfiguration.builder() + .clientResources(clientResources) + .commandTimeout(Duration.ofMillis(cache.commandTimeoutMillis())); + if (cache.useSsl() || cache.startTls()) { + LettuceClientConfiguration.LettuceSslClientConfigurationBuilder sslBuilder = + clientBuilder.useSsl(); + if (cache.startTls()) { + sslBuilder.startTls(); + } + if (cache.verifyPeer()) { + sslBuilder.verifyPeer(SslVerifyMode.FULL); + } else { + sslBuilder.disablePeerVerification(); + } + clientBuilder = sslBuilder.and(); + } + connectionFactory = new LettuceConnectionFactory(standalone, clientBuilder.build()); + connectionFactory.afterPropertiesSet(); + template = new StringRedisTemplate(connectionFactory); + template.afterPropertiesSet(); + } + + StringRedisTemplate template() { + return template; + } + + @Override + public void close() { + connectionFactory.destroy(); + clientResources.shutdown(); + } + + private static boolean sameConfiguredEndpoint( + String cacheHost, int cachePort, RedisProperties coordinationProperties) { + return normalizeHost(cacheHost).equals(normalizeHost(coordinationProperties.getHost())) + && cachePort == coordinationProperties.getPort(); + } + + private static String normalizeHost(String host) { + return host == null ? "" : host.trim().replaceAll("\\.$", "").toLowerCase(Locale.ROOT); + } + + private static Endpoint resolve(PlatformAuthRateLimitProperties.CacheRedis properties) { + int commandTimeoutMillis = properties.getCommandTimeoutMillis(); + if (commandTimeoutMillis < 1 || commandTimeoutMillis > 5_000) { + throw new IllegalStateException( + "Account platform-auth Cache Redis command timeout is invalid"); + } + if (properties.getUrl() == null || properties.getUrl().isBlank()) { + validateHostAndPort(properties.getHost(), properties.getPort()); + return new Endpoint( + properties.getHost().trim(), + properties.getPort(), + Math.max(0, properties.getDatabase()), + nullToEmpty(properties.getUsername()), + nullToEmpty(properties.getPassword()), + properties.isUseSsl(), + properties.isStartTls(), + properties.isVerifyPeer(), + commandTimeoutMillis); + } + try { + URI uri = URI.create(properties.getUrl()); + String scheme = uri.getScheme(); + if (uri.getHost() == null + || !("redis".equalsIgnoreCase(scheme) || "rediss".equalsIgnoreCase(scheme)) + || uri.getQuery() != null + || uri.getFragment() != null) { + throw new IllegalArgumentException("unsupported Redis URL"); + } + int port = uri.getPort() < 0 ? 6379 : uri.getPort(); + int database = parseDatabase(uri.getPath()); + String username = nullToEmpty(properties.getUsername()); + String password = nullToEmpty(properties.getPassword()); + String userInfo = uri.getUserInfo(); + if (userInfo != null) { + int separator = userInfo.indexOf(':'); + if (separator < 0) { + username = userInfo; + } else { + username = userInfo.substring(0, separator); + password = userInfo.substring(separator + 1); + } + } + validateHostAndPort(uri.getHost(), port); + boolean useSsl = "rediss".equalsIgnoreCase(scheme) || properties.isUseSsl(); + return new Endpoint( + uri.getHost(), + port, + database, + username, + password, + useSsl, + properties.isStartTls(), + properties.isVerifyPeer(), + commandTimeoutMillis); + } catch (RuntimeException ex) { + throw new IllegalStateException("Account platform-auth Cache Redis URL is invalid"); + } + } + + private static int parseDatabase(String path) { + if (path == null || path.isEmpty() || "/".equals(path)) { + return 0; + } + if (!path.matches("/[0-9]{1,9}")) { + throw new IllegalArgumentException("unsupported Redis URL path"); + } + return Integer.parseInt(path.substring(1)); + } + + private static void validateHostAndPort(String host, int port) { + if (host == null || host.isBlank() || port < 1 || port > 65535) { + throw new IllegalStateException("Account platform-auth Cache Redis endpoint is invalid"); + } + } + + private static String nullToEmpty(String value) { + return value == null ? "" : value; + } + + private record Endpoint( + String host, + int port, + int database, + String username, + String password, + boolean useSsl, + boolean startTls, + boolean verifyPeer, + int commandTimeoutMillis) { + private Endpoint { + if (database < 0) { + database = 0; + } + } + + @Override + public String toString() { + return "Endpoint[host=redacted, port=" + port + ", database=" + database + "]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RedisPlatformAuthBucketStore.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RedisPlatformAuthBucketStore.java new file mode 100644 index 0000000000..e4420850a8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RedisPlatformAuthBucketStore.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import java.time.Duration; +import java.util.List; +import net.firedevops.firemud.accountservice.service.PlatformAuthBucketStore; +import org.springframework.core.io.ClassPathResource; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.data.redis.core.script.RedisScript; + +/** One-key atomic Redis mutations and reads for Account platform-auth buckets. */ +public final class RedisPlatformAuthBucketStore implements PlatformAuthBucketStore { + private static final RedisScript BUCKET_SCRIPT = bucketScript(); + private final PlatformAuthCacheRedisClient cacheRedisClient; + + public RedisPlatformAuthBucketStore(PlatformAuthCacheRedisClient cacheRedisClient) { + this.cacheRedisClient = cacheRedisClient; + } + + @Override + public long increment(String key, String collisionFingerprint, Duration ttl, long maximumValue) { + if (ttl == null || ttl.isZero() || ttl.isNegative() || maximumValue < 1) { + throw new IllegalArgumentException("platform-auth bucket bounds are invalid"); + } + return execute( + key, + "increment", + collisionFingerprint, + Long.toString(ttl.toMillis()), + Long.toString(maximumValue)); + } + + @Override + public long count(String key, String collisionFingerprint) { + return execute(key, "read", collisionFingerprint, "0", "0"); + } + + private long execute( + String key, String operation, String collisionFingerprint, String ttlMillis, String cap) { + Long result = + cacheRedisClient + .template() + .execute(BUCKET_SCRIPT, List.of(key), operation, collisionFingerprint, ttlMillis, cap); + if (result == null || result < 0) { + throw new IllegalStateException("platform-auth rate-limit bucket integrity check failed"); + } + return result; + } + + private static RedisScript bucketScript() { + DefaultRedisScript script = new DefaultRedisScript<>(); + script.setLocation(new ClassPathResource("redis/platform_auth_rate_limit_bucket.lua")); + script.setResultType(Long.class); + return script; + } +} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index c3317a7215..45406e37f6 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -54,6 +54,32 @@ firemud: cleanup: batch-size: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_BATCH_SIZE:100} interval-ms: ${FIREMUD_ACCOUNT_CONNECT_SCOPE_CLEANUP_INTERVAL_MS:60000} + platform-auth-abuse: + cache-redis: + url: ${FIREMUD_REDIS_CACHE_URL:} + host: ${FIREMUD_REDIS_CACHE_HOST:redis-cache} + port: ${FIREMUD_REDIS_CACHE_PORT:6379} + database: ${FIREMUD_ACCOUNT_AUTH_ABUSE_CACHE_REDIS_DATABASE:0} + command-timeout-millis: ${FIREMUD_ACCOUNT_AUTH_ABUSE_CACHE_COMMAND_TIMEOUT_MS:1000} + username: ${FIREMUD_REDIS_CACHE_USERNAME:} + password: ${FIREMUD_REDIS_CACHE_PASSWORD:} + use-ssl: ${FIREMUD_REDIS_CACHE_USE_SSL:false} + start-tls: ${FIREMUD_REDIS_CACHE_START_TLS:false} + verify-peer: ${FIREMUD_REDIS_CACHE_VERIFY_PEER:true} + hmac-key-id: ${FIREMUD_ACCOUNT_AUTH_ABUSE_HMAC_KEY_ID:} + hmac-key-base64: ${FIREMUD_ACCOUNT_AUTH_ABUSE_HMAC_KEY_BASE64:} + subject-window-seconds: ${FIREMUD_ACCOUNT_AUTH_ABUSE_SUBJECT_WINDOW_SECONDS:300} + global-window-seconds: ${FIREMUD_ACCOUNT_AUTH_ABUSE_GLOBAL_WINDOW_SECONDS:60} + global-admissions-per-window: ${FIREMUD_ACCOUNT_AUTH_ABUSE_GLOBAL_ADMISSIONS_PER_WINDOW:1000} + source-attempts-per-window: ${FIREMUD_ACCOUNT_AUTH_ABUSE_SOURCE_ATTEMPTS_PER_WINDOW:60} + candidate-attempts-per-window: ${FIREMUD_ACCOUNT_AUTH_ABUSE_CANDIDATE_ATTEMPTS_PER_WINDOW:20} + source-failures-per-window: ${FIREMUD_ACCOUNT_AUTH_ABUSE_SOURCE_FAILURES_PER_WINDOW:20} + candidate-failures-per-window: ${FIREMUD_ACCOUNT_AUTH_ABUSE_CANDIDATE_FAILURES_PER_WINDOW:5} + source-retry-base-seconds: ${FIREMUD_ACCOUNT_AUTH_ABUSE_SOURCE_RETRY_BASE_SECONDS:5} + candidate-retry-base-seconds: ${FIREMUD_ACCOUNT_AUTH_ABUSE_CANDIDATE_RETRY_BASE_SECONDS:15} + global-retry-base-seconds: ${FIREMUD_ACCOUNT_AUTH_ABUSE_GLOBAL_RETRY_BASE_SECONDS:5} + max-retry-seconds: ${FIREMUD_ACCOUNT_AUTH_ABUSE_MAX_RETRY_SECONDS:300} + max-counter-value: ${FIREMUD_ACCOUNT_AUTH_ABUSE_MAX_COUNTER_VALUE:1000000} tokens: session-expiration-ms: 3600000 player-bootstrap-expiration-ms: 300000 diff --git a/services/account-service/src/main/resources/db/migration/V68__control_ui_credential_authentication_attempts.sql b/services/account-service/src/main/resources/db/migration/V68__control_ui_credential_authentication_attempts.sql new file mode 100644 index 0000000000..100a48a661 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V68__control_ui_credential_authentication_attempts.sql @@ -0,0 +1,59 @@ +-- Credential evidence only: the V66 row remains the sole issuance operation. +-- No password, OTP, credential hash, token, authority capture or completion is copied here. +CREATE TABLE account_control_ui_credential_authentication_attempts ( + attempt_id UUID PRIMARY KEY CHECK (attempt_id <> '00000000-0000-0000-0000-000000000000'), + operation_id UUID NOT NULL REFERENCES account_control_ui_issuance_operations(operation_id), + request_id UUID NOT NULL, + account_uuid UUID NOT NULL, + account_id BIGINT NOT NULL CHECK (account_id > 0), + account_provenance VARCHAR(40) NOT NULL, + purpose VARCHAR(32) NOT NULL CHECK (purpose IN ('INITIAL_ISSUANCE', 'EXACT_RESPONSE_RECOVERY')), + authentication_method VARCHAR(16) NOT NULL CHECK (authentication_method IN ('PASSWORD', 'EMAIL_OTP')), + consumed_challenge_id BIGINT UNIQUE, + authenticated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK ((authentication_method = 'PASSWORD' AND consumed_challenge_id IS NULL) + OR (authentication_method = 'EMAIL_OTP' AND consumed_challenge_id IS NOT NULL AND consumed_challenge_id > 0)) +); + +-- [jooq ignore start] +CREATE FUNCTION account_control_ui_credential_attempt_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + operation account_control_ui_issuance_operations%ROWTYPE; +BEGIN + EXECUTE format('SELECT * FROM %I.account_control_ui_issuance_operations WHERE operation_id = $1 FOR UPDATE', TG_TABLE_SCHEMA) + INTO operation USING NEW.operation_id; + IF operation.operation_id IS NULL + OR operation.request_id IS DISTINCT FROM NEW.request_id + OR operation.account_uuid IS DISTINCT FROM NEW.account_uuid + OR operation.account_id IS DISTINCT FROM NEW.account_id + OR operation.account_provenance IS DISTINCT FROM NEW.account_provenance + OR operation.profile <> 'control-ui' OR operation.audience <> 'control-ui' + OR (NEW.purpose = 'INITIAL_ISSUANCE' AND operation.status <> 'PENDING') + OR (NEW.purpose = 'EXACT_RESPONSE_RECOVERY' + AND (operation.status <> 'COMMITTED' OR operation.expires_at <= CURRENT_TIMESTAMP)) THEN + RAISE EXCEPTION 'Control-UI credential attempt must bind its exact original operation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_control_ui_credential_attempt_immutable_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-UI credential attempt evidence is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_control_ui_credential_attempt_insert + BEFORE INSERT ON account_control_ui_credential_authentication_attempts + FOR EACH ROW EXECUTE FUNCTION account_control_ui_credential_attempt_insert_guard(); +CREATE TRIGGER account_control_ui_credential_attempt_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_credential_authentication_attempts + FOR EACH ROW EXECUTE FUNCTION account_control_ui_credential_attempt_immutable_guard(); +CREATE TRIGGER account_control_ui_credential_attempt_no_truncate + BEFORE TRUNCATE ON account_control_ui_credential_authentication_attempts + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_credential_attempt_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/redis/platform_auth_rate_limit_bucket.lua b/services/account-service/src/main/resources/redis/platform_auth_rate_limit_bucket.lua new file mode 100644 index 0000000000..ca4cda5b4b --- /dev/null +++ b/services/account-service/src/main/resources/redis/platform_auth_rate_limit_bucket.lua @@ -0,0 +1,59 @@ +-- One-key platform-auth bucket. Values contain only a keyed integrity tag and a bounded counter. +local operation = ARGV[1] +local fingerprint = ARGV[2] +local ttl_ms = tonumber(ARGV[3]) +local maximum = tonumber(ARGV[4]) + +if operation ~= 'read' and operation ~= 'increment' then + return -2 +end +if not fingerprint or fingerprint == '' then + return -2 +end +if operation == 'increment' and (not ttl_ms or ttl_ms < 1 or not maximum or maximum < 1) then + return -2 +end + +local stored_fingerprint = redis.call('HGET', KEYS[1], 'fingerprint') +if not stored_fingerprint then + if redis.call('EXISTS', KEYS[1]) ~= 0 then + return -2 + end + if operation == 'read' then + return 0 + end + redis.call('HSET', KEYS[1], 'fingerprint', fingerprint, 'count', '0') + redis.call('PEXPIRE', KEYS[1], ttl_ms) + stored_fingerprint = fingerprint +end + +if stored_fingerprint ~= fingerprint then + return -1 +end + +local raw_count = redis.call('HGET', KEYS[1], 'count') +if not raw_count then + return -2 +end +local count = tonumber(raw_count) +if not count or count < 0 then + return -2 +end + +-- Existing buckets must already have a live bounded TTL; corruption is not repaired on the hot path. +if redis.call('PTTL', KEYS[1]) < 1 then + return -2 +end + +if operation == 'read' then + return count +end + +if count < maximum then + count = redis.call('HINCRBY', KEYS[1], 'count', 1) + if count > maximum then + count = maximum + redis.call('HSET', KEYS[1], 'count', tostring(maximum)) + end +end +return count diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java new file mode 100644 index 0000000000..902926b1ba --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java @@ -0,0 +1,716 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCredentialOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCredentialOperationRepository.CredentialOperationConflictException; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation.OriginalCapture; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperationRepository; +import net.firedevops.firemud.accountservice.security.AccountControlUiResponseEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiAuthenticationRequest.Purpose; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +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; + +/** + * Isolated PostgreSQL repository and migration proof. Credential verification and original source + * captures are stipulated fixtures, not authenticated LOGIN, a complete producer, token signing, + * registry activation or creator authorization. The repository performs the real operation binding, + * challenge predicates, consumption and evidence writes under real transactions. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountControlUiCredentialAuthenticationPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @TempDir Path temp; + + @Test + void v67ToV68UpgradePreservesNonemptyPendingCommittedAndEncryptedOriginalImages() + throws Exception { + Fixture fixture = fixture("67"); + Account account = account(fixture); + var pending = pending(fixture, account); + var committed = committed(fixture, account, false); + List before = originalImages(fixture); + assertThat(before).hasSize(3); + + migrate(fixture.dataSource(), fixture.schema(), "68"); + + assertThat(originalImages(fixture)).containsExactlyElementsOf(before); + assertThat(tx(fixture, () -> fixture.issuance().findByRequest(pending.request()).orElseThrow())) + .isEqualTo(pending); + assertThat( + tx(fixture, () -> fixture.issuance().findByRequest(committed.request()).orElseThrow())) + .isEqualTo(committed); + assertThat(attemptCount(fixture)).isZero(); + } + + @Test + void exactPasswordAndOtpEvidenceBindOriginalOperationAndFreshRecoveryRemainsSeparate() + throws Exception { + Fixture fixture = fixture("68"); + Account account = account(fixture); + var pending = pending(fixture, account); + List originals = originalImages(fixture); + var password = record(fixture, pending, account, Purpose.INITIAL_ISSUANCE, Optional.empty()); + AccountEmailLoginChallenge challenge = challenge(fixture, account); + var otp = record(fixture, pending, account, Purpose.INITIAL_ISSUANCE, Optional.of(challenge)); + + assertThat(password.operationId()).isEqualTo(pending.operationId()); + assertThat(password.method()).isEqualTo("PASSWORD"); + assertThat(otp.operationId()).isEqualTo(pending.operationId()); + assertThat(otp.method()).isEqualTo("EMAIL_OTP"); + assertThat(challengeImage(fixture, challenge.getId())).isNull(); + assertThat(originalImages(fixture)).containsExactlyElementsOf(originals); + assertExactAttempt(fixture, password.attemptId(), pending, account, null, "PASSWORD"); + assertExactAttempt(fixture, otp.attemptId(), pending, account, challenge.getId(), "EMAIL_OTP"); + + var committed = committed(fixture, account, false); + var recovery = + record(fixture, committed, account, Purpose.EXACT_RESPONSE_RECOVERY, Optional.empty()); + var freshRecovery = + record(fixture, committed, account, Purpose.EXACT_RESPONSE_RECOVERY, Optional.empty()); + assertThat(recovery.attemptId()).isNotEqualTo(freshRecovery.attemptId()); + assertThat(recovery.operationId()).isEqualTo(committed.operationId()); + assertThat(freshRecovery.operationId()).isEqualTo(committed.operationId()); + assertThat(attemptCount(fixture)).isEqualTo(4L); + assertThat(evidenceImage(fixture)) + .doesNotContain( + "fixture-verified-otp-hash", + "fixture-original-response", + "password_hash", + "code_hash", + "credential", + "ciphertext", + "authority_capture"); + } + + @Test + void wrongAccountRequestDigestAndMissingOriginalDenyWithoutCredentialEvidence() { + Fixture fixture = fixture("68"); + Account account = account(fixture); + var pending = pending(fixture, account); + Account other = account(fixture); + assertThatThrownBy( + () -> record(fixture, pending, other, Purpose.INITIAL_ISSUANCE, Optional.empty())) + .isInstanceOf(CredentialOperationConflictException.class); + assertThatThrownBy( + () -> + tx( + fixture, + () -> + fixture + .credentials() + .recordVerifiedCredential( + UUID.randomUUID(), + account, + Purpose.INITIAL_ISSUANCE, + Optional.empty()))) + .isInstanceOf(CredentialOperationConflictException.class); + + // Deliberately malformed historical request digest; the fixture copies a retained row's + // structure, not the production semantic-digest algorithm or authorization decisions. + UUID wrongDigestRequest = UUID.randomUUID(); + fixture + .dsl() + .execute( + "INSERT INTO account_control_ui_issuance_operations " + + "(operation_id, request_id, account_uuid, account_id, account_provenance, profile, audience, " + + "request_digest_version, request_digest, authority_capture, authority_capture_digest, " + + "issuance_fence_capture, issuance_fence_digest, status) " + + "SELECT ?, ?, account_uuid, account_id, account_provenance, profile, audience, " + + "request_digest_version, request_digest, authority_capture, authority_capture_digest, " + + "issuance_fence_capture, issuance_fence_digest, 'PENDING' " + + "FROM account_control_ui_issuance_operations WHERE operation_id = ?", + UUID.randomUUID(), + wrongDigestRequest, + pending.operationId()); + List originals = originalImages(fixture); + assertThatThrownBy( + () -> + tx( + fixture, + () -> + fixture + .credentials() + .recordVerifiedCredential( + wrongDigestRequest, + account, + Purpose.INITIAL_ISSUANCE, + Optional.empty()))) + .isInstanceOf(CredentialOperationConflictException.class); + + // Direct fixture attacks separately prove the database's operation/request/account binding. + assertThatThrownBy( + () -> rawPasswordAttempt(fixture, pending.operationId(), UUID.randomUUID(), account)) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("exact original operation"); + assertThatThrownBy( + () -> + rawPasswordAttempt( + fixture, + pending.operationId(), + UUID.fromString(pending.request().requestId()), + other)) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("exact original operation"); + assertThatThrownBy( + () -> + rawPasswordAttempt( + fixture, + UUID.randomUUID(), + UUID.fromString(pending.request().requestId()), + account)) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("exact original operation"); + assertThat(attemptCount(fixture)).isZero(); + assertThat(originalImages(fixture)).containsExactlyElementsOf(originals); + } + + @Test + void recoveryLifecycleAndExactLiveChallengePredicatesDenyWithoutConsumption() throws Exception { + Fixture fixture = fixture("68"); + Account account = account(fixture); + var pending = pending(fixture, account); + var expired = committed(fixture, account, true); + AccountEmailLoginChallenge challenge = challenge(fixture, account); + String originalChallenge = challengeImage(fixture, challenge.getId()); + for (var operation : List.of(pending, expired)) { + assertThatThrownBy( + () -> + record( + fixture, + operation, + account, + Purpose.EXACT_RESPONSE_RECOVERY, + Optional.of(challenge))) + .isInstanceOf(CredentialOperationConflictException.class); + assertThat(challengeImage(fixture, challenge.getId())).isEqualTo(originalChallenge); + } + + String verifiedHash = challenge.getCodeHash(); + challenge.setCodeHash("different-verified-hash"); + assertChallengeDenied(fixture, pending, account, challenge); + challenge.setCodeHash(verifiedHash); + Long actualId = challenge.getId(); + challenge.setId(actualId + 1L); + assertChallengeDenied(fixture, pending, account, challenge); + challenge.setId(actualId); + Account other = account(fixture); + fixture + .dsl() + .execute( + "UPDATE account_email_login_challenge SET account_id = ? WHERE id = ?", + other.getId(), + actualId); + assertChallengeDenied(fixture, pending, account, challenge); + fixture + .dsl() + .execute( + "UPDATE account_email_login_challenge SET account_id = ? WHERE id = ?", + account.getId(), + actualId); + fixture + .dsl() + .execute( + "UPDATE account_email_login_challenge SET expires_at = CAST(? AS timestamp) WHERE id = ?", + LocalDateTime.now().minusSeconds(1), + actualId); + assertChallengeDenied(fixture, pending, account, challenge); + fixture + .dsl() + .execute( + "UPDATE account_email_login_challenge SET expires_at = CAST(? AS timestamp), invalid_attempt_count = 5 WHERE id = ?", + LocalDateTime.now().plusMinutes(5), + actualId); + assertChallengeDenied(fixture, pending, account, challenge); + assertThat(attemptCount(fixture)).isZero(); + } + + @Test + void lateEvidenceInsertFailureRollsBackMatchingOtpConsumptionAndOriginalOperation() { + Fixture fixture = fixture("68"); + Account account = account(fixture); + var pending = pending(fixture, account); + AccountEmailLoginChallenge challenge = challenge(fixture, account); + String before = challengeImage(fixture, challenge.getId()); + List originals = originalImages(fixture); + // A fixture-only late database failure, reached after the real DELETE succeeds. + fixture + .dsl() + .execute( + "ALTER TABLE account_control_ui_credential_authentication_attempts " + + "ADD CONSTRAINT fixture_reject_otp_evidence CHECK (authentication_method <> 'EMAIL_OTP')"); + + assertThatThrownBy( + () -> + record(fixture, pending, account, Purpose.INITIAL_ISSUANCE, Optional.of(challenge))) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("fixture_reject_otp_evidence"); + + assertThat(challengeImage(fixture, challenge.getId())).isEqualTo(before); + assertThat(originalImages(fixture)).containsExactlyElementsOf(originals); + assertThat(attemptCount(fixture)).isZero(); + fixture + .dsl() + .execute( + "ALTER TABLE account_control_ui_credential_authentication_attempts DROP CONSTRAINT fixture_reject_otp_evidence"); + assertThat( + record(fixture, pending, account, Purpose.INITIAL_ISSUANCE, Optional.of(challenge)) + .method()) + .isEqualTo("EMAIL_OTP"); + assertThat(challengeImage(fixture, challenge.getId())).isNull(); + assertThat(attemptCount(fixture)).isEqualTo(1L); + } + + @Test + void simultaneousMatchedOtpClaimsBlockOnOriginalOperationAndConsumeOnlyOnce() throws Exception { + Fixture fixture = fixture("68"); + Account account = account(fixture); + var pending = pending(fixture, account); + AccountEmailLoginChallenge challenge = challenge(fixture, account); + List originals = originalImages(fixture); + CountDownLatch firstRecorded = new CountDownLatch(1); + CountDownLatch secondEntered = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + AtomicInteger firstPid = new AtomicInteger(); + AtomicInteger secondPid = new AtomicInteger(); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> + tx( + fixture, + () -> { + firstPid.set(backendPid(fixture)); + var attempt = + fixture + .credentials() + .recordVerifiedCredential( + UUID.fromString(pending.request().requestId()), + account, + Purpose.INITIAL_ISSUANCE, + Optional.of(challenge)); + firstRecorded.countDown(); + await(releaseFirst); + return attempt; + })); + assertThat(firstRecorded.await(10, TimeUnit.SECONDS)).isTrue(); + var second = + executor.submit( + () -> { + try { + tx( + fixture, + () -> { + secondPid.set(backendPid(fixture)); + secondEntered.countDown(); + return fixture + .credentials() + .recordVerifiedCredential( + UUID.fromString(pending.request().requestId()), + account, + Purpose.INITIAL_ISSUANCE, + Optional.of(challenge)); + }); + return true; + } catch (CredentialOperationConflictException expected) { + return false; + } + }); + assertThat(secondEntered.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(waitForDatabaseBlock(fixture, secondPid.get(), firstPid.get())).isTrue(); + releaseFirst.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS).method()).isEqualTo("EMAIL_OTP"); + assertThat(second.get(10, TimeUnit.SECONDS)).isFalse(); + assertThat(challengeImage(fixture, challenge.getId())).isNull(); + assertThat(attemptCount(fixture)).isEqualTo(1L); + assertThat(originalImages(fixture)).containsExactlyElementsOf(originals); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + } + } + + @Test + void credentialEvidenceRejectsUpdateDeleteAndTruncateAndPreservesExactStoredRows() { + Fixture fixture = fixture("68"); + Account account = account(fixture); + var pending = pending(fixture, account); + var attempt = record(fixture, pending, account, Purpose.INITIAL_ISSUANCE, Optional.empty()); + String original = evidenceImage(fixture); + for (String sql : + List.of( + "UPDATE account_control_ui_credential_authentication_attempts SET purpose = 'EXACT_RESPONSE_RECOVERY' WHERE attempt_id = ?", + "DELETE FROM account_control_ui_credential_authentication_attempts WHERE attempt_id = ?")) { + assertThatThrownBy(() -> tx(fixture, () -> fixture.dsl().execute(sql, attempt.attemptId()))) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThat(evidenceImage(fixture)).isEqualTo(original); + } + assertThatThrownBy( + () -> + tx( + fixture, + () -> + fixture + .dsl() + .execute( + "TRUNCATE account_control_ui_credential_authentication_attempts"))) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThat(evidenceImage(fixture)).isEqualTo(original); + } + + private Fixture fixture(String version) { + String schema = "control_ui_credential_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = new DriverManagerDataSource(); + source.setUrl( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema); + source.setUsername(postgres.getUsername()); + source.setPassword(postgres.getPassword()); + migrate(source, schema, version); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + return new Fixture( + schema, + source, + dsl, + new AccountControlUiIssuanceOperationRepository(dsl), + new AccountControlUiCredentialOperationRepository(dsl), + new TransactionTemplate(new DataSourceTransactionManager(source))); + } + + private static void migrate(DriverManagerDataSource source, String schema, String version) { + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target(MigrationVersion.fromVersion(version)) + .locations("classpath:db/migration") + .load() + .migrate(); + } + + private static Account account(Fixture fixture) { + String unique = UUID.randomUUID().toString().replace("-", ""); + Record row = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) " + + "RETURNING id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id", + "credential_" + unique.substring(0, 12), + unique + "@example.test", + "fixture-account-password-hash")); + Account account = new Account(); + account.setId(row.get("id", Long.class)); + account.setAccountUuid(row.get("account_uuid", UUID.class)); + account.setAccountUuidSourceNumericId(row.get("account_uuid_source_numeric_id", Long.class)); + account.setAccountUuidProvenance( + AccountIdentityProvenance.fromStorageValue( + row.get("account_uuid_provenance", String.class))); + return account; + } + + private static AccountControlUiIssuanceOperation pending(Fixture fixture, Account account) { + var request = + new AccountControlUiIssuanceRequest( + UUID.randomUUID().toString(), account.getAccountUuid().toString()); + OriginalCapture stipulatedCapture = + new OriginalCapture( + account.getId(), + account.getAccountUuidProvenance(), + "stipulated-original-source-capture".getBytes(StandardCharsets.UTF_8), + "stipulated-original-fence-capture".getBytes(StandardCharsets.UTF_8)); + return tx( + fixture, + () -> fixture.issuance().claim(request, Optional.of(stipulatedCapture)).operation()); + } + + private AccountControlUiIssuanceOperation committed( + Fixture fixture, Account account, boolean expired) throws Exception { + var operation = pending(fixture, account); + byte[] response = "fixture-original-response".getBytes(StandardCharsets.UTF_8); + Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS); + Instant issued = now.minusSeconds(120); + Instant expiry = expired ? now.minusSeconds(60) : now.plusSeconds(300); + var binding = + new AccountControlUiResponseEnvelopeBinding( + account.getAccountUuid().toString(), + operation.operationId().toString(), + operation.request().requestId(), + operation.requestDigest(), + java.util.HexFormat.of() + .formatHex(sha256("fixture-original-token".getBytes(StandardCharsets.UTF_8))), + sha256(response), + operation.originalCapture().authorityCaptureDigest(), + operation.originalCapture().issuanceFenceDigest(), + issued, + expiry); + Path manifest = temp.resolve("ring_" + UUID.randomUUID() + ".v1"); + var lines = new java.util.ArrayList(List.of("version=1", "activeKeyId=k1")); + int seed = 1; + for (String purpose : + List.of("bare-login", "connect-token", "pending-reset", "control-ui-response")) { + byte[] key = new byte[32]; + java.util.Arrays.fill(key, (byte) seed++); + lines.add( + "key:k1:" + purpose + "=" + Base64.getUrlEncoder().withoutPadding().encodeToString(key)); + } + Files.writeString(manifest, String.join("\n", lines) + "\n", StandardCharsets.US_ASCII); + var envelope = new AccountEnvelopeCrypto(manifest).encryptControlUiResponse(binding, response); + return tx( + fixture, + () -> + fixture + .issuance() + .complete( + fixture.issuance().claim(operation.request(), Optional.empty()), + binding, + envelope)); + } + + private static AccountEmailLoginChallenge challenge(Fixture fixture, Account account) { + Record row = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "INSERT INTO account_email_login_challenge (account_id, code_hash, expires_at, resend_available_at, created_at, updated_at) " + + "VALUES (?, ?, CAST(? AS timestamp), CAST(? AS timestamp), " + + "CAST(? AS timestamp), CAST(? AS timestamp)) " + + "RETURNING id, account_id, code_hash, expires_at", + account.getId(), + "fixture-verified-otp-hash", + LocalDateTime.now().plusMinutes(5), + LocalDateTime.now(), + LocalDateTime.now(), + LocalDateTime.now())); + AccountEmailLoginChallenge challenge = new AccountEmailLoginChallenge(); + challenge.setId(row.get("id", Long.class)); + challenge.setAccountId(row.get("account_id", Long.class)); + challenge.setCodeHash(row.get("code_hash", String.class)); + challenge.setExpiresAt(row.get("expires_at", LocalDateTime.class)); + return challenge; + } + + private static AccountControlUiCredentialOperationRepository.RecordedAttempt record( + Fixture fixture, + AccountControlUiIssuanceOperation operation, + Account account, + Purpose purpose, + Optional challenge) { + return tx( + fixture, + () -> + fixture + .credentials() + .recordVerifiedCredential( + UUID.fromString(operation.request().requestId()), account, purpose, challenge)); + } + + private static void assertChallengeDenied( + Fixture fixture, + AccountControlUiIssuanceOperation operation, + Account account, + AccountEmailLoginChallenge challenge) { + String before = challengeTableImage(fixture); + assertThatThrownBy( + () -> + record( + fixture, operation, account, Purpose.INITIAL_ISSUANCE, Optional.of(challenge))) + .isInstanceOf(CredentialOperationConflictException.class); + assertThat(challengeTableImage(fixture)).isEqualTo(before); + } + + private static void assertExactAttempt( + Fixture fixture, + UUID attemptId, + AccountControlUiIssuanceOperation operation, + Account account, + Long consumedChallengeId, + String method) { + Record row = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_control_ui_credential_authentication_attempts WHERE attempt_id = ?", + attemptId)); + assertThat(row.get("operation_id", UUID.class)).isEqualTo(operation.operationId()); + assertThat(row.get("request_id", UUID.class).toString()) + .isEqualTo(operation.request().requestId()); + assertThat(row.get("account_uuid", UUID.class)).isEqualTo(account.getAccountUuid()); + assertThat(row.get("account_id", Long.class)).isEqualTo(account.getId()); + assertThat(row.get("account_provenance", String.class)) + .isEqualTo(account.getAccountUuidProvenance().name()); + assertThat(row.get("consumed_challenge_id", Long.class)).isEqualTo(consumedChallengeId); + assertThat(row.get("authentication_method", String.class)).isEqualTo(method); + } + + private static void rawPasswordAttempt( + Fixture fixture, UUID operationId, UUID requestId, Account account) { + tx( + fixture, + () -> + fixture + .dsl() + .execute( + "INSERT INTO account_control_ui_credential_authentication_attempts " + + "(attempt_id, operation_id, request_id, account_uuid, account_id, account_provenance, purpose, authentication_method) " + + "VALUES (?, ?, ?, ?, ?, ?, 'INITIAL_ISSUANCE', 'PASSWORD')", + UUID.randomUUID(), + operationId, + requestId, + account.getAccountUuid(), + account.getId(), + account.getAccountUuidProvenance().name())); + } + + private static List originalImages(Fixture fixture) { + return fixture + .dsl() + .fetch( + "SELECT image FROM (" + + "SELECT 'operation:' || operation_id::text AS identity, to_jsonb(row_value)::text AS image " + + "FROM account_control_ui_issuance_operations row_value UNION ALL " + + "SELECT 'envelope:' || operation_id::text, to_jsonb(row_value)::text " + + "FROM account_control_ui_issuance_response_envelopes row_value) images ORDER BY identity") + .getValues("image", String.class); + } + + private static String challengeImage(Fixture fixture, Long id) { + Record row = + fixture + .dsl() + .fetchOne( + "SELECT to_jsonb(row_value)::text AS image FROM account_email_login_challenge row_value WHERE id = ?", + id); + return row == null ? null : row.get("image", String.class); + } + + private static String challengeTableImage(Fixture fixture) { + return Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT coalesce(jsonb_agg(to_jsonb(row_value) ORDER BY id), '[]'::jsonb)::text AS image " + + "FROM account_email_login_challenge row_value")) + .get("image", String.class); + } + + private static String evidenceImage(Fixture fixture) { + return Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT coalesce(jsonb_agg(to_jsonb(row_value) ORDER BY attempt_id), '[]'::jsonb)::text AS image " + + "FROM account_control_ui_credential_authentication_attempts row_value")) + .get("image", String.class); + } + + private static long attemptCount(Fixture fixture) { + return Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT count(*) AS count FROM account_control_ui_credential_authentication_attempts")) + .get("count", Long.class); + } + + private static int backendPid(Fixture fixture) { + return Objects.requireNonNull(fixture.dsl().fetchOne("SELECT pg_backend_pid() AS pid")) + .get("pid", Integer.class); + } + + private static boolean waitForDatabaseBlock(Fixture fixture, int waiting, int blocking) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + Boolean blocked = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT ? = ANY(pg_blocking_pids(?)) AS blocked", blocking, waiting)) + .get("blocked", Boolean.class); + if (Boolean.TRUE.equals(blocked)) return true; + Thread.sleep(20); + } + return false; + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(15, TimeUnit.SECONDS)) + throw new IllegalStateException("Credential race fixture timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Credential race fixture interrupted", failure); + } + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (Exception failure) { + throw new IllegalStateException("SHA-256 unavailable", failure); + } + } + + private static T tx(Fixture fixture, Supplier operation) { + return fixture.transaction().execute(status -> operation.get()); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + AccountControlUiIssuanceOperationRepository issuance, + AccountControlUiCredentialOperationRepository credentials, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java index 372f507417..c862b85ac0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java @@ -192,7 +192,8 @@ void abandonedPendingClaimCannotBeReportedCommittedWithoutExactEnvelope() { .dsl() .execute( "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', " - + "token_hash = ?, response_digest = ?, issued_at = ?, expires_at = ? " + + "token_hash = ?, response_digest = ?, " + + "issued_at = CAST(? AS timestamptz), expires_at = CAST(? AS timestamptz) " + "WHERE operation_id = ?", missingEnvelopeBinding.tokenHash(), missingEnvelopeBinding.responseDigest(), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java index 79e271773e..b8b1b1f4aa 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -18,6 +18,7 @@ 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; @@ -598,7 +599,8 @@ private Event producerFixture( .execute( "UPDATE accounts SET email_verified = ?, login_auth_modes = ?, lifecycle_state = ? WHERE account_uuid = ?", pending.request().desiredState().emailVerified(), - String.join(",", pending.request().desiredState().loginAuthModes()), + AccountLoginAuthModes.normalize( + String.join(",", pending.request().desiredState().loginAuthModes())), pending .request() .desiredState() diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiTokenFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiTokenFixture.java index 09b2cf9622..91c1f4156a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiTokenFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiTokenFixture.java @@ -173,6 +173,8 @@ Map registry(String token, Map claims) throws Ex "1", "sourceVersion", "1", + "sourceFence", + "7", "linearization", "123", "canonicalSha256", diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/PlatformAuthRateLimitRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/PlatformAuthRateLimitRedisIntegrationTest.java new file mode 100644 index 0000000000..63ef0a1d05 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/PlatformAuthRateLimitRedisIntegrationTest.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.config.PlatformAuthRateLimitProperties; +import net.firedevops.firemud.common.config.RedisProperties; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Docker-gated proof of the Account bucket Lua contract against disposable Redis. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class PlatformAuthRateLimitRedisIntegrationTest { + private static final String KEY = "ratelimit:platform-auth:v1:" + "a".repeat(64) + ":0"; + private static final String FINGERPRINT = "b".repeat(64); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + private PlatformAuthCacheRedisClient cacheClient; + private RedisPlatformAuthBucketStore buckets; + + @BeforeEach + void createCacheRoleClient() { + PlatformAuthRateLimitProperties.CacheRedis cacheProperties = + new PlatformAuthRateLimitProperties.CacheRedis(); + cacheProperties.setHost(redis.getHost()); + cacheProperties.setPort(redis.getMappedPort(6379)); + RedisProperties coordinationProperties = new RedisProperties(); + coordinationProperties.setHost("coordination.invalid"); + coordinationProperties.setPort(redis.getMappedPort(6379)); + cacheClient = new PlatformAuthCacheRedisClient(cacheProperties, coordinationProperties); + buckets = new RedisPlatformAuthBucketStore(cacheClient); + } + + @AfterEach + void removeFixtureKeysAndCloseClient() { + if (cacheClient != null) { + try { + cacheClient.template().delete(KEY); + } finally { + cacheClient.close(); + } + } + } + + @Test + void absentAndEvictedBucketsReadAsZeroAndCanStartFresh() { + assertThat(buckets.count(KEY, FINGERPRINT)).isZero(); + assertThat(buckets.increment(KEY, FINGERPRINT, Duration.ofSeconds(30), 10)).isEqualTo(1); + assertThat(cacheClient.template().getExpire(KEY, TimeUnit.MILLISECONDS)).isPositive(); + + // Exact-key deletion models reset/eviction without broadening the fixture to FLUSHDB. + assertThat(cacheClient.template().delete(KEY)).isTrue(); + assertThat(buckets.count(KEY, FINGERPRINT)).isZero(); + assertThat(buckets.increment(KEY, FINGERPRINT, Duration.ofSeconds(30), 10)).isEqualTo(1); + } + + @Test + void presentHashWithoutFingerprintIsCorruptionNotAnAbsentBucket() { + cacheClient.template().opsForHash().put(KEY, "count", "1"); + + assertThatThrownBy(() -> buckets.count(KEY, FINGERPRINT)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("platform-auth rate-limit bucket integrity check failed"); + } + + @Test + void existingBucketWithoutPositiveTtlFailsClosedAndIsNotRepaired() { + cacheClient + .template() + .opsForHash() + .putAll(KEY, Map.of("fingerprint", FINGERPRINT, "count", "1")); + + assertThatThrownBy(() -> buckets.count(KEY, FINGERPRINT)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("platform-auth rate-limit bucket integrity check failed"); + assertThatThrownBy(() -> buckets.increment(KEY, FINGERPRINT, Duration.ofSeconds(30), 10)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("platform-auth rate-limit bucket integrity check failed"); + assertThat(cacheClient.template().getExpire(KEY, TimeUnit.MILLISECONDS)).isEqualTo(-1L); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountControlUiCredentialOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountControlUiCredentialOperationRepositoryTest.java new file mode 100644 index 0000000000..bd51906513 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountControlUiCredentialOperationRepositoryTest.java @@ -0,0 +1,210 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequest; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequestDigest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiAuthenticationRequest.Purpose; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL-call unit proof only; real migration/concurrency/rollback proof remains PostgreSQL-owned. */ +class AccountControlUiCredentialOperationRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountControlUiCredentialOperationRepository repository = + new AccountControlUiCredentialOperationRepository(dsl); + private final UUID requestId = UUID.randomUUID(); + private final UUID operationId = UUID.randomUUID(); + private final Account account = new Account(); + private final Record operation = mock(Record.class); + + @BeforeEach + void prepareCurrentOriginalOperation() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + account.setId(9L); + account.setAccountUuid(UUID.randomUUID()); + account.setAccountUuidSourceNumericId(9L); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + when(operation.get("operation_id", UUID.class)).thenReturn(operationId); + when(operation.get("request_id", UUID.class)).thenReturn(requestId); + when(operation.get("account_uuid", UUID.class)).thenReturn(account.getAccountUuid()); + when(operation.get("account_id", Long.class)).thenReturn(9L); + when(operation.get("account_provenance", String.class)) + .thenReturn(account.getAccountUuidProvenance().name()); + when(operation.get("profile", String.class)).thenReturn("control-ui"); + when(operation.get("audience", String.class)).thenReturn("control-ui"); + when(operation.get("request_digest_version", Integer.class)).thenReturn(1); + when(operation.get("request_digest", byte[].class)) + .thenReturn( + AccountControlUiIssuanceRequestDigest.digest( + new AccountControlUiIssuanceRequest( + requestId.toString(), account.getAccountUuid().toString()))); + when(operation.get("status", String.class)).thenReturn("PENDING"); + when(operation.get("expires_at", OffsetDateTime.class)) + .thenReturn(OffsetDateTime.now().plusMinutes(5)); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + call -> { + String sql = call.getArgument(0); + if (sql.startsWith("SELECT")) return operation; + if (sql.startsWith("DELETE")) { + Record consumed = mock(Record.class); + when(consumed.get("id", Long.class)).thenReturn(73L); + return consumed; + } + Record inserted = mock(Record.class); + when(inserted.get("attempt_id", UUID.class)).thenReturn(call.getArgument(1)); + when(inserted.get("operation_id", UUID.class)).thenReturn(operationId); + when(inserted.get("authenticated_at", OffsetDateTime.class)) + .thenReturn(OffsetDateTime.now(ZoneOffset.UTC)); + return inserted; + }); + } + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void passwordAttemptBindsTheOriginalOperationWithoutChallengeDeletion() { + var result = + repository.recordVerifiedCredential( + requestId, account, Purpose.INITIAL_ISSUANCE, Optional.empty()); + assertEquals(operationId, result.operationId()); + assertEquals("PASSWORD", result.method()); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(dsl, org.mockito.Mockito.times(2)).fetchOne(sql.capture(), any(Object[].class)); + org.junit.jupiter.api.Assertions.assertTrue( + sql.getAllValues().stream().noneMatch(value -> value.startsWith("DELETE"))); + } + + @Test + void matchedOtpDeletesOnlyTheExactVerifiedChallengeBeforeEvidenceInsertion() { + var challenge = new AccountEmailLoginChallenge(); + challenge.setId(73L); + challenge.setAccountId(9L); + challenge.setCodeHash("actual-owner-verified-hash"); + challenge.setExpiresAt(LocalDateTime.now().plusMinutes(5)); + var result = + repository.recordVerifiedCredential( + requestId, account, Purpose.INITIAL_ISSUANCE, Optional.of(challenge)); + assertEquals("EMAIL_OTP", result.method()); + var order = org.mockito.Mockito.inOrder(dsl); + order + .verify(dsl) + .fetchOne(org.mockito.ArgumentMatchers.startsWith("SELECT"), any(Object[].class)); + order + .verify(dsl) + .fetchOne( + org.mockito.ArgumentMatchers.startsWith("DELETE"), + org.mockito.ArgumentMatchers.eq(73L), + org.mockito.ArgumentMatchers.eq(9L), + org.mockito.ArgumentMatchers.eq("actual-owner-verified-hash"), + any(LocalDateTime.class)); + order + .verify(dsl) + .fetchOne(org.mockito.ArgumentMatchers.startsWith("INSERT"), any(Object[].class)); + } + + @Test + void freshPasswordRecoveryRecordsANewAttemptForTheExactCommittedOperation() { + when(operation.get("status", String.class)).thenReturn("COMMITTED"); + var first = + repository.recordVerifiedCredential( + requestId, account, Purpose.EXACT_RESPONSE_RECOVERY, Optional.empty()); + var second = + repository.recordVerifiedCredential( + requestId, account, Purpose.EXACT_RESPONSE_RECOVERY, Optional.empty()); + assertEquals(operationId, first.operationId()); + assertEquals(operationId, second.operationId()); + org.junit.jupiter.api.Assertions.assertNotEquals(first.attemptId(), second.attemptId()); + } + + @Test + void missingOriginalOperationCannotConsumeOrCreateEvidence() { + when(dsl.fetchOne(org.mockito.ArgumentMatchers.startsWith("SELECT"), any(Object[].class))) + .thenReturn(null); + assertConflict(Purpose.INITIAL_ISSUANCE); + } + + @Test + void crossAccountOperationFailsBeforeConsumptionOrEvidence() { + when(operation.get("account_uuid", UUID.class)).thenReturn(UUID.randomUUID()); + assertConflict(Purpose.INITIAL_ISSUANCE); + } + + @Test + void changedSemanticDigestFailsBeforeConsumptionOrEvidence() { + when(operation.get("request_digest", byte[].class)).thenReturn(new byte[32]); + assertConflict(Purpose.INITIAL_ISSUANCE); + } + + @Test + void pendingOperationCannotAuthenticateExactCommittedResponseRecovery() { + assertConflict(Purpose.EXACT_RESPONSE_RECOVERY); + } + + @Test + void expiredOriginalResultCannotAuthenticateRecovery() { + when(operation.get("status", String.class)).thenReturn("COMMITTED"); + when(operation.get("expires_at", OffsetDateTime.class)) + .thenReturn(OffsetDateTime.now().minusSeconds(1)); + assertConflict(Purpose.EXACT_RESPONSE_RECOVERY); + } + + @Test + void unavailableOrAlreadyConsumedOtpCannotCreateAuthenticationEvidence() { + when(dsl.fetchOne(org.mockito.ArgumentMatchers.startsWith("DELETE"), any(Object[].class))) + .thenReturn(null); + var challenge = new AccountEmailLoginChallenge(); + challenge.setId(73L); + challenge.setAccountId(9L); + challenge.setCodeHash("actual-owner-verified-hash"); + assertThrows( + AccountControlUiCredentialOperationRepository.CredentialOperationConflictException.class, + () -> + repository.recordVerifiedCredential( + requestId, account, Purpose.INITIAL_ISSUANCE, Optional.of(challenge))); + verify(dsl, org.mockito.Mockito.never()) + .fetchOne(org.mockito.ArgumentMatchers.startsWith("INSERT"), any(Object[].class)); + } + + @Test + void recordingRequiresWritableOwnerTransaction() { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThrows( + IllegalStateException.class, + () -> + repository.recordVerifiedCredential( + requestId, account, Purpose.INITIAL_ISSUANCE, Optional.empty())); + org.mockito.Mockito.verifyNoInteractions(dsl); + } + + private void assertConflict(Purpose purpose) { + assertThrows( + AccountControlUiCredentialOperationRepository.CredentialOperationConflictException.class, + () -> repository.recordVerifiedCredential(requestId, account, purpose, Optional.empty())); + verify(dsl, org.mockito.Mockito.times(1)).fetchOne(anyString(), any(Object[].class)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/CredentialAttemptSourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/CredentialAttemptSourceTest.java new file mode 100644 index 0000000000..26d3ae9635 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/CredentialAttemptSourceTest.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class CredentialAttemptSourceTest { + @Test + void independentlyConstructedSourcesUseCanonicalAddressAndModeValueEquality() { + CredentialAttemptSource first = + source("203.0.113.8", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB); + CredentialAttemptSource equal = + source("203.0.113.8", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB); + + assertEquals(first, equal); + assertEquals(first.hashCode(), equal.hashCode()); + } + + @Test + void differentCanonicalAddressOrConnectionModeIsNotEqual() { + CredentialAttemptSource baseline = + source("203.0.113.8", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB); + + assertNotEquals( + baseline, source("203.0.113.9", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB)); + assertNotEquals( + baseline, source("203.0.113.8", CredentialAttemptSource.ConnectionMode.TRUSTED_TCP_PROXY)); + } + + @Test + void addressAccessorReturnsDefensiveCopy() { + CredentialAttemptSource source = + source("203.0.113.8", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB); + byte[] returned = source.canonicalClientAddress(); + returned[0] = 0; + + assertArrayEquals(new byte[] {(byte) 203, 0, 113, 8}, source.canonicalClientAddress()); + } + + @Test + void stringRepresentationRedactsAddressAndRetainsMode() { + CredentialAttemptSource source = + source("203.0.113.8", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB); + + assertTrue(source.toString().contains("clientAddress=redacted")); + assertTrue(source.toString().contains("connectionMode=FIRST_PARTY_WEB")); + assertFalse(source.toString().contains("203.0.113.8")); + } + + private static CredentialAttemptSource source( + String address, CredentialAttemptSource.ConnectionMode mode) { + return new CredentialAttemptSource(address, mode); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecksTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecksTest.java index 90057e4f43..2306730764 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecksTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenChecksTest.java @@ -11,6 +11,7 @@ import java.util.Set; import java.util.UUID; import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiTokenChecks; +import net.firedevops.firemud.common.security.AccountJwtExactValues; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -196,6 +197,8 @@ void durableCaptureVersionAndAccountSourceVersionAdvanceIndependently() throws E "1", "sourceVersion", Long.toString(versions[0]), + "sourceFence", + "19", "linearization", "123", "canonicalSha256", @@ -212,6 +215,114 @@ void durableCaptureVersionAndAccountSourceVersionAdvanceIndependently() throws E } } + @Test + void completeCaptureReferenceRejectsMissingAndUnknownFields() throws Exception { + Map claims = fixture.claims(UUID.randomUUID()); + String token = fixture.sign(claims); + for (String missing : + List.of( + "bundleVersion", "sourceVersion", "sourceFence", "linearization", "canonicalSha256")) { + Map record = fixture.registry(token, claims); + Map bundle = + new LinkedHashMap<>((Map) record.get("authEvidenceBundle")); + bundle.remove(missing); + record.put("authEvidenceBundle", bundle); + byte[] bytes = AccountControlUiTokenFixture.canonical(record); + assertThatThrownBy( + () -> + fixture + .checks() + .inspect( + "creator-candidate", + token, + bytes, + AccountControlUiTokenFixture.unscopedShape())) + .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class); + } + Map record = fixture.registry(token, claims); + Map bundle = + new LinkedHashMap<>((Map) record.get("authEvidenceBundle")); + bundle.put("issuanceFence", claims.get("issuanceFence")); + record.put("authEvidenceBundle", bundle); + byte[] bytes = AccountControlUiTokenFixture.canonical(record); + assertThatThrownBy( + () -> + fixture + .checks() + .inspect( + "creator-candidate", + token, + bytes, + AccountControlUiTokenFixture.unscopedShape())) + .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class); + } + + @Test + void captureSourceFenceRejectsNonpositiveNoncanonicalAndNumericWireForms() throws Exception { + Map claims = fixture.claims(UUID.randomUUID()); + String token = fixture.sign(claims); + for (Object invalid : + java.util.Arrays.asList( + null, 1L, "0", "-1", "+1", "01", " 1", "1 ", "1.0", "1e3", "", "bad")) { + Map record = fixture.registry(token, claims); + Map bundle = + new LinkedHashMap<>((Map) record.get("authEvidenceBundle")); + bundle.put("sourceFence", invalid); + record.put("authEvidenceBundle", bundle); + byte[] bytes = AccountControlUiTokenFixture.canonical(record); + assertThatThrownBy( + () -> + fixture + .checks() + .inspect( + "creator-candidate", + token, + bytes, + AccountControlUiTokenFixture.unscopedShape())) + .isInstanceOf(AccountControlUiTokenChecks.InvalidTokenException.class); + } + } + + @Test + void changedLargeCaptureReferenceCountersRemainExactIndependentAndNonAuthorizing() + throws Exception { + Map claims = fixture.claims(UUID.randomUUID()); + claims.put("issuanceFence", "11"); + String token = fixture.sign(claims); + var checks = fixture.checks(); + for (String[] counters : + List.of( + new String[] {"9007199254740992", "9007199254740993", "9223372036854775808"}, + new String[] {"9007199254740992", "9007199254740994", "9223372036854775808"}, + new String[] {"9223372036854775809", "9007199254740994", "9223372036854775808"}, + new String[] {"9223372036854775809", "9223372036854775810", "9223372036854775808"})) { + Map record = fixture.registry(token, claims); + Map bundle = + Map.of( + "bundleVersion", "1", + "sourceVersion", counters[0], + "sourceFence", counters[1], + "linearization", counters[2], + "canonicalSha256", "c".repeat(64)); + record.put("authEvidenceBundle", bundle); + var inspected = + checks.inspect( + "creator-candidate", + token, + AccountControlUiTokenFixture.canonical(record), + AccountControlUiTokenFixture.unscopedShape()); + assertThat(inspected.registryRecord().get("authEvidenceBundle")).isEqualTo(bundle); + assertThat(inspected.registryRecord().get("issuanceFence")).isEqualTo("11"); + assertThat( + AccountJwtExactValues.sameJsonValue( + inspected.registryRecord().get("authoritySourceVersions"), + record.get("authoritySourceVersions"))) + .isTrue(); + // A structurally valid changed reference is retained, not authenticated or made current. + assertThat(inspected.toString()).contains("non-authorizing"); + } + } + @Test void billingSafeMembershipDoesNotCreateTargetTenantAuthority() throws Exception { UUID tenant = UUID.randomUUID(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenFixture.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenFixture.java index b1b673e93b..9437423ea9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenFixture.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiTokenFixture.java @@ -169,6 +169,8 @@ public Map registry(String token, Map claims) th "1", "sourceVersion", "1", + "sourceFence", + "7", "linearization", "123", "canonicalSha256", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlatformAuthAbuseLimiterTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlatformAuthAbuseLimiterTest.java new file mode 100644 index 0000000000..efc3ba16c4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlatformAuthAbuseLimiterTest.java @@ -0,0 +1,373 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.HashMap; +import java.util.Map; +import net.firedevops.firemud.accountservice.config.PlatformAuthRateLimitProperties; +import net.firedevops.firemud.accountservice.service.CredentialAttemptSource; +import net.firedevops.firemud.accountservice.service.PlatformAuthBucketStore; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.config.RedisProperties; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +class AccountPlatformAuthAbuseLimiterTest { + @Test + void annotationContextWiresProductionConstructor() { + PlatformAuthBucketStore bucketStore = mock(PlatformAuthBucketStore.class); + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { + context.registerBean(PlatformAuthRateLimitProperties.class, () -> properties()); + context.registerBean(PlatformAuthBucketStore.class, () -> bucketStore); + context.register(AccountPlatformAuthAbuseLimiter.class); + + context.refresh(); + + assertNotNull(context.getBean(AccountPlatformAuthAbuseLimiter.class)); + } + } + + @Test + void cacheCommandTimeoutDefaultAndBoundsAreExplicit() { + assertEquals( + 1_000, new PlatformAuthRateLimitProperties().getCacheRedis().getCommandTimeoutMillis()); + + for (int invalidTimeout : new int[] {0, 5_001}) { + PlatformAuthRateLimitProperties.CacheRedis cache = + new PlatformAuthRateLimitProperties.CacheRedis(); + cache.setCommandTimeoutMillis(invalidTimeout); + IllegalStateException invalid = + assertThrows( + IllegalStateException.class, + () -> new PlatformAuthCacheRedisClient(cache, new RedisProperties())); + assertEquals( + "Account platform-auth Cache Redis command timeout is invalid", invalid.getMessage()); + } + } + + @Test + void sourceBudgetIsSharedAcrossConnectionModes() { + PlatformAuthRateLimitProperties properties = properties(); + properties.setSourceAttemptsPerWindow(1); + AccountPlatformAuthAbuseLimiter limiter = + new AccountPlatformAuthAbuseLimiter( + properties, + new InMemoryBuckets(), + Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneId.of("UTC"))); + + limiter.begin(source("198.51.100.7", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB)); + AuthenticationException rejected = + assertThrows( + AuthenticationException.class, + () -> + limiter.begin( + source( + "198.51.100.7", CredentialAttemptSource.ConnectionMode.TRUSTED_TCP_PROXY))); + + assertEquals("AUTH_RETRY_LATER", rejected.getCode()); + assertTrue(rejected.getRetryAfterSeconds() >= 1); + } + + @Test + void sharedCacheEnforcesOneSourceBudgetAcrossLimiterReplicas() { + PlatformAuthRateLimitProperties firstProperties = properties(); + firstProperties.setSourceAttemptsPerWindow(1); + PlatformAuthRateLimitProperties secondProperties = properties(); + secondProperties.setSourceAttemptsPerWindow(1); + InMemoryBuckets sharedCache = new InMemoryBuckets(); + Clock clock = Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneId.of("UTC")); + AccountPlatformAuthAbuseLimiter firstReplica = + new AccountPlatformAuthAbuseLimiter(firstProperties, sharedCache, clock); + AccountPlatformAuthAbuseLimiter secondReplica = + new AccountPlatformAuthAbuseLimiter(secondProperties, sharedCache, clock); + + firstReplica.begin( + source("198.51.100.7", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB)); + AuthenticationException rejected = + assertThrows( + AuthenticationException.class, + () -> + secondReplica.begin( + source( + "198.51.100.7", CredentialAttemptSource.ConnectionMode.TRUSTED_TCP_PROXY))); + + assertEquals("AUTH_RETRY_LATER", rejected.getCode()); + } + + @Test + void candidateFailureBudgetIsSharedAcrossSourceAddresses() { + PlatformAuthRateLimitProperties properties = properties(); + properties.setCandidateFailuresPerWindow(1); + AccountPlatformAuthAbuseLimiter limiter = + new AccountPlatformAuthAbuseLimiter( + properties, + new InMemoryBuckets(), + Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneId.of("UTC"))); + byte[] candidate = + AccountPlatformAuthAbuseLimiter.candidateIdentity("normalized-alias@example.test"); + + AccountPlatformAuthAbuseLimiter.AttemptPermit first = + limiter.begin( + source("198.51.100.7", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB)); + limiter.admitCandidate(first, candidate); + limiter.recordFailure(first, candidate); + + AccountPlatformAuthAbuseLimiter.AttemptPermit second = + limiter.begin( + source("198.51.100.8", CredentialAttemptSource.ConnectionMode.TRUSTED_TCP_PROXY)); + AuthenticationException rejected = + assertThrows( + AuthenticationException.class, () -> limiter.admitCandidate(second, candidate)); + + assertEquals("AUTH_RETRY_LATER", rejected.getCode()); + assertTrue(rejected.getRetryAfterSeconds() >= 1); + } + + @Test + void sharedStoreFailureFailsClosedWithUnavailableCode() { + PlatformAuthRateLimitProperties properties = properties(); + PlatformAuthBucketStore unavailableStore = + new PlatformAuthBucketStore() { + @Override + public long increment(String key, String fingerprint, Duration ttl, long maximumValue) { + throw new IllegalStateException("store unavailable"); + } + + @Override + public long count(String key, String fingerprint) { + throw new IllegalStateException("store unavailable"); + } + }; + AccountPlatformAuthAbuseLimiter limiter = + new AccountPlatformAuthAbuseLimiter( + properties, + unavailableStore, + Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneId.of("UTC"))); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + limiter.begin( + source( + "198.51.100.7", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB))); + + assertEquals("AUTH_ABUSE_CONTROL_UNAVAILABLE", unavailable.getCode()); + assertEquals(0, unavailable.getRetryAfterSeconds()); + } + + @Test + void globalPressureBoundsSubjectBucketAdmissionAndKeysContainNoRawSource() { + PlatformAuthRateLimitProperties properties = properties(); + properties.setGlobalAdmissionsPerWindow(1); + InMemoryBuckets buckets = new InMemoryBuckets(); + AccountPlatformAuthAbuseLimiter limiter = + new AccountPlatformAuthAbuseLimiter( + properties, + buckets, + Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneId.of("UTC"))); + + limiter.begin(source("198.51.100.7", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB)); + AuthenticationException rejected = + assertThrows( + AuthenticationException.class, + () -> + limiter.begin( + source( + "198.51.100.8", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB))); + + assertEquals("AUTH_RETRY_LATER", rejected.getCode()); + assertEquals(2, buckets.size()); + assertTrue(buckets.keys().stream().noneMatch(key -> key.contains("198.51.100."))); + } + + @Test + void resetAndWindowExpiryOnlyLoseHeuristicThrottleState() { + PlatformAuthRateLimitProperties properties = properties(); + properties.setSourceAttemptsPerWindow(1); + MutableClock clock = new MutableClock(Instant.parse("2026-01-01T00:00:00Z")); + InMemoryBuckets sharedCache = new InMemoryBuckets(clock); + AccountPlatformAuthAbuseLimiter limiter = + new AccountPlatformAuthAbuseLimiter(properties, sharedCache, clock); + CredentialAttemptSource source = + source("198.51.100.7", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB); + + limiter.begin(source); + assertThrows(AuthenticationException.class, () -> limiter.begin(source)); + + sharedCache.reset(); + limiter.begin(source); + assertThrows(AuthenticationException.class, () -> limiter.begin(source)); + + clock.advance(Duration.ofSeconds(properties.getSubjectWindowSeconds())); + limiter.begin(source); + } + + @Test + void missingActiveKeyFailsClosedBeforeCallingSharedStore() { + PlatformAuthRateLimitProperties properties = new PlatformAuthRateLimitProperties(); + InMemoryBuckets buckets = new InMemoryBuckets(); + AccountPlatformAuthAbuseLimiter limiter = + new AccountPlatformAuthAbuseLimiter( + properties, + buckets, + Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneId.of("UTC"))); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + limiter.begin( + source( + "198.51.100.7", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB))); + + assertEquals("AUTH_ABUSE_CONTROL_UNAVAILABLE", unavailable.getCode()); + assertEquals(0, buckets.size()); + } + + @Test + void keyRotationCreatesIsolatedBucketNamespaces() { + InMemoryBuckets buckets = new InMemoryBuckets(); + PlatformAuthRateLimitProperties firstProperties = properties(); + AccountPlatformAuthAbuseLimiter first = + new AccountPlatformAuthAbuseLimiter( + firstProperties, + buckets, + Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneId.of("UTC"))); + firstProperties.setSourceAttemptsPerWindow(1); + first.begin(source("198.51.100.7", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB)); + AuthenticationException oldKeyStillThrottles = + assertThrows( + AuthenticationException.class, + () -> + first.begin( + source( + "198.51.100.7", CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB))); + assertEquals("AUTH_RETRY_LATER", oldKeyStillThrottles.getCode()); + + PlatformAuthRateLimitProperties rotatedProperties = properties(); + rotatedProperties.setHmacKeyId("rotated"); + rotatedProperties.setHmacKeyBase64(java.util.Base64.getEncoder().encodeToString(new byte[32])); + rotatedProperties.setSourceAttemptsPerWindow(1); + AccountPlatformAuthAbuseLimiter rotated = + new AccountPlatformAuthAbuseLimiter( + rotatedProperties, + buckets, + Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneId.of("UTC"))); + + rotated.begin(source("198.51.100.7", CredentialAttemptSource.ConnectionMode.TRUSTED_TCP_PROXY)); + } + + private static PlatformAuthRateLimitProperties properties() { + PlatformAuthRateLimitProperties properties = new PlatformAuthRateLimitProperties(); + properties.setHmacKeyId("test-v1"); + properties.setHmacKeyBase64(java.util.Base64.getEncoder().encodeToString(new byte[32])); + return properties; + } + + private static CredentialAttemptSource source( + String ip, CredentialAttemptSource.ConnectionMode mode) { + return new CredentialAttemptSource(ip, mode); + } + + private static final class InMemoryBuckets implements PlatformAuthBucketStore { + private final Map values = new HashMap<>(); + private final Clock clock; + + private InMemoryBuckets() { + this(null); + } + + private InMemoryBuckets(Clock clock) { + this.clock = clock; + } + + @Override + public long increment(String key, String fingerprint, Duration ttl, long maximumValue) { + expireOldValues(); + Value old = values.get(key); + if (old != null && !old.fingerprint.equals(fingerprint)) { + throw new IllegalStateException("collision"); + } + long next = old == null ? 1 : Math.min(maximumValue, old.count + 1); + Instant expiresAt = + old == null && clock != null + ? clock.instant().plus(ttl) + : old == null ? null : old.expiresAt; + values.put(key, new Value(fingerprint, next, expiresAt)); + return next; + } + + @Override + public long count(String key, String fingerprint) { + expireOldValues(); + Value value = values.get(key); + if (value == null) { + return 0; + } + if (!value.fingerprint.equals(fingerprint)) { + throw new IllegalStateException("collision"); + } + return value.count; + } + + int size() { + expireOldValues(); + return values.size(); + } + + java.util.Set keys() { + expireOldValues(); + return values.keySet(); + } + + void reset() { + values.clear(); + } + + private void expireOldValues() { + if (clock == null) { + return; + } + Instant now = clock.instant(); + values.entrySet().removeIf(entry -> !entry.getValue().expiresAt.isAfter(now)); + } + + private record Value(String fingerprint, long count, Instant expiresAt) {} + } + + private static final class MutableClock extends Clock { + private Instant instant; + + private MutableClock(Instant instant) { + this.instant = instant; + } + + private void advance(Duration duration) { + instant = instant.plus(duration); + } + + @Override + public ZoneId getZone() { + return ZoneId.of("UTC"); + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return instant; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index e635fcf2fc..2999c9c34b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -312,6 +312,316 @@ void setup() { transactionManager); } + @Test + void controlUiPasswordAuthenticationRecordsFreshEvidenceWithoutMintingOrSessions() { + var fixture = controlUiCredentialFixture(); + var result = + service.authenticateControlUiOperation( + controlUiCredentialRequest( + fixture.requestId(), + "password", + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose.INITIAL_ISSUANCE)); + + assertEquals(fixture.account().getAccountUuid(), result.accountId()); + assertEquals(fixture.requestId(), result.requestId()); + assertEquals("PASSWORD", result.authenticationMethod()); + verify(fixture.operations()) + .recordVerifiedCredential( + fixture.requestId(), + fixture.account(), + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose.INITIAL_ISSUANCE, + Optional.empty()); + verifyNoInteractions( + sessionService, accountTenantMembershipRepository, accountConnectScopeRepository); + org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) + .delete(org.mockito.ArgumentMatchers.any()); + } + + @Test + void controlUiRecoveryAlwaysChecksTheFreshPasswordAgain() { + var fixture = controlUiCredentialFixture(); + var purpose = + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose.EXACT_RESPONSE_RECOVERY; + service.authenticateControlUiOperation( + controlUiCredentialRequest(fixture.requestId(), "password", purpose)); + AuthenticationException rejected = + assertThrows( + AuthenticationException.class, + () -> + service.authenticateControlUiOperation( + controlUiCredentialRequest(fixture.requestId(), "wrong", purpose))); + + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, rejected.getCode()); + verify(fixture.operations(), org.mockito.Mockito.times(1)) + .recordVerifiedCredential( + fixture.requestId(), fixture.account(), purpose, Optional.empty()); + verify(fixture.limiter()) + .recordFailure( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(byte[].class)); + verifyNoInteractions(sessionService); + } + + @Test + void controlUiFreshOtpBindsTheActualChallengeToTheExactOriginalRequest() { + var fixture = controlUiCredentialFixture(); + fixture.account().setLoginAuthModes("EMAIL_OTP"); + var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(73L); + challenge.setAccountId(fixture.account().getId()); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(LocalDateTime.now().plusMinutes(5)); + when(accountEmailLoginChallengeRepository.findByAccountId(fixture.account().getId())) + .thenReturn(Optional.of(challenge)); + var purpose = + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose.EXACT_RESPONSE_RECOVERY; + + service.authenticateControlUiOperation( + controlUiCredentialRequest(fixture.requestId(), "123456", purpose)); + + verify(fixture.operations()) + .recordVerifiedCredential( + fixture.requestId(), fixture.account(), purpose, Optional.of(challenge)); + verifyNoInteractions(sessionService); + } + + @Test + void controlUiConsumedOriginalOtpCannotAuthenticateRecovery() { + var fixture = controlUiCredentialFixture(); + fixture.account().setLoginAuthModes("EMAIL_OTP"); + when(accountEmailLoginChallengeRepository.findByAccountId(fixture.account().getId())) + .thenReturn(Optional.empty()); + + AuthenticationException rejected = + assertThrows( + AuthenticationException.class, + () -> + service.authenticateControlUiOperation( + controlUiCredentialRequest( + fixture.requestId(), + "123456", + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose + .EXACT_RESPONSE_RECOVERY))); + + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, rejected.getCode()); + verifyNoInteractions(fixture.operations(), sessionService); + } + + @Test + void controlUiExpiredOtpCannotAuthenticateRecovery() { + var fixture = controlUiCredentialFixture(); + fixture.account().setLoginAuthModes("EMAIL_OTP"); + var challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); + challenge.setId(73L); + challenge.setAccountId(fixture.account().getId()); + challenge.setCodeHash(hash("123456")); + challenge.setExpiresAt(LocalDateTime.now().minusMinutes(1)); + when(accountEmailLoginChallengeRepository.findByAccountId(fixture.account().getId())) + .thenReturn(Optional.of(challenge)); + AuthenticationException rejected = + assertThrows( + AuthenticationException.class, + () -> + service.authenticateControlUiOperation( + controlUiCredentialRequest( + fixture.requestId(), + "123456", + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose + .EXACT_RESPONSE_RECOVERY))); + assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, rejected.getCode()); + verifyNoInteractions(fixture.operations(), sessionService); + } + + @Test + void controlUiOperationConflictCannotBecomeAuthenticationSuccess() { + var fixture = controlUiCredentialFixture(); + when(fixture + .operations() + .recordVerifiedCredential( + fixture.requestId(), + fixture.account(), + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose.INITIAL_ISSUANCE, + Optional.empty())) + .thenThrow( + new net.firedevops.firemud.accountservice.repository + .AccountControlUiCredentialOperationRepository + .CredentialOperationConflictException()); + assertThrows( + net.firedevops.firemud.accountservice.repository + .AccountControlUiCredentialOperationRepository.CredentialOperationConflictException + .class, + () -> + service.authenticateControlUiOperation( + controlUiCredentialRequest( + fixture.requestId(), + "password", + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose.INITIAL_ISSUANCE))); + verifyNoInteractions(sessionService); + } + + @Test + void controlUiUnavailableAbuseControlStopsBeforeAccountLookup() { + var fixture = controlUiCredentialFixture(); + org.mockito.Mockito.doThrow( + new AuthenticationException("AUTH_ABUSE_CONTROL_UNAVAILABLE", "unavailable")) + .when(fixture.limiter()) + .begin(org.mockito.ArgumentMatchers.any()); + assertThrows( + AuthenticationException.class, + () -> + service.authenticateControlUiOperation( + controlUiCredentialRequest( + fixture.requestId(), + "password", + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose.INITIAL_ISSUANCE))); + verifyNoInteractions(accountRepository, fixture.operations(), sessionService); + } + + @Test + void controlUiMissingTrustedSourceStopsBeforeAccountLookup() { + var fixture = controlUiCredentialFixture(); + var request = + new net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest( + fixture.requestId(), + "creator@example.com", + "password", + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose.INITIAL_ISSUANCE, + null); + AuthenticationException rejected = + assertThrows( + AuthenticationException.class, () -> service.authenticateControlUiOperation(request)); + assertEquals("AUTH_ABUSE_CONTROL_UNAVAILABLE", rejected.getCode()); + verifyNoInteractions( + fixture.limiter(), accountRepository, fixture.operations(), sessionService); + } + + @ParameterizedTest + @EnumSource( + value = AccountLifecycleState.class, + names = {"SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"}) + void controlUiCurrentLifecycleDeniesCredentialEvidence(AccountLifecycleState state) { + var fixture = controlUiCredentialFixture(); + fixture.account().setLifecycleState(state); + assertThrows( + AuthenticationException.class, + () -> + service.authenticateControlUiOperation( + controlUiCredentialRequest( + fixture.requestId(), + "password", + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose.INITIAL_ISSUANCE))); + verifyNoInteractions(fixture.operations(), sessionService); + } + + @Test + void controlUiMissingCurrentSourceFailsWithoutAuthenticationEvidence() { + var fixture = controlUiCredentialFixture(); + when(accountAuthorityGenerationRepository.readCompositeSnapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + fixture.account().getAccountUuid(), + java.util.List.of(), + java.util.List.of())) + .thenThrow(new IllegalStateException("source unavailable")); + assertThrows( + IllegalStateException.class, + () -> + service.authenticateControlUiOperation( + controlUiCredentialRequest( + fixture.requestId(), + "password", + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose.INITIAL_ISSUANCE))); + verifyNoInteractions( + fixture.operations(), accountEmailLoginChallengeRepository, sessionService); + } + + private ControlUiCredentialFixture controlUiCredentialFixture() { + Account account = new Account(); + account.setId(9L); + setPersistedAuthenticationIdentity(account); + account.setEmail("creator@example.com"); + account.setPasswordHash(hash("password")); + account.setLoginAuthModes("PASSWORD"); + account.setLifecycleState(AccountLifecycleState.ACTIVE); + when(accountRepository.findByEmail("creator@example.com")).thenReturn(Optional.of(account)); + when(accountRepository.findByAccountUuidForUpdate(account.getAccountUuid())) + .thenReturn(Optional.of(account)); + IssuanceFence fence = new IssuanceFence(account.getAccountUuid(), 1L, 1L); + var snapshot = + new AccountAuthorityGenerationRepository.CompositeSnapshot( + new ScopeState( + AuthorityScope.issuer(AccountServiceImpl.ACCOUNT_JWT_ISSUER), 1L, 1L, null), + new ScopeState(AuthorityScope.account(account.getAccountUuid()), 1L, 1L, fence), + java.util.List.of(), + java.util.List.of(), + fence); + when(accountAuthorityGenerationRepository.readCompositeSnapshot( + AccountServiceImpl.ACCOUNT_JWT_ISSUER, + account.getAccountUuid(), + java.util.List.of(), + java.util.List.of())) + .thenReturn(snapshot); + var limiter = org.mockito.Mockito.mock(AccountPlatformAuthAbuseLimiter.class); + var operations = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository + .AccountControlUiCredentialOperationRepository.class); + UUID requestId = UUID.randomUUID(); + when(operations.recordVerifiedCredential( + org.mockito.ArgumentMatchers.eq(requestId), + org.mockito.ArgumentMatchers.eq(account), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + call -> + new net.firedevops.firemud.accountservice.repository + .AccountControlUiCredentialOperationRepository.RecordedAttempt( + UUID.randomUUID(), + UUID.randomUUID(), + ((Optional) call.getArgument(3)).isPresent() ? "EMAIL_OTP" : "PASSWORD", + java.time.Instant.now())); + service.configureControlUiAuthentication(limiter, operations); + return new ControlUiCredentialFixture(account, requestId, limiter, operations); + } + + private net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest + controlUiCredentialRequest( + UUID requestId, + String credential, + net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest.Purpose + purpose) { + return new net.firedevops.firemud.accountservice.service.controlui + .AccountControlUiAuthenticationRequest( + requestId, + "creator@example.com", + credential, + purpose, + new net.firedevops.firemud.accountservice.service.CredentialAttemptSource( + "198.51.100.7", + net.firedevops.firemud.accountservice.service.CredentialAttemptSource.ConnectionMode + .FIRST_PARTY_WEB)); + } + + private record ControlUiCredentialFixture( + Account account, + UUID requestId, + AccountPlatformAuthAbuseLimiter limiter, + net.firedevops.firemud.accountservice.repository.AccountControlUiCredentialOperationRepository + operations) {} + @Test void createAccountPersistsOnlyGlobalIdentity() { CreateAccountRequest request = diff --git a/services/common-data-runtime/src/main/java/net/firedevops/firemud/common/ratelimit/RateLimitSubjectHash.java b/services/common-data-runtime/src/main/java/net/firedevops/firemud/common/ratelimit/RateLimitSubjectHash.java new file mode 100644 index 0000000000..5c92f18b1a --- /dev/null +++ b/services/common-data-runtime/src/main/java/net/firedevops/firemud/common/ratelimit/RateLimitSubjectHash.java @@ -0,0 +1,363 @@ +package net.firedevops.firemud.common.ratelimit; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** Privacy-preserving subject hashing and key naming for isolated Redis rate-limit buckets. */ +public final class RateLimitSubjectHash { + private static final String SUBJECT_DOMAIN = "FireMUD/rateLimitSubject/v1"; + private static final String COLLISION_DOMAIN = "FireMUD/rateLimitSubjectCollisionCheck/v1"; + private static final Pattern KEY_ID = Pattern.compile("[a-z0-9][a-z0-9_-]{0,47}"); + private static final Pattern IPV4_CHARACTERS = Pattern.compile("[0-9.]+"); + private static final Pattern IPV6_CHARACTERS = Pattern.compile("[0-9A-Fa-f:.]+"); + + private RateLimitSubjectHash() {} + + /** Explicit platform-auth dimensions; the empty tenant segment means no tenant is involved. */ + public enum PlatformAuthPolicy { + GLOBAL_PRESSURE("global-pressure", "global-pressure"), + SOURCE_ATTEMPT("client-address", "source-attempt"), + CANDIDATE_ATTEMPT("account-candidate", "candidate-attempt"), + SOURCE_FAILURE("client-address", "source-failure"), + CANDIDATE_FAILURE("account-candidate", "candidate-failure"); + + private final String subjectKind; + private final String policyScope; + + PlatformAuthPolicy(String subjectKind, String policyScope) { + this.subjectKind = subjectKind; + this.policyScope = "platform-auth/" + policyScope; + } + } + + /** Immutable active key material. Its printable form intentionally omits the secret bytes. */ + public static final class HmacKey { + private final String keyId; + private final byte[] material; + + public HmacKey(String keyId, byte[] material) { + if (keyId == null || !KEY_ID.matcher(keyId).matches()) { + throw new IllegalArgumentException("rate-limit HMAC key ID is invalid"); + } + if (material == null || material.length != 32) { + throw new IllegalArgumentException("rate-limit HMAC key must contain exactly 32 bytes"); + } + this.keyId = keyId; + this.material = material.clone(); + } + + public String keyId() { + return keyId; + } + + private byte[] material() { + return material.clone(); + } + + @Override + public String toString() { + return "HmacKey[keyId=" + keyId + ", material=redacted]"; + } + } + + /** Two full-length keyed digests: one names the bucket and one detects a detected collision. */ + public record Digest(String subjectHash, String collisionFingerprint) { + public Digest { + Objects.requireNonNull(subjectHash, "subjectHash must not be null"); + Objects.requireNonNull(collisionFingerprint, "collisionFingerprint must not be null"); + } + } + + /** Hashes an explicitly typed platform-auth subject using the canonical framed HMAC preimage. */ + public static Digest platformAuthSubject( + HmacKey key, PlatformAuthPolicy policy, byte[] canonicalSubjectBytes) { + Objects.requireNonNull(policy, "policy must not be null"); + return hash(key, policy.subjectKind, "", policy.policyScope, canonicalSubjectBytes); + } + + /** Hashes a tenant subject without changing the established tenant key dimensions. */ + public static Digest tenantSubject( + HmacKey key, + String subjectKind, + String tenantId, + String policyScope, + byte[] canonicalSubjectBytes) { + if (tenantId == null || tenantId.isBlank() || tenantId.indexOf(':') >= 0) { + throw new IllegalArgumentException("tenant ID must be non-blank and key-safe"); + } + return hash(key, subjectKind, tenantId, policyScope, canonicalSubjectBytes); + } + + /** Canonical tenant-family key shape: ratelimit:::. */ + public static String tenantBucketKey(String tenantId, Digest digest, long timeWindow) { + if (tenantId == null || tenantId.isBlank() || tenantId.indexOf(':') >= 0 || timeWindow < 0) { + throw new IllegalArgumentException("tenant bucket dimensions are invalid"); + } + Objects.requireNonNull(digest, "digest must not be null"); + return "ratelimit:" + tenantId + ":" + digest.subjectHash() + ":" + timeWindow; + } + + /** Distinct, versioned namespace for Account's pre-tenant platform-auth windows. */ + public static String platformAuthBucketKey(Digest digest, long timeWindow) { + if (timeWindow < 0) { + throw new IllegalArgumentException("time window must not be negative"); + } + Objects.requireNonNull(digest, "digest must not be null"); + return "ratelimit:platform-auth:v1:" + digest.subjectHash() + ":" + timeWindow; + } + + /** Returns canonical network bytes without performing DNS lookup. Mapped IPv6 becomes IPv4. */ + public static byte[] canonicalClientAddressBytes(String address) { + byte[] parsed = parseLiteralAddress(address); + if (parsed.length == 16 && isIpv4MappedIpv6(parsed)) { + return Arrays.copyOfRange(parsed, 12, 16); + } + return parsed; + } + + /** Checks the wire-format canonical address using only numeric parsing, never name resolution. */ + public static boolean isCanonicalClientAddressLiteral(String address) { + try { + byte[] parsed = parseLiteralAddress(address); + return address.equals(InetAddress.getByAddress(parsed).getHostAddress()); + } catch (IllegalArgumentException | UnknownHostException ignored) { + return false; + } + } + + private static Digest hash( + HmacKey key, + String subjectKind, + String tenantId, + String policyScope, + byte[] canonicalSubjectBytes) { + Objects.requireNonNull(key, "key must not be null"); + requireAsciiToken(subjectKind, "subject kind"); + requireAsciiToken(policyScope, "policy scope"); + Objects.requireNonNull(tenantId, "tenant ID must not be null"); + Objects.requireNonNull(canonicalSubjectBytes, "canonical subject bytes must not be null"); + + byte[] framedSubject = + framedPreimage( + SUBJECT_DOMAIN, key.keyId(), subjectKind, tenantId, policyScope, canonicalSubjectBytes); + byte[] framedCollision = + framedPreimage( + COLLISION_DOMAIN, + key.keyId(), + subjectKind, + tenantId, + policyScope, + canonicalSubjectBytes); + String keyPrefix = "rsh-v1-" + key.keyId() + "-"; + String collisionPrefix = "rsc-v1-" + key.keyId() + "-"; + return new Digest( + keyPrefix + lowerHex(hmacSha256(key.material(), framedSubject)), + collisionPrefix + lowerHex(hmacSha256(key.material(), framedCollision))); + } + + static byte[] framedPreimage( + String domain, + String keyId, + String subjectKind, + String tenantId, + String policyScope, + byte[] canonicalSubjectBytes) { + List segments = + List.of( + utf8(domain), + utf8(keyId), + utf8(subjectKind), + utf8(tenantId), + utf8(policyScope), + canonicalSubjectBytes.clone()); + int length = + segments.stream().mapToInt(bytes -> decimalLength(bytes.length) + 1 + bytes.length).sum(); + ByteBuffer preimage = ByteBuffer.allocate(length); + for (byte[] segment : segments) { + preimage.put(utf8(Integer.toString(segment.length))); + preimage.put((byte) ':'); + preimage.put(segment); + } + return preimage.array(); + } + + private static int decimalLength(int value) { + return Integer.toString(value).length(); + } + + static byte[] hmacSha256(byte[] key, byte[] value) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(key, "HmacSHA256")); + return mac.doFinal(value); + } catch (GeneralSecurityException ex) { + throw new IllegalStateException("HMAC-SHA-256 is unavailable", ex); + } + } + + private static void requireAsciiToken(String value, String label) { + if (value == null + || value.isBlank() + || !value.chars().allMatch(character -> character >= 0x21 && character <= 0x7e) + || value.indexOf(':') >= 0) { + throw new IllegalArgumentException(label + " must be a non-blank printable ASCII token"); + } + } + + private static byte[] utf8(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String lowerHex(byte[] bytes) { + char[] encoded = new char[bytes.length * 2]; + final char[] digits = "0123456789abcdef".toCharArray(); + for (int index = 0; index < bytes.length; index++) { + int value = bytes[index] & 0xff; + encoded[index * 2] = digits[value >>> 4]; + encoded[index * 2 + 1] = digits[value & 0x0f]; + } + return new String(encoded); + } + + private static byte[] parseLiteralAddress(String address) { + if (address == null + || address.isEmpty() + || !address.equals(address.trim()) + || address.indexOf('%') >= 0 + || address.indexOf('[') >= 0 + || address.indexOf(']') >= 0) { + throw new IllegalArgumentException("client address must be a literal IP address"); + } + if (address.indexOf(':') < 0) { + if (!IPV4_CHARACTERS.matcher(address).matches()) { + throw new IllegalArgumentException("client address must be a literal IP address"); + } + return parseIpv4(address); + } + if (!IPV6_CHARACTERS.matcher(address).matches()) { + throw new IllegalArgumentException("client address must be a literal IP address"); + } + return parseIpv6(address); + } + + private static byte[] parseIpv4(String address) { + String[] octets = address.split("\\.", -1); + if (octets.length != 4) { + throw new IllegalArgumentException("client IPv4 address is invalid"); + } + byte[] bytes = new byte[4]; + for (int index = 0; index < octets.length; index++) { + String octet = octets[index]; + if (octet.isEmpty() || octet.length() > 3 || (octet.length() > 1 && octet.startsWith("0"))) { + throw new IllegalArgumentException("client IPv4 address is invalid"); + } + int value = 0; + for (int characterIndex = 0; characterIndex < octet.length(); characterIndex++) { + char character = octet.charAt(characterIndex); + if (character < '0' || character > '9') { + throw new IllegalArgumentException("client IPv4 address is invalid"); + } + value = value * 10 + character - '0'; + } + if (value > 255) { + throw new IllegalArgumentException("client IPv4 address is invalid"); + } + bytes[index] = (byte) value; + } + return bytes; + } + + private static byte[] parseIpv6(String address) { + int compression = address.indexOf("::"); + if (compression >= 0 && address.indexOf("::", compression + 2) >= 0) { + throw new IllegalArgumentException("client IPv6 address is invalid"); + } + int finalColon = address.lastIndexOf(':'); + if (address.indexOf('.') >= 0 + && (address.lastIndexOf('.') < finalColon + || (compression >= 0 && address.lastIndexOf('.') < compression))) { + throw new IllegalArgumentException("client IPv6 address is invalid"); + } + String leftText = compression < 0 ? address : address.substring(0, compression); + String rightText = compression < 0 ? "" : address.substring(compression + 2); + List left = parseIpv6Groups(leftText); + List right = parseIpv6Groups(rightText); + boolean hasCompression = compression >= 0; + int groupCount = left.size() + right.size(); + int zeroGroups = hasCompression ? 8 - groupCount : 0; + if ((hasCompression && zeroGroups < 1) || (!hasCompression && groupCount != 8)) { + throw new IllegalArgumentException("client IPv6 address is invalid"); + } + List groups = new ArrayList<>(8); + groups.addAll(left); + for (int index = 0; index < zeroGroups; index++) { + groups.add(0); + } + groups.addAll(right); + if (groups.size() != 8) { + throw new IllegalArgumentException("client IPv6 address is invalid"); + } + byte[] bytes = new byte[16]; + for (int index = 0; index < groups.size(); index++) { + int group = groups.get(index); + bytes[index * 2] = (byte) (group >>> 8); + bytes[index * 2 + 1] = (byte) group; + } + return bytes; + } + + private static List parseIpv6Groups(String text) { + if (text.isEmpty()) { + return List.of(); + } + String[] tokens = text.split(":", -1); + List groups = new ArrayList<>(tokens.length + 1); + for (int index = 0; index < tokens.length; index++) { + String token = tokens[index]; + if (token.isEmpty()) { + throw new IllegalArgumentException("client IPv6 address is invalid"); + } + if (token.indexOf('.') >= 0) { + if (index != tokens.length - 1) { + throw new IllegalArgumentException("client IPv6 address is invalid"); + } + byte[] ipv4 = parseIpv4(token); + groups.add(((ipv4[0] & 0xff) << 8) | (ipv4[1] & 0xff)); + groups.add(((ipv4[2] & 0xff) << 8) | (ipv4[3] & 0xff)); + continue; + } + if (token.length() > 4) { + throw new IllegalArgumentException("client IPv6 address is invalid"); + } + int group = 0; + for (int characterIndex = 0; characterIndex < token.length(); characterIndex++) { + int digit = Character.digit(token.charAt(characterIndex), 16); + if (digit < 0) { + throw new IllegalArgumentException("client IPv6 address is invalid"); + } + group = (group << 4) | digit; + } + groups.add(group); + } + return groups; + } + + private static boolean isIpv4MappedIpv6(byte[] bytes) { + for (int index = 0; index < 10; index++) { + if (bytes[index] != 0) { + return false; + } + } + return (bytes[10] & 0xff) == 0xff && (bytes[11] & 0xff) == 0xff; + } +} diff --git a/services/common-data-runtime/src/test/java/net/firedevops/firemud/common/ratelimit/RateLimitSubjectHashTest.java b/services/common-data-runtime/src/test/java/net/firedevops/firemud/common/ratelimit/RateLimitSubjectHashTest.java new file mode 100644 index 0000000000..f7220857c3 --- /dev/null +++ b/services/common-data-runtime/src/test/java/net/firedevops/firemud/common/ratelimit/RateLimitSubjectHashTest.java @@ -0,0 +1,181 @@ +package net.firedevops.firemud.common.ratelimit; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +class RateLimitSubjectHashTest { + private static final RateLimitSubjectHash.HmacKey KEY = + new RateLimitSubjectHash.HmacKey( + "test-1", + new byte[] { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 + }); + + @Test + void hmacSha256MatchesRfc4231GoldenVector() { + byte[] key = new byte[20]; + Arrays.fill(key, (byte) 0x0b); + + byte[] result = + RateLimitSubjectHash.hmacSha256(key, "Hi There".getBytes(StandardCharsets.US_ASCII)); + + assertEquals( + "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7", lowerHex(result)); + } + + @Test + void platformAuthPreimageMatchesTheFramedGoldenVector() { + byte[] expected = + concat( + ascii("27:FireMUD/rateLimitSubject/v1"), + ascii("6:test-1"), + ascii("14:client-address"), + ascii("0:"), + ascii("28:platform-auth/source-attempt"), + ascii("4:"), + new byte[] {(byte) 203, 0, 113, 9}); + + byte[] actual = + RateLimitSubjectHash.framedPreimage( + "FireMUD/rateLimitSubject/v1", + "test-1", + "client-address", + "", + "platform-auth/source-attempt", + new byte[] {(byte) 203, 0, 113, 9}); + + assertArrayEquals(expected, actual); + } + + @Test + void subjectAndCollisionDigestsAreFullLengthAndDomainSeparated() { + var source = + RateLimitSubjectHash.platformAuthSubject( + KEY, + RateLimitSubjectHash.PlatformAuthPolicy.SOURCE_ATTEMPT, + RateLimitSubjectHash.canonicalClientAddressBytes("203.0.113.9")); + var failure = + RateLimitSubjectHash.platformAuthSubject( + KEY, + RateLimitSubjectHash.PlatformAuthPolicy.SOURCE_FAILURE, + RateLimitSubjectHash.canonicalClientAddressBytes("203.0.113.9")); + + assertTrue(source.subjectHash().matches("rsh-v1-test-1-[0-9a-f]{64}")); + assertTrue(source.collisionFingerprint().matches("rsc-v1-test-1-[0-9a-f]{64}")); + assertNotEquals(source.subjectHash(), source.collisionFingerprint()); + assertNotEquals(source.subjectHash(), failure.subjectHash()); + assertNotEquals(source.collisionFingerprint(), failure.collisionFingerprint()); + } + + @Test + void activeKeyRotationChangesOpaqueSubjectAndCollisionDigests() { + var subject = RateLimitSubjectHash.canonicalClientAddressBytes("203.0.113.9"); + var first = + RateLimitSubjectHash.platformAuthSubject( + KEY, RateLimitSubjectHash.PlatformAuthPolicy.SOURCE_ATTEMPT, subject); + var rotated = + RateLimitSubjectHash.platformAuthSubject( + new RateLimitSubjectHash.HmacKey( + "test-2", + new byte[] { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32 + }), + RateLimitSubjectHash.PlatformAuthPolicy.SOURCE_ATTEMPT, + subject); + + assertNotEquals(first.subjectHash(), rotated.subjectHash()); + assertNotEquals(first.collisionFingerprint(), rotated.collisionFingerprint()); + assertTrue(RateLimitSubjectHash.platformAuthBucketKey(first, 17L).contains(":rsh-v1-test-1-")); + assertTrue( + RateLimitSubjectHash.platformAuthBucketKey(rotated, 17L).contains(":rsh-v1-test-2-")); + } + + @Test + void ipv4MappedIpv6AndIpv4HaveTheSameCanonicalNetworkBytes() { + assertArrayEquals( + RateLimitSubjectHash.canonicalClientAddressBytes("192.0.2.44"), + RateLimitSubjectHash.canonicalClientAddressBytes("0:0:0:0:0:ffff:c000:22c")); + assertArrayEquals( + RateLimitSubjectHash.canonicalClientAddressBytes("192.0.2.44"), + RateLimitSubjectHash.canonicalClientAddressBytes("::ffff:192.0.2.44")); + } + + @Test + void literalParserRejectsDnsNamesAndNonCanonicalWireAddressesWithoutResolution() { + assertThrows( + IllegalArgumentException.class, + () -> RateLimitSubjectHash.canonicalClientAddressBytes("example.invalid")); + assertThrows( + IllegalArgumentException.class, + () -> RateLimitSubjectHash.canonicalClientAddressBytes("192.000.2.1")); + assertTrue(RateLimitSubjectHash.isCanonicalClientAddressLiteral("203.0.113.9")); + } + + @Test + void tenantKeyShapeRemainsSeparateFromTypedPlatformAuthNamespace() { + var tenantDigest = + RateLimitSubjectHash.tenantSubject( + KEY, + "client-address", + "tenant-7", + "login", + RateLimitSubjectHash.canonicalClientAddressBytes("203.0.113.9")); + var platformDigest = + RateLimitSubjectHash.platformAuthSubject( + KEY, + RateLimitSubjectHash.PlatformAuthPolicy.SOURCE_ATTEMPT, + RateLimitSubjectHash.canonicalClientAddressBytes("203.0.113.9")); + + assertEquals( + "ratelimit:tenant-7:" + tenantDigest.subjectHash() + ":42", + RateLimitSubjectHash.tenantBucketKey("tenant-7", tenantDigest, 42L)); + assertTrue( + RateLimitSubjectHash.platformAuthBucketKey(platformDigest, 42L) + .startsWith("ratelimit:platform-auth:v1:rsh-v1-test-1-")); + assertNotEquals( + RateLimitSubjectHash.tenantBucketKey("tenant-7", tenantDigest, 42L), + RateLimitSubjectHash.platformAuthBucketKey(platformDigest, 42L)); + } + + @Test + void keyMaterialAndScopeInputsAreValidated() { + assertThrows( + IllegalArgumentException.class, + () -> new RateLimitSubjectHash.HmacKey("invalid:key", new byte[32])); + assertThrows( + IllegalArgumentException.class, + () -> new RateLimitSubjectHash.HmacKey("test-1", new byte[31])); + } + + private static byte[] concat(byte[]... values) { + int length = Arrays.stream(values).mapToInt(value -> value.length).sum(); + byte[] result = new byte[length]; + int offset = 0; + for (byte[] value : values) { + System.arraycopy(value, 0, result, offset, value.length); + offset += value.length; + } + return result; + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String lowerHex(byte[] bytes) { + StringBuilder output = new StringBuilder(bytes.length * 2); + for (byte value : bytes) { + output.append(String.format("%02x", value & 0xff)); + } + return output.toString(); + } +} From 8392f8ef2ee224296b75c5c1da28115a74fe48cc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 18:48:38 +1300 Subject: [PATCH 07/12] Prove real control-ui credentials and unsigned Account source reads --- .github/workflows/ci.yml | 12 +- .../player-access-and-session.md | 4 + ...countControlUiCurrentSourceRepository.java | 96 ++-- ...iCurrentSourcePostgresIntegrationTest.java | 154 +++++- ...lProducerPostgresRedisIntegrationTest.java | 457 ++++++++++++++++++ 5 files changed, 680 insertions(+), 43 deletions(-) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f43743bf5e..ac7411f514 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2492,6 +2492,8 @@ jobs: --require-suite integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest \ --require-suite integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest \ --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#unsignedInitialObservationReadsExactExistingAccountSourcesAndFenceWithoutEnrollment()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#unsignedObservationRetainsAdvancedIssuerEventAndSignedInspectionStillChecksCorrespondence()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#originalCallerAndFamilyBindingsCannotBeChangedOnRetry()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#concurrentExactClaimsSerializeToOneOriginalRequest()' \ @@ -2550,7 +2552,9 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: account-control-ui-credential-postgresql-proof-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} - path: services/account-service/build/test-results/integrationTest/TEST-*AccountControlUiCredentialAuthenticationPostgresIntegrationTest.xml + path: | + services/account-service/build/test-results/integrationTest/TEST-*AccountControlUiCredentialAuthenticationPostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountControlUiCredentialProducerPostgresRedisIntegrationTest.xml if-no-files-found: warn retention-days: 7 @@ -2560,6 +2564,12 @@ jobs: bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.service.impl.AccountControlUiCredentialProducerPostgresRedisIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.service.impl.AccountControlUiCredentialProducerPostgresRedisIntegrationTest#actualPasswordRecordsFreshEvidenceAgainstExactPendingOperationWithoutJwtOutcome()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.service.impl.AccountControlUiCredentialProducerPostgresRedisIntegrationTest#actualOtpConsumesExactChallengeOnceAndConsumedRetryAddsNoCredentialEvidence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.service.impl.AccountControlUiCredentialProducerPostgresRedisIntegrationTest#invalidPasswordAndOtpLeaveIssuanceAndEvidenceUnchangedAndUseRealFailureBuckets()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.service.impl.AccountControlUiCredentialProducerPostgresRedisIntegrationTest#wrongOriginalOperationBindingPreservesEligibleOtpAndCredentialEvidence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.service.impl.AccountControlUiCredentialProducerPostgresRedisIntegrationTest#committedUnexpiredResponseRecoveryAuthenticatesAgainWithoutChangingOriginalResponse()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest#v67ToV68UpgradePreservesNonemptyPendingCommittedAndEncryptedOriginalImages()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest#exactPasswordAndOtpEvidenceBindOriginalOperationAndFreshRecoveryRemainsSeparate()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest#wrongAccountRequestDigestAndMissingOriginalDenyWithoutCredentialEvidence()' \ 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 84a2a3a159..aa047d69d5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +Five additional PostgreSQL/Cache Redis definitions call the real Account credential producer, persisted Account/authority/challenge owners, Argon2 verifier and shared abuse limiter. They cover password evidence without a JWT outcome, exact single-use OTP and consumed-retry denial, invalid-credential counters with no issuance/evidence change, wrong-original-operation rollback, and fresh password authentication against an unexpired committed response. Only unused remote clients and mail are mocked. The original V66 capture, trusted first-party source descriptor and committed response remain explicit fixtures: this is not authenticated initial capture, a public route, signer/registry or response release. CI captures and strictly requires their executed XML; local Docker-dependent execution remains unavailable. + +The existing-only unscoped control-ui source reader now has a pre-sign entry, `readUnscopedCurrent`, independent of an already signed candidate. It retains issuer-first locking, Account provenance, fresh-empty roles, exact source history/checkpoints and the issuance fence in one writable owner transaction; signed inspection delegates to it and still compares every represented claim and registry source version. Two additional PostgreSQL definitions cover fresh non-mutating readback and advanced issuer evidence with mismatched signed inputs, while the existing denial cases also exercise unsigned reads. Strict CI requires all ten source-observation methods. This is a non-authorizing observation, not a complete durable capture, authenticated caller, current Coordination projection, signer or released credential; new PostgreSQL execution remains open. + The targetless control-ui credential component uses the existing Account password/OTP verifier and trusted first-party credential-attempt limiter, then records fresh credential evidence against an existing V66 operation. V68 retains that immutable evidence and atomically consumes only the exact eligible OTP challenge; it introduces no second issuance owner, plaintext credential, token or authority capture. Initial attempts require the original pending operation; response-recovery attempts require its unexpired committed result and authenticate again. Seven PostgreSQL definitions cover nonempty V67-to-V68 preservation, binding and lifecycle denial, exact challenge predicates, late-insert rollback, database-observed competing claims and immutability. Their original captures and verifier results are stipulated repository fixtures, not complete authenticated issuance. The closed control-ui inspection now requires the canonical capture `sourceFence`, independently of source versions and issuance fence, with exact large-decimal and incomplete-reference rejection tests. The composed five-module check, three service boot JARs, Account and Game Design jOOQ, formatting, Checkstyle, SpotBugs, links and Markdown pass in 1m45s (160 tasks: 21 executed). Account has 1054 clean unit outcomes; Common Platform Core 253 and Common Data Runtime 16 are clean reused results. Game Design has 542 executed unit cases and one object-store skip; World has 346 clean unit outcomes. All 714 integration cases skip without Docker (Account 443, Game Design 145 and World 126), including the seven new credential cases. The later physical Account reservation-client proof is outside this validated snapshot. The actual original capture producer, signer and pending/active registry composition, complete currentness, protected ring delivery and original-response release remain open. This component is not exposed as an enabled login route and does not grant creator or gameplay authority; executed PostgreSQL and activation evidence remain required. At published `c459bfd672d99fcd6858011caaf08c954bda2629`, V66 uses a PostgreSQL constraint trigger for its deferred exact-envelope requirement. The prior exact `e057e1f873753fe7141a53a1e65f2c9f214b1d38` [CI37414054058](https://github.com/benhook1013/FireMUD/actions/runs/37414054058) failed migration on the ordinary trigger's unsupported `DEFERRABLE` syntax: fifteen Account cases were reported, eleven failed startup, and the thirty-four required V65/V66/current-source/creation-order cases supplied no execution XML. Corrected-source [CI37415795444](https://github.com/benhook1013/FireMUD/actions/runs/37415795444) executes the twenty-seven V65/V66/current-source methods with zero skips: seventeen pass and ten fail. All eight current-source cases pass. The seven tenant-creation cases pass without skips according to their exact selector step and HTML report; standalone raw XML for that suite is unavailable. V66's additive migration succeeds, but its completion repository binds timestamps as varchar, and the missing-envelope negative also fails on that type mismatch before the deferred commit guard. Seven V65 failures come from the fixture storing event-array order instead of the canonical login-mode database representation. The correction adds explicit timestamp casts and uses the existing login-mode storage serializer without changing event digests, database guards or immutable readback. Its prepared V68 challenge queries use explicit timestamp-without-zone casts as well. Corrected PostgreSQL execution, genuine missing-envelope commit rejection and activation remain unproved; the aggregate run is separate from these executed component results. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java index 2ef33ce9f6..34b63d30be 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourceRepository.java @@ -65,10 +65,7 @@ public AccountControlUiCurrentSourceRepository( */ @Transactional(propagation = Propagation.MANDATORY) public CurrentSourceObservation inspectUnscopedCurrent(InspectedToken candidate) { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { - throw invalid(); - } + requireWritableOwnerTransaction(); Objects.requireNonNull(candidate); Map claims = candidate.claims(); if (!Map.of().equals(claims.get("scopedRoles")) @@ -76,14 +73,56 @@ public CurrentSourceObservation inspectUnscopedCurrent(InspectedToken candidate) || (claims.containsKey("globalRoles") && !List.of().equals(claims.get("globalRoles")))) { throw invalid(); } + CurrentSourceObservation observation = readUnscopedCurrent(candidate.accountId()); + CompositeSnapshot current = observation.authority(); + Map tuple = new java.util.LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", Long.toString(current.issuer().generation())); + tuple.put("accountAuthorityGeneration", Long.toString(current.account().generation())); + tuple.put("tenantAuthorityGeneration", Map.of()); + tuple.put("membershipAuthorityGeneration", Map.of()); + tuple.put("privateRealmGrantVersions", List.of()); + observation + .accountSource() + .latestEvent() + .ifPresent( + event -> { + try { + Map wire = + JSON.readValue(event.payload(), new TypeReference<>() {}); + tuple.put("accountSecurityCutoff", wire.get("accountSecurityCutoff")); + } catch (IOException failure) { + throw invalid(); + } + }); + requireEqual(tuple, claims.get("authorityTuple")); + requireEqual(Long.toString(current.issuanceFence().value()), claims.get("issuanceFence")); + Map expectedVersions = + Map.of( + "issuerSourceVersion", current.issuer().sourceVersion(), + "accountSourceVersion", current.account().sourceVersion(), + "issuanceFenceSourceVersion", current.issuanceFence().sourceVersion()); + requireEqual(expectedVersions, candidate.registryRecord().get("authoritySourceVersions")); + return observation; + } + + /** + * Reads existing unscoped source rows before signing in the caller's writable Account + * transaction. The Account identity is a lookup key, not an authenticated principal. This + * observation is not a complete evidence bundle, current Coordination projection, credential or + * token authority. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CurrentSourceObservation readUnscopedCurrent(UUID accountId) { + requireWritableOwnerTransaction(); + Objects.requireNonNull(accountId); // Lock issuer first, preserving the composite source-writer lock order. Both issuer history // and recipient evidence remain fenced until this same Account transaction finishes. IssuerAuthoritySnapshot issuer = issuerSource.readCurrentInAccountSnapshot(ControlUiJwtProfileValidator.ISSUER); - FreshEmptySource roles = globalRoles.readFreshEmptySourceForUpdate(candidate.accountId()); + FreshEmptySource roles = globalRoles.readFreshEmptySourceForUpdate(accountId); Account account = accounts - .findByAccountUuidForUpdate(candidate.accountId()) + .findByAccountUuidForUpdate(accountId) .orElseThrow(AccountControlUiCurrentSourceRepository::invalid); if (account.getLifecycleState() != AccountLifecycleState.ACTIVE || !roles.accountUuid().equals(account.getAccountUuid()) @@ -94,13 +133,13 @@ public CurrentSourceObservation inspectUnscopedCurrent(InspectedToken candidate) || roles.accountRowId() != account.getId()) throw invalid(); CompositeSnapshot current = generations.readCompositeSnapshot( - ControlUiJwtProfileValidator.ISSUER, candidate.accountId(), List.of(), List.of()); + ControlUiJwtProfileValidator.ISSUER, accountId, List.of(), List.of()); if (issuer.issuerAuthGeneration() != current.issuer().generation() || issuer.sourceVersion() != current.issuer().sourceVersion()) { throw invalid(); } var latest = accountSource.requireCurrentLatest(account, current.account()); - String stream = "account:auth-authority:v1:account/" + candidate.accountId(); + String stream = "account:auth-authority:v1:account/" + accountId; if (latest.outboxSequence() == 0L) { Long events = Objects.requireNonNull( @@ -114,39 +153,16 @@ public CurrentSourceObservation inspectUnscopedCurrent(InspectedToken candidate) } AccountSourceSnapshot source = new AccountSourceSnapshot( - candidate.accountId(), - current.account(), - stream, - latest.outboxSequence(), - latest.latestEvent()); - Map tuple = new java.util.LinkedHashMap<>(); - tuple.put("issuerAuthGeneration", Long.toString(current.issuer().generation())); - tuple.put("accountAuthorityGeneration", Long.toString(current.account().generation())); - tuple.put("tenantAuthorityGeneration", Map.of()); - tuple.put("membershipAuthorityGeneration", Map.of()); - tuple.put("privateRealmGrantVersions", List.of()); - latest - .latestEvent() - .ifPresent( - event -> { - try { - Map wire = - JSON.readValue(event.payload(), new TypeReference<>() {}); - tuple.put("accountSecurityCutoff", wire.get("accountSecurityCutoff")); - } catch (IOException failure) { - throw invalid(); - } - }); - requireEqual(tuple, claims.get("authorityTuple")); - requireEqual(Long.toString(current.issuanceFence().value()), claims.get("issuanceFence")); - Map expectedVersions = - Map.of( - "issuerSourceVersion", current.issuer().sourceVersion(), - "accountSourceVersion", current.account().sourceVersion(), - "issuanceFenceSourceVersion", current.issuanceFence().sourceVersion()); - requireEqual(expectedVersions, candidate.registryRecord().get("authoritySourceVersions")); + accountId, current.account(), stream, latest.outboxSequence(), latest.latestEvent()); return new CurrentSourceObservation( - candidate.accountId(), current, issuer, source, roles.globalRoleSourceVersion()); + accountId, current, issuer, source, roles.globalRoleSourceVersion()); + } + + private static void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw invalid(); + } } private static void requireEqual(Object left, Object right) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java index 6ffed179bd..1d7a601ff1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCurrentSourcePostgresIntegrationTest.java @@ -51,6 +51,116 @@ class AccountControlUiCurrentSourcePostgresIntegrationTest { @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + @Test + void unsignedInitialObservationReadsExactExistingAccountSourcesAndFenceWithoutEnrollment() { + Fixture fixture = fixture(true); + var accountBefore = + fixture + .dsl() + .fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", fixture.accountId()); + var rolesBefore = + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_global_role_sources WHERE account_uuid = ?", + fixture.accountId()); + assertThat(accountBefore).isNotNull(); + assertThat(rolesBefore).isNotNull(); + assertThat(accountBefore.get("account_uuid", UUID.class)).isEqualTo(fixture.accountId()); + assertThat(accountBefore.get("account_uuid_source_numeric_id", Long.class)) + .isEqualTo(accountBefore.get("id", Long.class)); + assertThat(accountBefore.get("account_uuid_provenance", String.class)) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + assertThat(rolesBefore.get("account_uuid_source_numeric_id", Long.class)) + .isEqualTo(accountBefore.get("account_uuid_source_numeric_id", Long.class)); + assertThat(rolesBefore.get("account_uuid_provenance", String.class)) + .isEqualTo(accountBefore.get("account_uuid_provenance", String.class)); + Long generationCount = count(fixture.dsl(), "account_authority_generations"); + Long fenceCount = count(fixture.dsl(), "account_authority_issuance_fences"); + var observation = + fixture.tx().execute(status -> fixture.source().readUnscopedCurrent(fixture.accountId())); + assertThat(observation).isNotNull(); + assertThat(observation.accountId()).isEqualTo(fixture.accountId()); + assertThat(observation.authority().issuer().scope()).isEqualTo(AuthorityScope.issuer(ISSUER)); + assertThat(observation.authority().issuer().generation()).isEqualTo(1L); + assertThat(observation.authority().issuer().sourceVersion()).isEqualTo(1L); + assertThat(observation.authority().account().scope()) + .isEqualTo(AuthorityScope.account(fixture.accountId())); + assertThat(observation.authority().account().generation()).isEqualTo(1L); + assertThat(observation.authority().account().sourceVersion()).isEqualTo(1L); + assertThat(observation.authority().tenants()).isEmpty(); + assertThat(observation.authority().memberships()).isEmpty(); + assertThat(observation.authority().issuanceFence().accountId()).isEqualTo(fixture.accountId()); + assertThat(observation.authority().issuanceFence().value()).isEqualTo(1L); + assertThat(observation.authority().issuanceFence().sourceVersion()).isEqualTo(1L); + assertThat(observation.accountSource().sourceState()) + .isEqualTo(observation.authority().account()); + assertThat(observation.accountSource().outboxStreamKey()) + .isEqualTo("account:auth-authority:v1:account/" + fixture.accountId()); + assertThat(observation.accountSource().outboxSequence()).isZero(); + assertThat(observation.accountSource().latestEvent()).isEmpty(); + assertThat(observation.issuerSource().issuerAuthGeneration()).isEqualTo(1L); + assertThat(observation.issuerSource().sourceVersion()).isEqualTo(1L); + assertThat(observation.issuerSource().outboxSequence()).isZero(); + assertThat(observation.issuerSource().latestEvent()).isEmpty(); + assertThat(observation.globalRoleSourceVersion()).isEqualTo(1L); + assertThat(observation.toString()).contains("non-authorizing"); + assertThat( + fixture + .dsl() + .fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", fixture.accountId())) + .isEqualTo(accountBefore); + assertThat( + fixture + .dsl() + .fetchOne( + "SELECT * FROM account_global_role_sources WHERE account_uuid = ?", + fixture.accountId())) + .isEqualTo(rolesBefore); + assertThat(count(fixture.dsl(), "account_authority_generations")).isEqualTo(generationCount); + assertThat(count(fixture.dsl(), "account_authority_issuance_fences")).isEqualTo(fenceCount); + assertThat(count(fixture.dsl(), "account_authority_outbox_events")).isZero(); + } + + @Test + void unsignedObservationRetainsAdvancedIssuerEventAndSignedInspectionStillChecksCorrespondence() + throws Exception { + Fixture fixture = fixture(true); + var event = fixture.issuer().advance(ISSUER, UUID.randomUUID(), 1L, 1L); + var observation = + fixture.tx().execute(status -> fixture.source().readUnscopedCurrent(fixture.accountId())); + assertThat(observation).isNotNull(); + assertThat(observation.issuerSource().issuerAuthGeneration()).isEqualTo(2L); + assertThat(observation.issuerSource().sourceVersion()).isEqualTo(2L); + assertThat(observation.issuerSource().outboxSequence()).isEqualTo(1L); + var retained = observation.issuerSource().latestEvent().orElseThrow(); + assertThat(retained.canonicalJsonUtf8()).isEqualTo(event.canonicalJsonUtf8()); + assertThat(retained.eventId()).isEqualTo(event.eventId()); + assertThat(retained.eventDigest()).isEqualTo(event.eventDigest()); + var exact = candidate(fixture.accountId(), 2L); + var exactObservation = + fixture.tx().execute(status -> fixture.source().inspectUnscopedCurrent(exact)); + assertThat(exactObservation).isNotNull(); + var prior = candidate(fixture.accountId()); + assertThatThrownBy( + () -> fixture.tx().execute(status -> fixture.source().inspectUnscopedCurrent(prior))) + .isInstanceOf(IllegalStateException.class); + for (long[] changed : + java.util.List.of( + new long[] {2L, 1L, 1L, 1L}, + new long[] {1L, 2L, 1L, 1L}, + new long[] {1L, 1L, 2L, 1L}, + new long[] {1L, 1L, 1L, 2L})) { + var mismatch = + candidate(fixture.accountId(), 2L, changed[0], changed[1], changed[2], changed[3]); + assertThatThrownBy( + () -> + fixture.tx().execute(status -> fixture.source().inspectUnscopedCurrent(mismatch))) + .isInstanceOf(IllegalStateException.class); + } + assertThat(count(fixture.dsl(), "account_authority_outbox_events")).isEqualTo(1L); + } + @Test void currentFreshSourceIsObservedAtOneOwnerTransactionWithoutEnrollmentOrMutation() throws Exception { @@ -103,6 +213,13 @@ void matchingAdvancedCountersWithoutTheirIssuerEventCannotProduceObservation() t .generations() .advance(fixture.generations().read(AuthorityScope.issuer(ISSUER)), null)); var matchingCounters = candidate(fixture.accountId(), 2L); + assertThatThrownBy( + () -> + fixture + .tx() + .execute(status -> fixture.source().readUnscopedCurrent(fixture.accountId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("sequence-zero"); assertThatThrownBy( () -> fixture @@ -150,6 +267,13 @@ void matchingCountersAndCheckpointCannotHideContradictoryIssuerEventDigest() thr event.canonicalJsonUtf8()); }); var matchingCounters = candidate(fixture.accountId(), 2L); + assertThatThrownBy( + () -> + fixture + .tx() + .execute(status -> fixture.source().readUnscopedCurrent(fixture.accountId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("contradict"); assertThatThrownBy( () -> fixture @@ -164,6 +288,12 @@ void matchingCountersAndCheckpointCannotHideContradictoryIssuerEventDigest() thr void missingAuthorityFailsWithoutInventingAnInitialGeneration() throws Exception { Fixture fixture = fixture(false); var candidate = candidate(fixture.accountId()); + assertThatThrownBy( + () -> + fixture + .tx() + .execute(status -> fixture.source().readUnscopedCurrent(fixture.accountId()))) + .isInstanceOf(IllegalStateException.class); assertThatThrownBy( () -> fixture.tx().execute(status -> fixture.source().inspectUnscopedCurrent(candidate))) @@ -177,10 +307,17 @@ void missingAuthorityFailsWithoutInventingAnInitialGeneration() throws Exception void absentOwnerTransactionAndReadOnlyTransactionCannotProduceObservation() throws Exception { Fixture fixture = fixture(true); var candidate = candidate(fixture.accountId()); + assertThatThrownBy(() -> fixture.source().readUnscopedCurrent(fixture.accountId())) + .isInstanceOf(IllegalStateException.class); assertThatThrownBy(() -> fixture.source().inspectUnscopedCurrent(candidate)) .isInstanceOf(IllegalStateException.class); TransactionTemplate readOnly = new TransactionTemplate(fixture.tx().getTransactionManager()); readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute( + status -> fixture.source().readUnscopedCurrent(fixture.accountId()))) + .isInstanceOf(IllegalStateException.class); assertThatThrownBy( () -> readOnly.execute(status -> fixture.source().inspectUnscopedCurrent(candidate))) .isInstanceOf(IllegalStateException.class); @@ -262,13 +399,26 @@ private static InspectedToken candidate(UUID accountId) throws Exception { } private static InspectedToken candidate(UUID accountId, long issuerVersion) throws Exception { + return candidate(accountId, issuerVersion, 1L, 1L, 1L, 1L); + } + + private static InspectedToken candidate( + UUID accountId, + long issuerVersion, + long issuanceFence, + long accountGeneration, + long accountSourceVersion, + long issuanceFenceSourceVersion) + throws Exception { var crypto = new AccountControlUiTokenFixture( Clock.fixed(AccountControlUiTokenFixture.NOW, ZoneOffset.UTC)); var claims = crypto.claims(accountId); + claims.put("issuanceFence", Long.toString(issuanceFence)); @SuppressWarnings("unchecked") var tuple = new java.util.LinkedHashMap<>((Map) claims.get("authorityTuple")); tuple.put("issuerAuthGeneration", Long.toString(issuerVersion)); + tuple.put("accountAuthorityGeneration", Long.toString(accountGeneration)); claims.put("authorityTuple", tuple); String token = crypto.sign(claims); var registry = crypto.registry(token, claims); @@ -278,9 +428,9 @@ private static InspectedToken candidate(UUID accountId, long issuerVersion) thro "issuerSourceVersion", issuerVersion, "accountSourceVersion", - 1L, + accountSourceVersion, "issuanceFenceSourceVersion", - 1L)); + issuanceFenceSourceVersion)); return crypto .checks() .inspect( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java new file mode 100644 index 0000000000..79f5f90021 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java @@ -0,0 +1,457 @@ +package integration.net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import de.mkammerer.argon2.Argon2; +import de.mkammerer.argon2.Argon2Factory; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.accountservice.AccountServiceApplication; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.config.PlatformAuthRateLimitProperties; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequest; +import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCredentialOperationRepository.CredentialOperationConflictException; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation.OriginalCapture; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.security.AccountControlUiResponseEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.service.CredentialAttemptSource; +import net.firedevops.firemud.accountservice.service.PlatformAuthBucketStore; +import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiAuthenticationRequest; +import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiAuthenticationRequest.Purpose; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountPlatformAuthAbuseLimiter; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl.ControlUiCredentialAuthentication; +import net.firedevops.firemud.common.ratelimit.RateLimitSubjectHash; +import net.firedevops.firemud.common.ratelimit.RateLimitSubjectHash.PlatformAuthPolicy; +import net.firedevops.firemud.test.GatewayTestProperties; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Runs the real Account credential producer against PostgreSQL, Argon2 verifiers and Cache Redis. + * The original V66 captures and FIRST_PARTY_WEB source descriptors are stipulated fixture inputs; + * this does not prove authenticated upstream capture, a public route, JWT/registry issuance or + * creator/gameplay authority. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.NONE, + classes = AccountServiceApplication.class, + properties = { + GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, + GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, + GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, + GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, + "firemud.grpc.workload-namespace=account-control-ui-credential-producer-test" + }) +class AccountControlUiCredentialProducerPostgresRedisIntegrationTest { + private static final String PASSWORD = "producer-integration-password"; + private static final String VALID_OTP = "482916"; + private static final String ABUSE_HMAC_KEY_ID = "credential-producer-test-key"; + private static final String ABUSE_HMAC_KEY_BASE64 = + Base64.getEncoder() + .encodeToString("0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8)); + private static final AtomicInteger NEXT_SOURCE_OCTET = new AtomicInteger(20); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + registry.add("firemud.account.platform-auth-abuse.cache-redis.host", redis::getHost); + registry.add( + "firemud.account.platform-auth-abuse.cache-redis.port", () -> redis.getMappedPort(6379)); + registry.add("firemud.account.platform-auth-abuse.hmac-key-id", () -> ABUSE_HMAC_KEY_ID); + registry.add( + "firemud.account.platform-auth-abuse.hmac-key-base64", () -> ABUSE_HMAC_KEY_BASE64); + registry.add("firemud.account.platform-auth-abuse.subject-window-seconds", () -> 3600); + } + + @TempDir Path tempDirectory; + + @Autowired private AccountServiceImpl accountService; + @Autowired private AccountRepository accountRepository; + @Autowired private AccountEmailLoginChallengeRepository challengeRepository; + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private PlatformAuthBucketStore authBuckets; + @Autowired private PlatformAuthRateLimitProperties authRateLimitProperties; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + private AccountControlUiIssuanceOperationRepository issuanceOperations; + private TransactionTemplate transaction; + + @BeforeEach + void initializeFixtureOwners() { + issuanceOperations = new AccountControlUiIssuanceOperationRepository(dsl); + transaction = new TransactionTemplate(transactionManager); + } + + @Test + void actualPasswordRecordsFreshEvidenceAgainstExactPendingOperationWithoutJwtOutcome() { + Fixture fixture = createAccountFixture(); + AccountControlUiIssuanceOperation original = pendingOperation(fixture.account()); + + ControlUiCredentialAuthentication authentication = + authenticate(fixture, original, PASSWORD, Purpose.INITIAL_ISSUANCE); + + assertThat(authentication.getClass()).isEqualTo(ControlUiCredentialAuthentication.class); + assertThat(authentication.accountId()).isEqualTo(fixture.account().getAccountUuid()); + assertThat(authentication.requestId()) + .isEqualTo(UUID.fromString(original.request().requestId())); + assertThat(authentication.operationId()).isEqualTo(original.operationId()); + assertThat(authentication.authenticationMethod()).isEqualTo("PASSWORD"); + assertThat(readOperation(original.request())).isEqualTo(original); + assertThat(attemptCount(original.operationId())).isEqualTo(1L); + assertThat(attemptMethod(authentication.authenticationAttemptId())).isEqualTo("PASSWORD"); + assertThat(challengeRepository.findByAccountId(fixture.account().getId())).isEmpty(); + } + + @Test + void actualOtpConsumesExactChallengeOnceAndConsumedRetryAddsNoCredentialEvidence() { + Fixture fixture = createAccountFixture(); + AccountControlUiIssuanceOperation original = pendingOperation(fixture.account()); + AccountEmailLoginChallenge challenge = createChallenge(fixture.account(), VALID_OTP); + + ControlUiCredentialAuthentication authentication = + authenticate(fixture, original, VALID_OTP, Purpose.INITIAL_ISSUANCE); + + assertThat(authentication.authenticationMethod()).isEqualTo("EMAIL_OTP"); + assertThat(authentication.operationId()).isEqualTo(original.operationId()); + assertThat(attemptCount(original.operationId())).isEqualTo(1L); + assertThat(attemptMethod(authentication.authenticationAttemptId())).isEqualTo("EMAIL_OTP"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT consumed_challenge_id FROM account_control_ui_credential_authentication_attempts " + + "WHERE attempt_id = ?", + authentication.authenticationAttemptId())) + .get(0, Long.class)) + .isEqualTo(challenge.getId()); + assertThat(challengeRepository.findByAccountId(fixture.account().getId())).isEmpty(); + assertThat(readOperation(original.request())).isEqualTo(original); + + assertInvalidCredentials( + () -> authenticate(fixture, original, VALID_OTP, Purpose.INITIAL_ISSUANCE)); + + assertThat(attemptCount(original.operationId())).isEqualTo(1L); + assertThat(readOperation(original.request())).isEqualTo(original); + assertThat(challengeRepository.findByAccountId(fixture.account().getId())).isEmpty(); + } + + @Test + void invalidPasswordAndOtpLeaveIssuanceAndEvidenceUnchangedAndUseRealFailureBuckets() { + Fixture fixture = createAccountFixture(); + AccountControlUiIssuanceOperation original = pendingOperation(fixture.account()); + createChallenge(fixture.account(), VALID_OTP); + long sourceFailuresBefore = + failureCount(PlatformAuthPolicy.SOURCE_FAILURE, fixture.source().canonicalClientAddress()); + long candidateFailuresBefore = + failureCount( + PlatformAuthPolicy.CANDIDATE_FAILURE, + AccountPlatformAuthAbuseLimiter.candidateIdentity(fixture.email())); + + assertInvalidCredentials( + () -> authenticate(fixture, original, "incorrect-password", Purpose.INITIAL_ISSUANCE)); + assertInvalidCredentials( + () -> authenticate(fixture, original, "incorrect-otp", Purpose.INITIAL_ISSUANCE)); + + assertThat(readOperation(original.request())).isEqualTo(original); + assertThat(attemptCount(original.operationId())).isZero(); + assertThat(challengeRepository.findByAccountId(fixture.account().getId())) + .get() + .satisfies(challenge -> assertThat(challenge.getInvalidAttemptCount()).isEqualTo(2)); + assertThat( + failureCount( + PlatformAuthPolicy.SOURCE_FAILURE, fixture.source().canonicalClientAddress()) + - sourceFailuresBefore) + .isEqualTo(2L); + assertThat( + failureCount( + PlatformAuthPolicy.CANDIDATE_FAILURE, + AccountPlatformAuthAbuseLimiter.candidateIdentity(fixture.email())) + - candidateFailuresBefore) + .isEqualTo(2L); + assertThat( + accountRepository + .findByAccountUuid(fixture.account().getAccountUuid()) + .orElseThrow() + .getLifecycleState()) + .isEqualTo(AccountLifecycleState.ACTIVE); + } + + @Test + void wrongOriginalOperationBindingPreservesEligibleOtpAndCredentialEvidence() { + Fixture originalOwner = createAccountFixture(); + Fixture authenticatingOwner = createAccountFixture(); + AccountControlUiIssuanceOperation original = pendingOperation(originalOwner.account()); + createChallenge(authenticatingOwner.account(), VALID_OTP); + AccountEmailLoginChallenge challengeBefore = + challengeRepository.findByAccountId(authenticatingOwner.account().getId()).orElseThrow(); + + assertThatThrownBy( + () -> authenticate(authenticatingOwner, original, VALID_OTP, Purpose.INITIAL_ISSUANCE)) + .isInstanceOf(CredentialOperationConflictException.class); + + assertThat( + challengeRepository + .findByAccountId(authenticatingOwner.account().getId()) + .orElseThrow()) + .isEqualTo(challengeBefore); + assertThat(readOperation(original.request())).isEqualTo(original); + assertThat(attemptCount(original.operationId())).isZero(); + assertThat(accountEvidenceCount(authenticatingOwner.account().getAccountUuid())).isZero(); + } + + @Test + void committedUnexpiredResponseRecoveryAuthenticatesAgainWithoutChangingOriginalResponse() + throws Exception { + Fixture fixture = createAccountFixture(); + AccountControlUiIssuanceOperation pending = pendingOperation(fixture.account()); + AccountControlUiIssuanceOperation committed = commitStipulatedOriginalResponse(pending); + assertThat(committed.lifecycle()) + .isEqualTo(AccountControlUiIssuanceOperation.Lifecycle.COMMITTED); + assertThat(committed.completedResponse()).isNotNull(); + assertThat(committed.completedResponse().binding().expiresAt()).isAfter(Instant.now()); + + ControlUiCredentialAuthentication authentication = + authenticate(fixture, committed, PASSWORD, Purpose.EXACT_RESPONSE_RECOVERY); + + assertThat(authentication.purpose()).isEqualTo(Purpose.EXACT_RESPONSE_RECOVERY); + assertThat(authentication.authenticationMethod()).isEqualTo("PASSWORD"); + assertThat(authentication.operationId()).isEqualTo(committed.operationId()); + assertThat(readOperation(committed.request())).isEqualTo(committed); + assertThat(attemptCount(committed.operationId())).isEqualTo(1L); + assertThat(attemptMethod(authentication.authenticationAttemptId())).isEqualTo("PASSWORD"); + } + + private Fixture createAccountFixture() { + String suffix = UUID.randomUUID().toString().replace("-", ""); + String username = "control-ui-" + suffix.substring(0, 12); + String email = "control-ui-" + suffix + "@example.test"; + accountService.createAccount(new CreateAccountRequest(username, email, PASSWORD)); + Account account = accountRepository.findByEmail(email).orElseThrow(); + return new Fixture(account, email, stipulatedWebSource()); + } + + private AccountControlUiIssuanceOperation pendingOperation(Account account) { + AccountControlUiIssuanceRequest request = + new AccountControlUiIssuanceRequest( + UUID.randomUUID().toString(), account.getAccountUuid().toString()); + OriginalCapture stipulatedCapture = + new OriginalCapture( + account.getId(), + account.getAccountUuidProvenance(), + ("stipulated-original-authority-capture:" + request.requestId()) + .getBytes(StandardCharsets.UTF_8), + ("stipulated-original-issuance-fence-capture:" + request.requestId()) + .getBytes(StandardCharsets.UTF_8)); + return inTransaction( + () -> issuanceOperations.claim(request, Optional.of(stipulatedCapture)).operation()); + } + + private AccountEmailLoginChallenge createChallenge(Account account, String otp) { + LocalDateTime now = LocalDateTime.now(); + AccountEmailLoginChallenge challenge = new AccountEmailLoginChallenge(); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(argon2Verifier(otp)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return inTransaction(() -> challengeRepository.save(challenge)); + } + + private ControlUiCredentialAuthentication authenticate( + Fixture fixture, + AccountControlUiIssuanceOperation operation, + String credential, + Purpose purpose) { + return accountService.authenticateControlUiOperation( + new AccountControlUiAuthenticationRequest( + UUID.fromString(operation.request().requestId()), + fixture.email(), + credential, + purpose, + fixture.source())); + } + + private AccountControlUiIssuanceOperation commitStipulatedOriginalResponse( + AccountControlUiIssuanceOperation pending) throws Exception { + byte[] response = "fixture-original-control-ui-response".getBytes(StandardCharsets.UTF_8); + Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS); + Instant issuedAt = now.minusSeconds(60); + Instant expiresAt = now.plusSeconds(300); + byte[] tokenBytes = "fixture-original-control-ui-token".getBytes(StandardCharsets.UTF_8); + AccountControlUiResponseEnvelopeBinding binding = + new AccountControlUiResponseEnvelopeBinding( + pending.request().accountUuid(), + pending.operationId().toString(), + pending.request().requestId(), + pending.requestDigest(), + HexFormat.of().formatHex(sha256(tokenBytes)), + sha256(response), + pending.originalCapture().authorityCaptureDigest(), + pending.originalCapture().issuanceFenceDigest(), + issuedAt, + expiresAt); + Path manifest = tempDirectory.resolve("control-ui-ring-" + UUID.randomUUID() + ".v1"); + writeFixtureKeyRing(manifest); + var envelope = new AccountEnvelopeCrypto(manifest).encryptControlUiResponse(binding, response); + return inTransaction( + () -> + issuanceOperations.complete( + issuanceOperations.claim(pending.request(), Optional.empty()), binding, envelope)); + } + + private static void writeFixtureKeyRing(Path manifest) throws Exception { + List lines = new ArrayList<>(List.of("version=1", "activeKeyId=k1")); + int seed = 1; + for (String purpose : + List.of("bare-login", "connect-token", "pending-reset", "control-ui-response")) { + byte[] key = new byte[32]; + java.util.Arrays.fill(key, (byte) seed++); + lines.add( + "key:k1:" + purpose + "=" + Base64.getUrlEncoder().withoutPadding().encodeToString(key)); + } + Files.writeString(manifest, String.join("\n", lines) + "\n", StandardCharsets.US_ASCII); + } + + private AccountControlUiIssuanceOperation readOperation(AccountControlUiIssuanceRequest request) { + return inTransaction(() -> issuanceOperations.findByRequest(request).orElseThrow()); + } + + private long attemptCount(UUID operationId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM account_control_ui_credential_authentication_attempts " + + "WHERE operation_id = ?", + operationId)) + .get(0, Long.class); + } + + private long accountEvidenceCount(UUID accountUuid) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM account_control_ui_credential_authentication_attempts " + + "WHERE account_uuid = ?", + accountUuid)) + .get(0, Long.class); + } + + private String attemptMethod(UUID attemptId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT authentication_method FROM account_control_ui_credential_authentication_attempts " + + "WHERE attempt_id = ?", + attemptId)) + .get(0, String.class); + } + + private long failureCount(PlatformAuthPolicy policy, byte[] subject) { + var digest = + RateLimitSubjectHash.platformAuthSubject( + authRateLimitProperties.activeHmacKey(), policy, subject); + long window = + Math.floorDiv( + Instant.now().getEpochSecond(), authRateLimitProperties.getSubjectWindowSeconds()); + return authBuckets.count( + RateLimitSubjectHash.platformAuthBucketKey(digest, window), digest.collisionFingerprint()); + } + + private static void assertInvalidCredentials(Runnable attempt) { + assertThatThrownBy(attempt::run) + .isInstanceOf(AuthenticationException.class) + .satisfies( + failure -> + assertThat(((AuthenticationException) failure).getCode()) + .isEqualTo(AuthenticationErrorCodes.INVALID_CREDENTIALS)); + } + + private static CredentialAttemptSource stipulatedWebSource() { + int sourceOctet = NEXT_SOURCE_OCTET.getAndIncrement(); + if (sourceOctet > 254) { + throw new IllegalStateException("Test source address pool is exhausted"); + } + return new CredentialAttemptSource( + "198.51.100." + sourceOctet, CredentialAttemptSource.ConnectionMode.FIRST_PARTY_WEB); + } + + private static String argon2Verifier(String value) { + Argon2 argon2 = Argon2Factory.create(); + char[] chars = value.toCharArray(); + try { + return argon2.hash(2, 65536, 1, chars); + } finally { + argon2.wipeArray(chars); + } + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private T inTransaction(Supplier work) { + return transaction.execute(status -> work.get()); + } + + private record Fixture(Account account, String email, CredentialAttemptSource source) {} +} From b5117b4c70ca0afe6688e71f13133258460a9d73 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 18:59:13 +1300 Subject: [PATCH 08/12] Account: reproject canonical issuer evidence from exact owner source --- .github/workflows/ci.yml | 23 ++ .../account-service/runtime-and-data.md | 6 + .../player-access-and-session.md | 2 + ...rrentGenerationProjectionRedisSupport.java | 5 +- .../service/IssuerGenerationProjection.java | 209 +++++++++++ ...suerGenerationProjectionRedisContract.java | 105 ++++++ .../RedisIssuerGenerationProjectionStore.java | 328 +++++++++++++++++ ...rojectionPostgresRedisIntegrationTest.java | 346 ++++++++++++++++++ ...GenerationProjectionRedisContractTest.java | 85 +++++ .../IssuerGenerationProjectionTest.java | 194 ++++++++++ 10 files changed, 1301 insertions(+), 2 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionRedisContract.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/RedisIssuerGenerationProjectionStore.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerGenerationProjectionPostgresRedisIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionRedisContractTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ac7411f514..ae8befcdda 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2579,6 +2579,29 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiCredentialAuthenticationPostgresIntegrationTest#credentialEvidenceRejectsUpdateDeleteAndTruncateAndPreservesExactStoredRows()' \ account-service + - name: Capture Account canonical issuer projection PostgreSQL and Redis raw XML + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-canonical-issuer-projection-postgresql-redis-proof-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: services/account-service/build/test-results/integrationTest/TEST-*IssuerGenerationProjectionPostgresRedisIntegrationTest.xml + if-no-files-found: warn + retention-days: 7 + + - name: Verify Account canonical issuer projection PostgreSQL and Redis proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.IssuerGenerationProjectionPostgresRedisIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerGenerationProjectionPostgresRedisIntegrationTest#installsActualIssuerBaselineThenLatestAdvanceAndExactRetryWithoutSqlMutationOrTtl()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerGenerationProjectionPostgresRedisIntegrationTest#malformedProjectionAndTtlDenyWithoutRepairingStoredBytes()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerGenerationProjectionPostgresRedisIntegrationTest#aheadSourceAndSameCheckpointDifferentActualEventDenyWithoutOverwrite()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerGenerationProjectionPostgresRedisIntegrationTest#actualCommittedSourceAdvanceBetweenOwnerReadsReturnsSourceChangedWithoutImplicitRetry()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerGenerationProjectionPostgresRedisIntegrationTest#missingAndContradictoryOwnerHistoryDenyWithoutEnrollmentOrRedisWrite()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.IssuerGenerationProjectionPostgresRedisIntegrationTest#explicitInitKnownIssuerEndpointSeparationAndAclPreventRoleOrDirectEvalSubstitution()' \ + account-service + - name: Verify Account generation projection PostgreSQL and Redis proof cases if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 2fdee85555..c5cc27c345 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -180,6 +180,12 @@ This is current-snapshot reprojection by the source owner, not delivery-consumer The record stores no recipient tuple, issuance fence, token identity or time-based freshness assertion. Its source evidence does not authenticate a caller, implement the complete authorization bundle or grant admission. [ADR 0036](../../decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md#generation-authorities) still requires the complete Account bundle and exact applicable durable/projected equality for authorization. Narrower resets preserve this family; cluster-loss repair remains Account-owned and subject to the existing [reset-policy matrix](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). This storage definition does not implement or authorize reset orchestration, live ACL/cohort cutover or runtime activation. Implementation and executed proof belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +### Issuer Generation Snapshot Projection + +Account's issuer-wide physical projection uses only `session:auth:generation:issuer:firemud-account-service`, under [ADR 0036's Account ownership](../../decisions/adr-0036-monotonic-authority-generations-for-bulk-token-revocation.md#generation-authorities). Its closed record has `schemaVersion: "account-auth-issuer-generation-projection/v1"`, `issuerId`, `issuerAuthGeneration`, `sourceVersion`, `outboxStreamKey`, and `lastAppliedSourceOutboxSequence`. The exact configured issuer is `firemud-account-service`, and the stream is `account:auth-authority:v1:issuer/firemud-account-service`. Counters are canonical decimal strings parsed without narrowing; only sequence permits zero. A proved original positive generation/source-version 1/1 baseline has sequence zero and omits all event fields. A positive checkpoint additionally requires `lastAppliedSourceEventId`, `lastAppliedSourceEventDigest`, and `sourceEvent`, the complete canonical closed issuer-event JSON as a string; its digest, identity, scope, generation, source version and checkpoint must agree exactly. Missing, null, duplicate, unknown or noncanonical fields are invalid, not alternate baseline forms. + +Candidates come from Account's existing-only fenced issuer owner readback, without a recipient tuple or issuance fence. The [Account snapshot reprojection rules](#account-generation-snapshot-projection) govern explicit Coordination-only initialization, registered byte CAS, no TTL, exact Redis readback, fresh durable-source reread and non-convergence on disagreement or source change. This reprojects the actual current latest source snapshot; it is not contiguous event ingestion or Game Session's separate derived `session:game:auth:issuer-generation:v1:` projection. The source-event and recipient-evidence distinction remains owned by [Authentication](../../system-architecture-authentication.md#authority-source-events-and-recipient-evidence), and [ADR 0030](../../decisions/adr-0030-risk-based-active-session-revocation.md) owns downstream cutoff obligations. The store is explicitly initialized and unwired; constructing or repairing this projection does not authenticate a caller, supply a complete authorization bundle, acknowledge cutoff enforcement or enable issuance. Implementation and executed-proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + ### Tenant Generation Snapshot Projection Account's tenant-wide projection uses `session:auth:generation:tenant:` with `schemaVersion: "account-auth-tenant-generation-projection/v1"` and exactly `tenantId`, `tenantAuthorityGeneration`, `sourceVersion`, `outboxStreamKey`, and `outboxSequence`; a positive checkpoint additionally requires `sourceEvent`, the complete canonical JSON of its latest closed tenant-generation event as a string. Counters use canonical decimal strings. The canonical non-nil tenant UUID, exact `account:auth-authority:v1:tenant/` stream and latest event must match Account's fenced tenant-source readback. Sequence zero requires the proved original generation/source-version 1/1 baseline and no committed event; it omits `sourceEvent`. For positive tenant-source sequences, both counters equal sequence plus one. Neither Redis absence nor caller-supplied identifiers establish enrollment or an absence baseline. 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 aa047d69d5..936cabc664 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The Account-owned canonical issuer projection now has `IssuerGenerationProjection`, `IssuerGenerationProjectionRedisContract`, and an explicit-init `RedisIssuerGenerationProjectionStore`. The descriptor registers the existing Account snapshot CAS resource for only the canonical issuer key family; the store itself is not registered as a Spring bean or wired into authentication. It reads actual existing Account issuer source/history, applies one Coordination byte CAS, requires exact no-TTL readback and re-reads the durable owner before reporting convergence. It remains separate from Game Session's derived issuer projection and supplies no recipient tuple, issuance fence, complete bundle, caller authorization or issuance activation. Five value tests, two descriptor tests and six real PostgreSQL/Redis methods are defined for exact baseline/advance/replay, closed canonical evidence, corruption/TTL, regression and conflicting checkpoints, actual interleaved source advancement, missing history, endpoint/ACL separation and direct-EVAL denial. The consolidated Account full check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass in 1m44s (72 tasks:23 executed,49 up-to-date). All1,059 unit cases execute cleanly, including these seven value/descriptor cases. All456 integration cases compile and skip without local Docker, including the six new PostgreSQL/Redis methods; database, ACL and real Redis execution remain unproved. CI captures their raw integration XML before later report overwrite and strictly requires the exact suite and all six methods, preserving the existing Account proof requirements. Complete capture, protected signing/registry, downstream cutoff and live activation proof remain open under [Account's physical projection contract](../../architecture/microservices/account-service/runtime-and-data.md#issuer-generation-snapshot-projection). + Five additional PostgreSQL/Cache Redis definitions call the real Account credential producer, persisted Account/authority/challenge owners, Argon2 verifier and shared abuse limiter. They cover password evidence without a JWT outcome, exact single-use OTP and consumed-retry denial, invalid-credential counters with no issuance/evidence change, wrong-original-operation rollback, and fresh password authentication against an unexpired committed response. Only unused remote clients and mail are mocked. The original V66 capture, trusted first-party source descriptor and committed response remain explicit fixtures: this is not authenticated initial capture, a public route, signer/registry or response release. CI captures and strictly requires their executed XML; local Docker-dependent execution remains unavailable. The existing-only unscoped control-ui source reader now has a pre-sign entry, `readUnscopedCurrent`, independent of an already signed candidate. It retains issuer-first locking, Account provenance, fresh-empty roles, exact source history/checkpoints and the issuance fence in one writable owner transaction; signed inspection delegates to it and still compares every represented claim and registry source version. Two additional PostgreSQL definitions cover fresh non-mutating readback and advanced issuer evidence with mismatched signed inputs, while the existing denial cases also exercise unsigned reads. Strict CI requires all ten source-observation methods. This is a non-authorizing observation, not a complete durable capture, authenticated caller, current Coordination projection, signer or released credential; new PostgreSQL execution remains open. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java index 7d620f23f5..ecf4fef283 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/CurrentGenerationProjectionRedisSupport.java @@ -121,9 +121,10 @@ static String decodeUtf8(byte[] value) throws CharacterCodingException { private static void requireSupportedDescriptor(RedisScriptDescriptor descriptor) { if (descriptor != AccountGenerationProjectionRedisContract.descriptor() && descriptor != TenantGenerationProjectionRedisContract.descriptor() - && descriptor != MembershipGenerationProjectionRedisContract.descriptor()) { + && descriptor != MembershipGenerationProjectionRedisContract.descriptor() + && descriptor != IssuerGenerationProjectionRedisContract.descriptor()) { throw new IllegalStateException( - "Only Account, tenant, and membership current-generation projection scripts may use this client"); + "Only Account issuer, account, tenant, and membership current-generation projection scripts may use this client"); } if (!"account-service".equals(descriptor.owner()) || !"account_coord_app".equals(descriptor.principal()) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java new file mode 100644 index 0000000000..e401d66c04 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java @@ -0,0 +1,209 @@ +package net.firedevops.firemud.accountservice.service; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.math.BigInteger; +import java.util.HashSet; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; + +/** Closed Account-owned current issuer projection; not recipient or token authorization. */ +public record IssuerGenerationProjection( + String issuerId, + String issuerAuthGeneration, + String sourceVersion, + String outboxStreamKey, + String lastAppliedSourceOutboxSequence, + Optional lastAppliedSourceEventId, + Optional lastAppliedSourceEventDigest, + Optional sourceEvent) { + public static final String SCHEMA_VERSION = "account-auth-issuer-generation-projection/v1"; + public static final String KEY_PREFIX = "session:auth:generation:issuer:"; + private static final String STREAM = + "account:auth-authority:v1:issuer/" + ControlUiJwtProfileValidator.ISSUER; + private static final Set BASE_FIELDS = + Set.of( + "schemaVersion", + "issuerId", + "issuerAuthGeneration", + "sourceVersion", + "outboxStreamKey", + "lastAppliedSourceOutboxSequence"); + private static final Set EVENT_FIELDS = + Set.of( + "schemaVersion", + "issuerId", + "issuerAuthGeneration", + "sourceVersion", + "outboxStreamKey", + "lastAppliedSourceOutboxSequence", + "lastAppliedSourceEventId", + "lastAppliedSourceEventDigest", + "sourceEvent"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + public IssuerGenerationProjection { + keyForIssuer(issuerId); + positive(issuerAuthGeneration); + positive(sourceVersion); + if (lastAppliedSourceOutboxSequence == null + || !lastAppliedSourceOutboxSequence.matches("0|[1-9][0-9]*") + || !STREAM.equals(outboxStreamKey)) { + throw new IllegalArgumentException("Issuer projection stream/checkpoint is not canonical"); + } + lastAppliedSourceEventId = Objects.requireNonNull(lastAppliedSourceEventId); + lastAppliedSourceEventDigest = Objects.requireNonNull(lastAppliedSourceEventDigest); + sourceEvent = Objects.requireNonNull(sourceEvent); + if (new BigInteger(lastAppliedSourceOutboxSequence).signum() == 0) { + if (!"1".equals(issuerAuthGeneration) + || !"1".equals(sourceVersion) + || lastAppliedSourceEventId.isPresent() + || lastAppliedSourceEventDigest.isPresent() + || sourceEvent.isPresent()) { + throw new IllegalArgumentException( + "Issuer sequence zero requires original 1/1 and no event"); + } + } else { + if (new BigInteger(issuerAuthGeneration).compareTo(BigInteger.ONE) <= 0 + || new BigInteger(sourceVersion).compareTo(BigInteger.ONE) <= 0 + || lastAppliedSourceEventId.isEmpty() + || lastAppliedSourceEventDigest.isEmpty() + || sourceEvent.isEmpty()) { + throw new IllegalArgumentException( + "Advanced issuer projection requires complete event evidence"); + } + var event = IssuerGenerationAuthorityEventV1Codec.verify(sourceEvent.orElseThrow()); + if (!sourceEvent.orElseThrow().equals(event.canonicalJson()) + || !issuerId.equals(event.issuerId()) + || !("issuer/" + issuerId).equals(event.sourceScope()) + || !issuerAuthGeneration.equals(event.issuerAuthGeneration()) + || !sourceVersion.equals(event.sourceVersion()) + || !outboxStreamKey.equals(event.outboxStreamKey()) + || !lastAppliedSourceOutboxSequence.equals(event.outboxSequence()) + || !lastAppliedSourceEventId.orElseThrow().equals(event.eventId()) + || !lastAppliedSourceEventDigest.orElseThrow().equals(event.eventDigest())) { + throw new IllegalArgumentException( + "Issuer projection differs from its exact canonical event"); + } + } + } + + public static IssuerGenerationProjection fromSource(IssuerAuthoritySnapshot source) { + Objects.requireNonNull(source); + return new IssuerGenerationProjection( + source.issuerId(), + Long.toString(source.issuerAuthGeneration()), + Long.toString(source.sourceVersion()), + source.outboxStreamKey(), + Long.toString(source.outboxSequence()), + source.latestEvent().map(event -> event.eventId()), + source.latestEvent().map(event -> event.eventDigest()), + source.latestEvent().map(event -> event.canonicalJson())); + } + + public static IssuerGenerationProjection parse(String json) { + Objects.requireNonNull(json); + final JsonNode root; + try { + root = JSON.readTree(json); + } catch (IOException failure) { + throw new IllegalArgumentException("Issuer projection JSON is malformed", failure); + } + if (!(root instanceof ObjectNode object)) { + throw new IllegalArgumentException("Issuer projection must be an object"); + } + Set fields = new HashSet<>(); + object.fieldNames().forEachRemaining(fields::add); + if (!fields.equals(BASE_FIELDS) && !fields.equals(EVENT_FIELDS)) { + throw new IllegalArgumentException("Issuer projection has missing or unknown fields"); + } + if (!SCHEMA_VERSION.equals(text(object, "schemaVersion"))) { + throw new IllegalArgumentException("Issuer projection schema is unsupported"); + } + boolean event = fields.equals(EVENT_FIELDS); + var projection = + new IssuerGenerationProjection( + text(object, "issuerId"), + text(object, "issuerAuthGeneration"), + text(object, "sourceVersion"), + text(object, "outboxStreamKey"), + text(object, "lastAppliedSourceOutboxSequence"), + event ? Optional.of(text(object, "lastAppliedSourceEventId")) : Optional.empty(), + event ? Optional.of(text(object, "lastAppliedSourceEventDigest")) : Optional.empty(), + event ? Optional.of(text(object, "sourceEvent")) : Optional.empty()); + if (!projection.toJson().equals(json)) { + throw new IllegalArgumentException("Issuer projection JSON is not canonical"); + } + return projection; + } + + public String toJson() { + ObjectNode object = JSON.createObjectNode(); + object.put("schemaVersion", SCHEMA_VERSION); + object.put("issuerId", issuerId); + object.put("issuerAuthGeneration", issuerAuthGeneration); + object.put("sourceVersion", sourceVersion); + object.put("outboxStreamKey", outboxStreamKey); + object.put("lastAppliedSourceOutboxSequence", lastAppliedSourceOutboxSequence); + lastAppliedSourceEventId.ifPresent(value -> object.put("lastAppliedSourceEventId", value)); + lastAppliedSourceEventDigest.ifPresent( + value -> object.put("lastAppliedSourceEventDigest", value)); + sourceEvent.ifPresent(value -> object.put("sourceEvent", value)); + try { + return JSON.writeValueAsString(object); + } catch (IOException failure) { + throw new IllegalStateException("Issuer projection cannot be serialized", failure); + } + } + + public String key() { + return keyForIssuer(issuerId); + } + + public BigInteger generationValue() { + return new BigInteger(issuerAuthGeneration); + } + + public BigInteger sourceVersionValue() { + return new BigInteger(sourceVersion); + } + + public BigInteger outboxSequenceValue() { + return new BigInteger(lastAppliedSourceOutboxSequence); + } + + public static String keyForIssuer(String issuerId) { + if (!ControlUiJwtProfileValidator.ISSUER.equals(issuerId)) { + throw new IllegalArgumentException( + "Issuer projection must bind the configured Account issuer"); + } + return KEY_PREFIX + issuerId; + } + + private static String text(ObjectNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Issuer projection field must be a string: " + field); + } + return value.textValue(); + } + + private static void positive(String value) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "Issuer projection counter must be a positive canonical decimal"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionRedisContract.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionRedisContract.java new file mode 100644 index 0000000000..d74f2b33b8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionRedisContract.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.PrefixDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisInvocationContract; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ArgumentSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.CompatibilityLevel; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.HashTagDeclaration; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.KeySpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.LossClass; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.MutationEffect; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeSpec; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.RedisRole; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ResetSensitivity; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ScriptCategory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.SupportedCoexistence; + +/** Registered Account-owned single-key compare-and-set for the issuer generation projection. */ +public final class IssuerGenerationProjectionRedisContract { + public static final String SCRIPT_ID = "account.issuer-generation-projection.v1"; + public static final String RESOURCE_PATH = "redis/account_generation_projection_cas.lua"; + public static final String OWNER = "account-service"; + public static final String PRINCIPAL = "account_coord_app"; + public static final RedisRole ROLE = RedisRole.COORDINATION; + public static final String KEY_PREFIX = IssuerGenerationProjection.KEY_PREFIX; + + private static final String RESOURCE_SHA256 = + "1c1df7fdf6edc42a9e3ad5dfd5a0db7c33295b41a9e5c28df2a65e98d9069c16"; + private static final RedisScriptDescriptor DESCRIPTOR = createDescriptor(); + private static final RedisContractRegistry REGISTRY = + new RedisContractRegistry( + List.of(new PrefixDeclaration(OWNER, ROLE, PRINCIPAL, KEY_PREFIX)), List.of(DESCRIPTOR)); + + private IssuerGenerationProjectionRedisContract() {} + + public static RedisScriptDescriptor descriptor() { + return DESCRIPTOR; + } + + /** Declarative registry only; executable access stays private to the Account owner store. */ + public static RedisContractRegistry registry() { + return REGISTRY; + } + + static RedisInvocationContract prepareInvocation( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + Objects.requireNonNull(key, "Account generation key is required"); + requireCanonicalIssuerKey(key); + return REGISTRY.prepareInvocation( + new InvocationRequest( + SCRIPT_ID, + RESOURCE_PATH, + RESOURCE_SHA256, + OWNER, + PRINCIPAL, + ROLE, + List.of(key), + List.of(expectedMode, expectedBytes, candidateBytes))); + } + + private static void requireCanonicalIssuerKey(String key) { + if (!IssuerGenerationProjection.keyForIssuer( + net.firedevops.firemud.common.security.ControlUiJwtProfileValidator.ISSUER) + .equals(key)) { + throw new IllegalArgumentException( + "Issuer generation key must bind the configured Account issuer"); + } + } + + private static RedisScriptDescriptor createDescriptor() { + return new RedisScriptDescriptor( + SCRIPT_ID, + RESOURCE_PATH, + RESOURCE_SHA256, + OWNER, + PRINCIPAL, + ROLE, + List.of( + new KeySpec("issuerGenerationProjection", KEY_PREFIX, HashTagDeclaration.NOT_REQUIRED)), + List.of( + new ArgumentSpec("expectedMode"), + new ArgumentSpec("expectedBytes"), + new ArgumentSpec("candidateBytes")), + ScriptCategory.SESSION_CAS, + List.of( + new OutcomeSpec("APPLIED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING), + new OutcomeSpec("REPLAY", OutcomeCategory.REPLAY, MutationEffect.NON_MUTATING), + new OutcomeSpec("STALE", OutcomeCategory.STALE, MutationEffect.NON_MUTATING), + new OutcomeSpec( + "INVALID", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING), + new OutcomeSpec( + "TTL_PRESENT", OutcomeCategory.VALIDATION_FAILURE, MutationEffect.NON_MUTATING)), + ResetSensitivity.CLUSTER, + LossClass.EMPTY_REDIS_COLD_START_OR_RESET, + "On loss, fail closed and rebuild only from Account's exact current durable source snapshot.", + CompatibilityLevel.COMPATIBLE, + List.of(new SupportedCoexistence("v1", "v1")), + null); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/RedisIssuerGenerationProjectionStore.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/RedisIssuerGenerationProjectionStore.java new file mode 100644 index 0000000000..dac3a5a796 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/RedisIssuerGenerationProjectionStore.java @@ -0,0 +1,328 @@ +package net.firedevops.firemud.accountservice.service; + +import java.io.IOException; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.common.redis.contracts.RedisInvocationContract; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.StringRedisTemplate; + +/** + * Explicitly initialized, unwired Account-owned store for the current issuer-generation projection. + */ +public final class RedisIssuerGenerationProjectionStore implements AutoCloseable { + private final AccountIssuerAuthorityEventProducer sourceReader; + private final CoordinationEndpoint coordinationEndpoint; + + private LettuceConnectionFactory connectionFactory; + private StringRedisTemplate redisTemplate; + private boolean closed; + + /** Captures explicit role endpoints without creating a bean or opening a Redis connection. */ + public RedisIssuerGenerationProjectionStore( + AccountIssuerAuthorityEventProducer reader, + CoordinationEndpoint coordination, + CacheRateLimitEndpoint cache) { + sourceReader = Objects.requireNonNull(reader, "Account source reader is required"); + coordinationEndpoint = + Objects.requireNonNull(coordination, "Coordination endpoint is required"); + Objects.requireNonNull(cache, "Cache/Rate-Limit endpoint is required"); + validateDistinctEndpoints(coordination, cache); + } + + /** Initializes this store's private Coordination-only Redis client. */ + public synchronized void init() { + if (closed) { + throw new IllegalStateException("Account generation projection store is closed"); + } + if (connectionFactory != null) { + return; + } + CurrentGenerationProjectionRedisSupport.verifyScriptDigest( + IssuerGenerationProjectionRedisContract.descriptor()); + CurrentGenerationProjectionRedisSupport.InitializedClient client = + CurrentGenerationProjectionRedisSupport.initialize( + coordinationEndpoint.host(), + coordinationEndpoint.port(), + coordinationEndpoint.principal(), + coordinationEndpoint.password()); + connectionFactory = client.connectionFactory(); + redisTemplate = client.template(); + } + + /** + * Reprojects one exact current Account snapshot. It reads source evidence before every attempt, + * performs at most one registered CAS, verifies exact Redis bytes, then rereads Account before + * reporting convergence. Source advancement never triggers an implicit retry. + */ + public synchronized ApplyResult refreshCurrent(String issuerId) { + requireInitialized(); + String key = IssuerGenerationProjection.keyForIssuer(issuerId); + IssuerAuthoritySnapshot source = sourceReader.readCurrent(issuerId); + IssuerGenerationProjection candidate = IssuerGenerationProjection.fromSource(source); + if (!key.equals(candidate.key())) { + return quarantined("ISSUER_SOURCE_IDENTITY_MISMATCH", Optional.empty()); + } + String candidateJson = candidate.toJson(); + byte[] candidateBytes = candidateJson.getBytes(StandardCharsets.UTF_8); + + CurrentGenerationProjectionRedisSupport.StoredValue observed = readStoredValue(key); + if (observed.bytes() != null && observed.ttlMillis() != -1L) { + return quarantined("TTL_PRESENT", Optional.empty()); + } + + IssuerGenerationProjection stored = null; + String storedJson = null; + if (observed.bytes() != null) { + try { + storedJson = decodeUtf8(observed.bytes()); + stored = IssuerGenerationProjection.parse(storedJson); + } catch (IOException | IllegalArgumentException malformed) { + return quarantined("MALFORMED_STORED_PROJECTION", Optional.empty()); + } + if (!key.equals(stored.key())) { + return quarantined("STORED_ISSUER_ID_MISMATCH", Optional.empty()); + } + if (isRegression(candidate, stored)) { + return staleSource(key, storedJson); + } + if (candidate.outboxSequenceValue().equals(stored.outboxSequenceValue()) + && !candidate.equals(stored)) { + return quarantined( + "SAME_CHECKPOINT_DISAGREEMENT", Optional.of(new ProjectionSnapshot(key, storedJson))); + } + } + + String mode; + String expectedJson; + if (stored == null) { + mode = "ABSENT"; + expectedJson = ""; + } else if (candidate.equals(stored)) { + mode = "VERIFY"; + expectedJson = storedJson; + } else { + mode = "PRESENT"; + expectedJson = storedJson; + } + + String scriptResult = + executeRegistered(key, mode, expectedJson, "VERIFY".equals(mode) ? "" : candidateJson); + if ("STALE".equals(scriptResult)) { + return new ApplyResult(Outcome.STALE, Optional.empty(), Optional.of("REDIS_CAS_STALE")); + } + if ("TTL_PRESENT".equals(scriptResult)) { + return quarantined("TTL_PRESENT", Optional.empty()); + } + if ("INVALID".equals(scriptResult)) { + throw new IllegalStateException( + "Registered Account generation projection script rejected its invocation"); + } + if (!"APPLIED".equals(scriptResult) && !"REPLAY".equals(scriptResult)) { + throw new IllegalStateException( + "Unknown registered Account generation projection script result: " + + Objects.toString(scriptResult, "null")); + } + + CurrentGenerationProjectionRedisSupport.StoredValue readback = readStoredValue(key); + if (readback.bytes() == null) { + return new ApplyResult( + Outcome.STALE, Optional.empty(), Optional.of("REDIS_READBACK_MISSING")); + } + if (readback.ttlMillis() != -1L) { + return quarantined("TTL_PRESENT", Optional.empty()); + } + if (!MessageDigest.isEqual(candidateBytes, readback.bytes())) { + return changedRedisReadback(key, readback.bytes()); + } + + IssuerGenerationProjection current = + IssuerGenerationProjection.fromSource(sourceReader.readCurrent(issuerId)); + if (!candidate.equals(current)) { + return new ApplyResult( + Outcome.SOURCE_CHANGED, + Optional.of(new ProjectionSnapshot(key, candidateJson)), + Optional.of("ISSUER_SOURCE_ADVANCED_DURING_REPROJECTION")); + } + Outcome convergedOutcome = "APPLIED".equals(scriptResult) ? Outcome.APPLIED : Outcome.REPLAYED; + return new ApplyResult( + convergedOutcome, + Optional.of(new ProjectionSnapshot(key, candidateJson)), + Optional.empty()); + } + + @Override + public synchronized void close() { + closed = true; + if (connectionFactory != null) { + connectionFactory.destroy(); + connectionFactory = null; + redisTemplate = null; + } + } + + private ApplyResult changedRedisReadback(String key, byte[] bytes) { + try { + String json = decodeUtf8(bytes); + IssuerGenerationProjection projection = IssuerGenerationProjection.parse(json); + if (!key.equals(projection.key())) { + return quarantined("READBACK_ISSUER_ID_MISMATCH", Optional.empty()); + } + return new ApplyResult( + Outcome.STALE, + Optional.of(new ProjectionSnapshot(key, json)), + Optional.of("REDIS_READBACK_CHANGED")); + } catch (IOException | IllegalArgumentException malformed) { + return quarantined("MALFORMED_REDIS_READBACK", Optional.empty()); + } + } + + private static boolean isRegression( + IssuerGenerationProjection candidate, IssuerGenerationProjection stored) { + return candidate.generationValue().compareTo(stored.generationValue()) < 0 + || candidate.sourceVersionValue().compareTo(stored.sourceVersionValue()) < 0 + || candidate.outboxSequenceValue().compareTo(stored.outboxSequenceValue()) < 0; + } + + private String executeRegistered( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + RedisInvocationContract invocation = + IssuerGenerationProjectionRedisContract.prepareInvocation( + key, expectedMode, expectedBytes, candidateBytes); + return CurrentGenerationProjectionRedisSupport.executeRegistered( + redisTemplate, + invocation, + IssuerGenerationProjectionRedisContract.descriptor(), + key, + expectedMode, + expectedBytes, + candidateBytes); + } + + private CurrentGenerationProjectionRedisSupport.StoredValue readStoredValue(String key) { + return CurrentGenerationProjectionRedisSupport.readStoredValue(redisTemplate, key); + } + + private void requireInitialized() { + if (closed || redisTemplate == null) { + throw new IllegalStateException( + "Account generation projection store requires explicit init()"); + } + } + + private static String decodeUtf8(byte[] value) throws CharacterCodingException { + return CurrentGenerationProjectionRedisSupport.decodeUtf8(value); + } + + private static void validateDistinctEndpoints( + CoordinationEndpoint coordination, CacheRateLimitEndpoint cache) { + if (normalizeHost(coordination.host()).equals(normalizeHost(cache.host())) + && coordination.port() == cache.port()) { + throw new IllegalArgumentException( + "Coordination and Cache/Rate-Limit Redis endpoints must be distinct"); + } + } + + private static String normalizeHost(String host) { + String normalized = host.toLowerCase(Locale.ROOT); + if (normalized.startsWith("[") && normalized.endsWith("]")) { + normalized = normalized.substring(1, normalized.length() - 1); + } + while (normalized.endsWith(".")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + return normalized; + } + + private static ApplyResult staleSource(String key, String storedJson) { + return new ApplyResult( + Outcome.STALE_SOURCE, + Optional.of(new ProjectionSnapshot(key, storedJson)), + Optional.of("STORED_PROJECTION_AHEAD_OF_ISSUER_SOURCE")); + } + + private static ApplyResult quarantined(String detail, Optional snapshot) { + return new ApplyResult(Outcome.QUARANTINED, snapshot, Optional.of(detail)); + } + + public enum Outcome { + APPLIED, + REPLAYED, + SOURCE_CHANGED, + STALE_SOURCE, + STALE, + QUARANTINED + } + + /** Exact byte observation returned for inspection; it grants no authorization. */ + public record ProjectionSnapshot(String key, String json) { + public ProjectionSnapshot { + Objects.requireNonNull(key, "projection key is required"); + Objects.requireNonNull(json, "projection JSON is required"); + } + } + + public record ApplyResult( + Outcome outcome, Optional snapshot, Optional detail) { + public ApplyResult { + Objects.requireNonNull(outcome, "outcome is required"); + snapshot = Objects.requireNonNull(snapshot, "snapshot optional is required"); + detail = Objects.requireNonNull(detail, "detail optional is required"); + } + } + + /** Explicit Coordination endpoint and ACL identity; the principal is not caller-selectable. */ + public record CoordinationEndpoint(String host, int port, String principal, String password) { + public CoordinationEndpoint { + validateHost(host, "Coordination host"); + validatePort(port, "Coordination port"); + if (!IssuerGenerationProjectionRedisContract.PRINCIPAL.equals(principal)) { + throw new IllegalArgumentException("Coordination principal must be account_coord_app"); + } + if (password == null || password.isBlank()) { + throw new IllegalArgumentException("Coordination ACL credential is required"); + } + } + + @Override + public String toString() { + return "CoordinationEndpoint[host=" + + host + + ", port=" + + port + + ", principal=" + + principal + + ", password=]"; + } + } + + /** Separate Cache/Rate-Limit endpoint used only to reject role endpoint collisions. */ + public record CacheRateLimitEndpoint(String host, int port) { + public CacheRateLimitEndpoint { + validateHost(host, "Cache/Rate-Limit host"); + validatePort(port, "Cache/Rate-Limit port"); + } + } + + private static void validateHost(String host, String label) { + if (host == null + || host.isBlank() + || !host.equals(host.trim()) + || host.contains("://") + || host.chars().anyMatch(Character::isWhitespace) + || host.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(label + " must be an explicit host or IP address"); + } + } + + private static void validatePort(int port, String label) { + if (port < 1 || port > 65535) { + throw new IllegalArgumentException(label + " must be between 1 and 65535"); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerGenerationProjectionPostgresRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerGenerationProjectionPostgresRedisIntegrationTest.java new file mode 100644 index 0000000000..ae4d4a4505 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerGenerationProjectionPostgresRedisIntegrationTest.java @@ -0,0 +1,346 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.accountservice.service.RedisIssuerGenerationProjectionStore; +import net.firedevops.firemud.accountservice.service.RedisIssuerGenerationProjectionStore.CacheRateLimitEndpoint; +import net.firedevops.firemud.accountservice.service.RedisIssuerGenerationProjectionStore.CoordinationEndpoint; +import net.firedevops.firemud.accountservice.service.RedisIssuerGenerationProjectionStore.Outcome; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.connection.RedisPassword; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Real owner SQL and Coordination projection proof; not complete bundle or issuance proof. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class IssuerGenerationProjectionPostgresRedisIntegrationTest { + private static final String ISSUER = ControlUiJwtProfileValidator.ISSUER; + private static final String KEY = IssuerGenerationProjection.keyForIssuer(ISSUER); + private static final String PASSWORD = "issuer-projection-test-only-secret"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--save", + "", + "--appendonly", + "no", + "--user", + "account_coord_app", + "on", + ">" + PASSWORD, + "~" + IssuerGenerationProjection.KEY_PREFIX + "*", + "+get", + "+set", + "+pttl", + "+evalsha", + "+script|load"); + + private final List stores = new ArrayList<>(); + private LettuceConnectionFactory adminFactory; + private LettuceConnectionFactory ownerFactory; + private StringRedisTemplate admin; + private StringRedisTemplate owner; + + @BeforeEach + void connections() { + adminFactory = + new LettuceConnectionFactory( + new RedisStandaloneConfiguration(redis.getHost(), redis.getMappedPort(6379))); + adminFactory.afterPropertiesSet(); + admin = new StringRedisTemplate(adminFactory); + admin.afterPropertiesSet(); + admin.delete(KEY); + var configuration = + new RedisStandaloneConfiguration(redis.getHost(), redis.getMappedPort(6379)); + configuration.setUsername("account_coord_app"); + configuration.setPassword(RedisPassword.of(PASSWORD)); + ownerFactory = new LettuceConnectionFactory(configuration); + ownerFactory.afterPropertiesSet(); + owner = new StringRedisTemplate(ownerFactory); + owner.afterPropertiesSet(); + } + + @AfterEach + void closeConnections() { + stores.forEach(RedisIssuerGenerationProjectionStore::close); + if (adminFactory != null) adminFactory.destroy(); + if (ownerFactory != null) ownerFactory.destroy(); + } + + @Test + void installsActualIssuerBaselineThenLatestAdvanceAndExactRetryWithoutSqlMutationOrTtl() { + Fixture fixture = fixture(true); + var store = store(fixture.producer()); + var baseline = store.refreshCurrent(ISSUER); + assertThat(baseline.outcome()).isEqualTo(Outcome.APPLIED); + assertThat(baseline.snapshot().orElseThrow().json()) + .isEqualTo( + IssuerGenerationProjection.fromSource(fixture.producer().readCurrent(ISSUER)).toJson()); + assertThat(baseline.snapshot().orElseThrow().json()).doesNotContain("sourceEvent"); + fixture.producer().advance(ISSUER, UUID.randomUUID(), 1L, 1L); + var latestEvent = fixture.producer().advance(ISSUER, UUID.randomUUID(), 2L, 2L); + var durable = fixture.producer().readCurrent(ISSUER); + var sqlBefore = + fixture + .dsl() + .fetch("SELECT * FROM account_authority_outbox_events ORDER BY outbox_sequence"); + var applied = store.refreshCurrent(ISSUER); + assertThat(applied.outcome()).isEqualTo(Outcome.APPLIED); + var projection = IssuerGenerationProjection.parse(applied.snapshot().orElseThrow().json()); + assertThat(projection).isEqualTo(IssuerGenerationProjection.fromSource(durable)); + assertThat(projection.lastAppliedSourceOutboxSequence()).isEqualTo("2"); + assertThat(projection.sourceEvent()).contains(latestEvent.canonicalJson()); + assertThat(projection.lastAppliedSourceEventId()).contains(latestEvent.eventId()); + assertThat(projection.lastAppliedSourceEventDigest()).contains(latestEvent.eventDigest()); + var replay = store.refreshCurrent(ISSUER); + assertThat(replay.outcome()).isEqualTo(Outcome.REPLAYED); + assertThat(replay.snapshot()).isEqualTo(applied.snapshot()); + assertThat(admin.opsForValue().get(KEY)).isEqualTo(projection.toJson()); + assertThat(admin.getExpire(KEY, TimeUnit.MILLISECONDS)).isEqualTo(-1L); + assertThat( + fixture + .dsl() + .fetch("SELECT * FROM account_authority_outbox_events ORDER BY outbox_sequence")) + .isEqualTo(sqlBefore); + } + + @Test + void malformedProjectionAndTtlDenyWithoutRepairingStoredBytes() { + Fixture fixture = fixture(true); + var store = store(fixture.producer()); + admin.opsForValue().set(KEY, "{\"unproved\":true}"); + assertThat(store.refreshCurrent(ISSUER).outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(admin.opsForValue().get(KEY)).isEqualTo("{\"unproved\":true}"); + String baseline = + IssuerGenerationProjection.fromSource(fixture.producer().readCurrent(ISSUER)).toJson(); + admin.opsForValue().set(KEY, baseline, 1L, TimeUnit.HOURS); + assertThat(store.refreshCurrent(ISSUER).outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(admin.opsForValue().get(KEY)).isEqualTo(baseline); + assertThat(admin.getExpire(KEY, TimeUnit.MILLISECONDS)).isPositive(); + } + + @Test + void aheadSourceAndSameCheckpointDifferentActualEventDenyWithoutOverwrite() { + Fixture first = fixture(true); + first.producer().advance(ISSUER, UUID.randomUUID(), 1L, 1L); + String firstJson = + IssuerGenerationProjection.fromSource(first.producer().readCurrent(ISSUER)).toJson(); + admin.opsForValue().set(KEY, firstJson); + Fixture second = fixture(true); + var secondStore = store(second.producer()); + assertThat(secondStore.refreshCurrent(ISSUER).outcome()).isEqualTo(Outcome.STALE_SOURCE); + second.producer().advance(ISSUER, UUID.randomUUID(), 1L, 1L); + var mismatch = secondStore.refreshCurrent(ISSUER); + assertThat(mismatch.outcome()).isEqualTo(Outcome.QUARANTINED); + assertThat(mismatch.detail()).contains("SAME_CHECKPOINT_DISAGREEMENT"); + assertThat(admin.opsForValue().get(KEY)).isEqualTo(firstJson); + } + + @Test + void actualCommittedSourceAdvanceBetweenOwnerReadsReturnsSourceChangedWithoutImplicitRetry() { + Fixture fixture = fixture(true); + AtomicInteger reads = new AtomicInteger(); + // Test-only scheduling hook. Both read results and the intervening advance use actual SQL. + PlatformTransactionManager interleaving = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + if (reads.incrementAndGet() == 2) { + fixture.producer().advance(ISSUER, UUID.randomUUID(), 1L, 1L); + } + return fixture.manager().getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + fixture.manager().commit(status); + } + + @Override + public void rollback(TransactionStatus status) { + fixture.manager().rollback(status); + } + }; + var reader = + new AccountIssuerAuthorityEventProducer( + ISSUER, fixture.generations(), fixture.outbox(), fixture.dsl(), interleaving); + var store = store(reader); + var result = store.refreshCurrent(ISSUER); + assertThat(result.outcome()).isEqualTo(Outcome.SOURCE_CHANGED); + assertThat(reads.get()).isEqualTo(2); + assertThat( + IssuerGenerationProjection.parse(admin.opsForValue().get(KEY)).issuerAuthGeneration()) + .isEqualTo("1"); + assertThat(fixture.producer().readCurrent(ISSUER).issuerAuthGeneration()).isEqualTo(2L); + assertThat(store.refreshCurrent(ISSUER).outcome()).isEqualTo(Outcome.APPLIED); + } + + @Test + void missingAndContradictoryOwnerHistoryDenyWithoutEnrollmentOrRedisWrite() { + Fixture missing = fixture(false); + assertThatThrownBy(() -> store(missing.producer()).refreshCurrent(ISSUER)) + .isInstanceOf(IllegalStateException.class); + assertThat(missing.dsl().fetchCount(DSL.table("account_authority_generations"))).isZero(); + assertThat(admin.opsForValue().get(KEY)).isNull(); + Fixture malformed = fixture(true); + new TransactionTemplate(malformed.manager()) + .executeWithoutResult( + status -> + malformed + .generations() + .advance(malformed.generations().read(AuthorityScope.issuer(ISSUER)), null)); + assertThatThrownBy(() -> store(malformed.producer()).refreshCurrent(ISSUER)) + .isInstanceOf(IllegalStateException.class); + assertThat(admin.opsForValue().get(KEY)).isNull(); + } + + @Test + void explicitInitKnownIssuerEndpointSeparationAndAclPreventRoleOrDirectEvalSubstitution() { + Fixture fixture = fixture(true); + var uninitialized = + new RedisIssuerGenerationProjectionStore(fixture.producer(), endpoint(), cache()); + stores.add(uninitialized); + assertThatThrownBy(() -> uninitialized.refreshCurrent(ISSUER)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + new RedisIssuerGenerationProjectionStore( + fixture.producer(), + endpoint(), + new CacheRateLimitEndpoint(redis.getHost(), redis.getMappedPort(6379)))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new CoordinationEndpoint( + redis.getHost(), redis.getMappedPort(6379), "cache_app", PASSWORD)) + .isInstanceOf(IllegalArgumentException.class); + var store = store(fixture.producer()); + assertThatThrownBy(() -> store.refreshCurrent("other-issuer")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> owner.opsForValue().get("session:game:auth:issuer-generation:v1:" + ISSUER)) + .satisfies(failure -> assertThat(messageChain(failure)).contains("NOPERM")); + assertThatThrownBy(() -> owner.opsForValue().get("ratelimit:test")) + .satisfies(failure -> assertThat(messageChain(failure)).contains("NOPERM")); + assertThatThrownBy( + () -> + owner.execute( + (RedisCallback) + connection -> + connection + .scriptingCommands() + .eval( + "return 1".getBytes(StandardCharsets.UTF_8), + ReturnType.INTEGER, + 0))) + .satisfies(failure -> assertThat(messageChain(failure)).contains("NOPERM")); + assertThat(admin.opsForValue().get(KEY)).isNull(); + store.close(); + assertThatThrownBy(() -> store.refreshCurrent(ISSUER)) + .isInstanceOf(IllegalStateException.class); + } + + private RedisIssuerGenerationProjectionStore store(AccountIssuerAuthorityEventProducer producer) { + var store = new RedisIssuerGenerationProjectionStore(producer, endpoint(), cache()); + stores.add(store); + store.init(); + return store; + } + + private CoordinationEndpoint endpoint() { + return new CoordinationEndpoint( + redis.getHost(), redis.getMappedPort(6379), "account_coord_app", PASSWORD); + } + + private CacheRateLimitEndpoint cache() { + return new CacheRateLimitEndpoint("cache-role.example.test", 6379); + } + + private static Fixture fixture(boolean enroll) { + String schema = "issuer_projection_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = new DriverManagerDataSource(); + dataSource.setUrl( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("67") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(dataSource); + var generations = new AccountAuthorityGenerationRepository(dsl); + if (enroll) + new TransactionTemplate(manager) + .executeWithoutResult(status -> generations.initializeIssuerIfAbsent(ISSUER)); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var producer = + new AccountIssuerAuthorityEventProducer(ISSUER, generations, outbox, dsl, manager); + return new Fixture(dsl, manager, generations, outbox, producer); + } + + private static String messageChain(Throwable failure) { + StringBuilder messages = new StringBuilder(); + for (Throwable current = failure; current != null; current = current.getCause()) + messages.append(current.getMessage()).append('\n'); + return messages.toString(); + } + + private record Fixture( + DSLContext dsl, + DataSourceTransactionManager manager, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox, + AccountIssuerAuthorityEventProducer producer) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionRedisContractTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionRedisContractTest.java new file mode 100644 index 0000000000..c42743b671 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionRedisContractTest.java @@ -0,0 +1,85 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjectionRedisContract; +import net.firedevops.firemud.common.redis.contracts.RedisContractRegistry.InvocationRequest; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.RedisRole; +import org.junit.jupiter.api.Test; +import org.springframework.core.io.ClassPathResource; + +class IssuerGenerationProjectionRedisContractTest { + @Test + void registersCanonicalAccountOwnerCoordinationDescriptorAndExactExistingResource() + throws Exception { + var descriptor = IssuerGenerationProjectionRedisContract.descriptor(); + assertThat(descriptor.owner()).isEqualTo("account-service"); + assertThat(descriptor.principal()).isEqualTo("account_coord_app"); + assertThat(descriptor.role()).isEqualTo(RedisRole.COORDINATION); + assertThat(IssuerGenerationProjectionRedisContract.KEY_PREFIX) + .isEqualTo("session:auth:generation:issuer:"); + try (var input = new ClassPathResource(descriptor.resourcePath()).getInputStream()) { + assertThat(descriptor.sha256()) + .isEqualTo( + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(input.readAllBytes()))); + } + var invocation = + IssuerGenerationProjectionRedisContract.registry() + .prepareInvocation( + request( + "account-service", + "account_coord_app", + RedisRole.COORDINATION, + "session:auth:generation:issuer:firemud-account-service")); + assertThat(invocation.descriptor()).isSameAs(descriptor); + } + + @Test + void rejectsCacheRoleWrongPrincipalAndGameSessionDerivedKey() { + for (InvocationRequest request : + List.of( + request( + "game-session-service", + "account_coord_app", + RedisRole.COORDINATION, + "session:auth:generation:issuer:firemud-account-service"), + request( + "account-service", + "cache_app", + RedisRole.COORDINATION, + "session:auth:generation:issuer:firemud-account-service"), + request( + "account-service", + "account_coord_app", + RedisRole.CACHE_RATE_LIMIT, + "session:auth:generation:issuer:firemud-account-service"), + request( + "account-service", + "account_coord_app", + RedisRole.COORDINATION, + "session:game:auth:issuer-generation:v1:firemud-account-service"))) { + assertThatThrownBy( + () -> IssuerGenerationProjectionRedisContract.registry().prepareInvocation(request)) + .isInstanceOf(RuntimeException.class); + } + } + + private static InvocationRequest request( + String owner, String principal, RedisRole role, String key) { + var descriptor = IssuerGenerationProjectionRedisContract.descriptor(); + return new InvocationRequest( + descriptor.scriptId(), + descriptor.resourcePath(), + descriptor.sha256(), + owner, + principal, + role, + List.of(key), + List.of("ABSENT", "", "test-candidate")); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java new file mode 100644 index 0000000000..001b1c9111 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/IssuerGenerationProjectionTest.java @@ -0,0 +1,194 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer.IssuerAuthoritySnapshot; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import org.junit.jupiter.api.Test; + +class IssuerGenerationProjectionTest { + private static final String ISSUER = ControlUiJwtProfileValidator.ISSUER; + private static final String STREAM = "account:auth-authority:v1:issuer/" + ISSUER; + + @Test + void baselineOmitsAllEventFieldsAndUsesOnlyCanonicalAccountIssuerKey() { + var projection = + IssuerGenerationProjection.fromSource( + new IssuerAuthoritySnapshot(ISSUER, 1L, 1L, STREAM, 0L, Optional.empty())); + assertThat(IssuerGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + assertThat(projection.key()).isEqualTo("session:auth:generation:issuer:" + ISSUER); + assertThat(projection.toJson()) + .doesNotContain("sourceEvent", "lastAppliedSourceEventId", "lastAppliedSourceEventDigest"); + assertThatThrownBy(() -> IssuerGenerationProjection.keyForIssuer("other-issuer")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactPositiveOwnerEventRetainsIdentityDigestScopeAndCheckpoint() { + var event = IssuerGenerationAuthorityEventV1Codec.seal(eventFields("2", "2", "1")); + var projection = + IssuerGenerationProjection.fromSource( + new IssuerAuthoritySnapshot(ISSUER, 2L, 2L, STREAM, 1L, Optional.of(event))); + assertThat(IssuerGenerationProjection.parse(projection.toJson())).isEqualTo(projection); + assertThat(projection.lastAppliedSourceEventId()).contains(event.eventId()); + assertThat(projection.lastAppliedSourceEventDigest()).contains(event.eventDigest()); + assertThat(projection.sourceEvent()).contains(event.canonicalJson()); + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "3", + "2", + STREAM, + "1", + Optional.of(event.eventId()), + Optional.of(event.eventDigest()), + Optional.of(event.canonicalJson()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "2", + "2", + STREAM, + "1", + Optional.of("different-event"), + Optional.of(event.eventDigest()), + Optional.of(event.canonicalJson()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "2", + "2", + STREAM, + "1", + Optional.of(event.eventId()), + Optional.of("sha256:" + "f".repeat(64)), + Optional.of(event.canonicalJson()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "2", + "2", + STREAM, + "1", + Optional.of(event.eventId()), + Optional.of(event.eventDigest()), + Optional.of( + event + .canonicalJson() + .replace("\"sourceVersion\":\"2\"", "\"sourceVersion\":\"3\"")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void independentLargeDecimalCountersRemainExactWithoutFloatingPointOrLongNarrowing() { + var event = + IssuerGenerationAuthorityEventV1Codec.seal( + eventFields("9007199254740993", "9223372036854775809", "9007199254740992")); + var projection = + new IssuerGenerationProjection( + ISSUER, + event.issuerAuthGeneration(), + event.sourceVersion(), + STREAM, + event.outboxSequence(), + Optional.of(event.eventId()), + Optional.of(event.eventDigest()), + Optional.of(event.canonicalJson())); + var parsed = IssuerGenerationProjection.parse(projection.toJson()); + assertThat(parsed.generationValue()).isEqualTo(new BigInteger("9007199254740993")); + assertThat(parsed.sourceVersionValue()).isEqualTo(new BigInteger("9223372036854775809")); + assertThat(parsed.outboxSequenceValue()).isEqualTo(new BigInteger("9007199254740992")); + } + + @Test + void closedParserRejectsDuplicateUnknownNullTrailingAndNoncanonicalForms() { + String json = + IssuerGenerationProjection.fromSource( + new IssuerAuthoritySnapshot(ISSUER, 1L, 1L, STREAM, 0L, Optional.empty())) + .toJson(); + for (String invalid : + List.of( + json + " {}", + " " + json, + json.replace("\"issuerAuthGeneration\":\"1\"", "\"issuerAuthGeneration\":1"), + json.replace("\"issuerAuthGeneration\":\"1\"", "\"issuerAuthGeneration\":null"), + json.replace( + "\"issuerAuthGeneration\":\"1\"", + "\"issuerAuthGeneration\":\"1\",\"issuerAuthGeneration\":\"1\""), + json.substring(0, json.length() - 1) + ",\"unknown\":\"1\"}", + json.substring(0, json.length() - 1) + ",\"sourceEvent\":null}")) { + assertThatThrownBy(() -> IssuerGenerationProjection.parse(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + for (String counter : List.of("0", "-1", "+1", "01", " 1", "1 ", "1.0", "1e3", "")) { + assertThatThrownBy( + () -> + IssuerGenerationProjection.parse( + json.replace( + "\"issuerAuthGeneration\":\"1\"", + "\"issuerAuthGeneration\":\"" + counter + "\""))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void sequenceZeroCannotInventAdvancedStateAndPositiveSequenceCannotOmitEvidence() { + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "2", + "2", + STREAM, + "0", + Optional.empty(), + Optional.empty(), + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new IssuerGenerationProjection( + ISSUER, + "2", + "2", + STREAM, + "1", + Optional.empty(), + Optional.empty(), + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Map eventFields( + String generation, String version, String sequence) { + UUID request = UUID.randomUUID(); + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION); + fields.put("eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE); + fields.put("eventId", "account-issuer-authority-event-v1:" + request); + fields.put("requestId", request.toString()); + fields.put("issuerId", ISSUER); + fields.put("sourceScope", "issuer/" + ISSUER); + fields.put("outboxStreamKey", STREAM); + fields.put("outboxSequence", sequence); + fields.put("issuerAuthGeneration", generation); + fields.put("sourceVersion", version); + return fields; + } +} From bfd38c7b945194c1ed70a0d7964cf41c6b1943d9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:43:26 +1300 Subject: [PATCH 09/12] Persist original control-ui signing intent before token hash binding --- .github/workflows/ci.yml | 11 + .../account-service/runtime-and-data.md | 2 + .../player-access-and-session.md | 4 + .../AccountControlUiIssuanceIntent.java | 55 ++ ...ountControlUiIssuanceIntentRepository.java | 140 +++++ ...tControlUiIssuanceOperationRepository.java | 19 +- ...AccountControlUiOriginalSourceCapture.java | 181 ++++++ .../AccountControlUiPreSignIntentService.java | 111 ++++ .../V74__control_ui_presign_intent.sql | 77 +++ ...AuthenticationPostgresIntegrationTest.java | 21 +- ...IssuanceIntentPostgresIntegrationTest.java | 552 ++++++++++++++++++ ...uanceOperationPostgresIntegrationTest.java | 82 ++- ...lProducerPostgresRedisIntegrationTest.java | 19 +- ...untControlUiOriginalSourceCaptureTest.java | 242 ++++++++ 14 files changed, 1490 insertions(+), 26 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceIntent.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceIntentRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiOriginalSourceCapture.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiPreSignIntentService.java create mode 100644 services/account-service/src/main/resources/db/migration/V74__control_ui_presign_intent.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiOriginalSourceCaptureTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ae8befcdda..12d51bd8eb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2481,6 +2481,7 @@ jobs: services/account-service/build/test-results/integrationTest/TEST-*AccountSecurityStateOperationPostgresIntegrationTest.xml services/account-service/build/test-results/integrationTest/TEST-*AccountControlUiIssuanceOperationPostgresIntegrationTest.xml services/account-service/build/test-results/integrationTest/TEST-*AccountControlUiCurrentSourcePostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountControlUiIssuanceIntentPostgresIntegrationTest.xml if-no-files-found: warn retention-days: 7 @@ -2492,8 +2493,18 @@ jobs: --require-suite integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest \ --require-suite integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceOperationPostgresIntegrationTest \ --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceIntentPostgresIntegrationTest \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#unsignedInitialObservationReadsExactExistingAccountSourcesAndFenceWithoutEnrollment()' \ --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourcePostgresIntegrationTest#unsignedObservationRetainsAdvancedIssuerEventAndSignedInspectionStillChecksCorrespondence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceIntentPostgresIntegrationTest#ownerSourceCapturePrecedesSigningAndRestartRecoversOriginalReservationWithoutRecapture()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceIntentPostgresIntegrationTest#differentHashIdentityOrFenceCannotReplaceOriginalAndSqlCannotMutateReservation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceIntentPostgresIntegrationTest#changedCurrentIssuerDeniesProgressionAndPreservesHistoricalCaptureAndHash()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceIntentPostgresIntegrationTest#advancedIssuerEventIsCapturedExactlyAndMissingAuthorityNeverEnrolls()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceIntentPostgresIntegrationTest#abortedPresignAndPostsignTransactionsDoNotLeavePartialProgress()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceIntentPostgresIntegrationTest#preexistingV66OperationWithoutSigningReservationIsNeverRepairedOnRetry()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceIntentPostgresIntegrationTest#postSignCasSerializesWithIssuerWriterAndRetainsOriginalHash()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceIntentPostgresIntegrationTest#concurrentPresignRetriesRecoverOneOriginalIdentityAndDifferentHashCasHasOneWinner()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountControlUiIssuanceIntentPostgresIntegrationTest#committedAccountLifecycleChangeSerializesWithPostSignCasAndDeniesHashBinding()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#pendingClaimAndExactRetryRetainOneOriginalCaptureWithoutSourceMutation()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#originalCallerAndFamilyBindingsCannotBeChangedOnRetry()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountSecurityStateOperationPostgresIntegrationTest#concurrentExactClaimsSerializeToOneOriginalRequest()' \ diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index c5cc27c345..3c22a3005e 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -255,6 +255,8 @@ Every recovery authenticates a currently valid credential for the same Account a Only after those checks may Account return the original encrypted response bytes. It never remints a token, extends expiry, resets issuance time, relabels a delegation token, or treats recovery as tenant/gameplay admission. Missing custody or currentness, wrong key/purpose/binding, conflicting operation evidence, and revoked or expired registry state fail closed. Confidential response retention is bounded by its documented recovery horizon, no later than original token expiry; immutable non-secret operation evidence and the existing safe key-retirement proof remain separate. +V74 adds an unwired `account_control_ui_issuance_intents` reservation for an existing V66 operation. Its pre-sign owner transaction reads only existing Account sources issuer-first and preserves the complete exact source capture, checkpoints, and positive source-version, source-fence, and issuance-fence evidence while reserving the token `jti` and authority-evidence bundle UUID/version. After a future caller obtains signer output, a separate owner transaction re-reads the source and binds only the SHA-256 hash of the exact compact JWT by write-once CAS; an exact retry returns the original reservation, while changed currentness or a competing hash cannot replace it. This component does not call a signer, verify a token, complete the authority bundle, write or activate the issued-token registry, or release credentials. It does not disable the existing legacy `/auth/login` implementation in this candidate. Producer activation and complete currentness, signer/JWKS correspondence, immutable bundle, registry, response-recovery, and fresh-image/runtime proof remain open under [ADR 0014](../../decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md) and [ADR 0035](../../decisions/adr-0035-single-record-issued-token-registry.md); this paragraph records only the local V74 storage and retry consequence. + The unmerged creator-route components do not yet implement complete issuance or original-response recovery. Fresh credential evidence alone cannot authorize either result release or creator mutation. Lost-response/restart, fresh-credential exact recovery, consumed-OTP denial, cross-Account and conflicting-request denial, expiry/revocation/currentness, and wrong-key/purpose/binding proof remain required before activation; detailed implementation status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). ## Membership and Entitlement Authority 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 936cabc664..6d03cc55ed 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,10 @@ Five additional PostgreSQL/Cache Redis definitions call the real Account credent The existing-only unscoped control-ui source reader now has a pre-sign entry, `readUnscopedCurrent`, independent of an already signed candidate. It retains issuer-first locking, Account provenance, fresh-empty roles, exact source history/checkpoints and the issuance fence in one writable owner transaction; signed inspection delegates to it and still compares every represented claim and registry source version. Two additional PostgreSQL definitions cover fresh non-mutating readback and advanced issuer evidence with mismatched signed inputs, while the existing denial cases also exercise unsigned reads. Strict CI requires all ten source-observation methods. This is a non-authorizing observation, not a complete durable capture, authenticated caller, current Coordination projection, signer or released credential; new PostgreSQL execution remains open. +V74 adds an unwired `AccountControlUiPreSignIntentService` over the existing V66 operation. Its first owner transaction captures only existing issuer-first Account sources, retains the exact source bytes/checkpoints and positive database source-version, source-fence, and issuance-fence values, and reserves the `jti` and authority-evidence bundle UUID/version. Exact retries recover that original reservation without recapture; a separate post-sign owner transaction rechecks the same current source and binds the exact compact-token SHA-256 hash with write-once CAS. The reservation is non-authorizing and does not call a signer, finish a bundle, write/activate the registry, or release a credential. The existing legacy `/auth/login` remains functional in this candidate; new producer activation is closed. The nine PostgreSQL methods are required by strict CI, but their execution is unproved. Sign-in wiring, exact token and signer/JWKS fencing, current Coordination projections, complete immutable bundle, pending/active registry, encrypted response/recovery, and fresh-image/runtime proof remain open under [Account's recovery contract](../../architecture/microservices/account-service/runtime-and-data.md#exact-control-ui-issuance-recovery). + +The composed V74 preparation and inherited Game Logic fixture correction pass Account jOOQ, full Account and Game Logic checks, Account boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown in 1m55s (102 tasks, 24 executed). Account records 1,062 clean unit executions; all 465 integration cases, including the nine V74 definitions, skip without Docker. Game Logic reuses 101 clean unit and five non-PostgreSQL integration outcomes, while ten PostgreSQL cases skip. Actionlint, 25 CI classifier cases, validation-summary and Gradle-proof tooling contracts, Flyway sanity (12 sets/207 files), and diff hygiene pass. Configuration-cache storage is discarded for 36 protobuf problems. Compilation and skipped definitions do not establish PostgreSQL migration, race, signer, deployed custody or end-to-end credential proof. + The targetless control-ui credential component uses the existing Account password/OTP verifier and trusted first-party credential-attempt limiter, then records fresh credential evidence against an existing V66 operation. V68 retains that immutable evidence and atomically consumes only the exact eligible OTP challenge; it introduces no second issuance owner, plaintext credential, token or authority capture. Initial attempts require the original pending operation; response-recovery attempts require its unexpired committed result and authenticate again. Seven PostgreSQL definitions cover nonempty V67-to-V68 preservation, binding and lifecycle denial, exact challenge predicates, late-insert rollback, database-observed competing claims and immutability. Their original captures and verifier results are stipulated repository fixtures, not complete authenticated issuance. The closed control-ui inspection now requires the canonical capture `sourceFence`, independently of source versions and issuance fence, with exact large-decimal and incomplete-reference rejection tests. The composed five-module check, three service boot JARs, Account and Game Design jOOQ, formatting, Checkstyle, SpotBugs, links and Markdown pass in 1m45s (160 tasks: 21 executed). Account has 1054 clean unit outcomes; Common Platform Core 253 and Common Data Runtime 16 are clean reused results. Game Design has 542 executed unit cases and one object-store skip; World has 346 clean unit outcomes. All 714 integration cases skip without Docker (Account 443, Game Design 145 and World 126), including the seven new credential cases. The later physical Account reservation-client proof is outside this validated snapshot. The actual original capture producer, signer and pending/active registry composition, complete currentness, protected ring delivery and original-response release remain open. This component is not exposed as an enabled login route and does not grant creator or gameplay authority; executed PostgreSQL and activation evidence remain required. At published `c459bfd672d99fcd6858011caaf08c954bda2629`, V66 uses a PostgreSQL constraint trigger for its deferred exact-envelope requirement. The prior exact `e057e1f873753fe7141a53a1e65f2c9f214b1d38` [CI37414054058](https://github.com/benhook1013/FireMUD/actions/runs/37414054058) failed migration on the ordinary trigger's unsupported `DEFERRABLE` syntax: fifteen Account cases were reported, eleven failed startup, and the thirty-four required V65/V66/current-source/creation-order cases supplied no execution XML. Corrected-source [CI37415795444](https://github.com/benhook1013/FireMUD/actions/runs/37415795444) executes the twenty-seven V65/V66/current-source methods with zero skips: seventeen pass and ten fail. All eight current-source cases pass. The seven tenant-creation cases pass without skips according to their exact selector step and HTML report; standalone raw XML for that suite is unavailable. V66's additive migration succeeds, but its completion repository binds timestamps as varchar, and the missing-envelope negative also fails on that type mismatch before the deferred commit guard. Seven V65 failures come from the fixture storing event-array order instead of the canonical login-mode database representation. The correction adds explicit timestamp casts and uses the existing login-mode storage serializer without changing event digests, database guards or immutable readback. Its prepared V68 challenge queries use explicit timestamp-without-zone casts as well. Corrected PostgreSQL execution, genuine missing-envelope commit rejection and activation remain unproved; the aggregate run is separate from these executed component results. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceIntent.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceIntent.java new file mode 100644 index 0000000000..3185e72335 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceIntent.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiOriginalSourceCapture; + +/** + * Reserved identity and write-once post-sign hash, not a completed evidence bundle or credential. + */ +public record AccountControlUiIssuanceIntent( + AccountControlUiIssuanceOperation operation, + UUID jti, + UUID bundleId, + long bundleVersion, + long sourceVersion, + long sourceFence, + Optional tokenHash) { + public AccountControlUiIssuanceIntent { + Objects.requireNonNull(operation); + nonNil(jti); + nonNil(bundleId); + if (bundleVersion != 1L || sourceVersion <= 0L || sourceFence <= 0L) { + throw new IllegalArgumentException("Invalid reserved control-ui capture reference"); + } + tokenHash = Objects.requireNonNull(tokenHash); + tokenHash.ifPresent( + hash -> { + if (!hash.matches("[0-9a-f]{64}")) + throw new IllegalArgumentException("Invalid compact JWT hash"); + }); + if (!AccountControlUiOriginalSourceCapture.read(operation.originalCapture()) + .accountUuid() + .equals(operation.request().accountUuid())) { + throw new IllegalStateException("Original source subject differs from its operation"); + } + if (operation.completedResponse() != null + && !tokenHash.equals(Optional.of(operation.completedResponse().binding().tokenHash()))) { + throw new IllegalStateException( + "Original committed result differs from reserved token identity"); + } + } + + private static void nonNil(UUID value) { + if (value == null || value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException("Non-nil reserved identity required"); + } + + @Override + public String toString() { + return "AccountControlUiIssuanceIntent[operationId=" + + operation.operationId() + + ", non-authorizing]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceIntentRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceIntentRepository.java new file mode 100644 index 0000000000..749d90b116 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceIntentRepository.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Supplemental V74 storage; V66 retains sole ownership of operation/request correlation. */ +public final class AccountControlUiIssuanceIntentRepository { + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account persistence context remains an internal owner collaborator.") + public AccountControlUiIssuanceIntentRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public AccountControlUiIssuanceIntent reserve( + AccountControlUiIssuanceOperation operation, UUID jti, UUID bundleId) { + transaction(); + // The durable source version/fence are database allocated, never inferred. + if (jti == null + || bundleId == null + || jti.equals(new UUID(0L, 0L)) + || bundleId.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException("Non-nil signing identities required"); + if (operation.lifecycle() != AccountControlUiIssuanceOperation.Lifecycle.PENDING) + throw conflict(); + int inserted = + dsl.execute( + "INSERT INTO account_control_ui_issuance_intents " + + "(operation_id, jti, bundle_id, bundle_version, authority_capture_digest, issuance_fence_digest, phase) " + + "VALUES (?, ?, ?, 1, ?, ?, 'PENDING') ON CONFLICT (operation_id) DO NOTHING", + operation.operationId(), + jti, + bundleId, + operation.originalCapture().authorityCaptureDigest(), + operation.originalCapture().issuanceFenceDigest()); + AccountControlUiIssuanceIntent stored = + read(operation).orElseThrow(AccountControlUiIssuanceIntentRepository::conflict); + if (inserted != 1 + || !stored.jti().equals(jti) + || !stored.bundleId().equals(bundleId) + || stored.tokenHash().isPresent()) throw conflict(); + return stored; + } + + public Optional read( + AccountControlUiIssuanceOperation operation) { + transaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_intents WHERE operation_id = ? FOR UPDATE", + operation.operationId()); + if (row == null) return Optional.empty(); + if (!MessageDigest.isEqual( + row.get("authority_capture_digest", byte[].class), + operation.originalCapture().authorityCaptureDigest()) + || !MessageDigest.isEqual( + row.get("issuance_fence_digest", byte[].class), + operation.originalCapture().issuanceFenceDigest())) throw conflict(); + String hash = row.get("token_hash", String.class); + if (!(hash == null ? "PENDING" : "HASH_BOUND").equals(row.get("phase", String.class))) + throw conflict(); + return Optional.of( + new AccountControlUiIssuanceIntent( + operation, + row.get("jti", UUID.class), + row.get("bundle_id", UUID.class), + row.get("bundle_version", Long.class), + row.get("source_version", Long.class), + row.get("source_fence", Long.class), + Optional.ofNullable(hash))); + } + + /** + * The owner service must already hold issuer-first current-source locks and prove exact equality. + */ + public AccountControlUiIssuanceIntent bindTokenHash( + AccountControlUiIssuanceIntent expected, String tokenHash) { + transaction(); + if (tokenHash == null || !tokenHash.matches("[0-9a-f]{64}")) + throw new IllegalArgumentException("Invalid compact JWT hash"); + if (expected.tokenHash().isPresent() && !expected.tokenHash().orElseThrow().equals(tokenHash)) + throw conflict(); + var stored = + read(expected.operation()).orElseThrow(AccountControlUiIssuanceIntentRepository::conflict); + if (!sameIdentity(stored, expected)) throw conflict(); + if (stored.tokenHash().isPresent()) { + if (!stored.tokenHash().orElseThrow().equals(tokenHash)) throw conflict(); + return stored; + } + if (dsl.execute( + "UPDATE account_control_ui_issuance_intents SET phase = 'HASH_BOUND', token_hash = ? " + + "WHERE operation_id = ? AND jti = ? AND bundle_id = ? AND bundle_version = ? " + + "AND source_version = ? AND source_fence = ? AND phase = 'PENDING' AND token_hash IS NULL", + tokenHash, + stored.operation().operationId(), + expected.jti(), + expected.bundleId(), + expected.bundleVersion(), + expected.sourceVersion(), + expected.sourceFence()) + != 1) throw conflict(); + var readback = + read(expected.operation()).orElseThrow(AccountControlUiIssuanceIntentRepository::conflict); + if (!sameIdentity(readback, expected) || !readback.tokenHash().equals(Optional.of(tokenHash))) + throw conflict(); + return readback; + } + + private static boolean sameIdentity( + AccountControlUiIssuanceIntent left, AccountControlUiIssuanceIntent right) { + return left.operation().operationId().equals(right.operation().operationId()) + && left.operation().request().equals(right.operation().request()) + && left.operation().originalCapture().equals(right.operation().originalCapture()) + && left.jti().equals(right.jti()) + && left.bundleId().equals(right.bundleId()) + && left.bundleVersion() == right.bundleVersion() + && left.sourceVersion() == right.sourceVersion() + && left.sourceFence() == right.sourceFence(); + } + + private static void transaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + throw new IllegalStateException("Writable Account owner transaction required"); + } + + private static IllegalStateException conflict() { + return new IllegalStateException( + "Original control-ui signing intent conflicts or is incomplete"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java index b4657c1db6..33358bb4a3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiIssuanceOperationRepository.java @@ -38,12 +38,20 @@ public AccountControlUiIssuanceOperationRepository(DSLContext dsl) { } /** - * Claims the stable request identity or recovers its original capture. An existing exact retry - * may omit a new capture; if it supplies one, it must byte-match the immutable first capture. + * Claims the stable request identity with its caller-preallocated internal operation ID, or + * recovers the original capture. An existing exact retry returns the stored operation ID even + * when the caller's proposed ID differs; a supplied capture must byte-match the immutable first + * capture. */ public Claim claim( - AccountControlUiIssuanceRequest request, Optional proposedCapture) { + UUID operationId, + AccountControlUiIssuanceRequest request, + Optional proposedCapture) { requireWritableOwnerTransaction(); + Objects.requireNonNull(operationId, "operationId"); + if (operationId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("operationId must be non-nil"); + } Objects.requireNonNull(request, "request"); Objects.requireNonNull(proposedCapture, "proposedCapture"); byte[] requestDigest = AccountControlUiIssuanceRequestDigest.digest(request); @@ -67,7 +75,6 @@ public Claim claim( proposedCapture.orElseThrow( () -> new IllegalArgumentException("First control-UI claim requires original capture")); requireCaptureAssociation(capture, association); - UUID proposedOperationId = UUID.randomUUID(); int inserted = dsl.execute( "INSERT INTO " @@ -78,7 +85,7 @@ public Claim claim( + "issuance_fence_digest, status) " + "VALUES (?, ?, ?, ?, ?, 'control-ui', 'control-ui', ?, ?, ?, ?, ?, ?, 'PENDING') " + "ON CONFLICT (request_id) DO NOTHING", - proposedOperationId, + operationId, UUID.fromString(request.requestId()), UUID.fromString(request.accountUuid()), association.accountId(), @@ -101,7 +108,7 @@ public Claim claim( "Control-UI issuance claim has no durable operation readback")); requireRequestAndAssociation(stored, request, requestDigest, association); if (inserted == 1 - && (!stored.operationId().equals(proposedOperationId) + && (!stored.operationId().equals(operationId) || !stored.originalCapture().equals(capture))) { throw new IllegalStateException("First control-UI claim readback differs from its proposal"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiOriginalSourceCapture.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiOriginalSourceCapture.java new file mode 100644 index 0000000000..f518dc00e0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiOriginalSourceCapture.java @@ -0,0 +1,181 @@ +package net.firedevops.firemud.accountservice.service.controlui; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.json.JsonMapper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourceRepository.CurrentSourceObservation; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation.OriginalCapture; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Exact original unscoped owner-source bytes. This is not a completed authorization bundle. */ +public final class AccountControlUiOriginalSourceCapture { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Set FIELDS = + Set.of( + "schemaVersion", + "profile", + "audience", + "accountId", + "authorityTuple", + "membershipVersion", + "scopedRoles", + "globalRoles", + "issuerSource", + "accountSource", + "globalRoleSourceVersion"); + private final OriginalCapture capture; + + private AccountControlUiOriginalSourceCapture(OriginalCapture capture) { + this.capture = Objects.requireNonNull(capture); + Map authority = decode(capture.authorityCapture()); + Map fence = decode(capture.issuanceFenceCapture()); + if (!authority.keySet().equals(FIELDS) + || !"account-control-ui-original-source/v1".equals(authority.get("schemaVersion")) + || !"control-ui".equals(authority.get("profile")) + || !"control-ui".equals(authority.get("audience")) + || !Map.of().equals(authority.get("membershipVersion")) + || !Map.of().equals(authority.get("scopedRoles")) + || !List.of().equals(authority.get("globalRoles"))) throw invalid(); + var issuer = IssuerGenerationProjection.parse(text(authority, "issuerSource")); + var account = AccountGenerationProjection.parse(text(authority, "accountSource")); + positive(authority.get("globalRoleSourceVersion")); + if (!account.accountId().equals(authority.get("accountId")) + || !fence + .keySet() + .equals(Set.of("schemaVersion", "accountId", "issuanceFence", "sourceVersion")) + || !"account-control-ui-original-fence/v1".equals(fence.get("schemaVersion")) + || !account.accountId().equals(fence.get("accountId"))) throw invalid(); + positive(fence.get("issuanceFence")); + positive(fence.get("sourceVersion")); + if (!tuple(issuer, account).equals(authority.get("authorityTuple"))) throw invalid(); + } + + /** Called only after the existing-only reader has acquired the canonical issuer/Account locks. */ + public static AccountControlUiOriginalSourceCapture fromCurrent( + CurrentSourceObservation source, Account account) { + Objects.requireNonNull(source); + Objects.requireNonNull(account); + if (!source.accountId().equals(account.getAccountUuid()) + || account.getId() == null + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || account.getAccountUuidProvenance() == null + || !source.authority().tenants().isEmpty() + || !source.authority().memberships().isEmpty()) throw invalid(); + var issuer = IssuerGenerationProjection.fromSource(source.issuerSource()); + var currentAccount = AccountGenerationProjection.fromSource(source.accountSource()); + Map authority = new LinkedHashMap<>(); + authority.put("schemaVersion", "account-control-ui-original-source/v1"); + authority.put("profile", "control-ui"); + authority.put("audience", "control-ui"); + authority.put("accountId", source.accountId().toString()); + authority.put("authorityTuple", tuple(issuer, currentAccount)); + authority.put("membershipVersion", Map.of()); + authority.put("scopedRoles", Map.of()); + authority.put("globalRoles", List.of()); + authority.put("issuerSource", issuer.toJson()); + authority.put("accountSource", currentAccount.toJson()); + authority.put("globalRoleSourceVersion", Long.toString(source.globalRoleSourceVersion())); + var fence = source.authority().issuanceFence(); + return new AccountControlUiOriginalSourceCapture( + new OriginalCapture( + account.getId(), + account.getAccountUuidProvenance(), + encode(authority), + encode( + Map.of( + "schemaVersion", "account-control-ui-original-fence/v1", + "accountId", source.accountId().toString(), + "issuanceFence", Long.toString(fence.value()), + "sourceVersion", Long.toString(fence.sourceVersion()))))); + } + + public static AccountControlUiOriginalSourceCapture read(OriginalCapture capture) { + return new AccountControlUiOriginalSourceCapture(capture); + } + + public OriginalCapture originalCapture() { + return capture; + } + + public String accountUuid() { + return text(decode(capture.authorityCapture()), "accountId"); + } + + public Map authorityTuple() { + return tuple( + IssuerGenerationProjection.parse(text(decode(capture.authorityCapture()), "issuerSource")), + AccountGenerationProjection.parse( + text(decode(capture.authorityCapture()), "accountSource"))); + } + + public String issuanceFence() { + return text(decode(capture.issuanceFenceCapture()), "issuanceFence"); + } + + private static Map tuple( + IssuerGenerationProjection issuer, AccountGenerationProjection account) { + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", issuer.issuerAuthGeneration()); + tuple.put("accountAuthorityGeneration", account.accountAuthorityGeneration()); + tuple.put("tenantAuthorityGeneration", Map.of()); + tuple.put("membershipAuthorityGeneration", Map.of()); + tuple.put("privateRealmGrantVersions", List.of()); + account + .sourceEvent() + .ifPresent( + event -> { + Map wire = decode(event.getBytes(StandardCharsets.UTF_8)); + if (wire.containsKey("accountSecurityCutoff")) + tuple.put("accountSecurityCutoff", wire.get("accountSecurityCutoff")); + }); + return java.util.Collections.unmodifiableMap(tuple); + } + + private static byte[] encode(Map value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException failure) { + throw new IllegalStateException("Cannot encode original source", failure); + } + } + + private static Map decode(byte[] bytes) { + try { + String json = new String(bytes, StandardCharsets.UTF_8); + if (!java.util.Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(json))) + throw invalid(); + return JSON.readValue(bytes, new TypeReference<>() {}); + } catch (IOException failure) { + throw new IllegalArgumentException("Invalid original source", failure); + } + } + + private static String text(Map source, String key) { + Object value = source.get(key); + if (!(value instanceof String text)) throw invalid(); + return text; + } + + private static void positive(Object value) { + if (!(value instanceof String text) || !text.matches("[1-9][0-9]*")) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid original control-ui source capture"); + } + + @Override + public String toString() { + return "AccountControlUiOriginalSourceCapture[non-authorizing]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiPreSignIntentService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiPreSignIntentService.java new file mode 100644 index 0000000000..90281124b0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiPreSignIntentService.java @@ -0,0 +1,111 @@ +package net.firedevops.firemud.accountservice.service.controlui; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequest; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourceRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceIntent; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceIntentRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Unwired two-phase preparation for actual control-ui issuance. A durable reservation precedes + * signing; a separate owner transaction binds the signer's exact returned compact-JWT hash. Neither + * phase authenticates credentials, signs, completes a bundle, or activates a registry. + */ +public final class AccountControlUiPreSignIntentService { + private final AccountControlUiCurrentSourceRepository sources; + private final AccountRepository accounts; + private final AccountControlUiIssuanceOperationRepository operations; + private final AccountControlUiIssuanceIntentRepository intents; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected persistence owners remain internal collaborators.") + public AccountControlUiPreSignIntentService( + AccountControlUiCurrentSourceRepository sources, + AccountRepository accounts, + AccountControlUiIssuanceOperationRepository operations, + AccountControlUiIssuanceIntentRepository intents) { + this.sources = Objects.requireNonNull(sources); + this.accounts = Objects.requireNonNull(accounts); + this.operations = Objects.requireNonNull(operations); + this.intents = Objects.requireNonNull(intents); + } + + /** Caller must commit this owner transaction before invoking any signer. */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountControlUiIssuanceIntent prepare(AccountControlUiIssuanceRequest request) { + Objects.requireNonNull(request); + UUID proposedOperation = UUID.randomUUID(); + UUID proposedJti = UUID.randomUUID(); + UUID proposedBundle = UUID.randomUUID(); + // Issuer-first source locking precedes V66's Account/operation lock even on retry. + var current = currentSource(request); + var prior = operations.findByRequest(request); + if (prior.isPresent()) { + var original = prior.orElseThrow(); + if (!original.originalCapture().equals(current.originalCapture())) throw stale(); + return intents + .read(original) + .orElseThrow( + () -> + new IllegalStateException( + "Existing control-ui operation has no original signing reservation; cannot recapture")); + } + var claim = + operations.claim(proposedOperation, request, Optional.of(current.originalCapture())); + if (!claim.created()) + throw new IllegalStateException("Control-ui reservation lost its first-writer claim"); + return intents.reserve(claim.operation(), proposedJti, proposedBundle); + } + + /** Hashes the exact signer output; this method does not verify its signature or authorize it. */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountControlUiIssuanceIntent bindSignedToken( + AccountControlUiIssuanceIntent original, String compactJwt) { + Objects.requireNonNull(original); + if (compactJwt == null + || !compactJwt.matches("[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+")) { + throw new IllegalArgumentException("Exact compact JWT signer output required"); + } + var current = currentSource(original.operation().request()); + if (!original.operation().originalCapture().equals(current.originalCapture())) throw stale(); + var operation = + operations.findByRequest(original.operation().request()).orElseThrow(() -> stale()); + if (!operation.operationId().equals(original.operation().operationId()) + || !operation.originalCapture().equals(original.operation().originalCapture())) + throw stale(); + try { + String hash = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(compactJwt.getBytes(StandardCharsets.US_ASCII))); + return intents.bindTokenHash(original, hash); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 unavailable", failure); + } + } + + private AccountControlUiOriginalSourceCapture currentSource( + AccountControlUiIssuanceRequest request) { + UUID accountUuid = UUID.fromString(request.accountUuid()); + var source = sources.readUnscopedCurrent(accountUuid); + var account = accounts.findByAccountUuidForUpdate(accountUuid).orElseThrow(() -> stale()); + return AccountControlUiOriginalSourceCapture.fromCurrent(source, account); + } + + private static IllegalStateException stale() { + return new IllegalStateException("Original control-ui source is no longer exact and current"); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V74__control_ui_presign_intent.sql b/services/account-service/src/main/resources/db/migration/V74__control_ui_presign_intent.sql new file mode 100644 index 0000000000..7eeae09a86 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V74__control_ui_presign_intent.sql @@ -0,0 +1,77 @@ +-- Supplemental signing identity for the SAME V66 operation, never a second operation owner. +-- These sequences allocate durable capture metadata, not authority generations or checkpoints. +CREATE SEQUENCE account_control_ui_capture_source_version_seq AS BIGINT MINVALUE 1 NO CYCLE; +CREATE SEQUENCE account_control_ui_capture_source_fence_seq AS BIGINT MINVALUE 1 NO CYCLE; +CREATE TABLE account_control_ui_issuance_intents ( + operation_id UUID PRIMARY KEY REFERENCES account_control_ui_issuance_operations(operation_id) ON DELETE RESTRICT, + jti UUID NOT NULL UNIQUE CHECK (jti <> '00000000-0000-0000-0000-000000000000'), + bundle_id UUID NOT NULL UNIQUE CHECK (bundle_id <> '00000000-0000-0000-0000-000000000000'), + bundle_version BIGINT NOT NULL CHECK (bundle_version = 1), + source_version BIGINT NOT NULL UNIQUE DEFAULT nextval('account_control_ui_capture_source_version_seq') CHECK (source_version > 0), + source_fence BIGINT NOT NULL UNIQUE DEFAULT nextval('account_control_ui_capture_source_fence_seq') CHECK (source_fence > 0), + authority_capture_digest BYTEA NOT NULL CHECK (octet_length(authority_capture_digest) = 32), + issuance_fence_digest BYTEA NOT NULL CHECK (octet_length(issuance_fence_digest) = 32), + phase VARCHAR(16) NOT NULL CHECK (phase IN ('PENDING', 'HASH_BOUND')), + token_hash VARCHAR(64), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_control_ui_intent_hash_shape CHECK ( + (phase = 'PENDING' AND token_hash IS NULL) OR + (phase = 'HASH_BOUND' AND token_hash ~ '^[0-9a-f]{64}$' AND token_hash IS NOT NULL)) +); + +-- [jooq ignore start] +CREATE FUNCTION account_control_ui_intent_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE operation account_control_ui_issuance_operations%ROWTYPE; +BEGIN + IF TG_OP = 'INSERT' THEN + SELECT * INTO operation FROM account_control_ui_issuance_operations + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF NOT FOUND OR operation.status <> 'PENDING' OR NEW.phase <> 'PENDING' + OR NEW.token_hash IS NOT NULL + OR NEW.authority_capture_digest IS DISTINCT FROM operation.authority_capture_digest + OR NEW.issuance_fence_digest IS DISTINCT FROM operation.issuance_fence_digest THEN + RAISE EXCEPTION 'Control-UI intent requires the exact pending original operation capture' + USING ERRCODE = '23514', CONSTRAINT = 'account_control_ui_intent_operation_binding'; + END IF; + ELSIF TG_OP = 'UPDATE' THEN + IF OLD.phase <> 'PENDING' OR NEW.phase <> 'HASH_BOUND' OR NEW.token_hash IS NULL + OR (to_jsonb(NEW) - ARRAY['phase','token_hash']) IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['phase','token_hash']) THEN + RAISE EXCEPTION 'Control-UI signing identity and original capture are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_control_ui_intent_identity_immutable'; + END IF; + ELSE + RAISE EXCEPTION 'Control-UI signing evidence is retained' + USING ERRCODE = '23514', CONSTRAINT = 'account_control_ui_intent_retained'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_control_ui_intent_guard_trigger + BEFORE INSERT OR UPDATE OR DELETE ON account_control_ui_issuance_intents + FOR EACH ROW EXECUTE FUNCTION account_control_ui_intent_guard(); +CREATE TRIGGER account_control_ui_intent_no_truncate_trigger + BEFORE TRUNCATE ON account_control_ui_issuance_intents + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_intent_guard(); +-- Existing V66-only fixtures/retained operations remain unchanged. Once a reservation exists, +-- the final original response must use its already-bound exact token hash. +CREATE FUNCTION account_control_ui_intent_result_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.status = 'COMMITTED' AND EXISTS ( + SELECT 1 FROM account_control_ui_issuance_intents WHERE operation_id = NEW.operation_id + ) AND NOT EXISTS ( + SELECT 1 FROM account_control_ui_issuance_intents + WHERE operation_id = NEW.operation_id AND phase = 'HASH_BOUND' AND token_hash = NEW.token_hash + AND authority_capture_digest = NEW.authority_capture_digest + AND issuance_fence_digest = NEW.issuance_fence_digest + ) THEN + RAISE EXCEPTION 'Control-UI original response differs from its reserved signing identity' + USING ERRCODE = '23514', CONSTRAINT = 'account_control_ui_intent_result_binding'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_control_ui_intent_result_guard_trigger + AFTER UPDATE ON account_control_ui_issuance_operations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_control_ui_intent_result_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java index 902926b1ba..de646f3e36 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java @@ -94,6 +94,7 @@ void exactPasswordAndOtpEvidenceBindOriginalOperationAndFreshRecoveryRemainsSepa AccountEmailLoginChallenge challenge = challenge(fixture, account); var otp = record(fixture, pending, account, Purpose.INITIAL_ISSUANCE, Optional.of(challenge)); + assertThat(pending.operationId()).isNotEqualTo(UUID.fromString(pending.request().requestId())); assertThat(password.operationId()).isEqualTo(pending.operationId()); assertThat(password.method()).isEqualTo("PASSWORD"); assertThat(otp.operationId()).isEqualTo(pending.operationId()); @@ -460,15 +461,24 @@ private static AccountControlUiIssuanceOperation pending(Fixture fixture, Accoun var request = new AccountControlUiIssuanceRequest( UUID.randomUUID().toString(), account.getAccountUuid().toString()); + UUID operationId = UUID.randomUUID(); OriginalCapture stipulatedCapture = new OriginalCapture( account.getId(), account.getAccountUuidProvenance(), "stipulated-original-source-capture".getBytes(StandardCharsets.UTF_8), "stipulated-original-fence-capture".getBytes(StandardCharsets.UTF_8)); - return tx( - fixture, - () -> fixture.issuance().claim(request, Optional.of(stipulatedCapture)).operation()); + AccountControlUiIssuanceOperation operation = + tx( + fixture, + () -> + fixture + .issuance() + .claim(operationId, request, Optional.of(stipulatedCapture)) + .operation()); + assertThat(operation.operationId()).isEqualTo(operationId); + assertThat(operation.operationId()).isNotEqualTo(UUID.fromString(request.requestId())); + return operation; } private AccountControlUiIssuanceOperation committed( @@ -503,13 +513,16 @@ private AccountControlUiIssuanceOperation committed( } Files.writeString(manifest, String.join("\n", lines) + "\n", StandardCharsets.US_ASCII); var envelope = new AccountEnvelopeCrypto(manifest).encryptControlUiResponse(binding, response); + UUID retryOperationId = UUID.randomUUID(); return tx( fixture, () -> fixture .issuance() .complete( - fixture.issuance().claim(operation.request(), Optional.empty()), + fixture + .issuance() + .claim(retryOperationId, operation.request(), Optional.empty()), binding, envelope)); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java new file mode 100644 index 0000000000..1a95f444af --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java @@ -0,0 +1,552 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.accountservice.dto.AccountControlUiIssuanceRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCurrentSourceRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceIntent; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceIntentRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountGlobalRoleSourceRepository; +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.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountIssuerAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiOriginalSourceCapture; +import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiPreSignIntentService; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real source/claim/reservation/hash SQL only; synthetic signer bytes prove no signing or registry. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountControlUiIssuanceIntentPostgresIntegrationTest { + private static final String ISSUER = "firemud-account-service"; + private static final String SIGNER_BYTES = "eyJ0ZXN0IjoxfQ.eyJ0ZXN0IjoyfQ.c3ludGhldGlj"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void ownerSourceCapturePrecedesSigningAndRestartRecoversOriginalReservationWithoutRecapture() { + Fixture fixture = fixture(true); + var request = fixture.request(); + var initial = fixture.tx().execute(status -> fixture.service().prepare(request)); + assertThat(initial).isNotNull(); + assertThat(initial.operation().operationId().toString()).isNotEqualTo(request.requestId()); + assertThat(initial.tokenHash()).isEmpty(); + assertThat(initial.sourceVersion()).isPositive(); + assertThat(initial.sourceFence()).isPositive(); + assertThat(initial.bundleVersion()).isEqualTo(1L); + var capture = AccountControlUiOriginalSourceCapture.read(initial.operation().originalCapture()); + assertThat(capture.issuanceFence()).isEqualTo("1"); + assertThat(capture.authorityTuple()) + .containsEntry("issuerAuthGeneration", "1") + .containsEntry("accountAuthorityGeneration", "1") + .containsEntry("tenantAuthorityGeneration", Map.of()) + .containsEntry("membershipAuthorityGeneration", Map.of()) + .containsEntry("privateRealmGrantVersions", java.util.List.of()); + var restart = fixture.restartedService(); + assertThat( + fixture + .tx() + .execute(status -> restart.prepare(request))) + .isEqualTo(initial); + var bound = fixture.tx().execute(status -> restart.bindSignedToken(initial, SIGNER_BYTES)); + assertThat(bound).isNotNull(); + assertThat(bound.tokenHash()) + .hasValue( + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(SIGNER_BYTES)); + assertThat( + fixture + .tx() + .execute( + status -> fixture.service().bindSignedToken(initial, SIGNER_BYTES))) + .isEqualTo(bound); + assertThat( + fixture + .tx() + .execute(status -> restart.prepare(request))) + .isEqualTo(bound); + assertThat(count(fixture.dsl(), "account_control_ui_issuance_operations")).isEqualTo(1L); + assertThat(count(fixture.dsl(), "account_control_ui_issuance_intents")).isEqualTo(1L); + assertThat(count(fixture.dsl(), "account_authority_outbox_events")).isZero(); + } + + @Test + void differentHashIdentityOrFenceCannotReplaceOriginalAndSqlCannotMutateReservation() { + Fixture fixture = fixture(true); + var original = + Objects.requireNonNull( + fixture.tx().execute(status -> fixture.service().prepare(fixture.request()))); + var bound = + fixture.tx().execute(status -> fixture.service().bindSignedToken(original, SIGNER_BYTES)); + assertThatThrownBy( + () -> + fixture + .tx() + .execute( + status -> fixture.service().bindSignedToken(original, SIGNER_BYTES + "x"))) + .isInstanceOf(IllegalStateException.class); + for (var forged : + java.util.List.of( + new AccountControlUiIssuanceIntent( + original.operation(), + UUID.randomUUID(), + original.bundleId(), + original.bundleVersion(), + original.sourceVersion(), + original.sourceFence(), + Optional.empty()), + new AccountControlUiIssuanceIntent( + original.operation(), + original.jti(), + original.bundleId(), + original.bundleVersion(), + original.sourceVersion(), + original.sourceFence() + 1L, + Optional.empty()))) { + assertThatThrownBy( + () -> + fixture + .tx() + .execute(status -> fixture.service().bindSignedToken(forged, SIGNER_BYTES))) + .isInstanceOf(IllegalStateException.class); + } + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE account_control_ui_issuance_intents SET jti = ? WHERE operation_id = ?", + UUID.randomUUID(), + original.operation().operationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM account_control_ui_issuance_intents WHERE operation_id = ?", + original.operation().operationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat( + fixture + .tx() + .execute( + status -> fixture.service().prepare(original.operation().request()))) + .isEqualTo(bound); + } + + @Test + void changedCurrentIssuerDeniesProgressionAndPreservesHistoricalCaptureAndHash() { + Fixture fixture = fixture(true); + var original = + Objects.requireNonNull( + fixture.tx().execute(status -> fixture.service().prepare(fixture.request()))); + fixture.issuer().advance(ISSUER, UUID.randomUUID(), 1L, 1L); + assertThatThrownBy( + () -> + fixture + .tx() + .execute(status -> fixture.service().prepare(original.operation().request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no longer exact"); + assertThatThrownBy( + () -> + fixture + .tx() + .execute(status -> fixture.service().bindSignedToken(original, SIGNER_BYTES))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no longer exact"); + assertThat( + fixture + .tx() + .execute( + status -> fixture.intents().read(original.operation()).orElseThrow())) + .isEqualTo(original); + assertThat(count(fixture.dsl(), "account_control_ui_issuance_intents")).isEqualTo(1L); + } + + @Test + void advancedIssuerEventIsCapturedExactlyAndMissingAuthorityNeverEnrolls() { + Fixture fixture = fixture(true); + var event = fixture.issuer().advance(ISSUER, UUID.randomUUID(), 1L, 1L); + var original = + Objects.requireNonNull( + fixture.tx().execute(status -> fixture.service().prepare(fixture.request()))); + String source = + new String( + original.operation().originalCapture().authorityCapture(), + java.nio.charset.StandardCharsets.UTF_8); + assertThat(source).contains("issuerSource"); + assertThat( + AccountControlUiOriginalSourceCapture.read(original.operation().originalCapture()) + .authorityTuple()) + .containsEntry("issuerAuthGeneration", "2"); + // The canonical nested projection preserves the exact event; its bytes are not re-created. + assertThat(source).contains(event.eventDigest()).contains(event.eventId()); + Fixture absent = fixture(false); + assertThatThrownBy( + () -> absent.tx().execute(status -> absent.service().prepare(absent.request()))) + .isInstanceOf(IllegalStateException.class); + assertThat(count(absent.dsl(), "account_authority_generations")).isZero(); + assertThat(count(absent.dsl(), "account_authority_issuance_fences")).isZero(); + assertThat(count(absent.dsl(), "account_control_ui_issuance_operations")).isZero(); + assertThat(count(absent.dsl(), "account_control_ui_issuance_intents")).isZero(); + } + + @Test + void abortedPresignAndPostsignTransactionsDoNotLeavePartialProgress() { + Fixture fixture = fixture(true); + var request = fixture.request(); + fixture + .tx() + .executeWithoutResult( + status -> { + fixture.service().prepare(request); + status.setRollbackOnly(); + }); + assertThat(count(fixture.dsl(), "account_control_ui_issuance_operations")).isZero(); + assertThat(count(fixture.dsl(), "account_control_ui_issuance_intents")).isZero(); + var original = + Objects.requireNonNull(fixture.tx().execute(status -> fixture.service().prepare(request))); + fixture + .tx() + .executeWithoutResult( + status -> { + fixture.service().bindSignedToken(original, SIGNER_BYTES); + status.setRollbackOnly(); + }); + assertThat( + fixture + .tx() + .execute( + status -> fixture.service().prepare(request))) + .isEqualTo(original); + assertThat( + fixture + .tx() + .execute( + status -> fixture.service().bindSignedToken(original, SIGNER_BYTES))) + .isNotNull(); + } + + @Test + void preexistingV66OperationWithoutSigningReservationIsNeverRepairedOnRetry() { + Fixture fixture = fixture(true); + var request = fixture.request(); + fixture + .tx() + .executeWithoutResult( + status -> { + var observation = fixture.sources().readUnscopedCurrent(fixture.accountId()); + var account = + fixture.accounts().findByAccountUuidForUpdate(fixture.accountId()).orElseThrow(); + var capture = AccountControlUiOriginalSourceCapture.fromCurrent(observation, account); + fixture + .operations() + .claim(UUID.randomUUID(), request, Optional.of(capture.originalCapture())); + }); + assertThatThrownBy(() -> fixture.tx().execute(status -> fixture.service().prepare(request))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot recapture"); + assertThat(count(fixture.dsl(), "account_control_ui_issuance_intents")).isZero(); + } + + @Test + void postSignCasSerializesWithIssuerWriterAndRetainsOriginalHash() throws Exception { + Fixture fixture = fixture(true); + var original = + Objects.requireNonNull( + fixture.tx().execute(status -> fixture.service().prepare(fixture.request()))); + CountDownLatch hashLocked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch advanceEntered = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(3)) { + var bound = + executor.submit( + () -> + fixture + .tx() + .execute( + status -> { + var result = fixture.service().bindSignedToken(original, SIGNER_BYTES); + hashLocked.countDown(); + await(release); + return result; + })); + assertThat(hashLocked.await(10L, TimeUnit.SECONDS)).isTrue(); + var advanced = + executor.submit( + () -> { + advanceEntered.countDown(); + return fixture.issuer().advance(ISSUER, UUID.randomUUID(), 1L, 1L); + }); + assertThat(advanceEntered.await(10L, TimeUnit.SECONDS)).isTrue(); + try { + assertThatThrownBy(() -> advanced.get(150L, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + } finally { + release.countDown(); + } + var retained = bound.get(10L, TimeUnit.SECONDS); + assertThat(advanced.get(10L, TimeUnit.SECONDS)).isNotNull(); + assertThat( + fixture + .tx() + .execute( + status -> fixture.intents().read(original.operation()).orElseThrow())) + .isEqualTo(retained); + assertThatThrownBy( + () -> + fixture + .tx() + .execute(status -> fixture.service().bindSignedToken(original, SIGNER_BYTES))) + .isInstanceOf(IllegalStateException.class); + } finally { + release.countDown(); + } + } + + @Test + void concurrentPresignRetriesRecoverOneOriginalIdentityAndDifferentHashCasHasOneWinner() + throws Exception { + Fixture fixture = fixture(true); + var request = fixture.request(); + CountDownLatch start = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var first = + executor.submit( + () -> { + await(start); + return fixture.tx().execute(status -> fixture.service().prepare(request)); + }); + var second = + executor.submit( + () -> { + await(start); + return fixture.tx().execute(status -> fixture.service().prepare(request)); + }); + start.countDown(); + var original = Objects.requireNonNull(first.get(10L, TimeUnit.SECONDS)); + assertThat(second.get(10L, TimeUnit.SECONDS)).isEqualTo(original); + CountDownLatch signStart = new CountDownLatch(1); + var a = + executor.submit( + () -> { + await(signStart); + return bindOutcome(fixture, original, SIGNER_BYTES); + }); + var b = + executor.submit( + () -> { + await(signStart); + return bindOutcome(fixture, original, SIGNER_BYTES + "x"); + }); + signStart.countDown(); + assertThat(java.util.List.of(a.get(10L, TimeUnit.SECONDS), b.get(10L, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + assertThat(count(fixture.dsl(), "account_control_ui_issuance_operations")).isEqualTo(1L); + assertThat(count(fixture.dsl(), "account_control_ui_issuance_intents")).isEqualTo(1L); + } finally { + start.countDown(); + } + } + + private static boolean bindOutcome( + Fixture fixture, AccountControlUiIssuanceIntent original, String token) { + try { + fixture.tx().execute(status -> fixture.service().bindSignedToken(original, token)); + return true; + } catch (IllegalStateException expectedConflict) { + return false; + } + } + + @Test + void committedAccountLifecycleChangeSerializesWithPostSignCasAndDeniesHashBinding() + throws Exception { + Fixture fixture = fixture(true); + var original = + Objects.requireNonNull( + fixture.tx().execute(status -> fixture.service().prepare(fixture.request()))); + CountDownLatch ownerLocked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch casEntered = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var changed = + executor.submit( + () -> + fixture + .tx() + .execute( + status -> { + // Fixture owner mutation follows the same issuer-first order. This does + // not claim a live + // lifecycle ingress or its separately required source-event production. + fixture.sources().readUnscopedCurrent(fixture.accountId()); + fixture + .dsl() + .execute( + "UPDATE accounts SET lifecycle_state = 'security_locked' WHERE account_uuid = ?", + fixture.accountId()); + ownerLocked.countDown(); + await(release); + return true; + })); + assertThat(ownerLocked.await(10L, TimeUnit.SECONDS)).isTrue(); + var binding = + executor.submit( + () -> { + casEntered.countDown(); + return bindOutcome(fixture, original, SIGNER_BYTES); + }); + assertThat(casEntered.await(10L, TimeUnit.SECONDS)).isTrue(); + try { + assertThatThrownBy(() -> binding.get(150L, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + } finally { + release.countDown(); + } + assertThat(changed.get(10L, TimeUnit.SECONDS)).isTrue(); + assertThat(binding.get(10L, TimeUnit.SECONDS)).isFalse(); + assertThat( + fixture + .tx() + .execute( + status -> fixture.intents().read(original.operation()).orElseThrow())) + .isEqualTo(original); + } finally { + release.countDown(); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10L, TimeUnit.SECONDS)) + throw new IllegalStateException("Fixture latch timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(failure); + } + } + + private static long count(DSLContext dsl, String table) { + return Objects.requireNonNull(dsl.fetchOne("SELECT COUNT(*) AS n FROM " + table)) + .get("n", Long.class); + } + + private static Fixture fixture(boolean enroll) { + String schema = "control_ui_intent_" + 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()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("74")) + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var accounts = new AccountRepository(dsl); + Account account = new Account(); + account.setUsername("intent_source"); + account.setEmail("intent-source@example.test"); + account.setPasswordHash("test-only-owner-source-fixture"); + accounts.save(account); + var generations = new AccountAuthorityGenerationRepository(dsl); + var tx = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + if (enroll) + tx.executeWithoutResult( + status -> { + generations.initializeIssuerIfAbsent(ISSUER); + generations.initialize(AuthorityScope.account(account.getAccountUuid())); + }); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var issuer = + new AccountIssuerAuthorityEventProducer( + ISSUER, generations, outbox, dsl, Objects.requireNonNull(tx.getTransactionManager())); + var readback = + new AccountAuthoritySourceEventReadback( + outbox, + new AccountPasswordResetOperationRepository(dsl), + new AccountLogoutAllOperationRepository(dsl), + new AccountSecurityStateOperationRepository(dsl)); + var sources = + new AccountControlUiCurrentSourceRepository( + dsl, + accounts, + new AccountGlobalRoleSourceRepository(dsl, dataSource), + generations, + readback, + issuer); + var operations = new AccountControlUiIssuanceOperationRepository(dsl); + var intents = new AccountControlUiIssuanceIntentRepository(dsl); + var service = new AccountControlUiPreSignIntentService(sources, accounts, operations, intents); + return new Fixture( + dsl, tx, account.getAccountUuid(), accounts, sources, operations, intents, issuer, service); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate tx, + UUID accountId, + AccountRepository accounts, + AccountControlUiCurrentSourceRepository sources, + AccountControlUiIssuanceOperationRepository operations, + AccountControlUiIssuanceIntentRepository intents, + AccountIssuerAuthorityEventProducer issuer, + AccountControlUiPreSignIntentService service) { + AccountControlUiIssuanceRequest request() { + return new AccountControlUiIssuanceRequest( + UUID.randomUUID().toString(), accountId.toString()); + } + + AccountControlUiPreSignIntentService restartedService() { + return new AccountControlUiPreSignIntentService( + sources, + accounts, + new AccountControlUiIssuanceOperationRepository(dsl), + new AccountControlUiIssuanceIntentRepository(dsl)); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java index c862b85ac0..6b25bbb04c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceOperationPostgresIntegrationTest.java @@ -59,9 +59,11 @@ class AccountControlUiIssuanceOperationPostgresIntegrationTest { void claimRequiresAnActiveWritableOwnerTransaction() { TestContext context = newTestContext(); AccountControlUiIssuanceRequest request = request(context.account().uuid()); + UUID operationId = UUID.randomUUID(); + OriginalCapture originalCapture = capture(context.account()); assertThatThrownBy( - () -> context.repository().claim(request, Optional.of(capture(context.account())))) + () -> context.repository().claim(operationId, request, Optional.of(originalCapture))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable caller-owned Account transaction"); } @@ -70,18 +72,27 @@ void claimRequiresAnActiveWritableOwnerTransaction() { void exactClaimsRecoverOriginalCaptureAndChangedAccountOrCaptureConflicts() { TestContext context = newTestContext(); AccountControlUiIssuanceRequest request = request(context.account().uuid()); + UUID proposedOperationId = UUID.randomUUID(); + UUID retryOperationId = UUID.randomUUID(); OriginalCapture originalCapture = capture(context.account()); var first = inTransaction( context.transaction(), - () -> context.repository().claim(request, Optional.of(originalCapture))); + () -> + context + .repository() + .claim(proposedOperationId, request, Optional.of(originalCapture))); var retry = inTransaction( - context.transaction(), () -> context.repository().claim(request, Optional.empty())); + context.transaction(), + () -> context.repository().claim(retryOperationId, request, Optional.empty())); assertThat(first.created()).isTrue(); assertThat(retry.created()).isFalse(); + assertThat(first.operation().operationId()).isEqualTo(proposedOperationId); + assertThat(proposedOperationId).isNotEqualTo(UUID.fromString(request.requestId())); + assertThat(retryOperationId).isNotEqualTo(proposedOperationId); assertThat(retry.operation().operationId()).isEqualTo(first.operation().operationId()); assertThat(retry.operation().lifecycle()) .isEqualTo(AccountControlUiIssuanceOperation.Lifecycle.PENDING); @@ -94,9 +105,13 @@ void exactClaimsRecoverOriginalCaptureAndChangedAccountOrCaptureConflicts() { () -> inTransaction( context.transaction(), - () -> context.repository().claim(changedAccount, Optional.empty()))) + () -> + context + .repository() + .claim(UUID.randomUUID(), changedAccount, Optional.empty()))) .isInstanceOf(AccountControlUiIssuanceOperationRepository.OperationConflictException.class); + UUID conflictingCaptureOperationId = UUID.randomUUID(); OriginalCapture changedCapture = new OriginalCapture( originalCapture.accountId(), @@ -107,7 +122,13 @@ void exactClaimsRecoverOriginalCaptureAndChangedAccountOrCaptureConflicts() { () -> inTransaction( context.transaction(), - () -> context.repository().claim(request, Optional.of(changedCapture)))) + () -> + context + .repository() + .claim( + conflictingCaptureOperationId, + request, + Optional.of(changedCapture)))) .isInstanceOf(AccountControlUiIssuanceOperationRepository.OperationConflictException.class); assertThat( inTransaction( @@ -120,12 +141,15 @@ void exactClaimsRecoverOriginalCaptureAndChangedAccountOrCaptureConflicts() { void simultaneousExactClaimsAllocateOneOperationAndRetainTheFirstCapture() throws Exception { TestContext context = newTestContext(); AccountControlUiIssuanceRequest request = request(context.account().uuid()); + UUID firstOperationId = UUID.randomUUID(); + UUID secondOperationId = UUID.randomUUID(); + assertThat(secondOperationId).isNotEqualTo(firstOperationId); OriginalCapture originalCapture = capture(context.account()); CountDownLatch ready = new CountDownLatch(2); CountDownLatch start = new CountDownLatch(1); ExecutorService executor = Executors.newFixedThreadPool(2); try { - Callable attempt = + Callable firstAttempt = () -> { ready.countDown(); if (!start.await(5, TimeUnit.SECONDS)) { @@ -133,10 +157,28 @@ void simultaneousExactClaimsAllocateOneOperationAndRetainTheFirstCapture() throw } return inTransaction( context.transaction(), - () -> context.repository().claim(request, Optional.of(originalCapture))); + () -> + context + .repository() + .claim(firstOperationId, request, Optional.of(originalCapture))); }; - Future first = executor.submit(attempt); - Future second = executor.submit(attempt); + Callable secondAttempt = + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Control-UI claim race did not start"); + } + return inTransaction( + context.transaction(), + () -> + context + .repository() + .claim(secondOperationId, request, Optional.of(originalCapture))); + }; + Future first = + executor.submit(firstAttempt); + Future second = + executor.submit(secondAttempt); assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); List claims = @@ -147,9 +189,17 @@ void simultaneousExactClaimsAllocateOneOperationAndRetainTheFirstCapture() throw assertThat(claims) .extracting(claim -> claim.operation().operationId()) .containsOnly(claims.get(0).operation().operationId()); + assertThat(claims.get(0).operation().operationId()) + .isIn(firstOperationId, secondOperationId) + .isNotEqualTo(UUID.fromString(request.requestId())); assertThat(claims) .extracting(claim -> claim.operation().originalCapture()) .containsOnly(originalCapture); + assertThat( + inTransaction( + context.transaction(), + () -> context.repository().findByRequest(request).orElseThrow())) + .isEqualTo(claims.get(0).operation()); } finally { start.countDown(); executor.shutdownNow(); @@ -160,10 +210,12 @@ void simultaneousExactClaimsAllocateOneOperationAndRetainTheFirstCapture() throw void abandonedPendingClaimCannotBeReportedCommittedWithoutExactEnvelope() { TestContext context = newTestContext(); AccountControlUiIssuanceRequest request = request(context.account().uuid()); + UUID operationId = UUID.randomUUID(); + OriginalCapture originalCapture = capture(context.account()); var claim = inTransaction( context.transaction(), - () -> context.repository().claim(request, Optional.of(capture(context.account())))); + () -> context.repository().claim(operationId, request, Optional.of(originalCapture))); assertThatThrownBy( () -> @@ -233,17 +285,19 @@ void exactEncryptedResultSurvivesRestartRotationAndLaterTransactionRetry(@TempDi throws Exception { TestContext context = newTestContext(); AccountControlUiIssuanceRequest request = request(context.account().uuid()); + UUID operationId = UUID.randomUUID(); + OriginalCapture originalCapture = capture(context.account()); var claim = inTransaction( context.transaction(), - () -> context.repository().claim(request, Optional.of(capture(context.account())))); + () -> context.repository().claim(operationId, request, Optional.of(originalCapture))); byte[] exactResponse = "{\"accountId\":\"" .concat(request.accountUuid()) .concat("\",\"token\":\"synthetic-original-token\"}") .getBytes(StandardCharsets.UTF_8); String tokenHash = hex(sha256("synthetic-original-token".getBytes(StandardCharsets.UTF_8))); - OriginalCapture originalCapture = claim.operation().originalCapture(); + assertThat(claim.operation().originalCapture()).isEqualTo(originalCapture); AccountControlUiResponseEnvelopeBinding binding = new AccountControlUiResponseEnvelopeBinding( request.accountUuid(), @@ -331,10 +385,12 @@ void exactEncryptedResultSurvivesRestartRotationAndLaterTransactionRetry(@TempDi void lateRollbackLeavesOriginalPendingCaptureAndNoEncryptedResult() throws Exception { TestContext context = newTestContext(); AccountControlUiIssuanceRequest request = request(context.account().uuid()); + UUID operationId = UUID.randomUUID(); + OriginalCapture originalCapture = capture(context.account()); var claim = inTransaction( context.transaction(), - () -> context.repository().claim(request, Optional.of(capture(context.account())))); + () -> context.repository().claim(operationId, request, Optional.of(originalCapture))); byte[] response = "synthetic response held only by this fixture".getBytes(StandardCharsets.UTF_8); AccountControlUiResponseEnvelopeBinding binding = binding(claim.operation(), response); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java index 79f5f90021..edb4e5e478 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java @@ -154,6 +154,8 @@ void actualPasswordRecordsFreshEvidenceAgainstExactPendingOperationWithoutJwtOut assertThat(authentication.requestId()) .isEqualTo(UUID.fromString(original.request().requestId())); assertThat(authentication.operationId()).isEqualTo(original.operationId()); + assertThat(original.operationId()) + .isNotEqualTo(UUID.fromString(original.request().requestId())); assertThat(authentication.authenticationMethod()).isEqualTo("PASSWORD"); assertThat(readOperation(original.request())).isEqualTo(original); assertThat(attemptCount(original.operationId())).isEqualTo(1L); @@ -292,6 +294,7 @@ private AccountControlUiIssuanceOperation pendingOperation(Account account) { AccountControlUiIssuanceRequest request = new AccountControlUiIssuanceRequest( UUID.randomUUID().toString(), account.getAccountUuid().toString()); + UUID operationId = UUID.randomUUID(); OriginalCapture stipulatedCapture = new OriginalCapture( account.getId(), @@ -300,8 +303,15 @@ private AccountControlUiIssuanceOperation pendingOperation(Account account) { .getBytes(StandardCharsets.UTF_8), ("stipulated-original-issuance-fence-capture:" + request.requestId()) .getBytes(StandardCharsets.UTF_8)); - return inTransaction( - () -> issuanceOperations.claim(request, Optional.of(stipulatedCapture)).operation()); + AccountControlUiIssuanceOperation operation = + inTransaction( + () -> + issuanceOperations + .claim(operationId, request, Optional.of(stipulatedCapture)) + .operation()); + assertThat(operation.operationId()).isEqualTo(operationId); + assertThat(operation.operationId()).isNotEqualTo(UUID.fromString(request.requestId())); + return operation; } private AccountEmailLoginChallenge createChallenge(Account account, String otp) { @@ -352,10 +362,13 @@ private AccountControlUiIssuanceOperation commitStipulatedOriginalResponse( Path manifest = tempDirectory.resolve("control-ui-ring-" + UUID.randomUUID() + ".v1"); writeFixtureKeyRing(manifest); var envelope = new AccountEnvelopeCrypto(manifest).encryptControlUiResponse(binding, response); + UUID retryOperationId = UUID.randomUUID(); return inTransaction( () -> issuanceOperations.complete( - issuanceOperations.claim(pending.request(), Optional.empty()), binding, envelope)); + issuanceOperations.claim(retryOperationId, pending.request(), Optional.empty()), + binding, + envelope)); } private static void writeFixtureKeyRing(Path manifest) throws Exception { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiOriginalSourceCaptureTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiOriginalSourceCaptureTest.java new file mode 100644 index 0000000000..53a3335ae6 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/controlui/AccountControlUiOriginalSourceCaptureTest.java @@ -0,0 +1,242 @@ +package unit.net.firedevops.firemud.accountservice.service.controlui; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.json.JsonMapper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountControlUiIssuanceOperation.OriginalCapture; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.accountservice.service.controlui.AccountControlUiOriginalSourceCapture; +import net.firedevops.firemud.common.account.authority.IssuerGenerationAuthorityEventV1Codec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; + +class AccountControlUiOriginalSourceCaptureTest { + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final String ISSUER = "firemud-account-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + @SuppressWarnings("unchecked") + void exactIndependentLargeDecimalSourceCountersEventHistoryAndCheckpointsSurviveReadback() + throws IOException { + var event = + IssuerGenerationAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", IssuerGenerationAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", IssuerGenerationAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", + "account-issuer-authority-event-v1:22222222-2222-4222-8222-222222222222"), + Map.entry("requestId", "22222222-2222-4222-8222-222222222222"), + Map.entry("issuerId", ISSUER), + Map.entry("sourceScope", "issuer/" + ISSUER), + Map.entry("outboxStreamKey", "account:auth-authority:v1:issuer/" + ISSUER), + Map.entry("outboxSequence", "9007199254740992"), + Map.entry("issuerAuthGeneration", "9007199254740993"), + Map.entry("sourceVersion", "9223372036854775809"))); + var issuer = + new IssuerGenerationProjection( + ISSUER, + event.issuerAuthGeneration(), + event.sourceVersion(), + event.outboxStreamKey(), + event.outboxSequence(), + Optional.of(event.eventId()), + Optional.of(event.eventDigest()), + Optional.of(event.canonicalJson())); + var authority = authority(issuer); + var original = original(authority, fence()); + var readback = AccountControlUiOriginalSourceCapture.read(original); + assertThat(readback.originalCapture()).isEqualTo(original); + assertThat(readback.authorityTuple()) + .containsEntry("issuerAuthGeneration", "9007199254740993") + .containsEntry("membershipAuthorityGeneration", Map.of()) + .containsEntry("tenantAuthorityGeneration", Map.of()) + .containsEntry("privateRealmGrantVersions", List.of()); + assertThat(readback.issuanceFence()).isEqualTo("9223372036854775808"); + assertThat(new String(readback.originalCapture().authorityCapture(), StandardCharsets.UTF_8)) + .contains("9223372036854775809", "9007199254740992", event.eventDigest(), event.eventId()); + assertThat(readback.toString()).contains("non-authorizing"); + ((Map) authority.get("authorityTuple")) + .put("issuerAuthGeneration", "9007199254740992"); + assertThatThrownBy( + () -> AccountControlUiOriginalSourceCapture.read(original(authority, fence()))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @SuppressWarnings("unchecked") + void applicableAccountCutoffRetainsOriginalEventAndExactIndependentCheckpoint() + throws IOException { + String stream = "account:auth-authority:v1:account/" + ACCOUNT; + var cutoff = + Map.of( + "accountAuthorityGeneration", + "9007199254740993", + "outboxStreamKey", + stream, + "outboxSequence", + "9007199254740992"); + var event = + net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry( + "schemaVersion", + net.firedevops.firemud.common.account.authority + .PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry( + "eventType", + net.firedevops.firemud.common.account.authority + .PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "account-password-reset-event-v1:sample"), + Map.entry("requestId", "account-password-reset-request-v1:sample"), + Map.entry("accountId", ACCOUNT.toString()), + Map.entry("sourceScope", "account/" + ACCOUNT), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", "9007199254740992"), + Map.entry("accountAuthorityGeneration", "9007199254740993"), + Map.entry("sourceVersion", "9223372036854775809"), + Map.entry("accountSecurityCutoff", cutoff))); + var projection = + new AccountGenerationProjection( + ACCOUNT.toString(), + "9007199254740993", + "9223372036854775809", + stream, + "9007199254740992", + Optional.of(new String(event.canonicalJsonUtf8(), StandardCharsets.UTF_8))); + var authority = authority(baselineIssuer()); + authority.put("accountSource", projection.toJson()); + var tuple = (Map) authority.get("authorityTuple"); + tuple.put("accountAuthorityGeneration", "9007199254740993"); + tuple.put("accountSecurityCutoff", cutoff); + assertThat( + AccountControlUiOriginalSourceCapture.read(original(authority, fence())) + .authorityTuple()) + .containsEntry("accountSecurityCutoff", cutoff); + tuple.remove("accountSecurityCutoff"); + assertThatThrownBy( + () -> AccountControlUiOriginalSourceCapture.read(original(authority, fence()))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiredEmptyShapesCanonicalBytesAndActualSourceCorrespondenceAreMandatory() + throws IOException { + var issuer = baselineIssuer(); + for (String field : + List.of( + "membershipVersion", "scopedRoles", "globalRoles", "issuerSource", "accountSource")) { + var authority = authority(issuer); + authority.remove(field); + assertThatThrownBy( + () -> AccountControlUiOriginalSourceCapture.read(original(authority, fence()))) + .isInstanceOf(IllegalArgumentException.class); + } + for (Object bad : List.of(List.of(), "1", 1L, Map.of("unexpected", "1"))) { + var authority = authority(issuer); + authority.put("membershipVersion", bad); + assertThatThrownBy( + () -> AccountControlUiOriginalSourceCapture.read(original(authority, fence()))) + .isInstanceOf(IllegalArgumentException.class); + } + for (Object bad : List.of("0", "01", "1e3", 1L, " 1", "-1")) { + var fence = fence(); + fence.put("issuanceFence", bad); + assertThatThrownBy( + () -> AccountControlUiOriginalSourceCapture.read(original(authority(issuer), fence))) + .isInstanceOf(IllegalArgumentException.class); + } + var original = original(authority(issuer), fence()); + assertThatThrownBy( + () -> + AccountControlUiOriginalSourceCapture.read( + new OriginalCapture( + 1L, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, + (" " + new String(original.authorityCapture(), StandardCharsets.UTF_8)) + .getBytes(StandardCharsets.UTF_8), + original.issuanceFenceCapture()))) + .isInstanceOf(IllegalArgumentException.class); + var wrongFence = fence(); + wrongFence.put("accountId", UUID.randomUUID().toString()); + assertThatThrownBy( + () -> + AccountControlUiOriginalSourceCapture.read(original(authority(issuer), wrongFence))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static IssuerGenerationProjection baselineIssuer() { + return new IssuerGenerationProjection( + ISSUER, + "1", + "1", + "account:auth-authority:v1:issuer/" + ISSUER, + "0", + Optional.empty(), + Optional.empty(), + Optional.empty()); + } + + private static Map authority(IssuerGenerationProjection issuer) { + var account = + new AccountGenerationProjection( + ACCOUNT.toString(), + "1", + "1", + "account:auth-authority:v1:account/" + ACCOUNT, + "0", + Optional.empty()); + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", issuer.issuerAuthGeneration()); + tuple.put("accountAuthorityGeneration", "1"); + tuple.put("tenantAuthorityGeneration", Map.of()); + tuple.put("membershipAuthorityGeneration", Map.of()); + tuple.put("privateRealmGrantVersions", List.of()); + Map authority = new LinkedHashMap<>(); + authority.put("schemaVersion", "account-control-ui-original-source/v1"); + authority.put("profile", "control-ui"); + authority.put("audience", "control-ui"); + authority.put("accountId", ACCOUNT.toString()); + authority.put("authorityTuple", tuple); + authority.put("membershipVersion", Map.of()); + authority.put("scopedRoles", Map.of()); + authority.put("globalRoles", List.of()); + authority.put("issuerSource", issuer.toJson()); + authority.put("accountSource", account.toJson()); + authority.put("globalRoleSourceVersion", "9007199254740993"); + return authority; + } + + private static Map fence() { + return new LinkedHashMap<>( + Map.of( + "schemaVersion", + "account-control-ui-original-fence/v1", + "accountId", + ACCOUNT.toString(), + "issuanceFence", + "9223372036854775808", + "sourceVersion", + "9223372036854775809")); + } + + private static OriginalCapture original(Map authority, Map fence) + throws IOException { + return new OriginalCapture( + 1L, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(authority)), + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fence))); + } +} From 0b819ae419284e4474bb42b3e75495e024348159 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 20:31:06 +1300 Subject: [PATCH 10/12] test(account): correct issuance and bootstrap CI fixtures --- .github/workflows/ci.yml | 7 ++++--- ...lUiCredentialAuthenticationPostgresIntegrationTest.java | 3 ++- ...ountControlUiIssuanceIntentPostgresIntegrationTest.java | 3 +-- ...antCreationBootstrapServicePostgresIntegrationTest.java | 2 +- ...untTenantCreationProvenancePostgresIntegrationTest.java | 2 +- ...ootstrapOperationRepositoryPostgresIntegrationTest.java | 2 +- 6 files changed, 10 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12d51bd8eb..c0f36f33ad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -906,9 +906,10 @@ jobs: permissions: contents: read id-token: write - # Game Session runs composed owner proofs before its full checks and runtime JAR. - # Exact CI37121026340 exhausted 20m after those proofs passed, at JAR packaging. - timeout-minutes: ${{ matrix.module == 'game-session-service' && 30 || 20 }} + # Game Session and Account run composed owner proofs before full checks and runtime JARs. + # CI37121026340 exhausted 20m at Game Session packaging; CI37425364000 + # reached Account PostgreSQL cases but exhausted 20m before raw XML finalized. + timeout-minutes: ${{ (matrix.module == 'game-session-service' || matrix.module == 'account-service') && 30 || 20 }} strategy: fail-fast: false matrix: diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java index de646f3e36..7478915978 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiCredentialAuthenticationPostgresIntegrationTest.java @@ -158,7 +158,8 @@ void wrongAccountRequestDigestAndMissingOriginalDenyWithoutCredentialEvidence() + "request_digest_version, request_digest, authority_capture, authority_capture_digest, " + "issuance_fence_capture, issuance_fence_digest, status) " + "SELECT ?, ?, account_uuid, account_id, account_provenance, profile, audience, " - + "request_digest_version, request_digest, authority_capture, authority_capture_digest, " + + "request_digest_version, set_byte(request_digest, 0, get_byte(request_digest, 0) # 1), " + + "authority_capture, authority_capture_digest, " + "issuance_fence_capture, issuance_fence_digest, 'PENDING' " + "FROM account_control_ui_issuance_operations WHERE operation_id = ?", UUID.randomUUID(), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java index 1a95f444af..7d9c0c41e8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountControlUiIssuanceIntentPostgresIntegrationTest.java @@ -83,8 +83,7 @@ void ownerSourceCapturePrecedesSigningAndRestartRecoversOriginalReservationWitho var bound = fixture.tx().execute(status -> restart.bindSignedToken(initial, SIGNER_BYTES)); assertThat(bound).isNotNull(); assertThat(bound.tokenHash()) - .hasValue( - net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash(SIGNER_BYTES)); + .hasValue("bbd9b4fbf04eea2ba68c68d87cd16a878a1f52c1be163a94009dfaed28592d51"); assertThat( fixture .tx() diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java index 77b2f64bb9..7937abb8a2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java @@ -72,7 +72,7 @@ class AccountTenantCreationBootstrapServicePostgresIntegrationTest { private static final String TEST_NAMESPACE = "creator-bootstrap-proof"; private static final String AUDIT_EVENT_TYPE = "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED"; - private static final String SCHEMA_PREFIX = "creator_bootstrap_service_proof_"; + private static final String SCHEMA_PREFIX = "creator_bootstrap_service_"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationProvenancePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationProvenancePostgresIntegrationTest.java index 799f446dd8..73e66164e2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationProvenancePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationProvenancePostgresIntegrationTest.java @@ -192,7 +192,7 @@ private static AccountRow insertAccount(DataSource dataSource, String label) thr "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) " + "RETURNING id")) { String suffix = UUID.randomUUID().toString().replace("-", ""); - statement.setString(1, label + "-" + suffix); + statement.setString(1, label + "-" + suffix.substring(0, 16)); statement.setString(2, label + "-" + suffix + "@example.com"); statement.setString(3, "test-hash"); try (var result = statement.executeQuery()) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java index ee566af4d7..71225525d1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java @@ -49,7 +49,7 @@ */ @Testcontainers(disabledWithoutDocker = true) class AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest { - private static final String SCHEMA_PREFIX = "creator_bootstrap_operation_proof_"; + private static final String SCHEMA_PREFIX = "creator_bootstrap_operation_"; private static final String AUDIT_EVENT_TYPE = "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED"; @Container From 5105c4fbb22e49e7910a13b7e888af6e57b8bdb5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 21:12:15 +1300 Subject: [PATCH 11/12] fix(account): compare canonical bootstrap readback and isolate auth Cache Redis --- .../AccountTenantCreationBootstrapService.java | 2 +- ...dentialProducerPostgresRedisIntegrationTest.java | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java index 1fd4e7a3a9..6096d8e0e9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java @@ -321,7 +321,7 @@ private AccountTenantCreationBootstrapResult commitNew( || checkpoint.outboxSequence() != 1L || !checkpoint.sourceEventId().equals(event.eventId()) || !checkpoint.sourceEventDigest().equals(event.eventDigest()) - || !verifiedEvent.equals(expectedEvent) + || !verifiedEvent.canonicalJson().equals(expectedEvent.canonicalJson()) || !verifiedEvent.roles().equals(List.of("tenantAdmin")) || verifiedEvent.gameplayAdmissionAllowed() || verifiedEvent.callerBoundAuthorityInvalidated() diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java index edb4e5e478..bff56483d0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/impl/AccountControlUiCredentialProducerPostgresRedisIntegrationTest.java @@ -104,13 +104,18 @@ class AccountControlUiCredentialProducerPostgresRedisIntegrationTest { static GenericContainer redis = new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + @Container + static GenericContainer cacheRedis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); PostgresBackedServiceTestSupport.registerRedisService(registry, redis); - registry.add("firemud.account.platform-auth-abuse.cache-redis.host", redis::getHost); + registry.add("firemud.account.platform-auth-abuse.cache-redis.host", cacheRedis::getHost); registry.add( - "firemud.account.platform-auth-abuse.cache-redis.port", () -> redis.getMappedPort(6379)); + "firemud.account.platform-auth-abuse.cache-redis.port", + () -> cacheRedis.getMappedPort(6379)); registry.add("firemud.account.platform-auth-abuse.hmac-key-id", () -> ABUSE_HMAC_KEY_ID); registry.add( "firemud.account.platform-auth-abuse.hmac-key-base64", () -> ABUSE_HMAC_KEY_BASE64); @@ -137,6 +142,10 @@ static void configure(DynamicPropertyRegistry registry) { @BeforeEach void initializeFixtureOwners() { + assertThat(cacheRedis.getMappedPort(6379)).isNotEqualTo(redis.getMappedPort(6379)); + assertThat(authRateLimitProperties.getCacheRedis().getHost()).isEqualTo(cacheRedis.getHost()); + assertThat(authRateLimitProperties.getCacheRedis().getPort()) + .isEqualTo(cacheRedis.getMappedPort(6379)); issuanceOperations = new AccountControlUiIssuanceOperationRepository(dsl); transaction = new TransactionTemplate(transactionManager); } From 1fcac809c159f5c05261cb3bb4fd4b444f0fb5d7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:11:19 +1300 Subject: [PATCH 12/12] Correct creator bootstrap sequence proof and capture raw PostgreSQL results --- .github/workflows/ci.yml | 37 +++++++++++++++++++ .../player-access-and-session.md | 2 + ...otstrapServicePostgresIntegrationTest.java | 2 +- 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c0f36f33ad..4c0b890564 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3056,6 +3056,43 @@ jobs: if-no-files-found: warn retention-days: 7 + - name: Run Account creator-bootstrap PostgreSQL proof cases + if: ${{ matrix.module == 'account-service' }} + run: | + ./gradlew :account-service:integrationTest \ + --tests integration.net.firedevops.firemud.accountservice.AccountTenantCreationProvenancePostgresIntegrationTest \ + --tests integration.net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest \ + --tests integration.net.firedevops.firemud.accountservice.AccountTenantCreationBootstrapServicePostgresIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + + - name: Capture Account creator-bootstrap PostgreSQL raw XML + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-creator-bootstrap-postgresql-proof-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + services/account-service/build/test-results/integrationTest/TEST-*AccountTenantCreationProvenancePostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*AccountTenantCreationBootstrapServicePostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Verify Account creator-bootstrap PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountTenantCreationProvenancePostgresIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest \ + --require-suite integration.net.firedevops.firemud.accountservice.AccountTenantCreationBootstrapServicePostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountTenantCreationProvenancePostgresIntegrationTest#forwardMigrationPreservesRetainedStateAndAllowsOnlyControlOnlyCreatorShape()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest#exactImmutableInputReplaysOriginalReceiptAndChangedSnapshotConflicts()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest#claimedReceiptRollsBackWithItsAccountTransaction()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest#concurrentExactClaimsConvergeOnOneCommittedReceipt()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountTenantCreationBootstrapServicePostgresIntegrationTest#commitIsControlOnlyAndHistoricalRetryDoesNotOverwriteLaterMembershipAdvance()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountTenantCreationBootstrapServicePostgresIntegrationTest#lateReceiptFailureRollsBackMembershipRolesPairEventAuditAndClaimTogether()' \ + account-service + - name: Verify Game Session LOGIN fixture isolation proof if: ${{ !cancelled() && matrix.module == 'game-session-service' }} run: | diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 6d03cc55ed..728d43b28f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +Exact composed source `2ac634ff209309341c43ff79bb7f02455e2099b9` [CI37435549047](https://github.com/benhook1013/FireMUD/actions/runs/37435549047) provides clean raw XML for all nine pre-sign intent, seven credential-authentication and five actual credential-producer PostgreSQL/Redis cases. The six creator-provenance/bootstrap cases have HTML reports only: five pass and the historical-bootstrap service case fails because its decoded canonical event sequence string was compared with a Java `Long`. The fixture now expects the exact string while preserving numeric owner-row assertions; a dedicated run captures and strictly requires raw XML for all six cases before later report overwrite. Corrected database execution remains required. This does not prove initial authenticated capture, creator authorization, a protected signer or public credential release. + The Account-owned canonical issuer projection now has `IssuerGenerationProjection`, `IssuerGenerationProjectionRedisContract`, and an explicit-init `RedisIssuerGenerationProjectionStore`. The descriptor registers the existing Account snapshot CAS resource for only the canonical issuer key family; the store itself is not registered as a Spring bean or wired into authentication. It reads actual existing Account issuer source/history, applies one Coordination byte CAS, requires exact no-TTL readback and re-reads the durable owner before reporting convergence. It remains separate from Game Session's derived issuer projection and supplies no recipient tuple, issuance fence, complete bundle, caller authorization or issuance activation. Five value tests, two descriptor tests and six real PostgreSQL/Redis methods are defined for exact baseline/advance/replay, closed canonical evidence, corruption/TTL, regression and conflicting checkpoints, actual interleaved source advancement, missing history, endpoint/ACL separation and direct-EVAL denial. The consolidated Account full check, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass in 1m44s (72 tasks:23 executed,49 up-to-date). All1,059 unit cases execute cleanly, including these seven value/descriptor cases. All456 integration cases compile and skip without local Docker, including the six new PostgreSQL/Redis methods; database, ACL and real Redis execution remain unproved. CI captures their raw integration XML before later report overwrite and strictly requires the exact suite and all six methods, preserving the existing Account proof requirements. Complete capture, protected signing/registry, downstream cutoff and live activation proof remain open under [Account's physical projection contract](../../architecture/microservices/account-service/runtime-and-data.md#issuer-generation-snapshot-projection). Five additional PostgreSQL/Cache Redis definitions call the real Account credential producer, persisted Account/authority/challenge owners, Argon2 verifier and shared abuse limiter. They cover password evidence without a JWT outcome, exact single-use OTP and consumed-retry denial, invalid-credential counters with no issuance/evidence change, wrong-original-operation rollback, and fresh password authentication against an unexpired committed response. Only unused remote clients and mail are mocked. The original V66 capture, trusted first-party source descriptor and committed response remain explicit fixtures: this is not authenticated initial capture, a public route, signer/registry or response release. CI captures and strictly requires their executed XML; local Docker-dependent execution remains unavailable. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java index 7937abb8a2..012f05d78c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java @@ -99,7 +99,7 @@ void commitIsControlOnlyAndHistoricalRetryDoesNotOverwriteLaterMembershipAdvance MembershipEvent originalEvent = MembershipAuthorityEventV1Codec.verify( new String(originalOutboxEvent.payload(), StandardCharsets.UTF_8)); - assertThat(originalEvent.outboxSequence()).isEqualTo(1L); + assertThat(originalEvent.outboxSequence()).isEqualTo("1"); assertThat(originalEvent.membershipLifecycleState()).isEqualTo("ACTIVE"); assertThat(originalEvent.membershipVersion()) .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2"));