From 866f537b09f240e2d979af82577bbb9bb302410d Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sat, 10 Oct 2026 07:38:59 +1300
Subject: [PATCH 01/10] Bring forward Account source-currentness and exact
writer fences
---
.../microservices/account-service/README.md | 3 +-
.../account-service/runtime-and-data.md | 8 +-
.../player-access-and-session.md | 8 +-
.../DraftAuthorizationFenceRepository.java | 936 ++++++++++++++
.../creatorparty/CreatorPartyEncoding.java | 108 ++
.../IndividualCreatorPartyRepository.java | 453 +++++++
.../IndividualCreatorPartySource.java | 52 +
.../dto/AccountLogoutRequestDigest.java | 116 ++
...AccountPlatformRestrictionBirthSource.java | 197 +++
.../AccountSecurityStateMutationRequest.java | 180 +++
.../AccountSecurityStateRequestDigest.java | 51 +
.../AccountTenantCreationBootstrapResult.java | 49 +
...DeploymentEnvironmentBoundaryProvider.java | 74 ++
.../AccountHostedTermsService.java | 1151 +++++++++++++++++
.../HostedTermsCatalogVersion.java | 144 +++
.../hostedterms/HostedTermsEncoding.java | 248 ++++
.../HostedTermsEnvironmentBinding.java | 147 +++
...HostedTermsEnvironmentBindingEncoding.java | 87 ++
...stedTermsEnvironmentBindingRepository.java | 422 ++++++
.../hostedterms/HostedTermsRepository.java | 550 ++++++++
.../IndividualHostedTermsAcceptance.java | 105 ++
...ountAuthoritySourceEvidenceRepository.java | 561 +++++++-
.../AccountLogoutAllOperationRepository.java | 321 +++++
...countPasswordResetOperationRepository.java | 316 +++++
...untPlatformRestrictionBirthRepository.java | 325 +++++
.../repository/AccountRepository.java | 73 ++
...countSecurityStateOperationRepository.java | 693 ++++++++++
.../AccountTenantCreationBootstrapDigest.java | 251 ++++
...tCreationBootstrapOperationRepository.java | 573 ++++++++
.../AccountTenantMembershipRepository.java | 89 ++
.../PasswordResetTokenRepository.java | 23 +
.../AccountAuthoritySourceEventReadback.java | 714 ++++++++++
.../service/AccountAuthoritySourceReader.java | 237 ++++
.../AccountCreatorMembershipSourceReader.java | 568 ++++++++
.../service/AccountGenerationProjection.java | 355 +++++
...ccountLogoutAllAuthorityEventProducer.java | 680 ++++++++++
...tLogoutAllDraftSourceChangeRepository.java | 484 +++++++
...countMembershipAuthorityEventProducer.java | 289 +++++
...swordResetDraftSourceChangeRepository.java | 758 +++++++++++
...tCreationBootstrapAuthorizationSource.java | 20 +
...AccountTenantCreationBootstrapService.java | 792 ++++++++++++
.../service/IssuerGenerationProjection.java | 272 ++++
.../service/impl/AccountServiceImpl.java | 701 +++++++++-
...GameplayDelegationAuthorityProjection.java | 180 +++
.../V74__account_global_role_source.sql | 158 +++
...V75__draft_commit_authorization_fences.sql | 188 +++
...76__account_draft_required_owner_fence.sql | 371 ++++++
...ount_password_reset_operation_receipts.sql | 91 ++
..._account_logout_all_operation_receipts.sql | 90 ++
...V79__account_security_state_operations.sql | 401 ++++++
...0__account_security_event_source_guard.sql | 398 ++++++
...unt_platform_restriction_birth_sources.sql | 261 ++++
.../V82__creator_membership_provenance.sql | 11 +
...V83__account_tenant_creation_bootstrap.sql | 189 +++
.../V84__individual_creator_party_sources.sql | 153 +++
...count_hosted_terms_acceptance_workflow.sql | 383 ++++++
...count_hosted_terms_environment_binding.sql | 288 +++++
...account_control_ui_owner_source_guards.sql | 156 +++
...ogout_all_pending_draft_source_changes.sql | 295 +++++
...ord_reset_pending_draft_source_changes.sql | 378 ++++++
...horityProducerPostgresIntegrationTest.java | 730 +++++++++++
...rceEvidencePersistenceIntegrationTest.java | 16 +-
.../AccountRepositoryIntegrationTest.java | 12 +
...wardMigrationsPostgresIntegrationTest.java | 650 ++++++++++
...tionV73UpgradePostgresIntegrationTest.java | 116 ++
.../IndividualCreatorPartyRepositoryTest.java | 416 ++++++
...oymentEnvironmentBoundaryProviderTest.java | 130 ++
...tPasswordResetOperationRepositoryTest.java | 132 ++
...ountCreatorMembershipSourceReaderTest.java | 116 ++
...ntLogoutAllAuthorityEventProducerTest.java | 240 ++++
.../service/impl/AccountServiceImplTest.java | 52 +-
...playDelegationAuthorityProjectionTest.java | 106 ++
...AccountLogoutAllAuthorityEventV1Codec.java | 355 +++++
...untSecurityStateAuthorityEventV1Codec.java | 391 ++++++
.../PasswordResetAuthorityEventV1Codec.java | 372 ++++++
...eMembershipAuthorityEvidenceValidator.java | 685 ++++++++++
.../tenant/FreshTenantCreatorDigest.java | 103 ++
.../tenant/FreshTenantCreatorEvidence.java | 54 +
...untLogoutAllAuthorityEventV1CodecTest.java | 118 ++
...ecurityStateAuthorityEventV1CodecTest.java | 157 +++
...asswordResetAuthorityEventV1CodecTest.java | 122 ++
...bershipAuthorityEvidenceValidatorTest.java | 317 +++++
.../tenant/FreshTenantCreatorDigestTest.java | 161 +++
.../FreshTenantCreatorEvidenceTest.java | 164 +++
84 files changed, 23846 insertions(+), 44 deletions(-)
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartySource.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.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/dto/AccountTenantCreationBootstrapResult.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProvider.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsCatalogVersion.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBinding.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/IndividualHostedTermsAcceptance.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepository.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/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllDraftSourceChangeRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java
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/session/AccountGameplayDelegationAuthorityProjection.java
create mode 100644 services/account-service/src/main/resources/db/migration/V74__account_global_role_source.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V75__draft_commit_authorization_fences.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V76__account_draft_required_owner_fence.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V79__account_security_state_operations.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V80__account_security_event_source_guard.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V81__account_platform_restriction_birth_sources.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V82__creator_membership_provenance.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V84__individual_creator_party_sources.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V86__account_hosted_terms_environment_binding.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V87__account_control_ui_owner_source_guards.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V88__account_logout_all_pending_draft_source_changes.sql
create mode 100644 services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceFoundationV73UpgradePostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java
create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java
create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java
create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java
create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java
create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java
create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java
create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java
diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md
index 084cafc2a4..366b18eb51 100644
--- a/design/architecture/microservices/account-service/README.md
+++ b/design/architecture/microservices/account-service/README.md
@@ -6,10 +6,11 @@ Manages user accounts and authentication for the platform. It stores profile dat
## Implementation Status
+- The current Account source/currentness cut adds local persistence and writer-fencing consequences to the existing Account ownership boundary. Focused checks and integration-source compilation pass; physical PostgreSQL proof remains pending. This does not activate public JOIN, logout-all authority, hosted-terms workflows, or creator UI; see the [runtime and data status](./runtime-and-data.md#implementation-status) and [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status).
- Provider-specific external identity linking is target-state only; no provider is advertised until its server-verified authorization, global subject uniqueness, recovery, unlink, and end-to-end login proof are complete.
- The caller-asserted external-link persistence/service scaffold remains unsupported implementation drift, but its REST route is removed and the exact legacy public-edge path is denied. No provider integration is advertised or externally available.
- Credential-bearing gameplay `Authenticate` and its verified-email challenge authenticate global Account identity without a tenant or membership prerequisite. The resulting private delegation token is account-scoped; Game Session retains any bootstrap tenant only as local transport context, and selected-target membership, grant, and entitlement remain separate `JOIN`/`PLAY` checks.
-- Account is the target authority for the hosted Creator Party, identified operator and hosted-terms catalog, and acceptance/currentness evidence under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md); changed-term notice, decline, continuity, and lifecycle consequences are separately governed by [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These hosted-terms contracts are target-only: no current party/signer registry, terms catalog, acceptance or transfer API/storage, creator UI, or downstream write-gate proof exists, and organization support is not enabled.
+- Account is the target authority for the hosted Creator Party, identified operator and hosted-terms catalog, and acceptance/currentness evidence under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md); changed-term notice, decline, continuity, and lifecycle consequences are separately governed by [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Current source-only persistence does not register the hosted-terms workflow. The fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery; authenticated publication, registry/runtime binding, creator UI, and downstream write-gate proof remain absent. Organization support is not enabled.
- Future managed-creator-commerce financial/provider reconciliation and entitlement authority are a separate target-only boundary under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); it does not expand hosted-terms acceptance/currentness authority or enable marketplace commerce, and no marketplace route or payout workflow is enabled.
### Responsibilities
diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md
index 5460e97b28..daaa9dfd63 100644
--- a/design/architecture/microservices/account-service/runtime-and-data.md
+++ b/design/architecture/microservices/account-service/runtime-and-data.md
@@ -8,7 +8,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn
## Implementation Status
-Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation. New repository-created Accounts and a genuinely new issuer receive these baselines; retained rows are not backfilled. Exact security-relevant Account updates compose source generation, issuance fence, canonical event, and current readback in their owner transaction. The owner-local first-JOIN producer/coordinator retains membership, pair/event, audit, and terminal-operation evidence. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime wiring. Reconciled V40/source-currentness/coordinator proof remains pending; see the [Player Access and Session implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Hard deletion remains denied, revoked grants remain tombstones, and this stage does not enable signer provisioning, LOGIN, PLAY, or activation.
+Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation; V74–V89 preserve that baseline and add source/global-role guards, draft-source writer exclusions and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion now atomically claims and consumes its token, updates the Account, appends the canonical event and receipt, and reads back current source evidence in the owner transaction. If an earlier source intent is still pending, the request waits for its owner-fence outcome before mutating the token or password; exact retries retain the original operation identity. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Account and Common checks passed: 626 Account unit tests and 245 Common Platform Core tests executed with zero failures or skips, and Account production/test compilation, formatting, Checkstyle, and SpotBugs passed. Repository link checking and Markdown linting also passed. The Account integration suite contains 80 cases: two executed and 78 skipped because Docker was disabled. All five forward-migration cases, the V73-upgrade case, and seven password-reset PostgreSQL cases were skipped, so physical PostgreSQL proof is not established. See the [Player Access and Session implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Hard deletion remains denied, revoked grants remain tombstones, and this stage does not enable signer provisioning, LOGIN, PLAY, or activation.
Account's actor-staging eligibility owner read is a read-only, same-namespace Entity workload RPC gated off by default. Under one repeatable-read Account transaction it verifies persisted Account UUID/provenance, current Account membership and pair authority, fresh Game Design tenant-source evidence, and the current membership event/checkpoint, then returns digest-sealed evidence scoped to `PUBLIC_PRODUCTION_STAGING_ONLY`. It reports an eligible or ineligible source snapshot but creates no membership, actor assignment, JOIN, PLAY, or gameplay admission. The staged foundation passed 43 focused Account tests and 92 shared-evidence tests with no failures or skips, plus source generation and Account integration-source compilation. PostgreSQL migration/persistence proof sources are included but physical PostgreSQL and live runtime execution remain unrun; the RPC is not runtime-ready or admission authority.
@@ -26,7 +26,7 @@ Account also performs a bounded sweep of public connect-scope evidence after its
The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback applies the terminal retry checks when a terminal row is present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. An exact retry of a terminal JOIN replays its stored result only after the retained scope is still unexpired and current target/entitlement authority is available and matches the stored policy digest; expiry, unavailable authority, or changed policy fails closed without rewriting the terminal operation or membership. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design.
-Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model.
+Account now has source-only persistence for individual Creator Party identity and hosted-terms acceptance/environment-binding evidence. A fixed server environment-evidence adapter exists but remains deliberately unregistered; it supplies no genuine input delivery. The hosted-terms workflow does not manufacture an external observer, authenticated legal publication, registry/runtime binding, creator UI, or Game Design evidence binding. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), and local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled.
The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current consumers still rely on only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and do not enforce the complete atomic-freshness contract or consume the emitted lifecycle/generation fields. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and character discovery require membership after applicable target and entitlement checks; on an eligible public-production target only absent membership may return non-actionable `JOIN_REQUIRED`, while existing membership with `gameplayAdmissionAllowed=false` is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` can still return non-actionable `JOIN_REQUIRED` for missing or present non-admitting membership before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. These flows do not create or restore membership. The Account-owned public-production `JOIN` writer is implemented locally with a v1 policy-bound digest and atomic membership, operation-outcome, and audit-outbox evidence. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Exact-final-head PostgreSQL runtime proof remains unavailable locally without Docker; no live PostgreSQL runtime proof or direct text-client end-to-end proof is claimed. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented.
@@ -34,7 +34,7 @@ The current `application.yml` and `application-prod.yml` classify `GetTenantMemb
The target realm-grant mutation boundary remains the Account API's tenant-admin or separately authorized platform-admin operator path ([Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract)). The live legacy `POST`/`DELETE /internal/runtime/realm-access-grants` routes instead admit the broad shared global-privileged-role helper (including `moderator`), accept caller-supplied `grantedBy`/`grantReason`, and do not apply the target lifecycle identity, revision, digest, or request-replay contract. They must be removed or fail closed until the canonical owner transport and its authenticated attribution and replay proof are implemented; this route is not an additional grant authority.
-Recovery/verification foundations are live, but the current password-reset transaction reads a token, updates the account, and deletes the token as separate operations. Concurrent requests can therefore consume the same valid reset token more than once; atomic single-use consumption and concurrent-reuse proof remain required under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md).
+Recovery/verification foundations are live. Password-reset completion now uses an owner-locked atomic token claim/consume, Account update, canonical event and operation receipt, and current-source readback; an unresolved prior source intent fences token/password mutation until its outcome is known. Exact retry, concurrent reuse, and physical PostgreSQL proof for this cut remain pending under the [Account API recovery boundary](./api-contracts.md#rest-apis) and [authentication security contract](../../system-architecture-authentication.md).
Account locally implements `IssueDirectTextConnectScope` for an authenticated caller and the exact Game Session-resolved public-production target from `REALMS`, validating its retained target snapshot and caller binding. Game Session does not yet wire this RPC into text `REALMS` or retain the returned scope in transport context. Account also implements the `JoinPublicProductionMembership` RPC/operation and local HTTP JOIN route, including retained-target and caller-binding validation; Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898. These local Account capabilities do not yet form an end-to-end direct-text `REALMS`-to-`JOIN` flow. Account request retries can resume a committed policy-independent intent across entitlement outages; after an uncertain second-transaction outcome, Account reads back and returns a terminal result if committed, otherwise asks the caller to retry that request ID. No background recovery worker or direct text-client end-to-end proof is claimed. The canonical scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative).
@@ -69,7 +69,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi
- Target `external_account` records link a server-verified canonical `{provider, issuer, subject}` to one global platform account without tenant scope. The current tenant-scoped, caller-asserted row shape is implementation drift.
- Tenant-bound billing tables such as `subscription` and tenant-bound `payment_transaction` records associate `accountId` with `tenantId` for hosted games and hosting plans. Account-scoped transactions, grants, and donations carry no fabricated `tenantId`.
- Account-owned safety records persist separate `account_security_lock` and `platform_access_ban` revisions keyed by global `accountId` and category. Their current projection, monotonic enforcement epoch, idempotency/result records, source case/security-event identity, and safe notice support auth-generation and player-safe denial decisions without a Logging & Admin read. The complete schema/command implementation remains a target gap.
-- Account-owned Creator Party, identified operator/terms versions, acceptance/currentness evidence, and future financial-reconciliation records are target-only. Each committed covered creator mutation records the local `tenantId`, exact `creatorPartyId`, `acceptanceEvidenceId`, and material-acceptance `generation` binding; Account remains sole owner of the party and terms catalogs, which Game Design must not copy. No current storage or focused proof implements this boundary; see [Account API Contracts](./api-contracts.md#account-owned-hosted-terms-and-creator-party).
+- Account-owned Creator Party, identified operator/terms versions, acceptance/currentness evidence, and future financial-reconciliation records remain target-state authority. Source-only persistence now records individual Creator Party and hosted-terms/environment-binding evidence. The fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery; authenticated publication, runtime binding, and focused end-to-end proof are absent. Account remains sole owner of the party and terms catalogs, which Game Design must not copy; see [Account API Contracts](./api-contracts.md#account-owned-hosted-terms-and-creator-party).
- Durable purchased-product grants are reserved for deferred future commerce and are separate from raw payment attempts. A future tenant-bound one-time purchase would store bindings to `accountId`, `tenantId`, an optional Entity-resolvable actor reference `{tenantId, playableStateNamespaceId, characterId}`, and `productCode`; those association fields are not fulfillment-uniqueness inputs. The sole fulfillment uniqueness pair is the immutable `(purchase_operation_id, product_grant_key)` defined by [Stripe Integration Design](./stripe-integration.md). Server-derived `playableStateScope` travels as separately validated policy/routing/authorization evidence for that actor and active instance, not as a durable actor key or uniqueness dimension. `gameInstanceId` may be added only as an explicit replaceable runtime fence when the operation requires it. Account-scoped grants use Account-owned records without `tenantId`. No v1 hosting-billing PaymentIntent, donation, or receipt creates this entitlement. Applying an account-scoped grant to a tenant-scoped feature requires an explicit tenant binding or consumption record. Payment rows remain financial/provider evidence, not entitlement authority.
Google, Discord, and Steam are optional provider-specific HTTPS integrations, not simultaneously promised launch capabilities. Initial delivery links a verified provider subject to an already authenticated global account; provider-first account creation is deferred. Provider email or display-name matches never merge accounts, every account retains Account-owned verified-email recovery and an ordinary login mode, and provider outage does not invalidate existing FireMUD sessions.
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 796c7135e7..3e6846526b 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,7 @@ This is a non-normative implementation tracker for player access and session. Ca
## Current Status
-The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged.
+The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. Account and Common unit checks and Account compile/static-analysis gates passed; the Account integration sources also compiled. Physical fresh-install/V73-upgrade PostgreSQL proof remains pending because the PostgreSQL cases were skipped with Docker disabled; exact scope and counts are recorded in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. The hosted-terms workflow, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898/#2848 and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status).
Canonical first-JOIN membership-event production requires current public-JOIN entitlement; a bare fresh tenant 1/1 baseline is denied and does not preserve admission. Tenant authority requires Account's exact typed tenant event, fresh Game Design provenance, and matching composite generation/source-version and billing coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Historical gate 108 passed 593 Account unit cases and five focused shared World hold cases. Later gate 123 passed 598 Account unit cases, and gate 124 passed 27 focused shared-evidence cases across a broader selection; these are distinct executed snapshots and suite scopes, not conflicting totals. jOOQ generation and integration-test compilation passed. Published checkpoint `b5234acd7f93440170178d1b808e19b4a00ac644` subsequently passed required CI. PostgreSQL-backed integration sources, including the later-generation JOIN and exact outbox replay cases, remain unexecuted locally; neither unit proof nor historical CI establishes fresh-image playable proof for subsequent corrections.
@@ -18,7 +18,7 @@ Internal Account-carrier typing is prepared in Game Session, while current produ
Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker.
-Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present.
+Official-hosted creator-content acceptance remains an unregistered target workflow; source-only persistence for Creator Party and hosted-terms/environment-binding evidence does not supply external environment observation, authenticated publication, registry/runtime binding, creator UI, or downstream write-gate proof. The fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Its target authority remains under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md), outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present.
Account runtime admission reads remain a security/proof blocker: both `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are currently configured as public gRPC methods, and handlers accept caller-selected identifiers without exact Game Session/World Management workload or tenant binding. The target internal-workload boundary and required negative proof are canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md).
@@ -30,9 +30,9 @@ SEC-04 does not move player session ownership into Logging & Admin. Game Session
## Retained Account Source Prerequisite
-V40 deliberately does not enroll retained pre-V40 Accounts into fresh authority-source baselines. Security-relevant repository updates, including password-reset completion, require the existing owner-proven source. Missing source evidence produces the typed owner denial and a safe `AUTH_UNAVAILABLE` HTTP response after rollback, without changing the password, consuming the reset token, advancing generation/fences, appending an event, or creating a baseline. Other inconsistent source evidence remains denied; unrelated transaction or database failures are not converted by this narrow handler.
+V40 deliberately does not enroll retained pre-V40 Accounts into fresh authority-source baselines. Fresh repository-created Accounts use owner-proven source baselines, and security-relevant updates require that source. Password-reset completion now atomically claims and consumes its token with the Account update, canonical event/receipt, and current-source readback. If source evidence is missing, the owner denial and safe `AUTH_UNAVAILABLE` response occur after rollback; if an earlier source intent is pending, token/password mutation waits for its owner-fence outcome. Retained pre-V40 rows remain denied and are neither backfilled nor admitted; unrelated transaction or database failures are not converted by this handler.
-Deployment must not advertise retained credential/security-write workflows as ready merely because V40 installs successfully. A separately authorized, provenance-complete retained-source enrollment mechanism and its migration/rollback proof remain prerequisites to enabling those workflows for retained Accounts; no such enrollment or backfill is implemented here. Focused HTTP/gRPC and service denial tests passed within the 249-test correction gate. A PostgreSQL regression creates the Account/reset token before V40, migrates forward, and invokes the actual reset/repository owners; its source compiles, but physical execution remains unavailable locally. This consequence does not activate public JOIN, LOGIN/PLAY, recovery-token release, or change capability status; see [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md).
+Deployment must not advertise retained credential/security-write workflows as ready merely because V40 installs successfully. A separately authorized, provenance-complete retained-source enrollment mechanism and its migration/rollback proof remain prerequisites for retained Accounts; no enrollment or backfill is implemented. Password-reset token consumption is now implemented atomically for Accounts with valid current source evidence; reset-driven revocation and other recovery workflows remain incomplete. Account and Common unit checks, Account compilation and static analysis, and Account integration-source compilation passed; physical fresh-install/V73-upgrade execution remains unestablished because those PostgreSQL cases were skipped with Docker disabled. This consequence does not activate public JOIN, LOGIN/PLAY, recovery-token release, or change capability status; see [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md).
## Packet 4 Status and Proof Gaps
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
new file mode 100644
index 0000000000..66099c9f28
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java
@@ -0,0 +1,936 @@
+package net.firedevops.firemud.accountservice.authordraft;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.ByteArrayOutputStream;
+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.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Unwired durable ordering component. Every method requires a writable caller READ_COMMITTED
+ * Account transaction. Callers lock/revalidate actual authority sources first, then this component
+ * locks sorted source participation rows and sorted operations. Never hold these locks across RPC.
+ * Reservation and returned source evidence alone grant no owner commit permission.
+ *
+ *
Future authenticated capture/source-change and owner-readback producers are mandatory. This
+ * class does not authenticate supplied evidence or manufacture missing role/terms source state.
+ */
+public final class DraftAuthorizationFenceRepository {
+ private static final String FENCES = "account_draft_authorization_fences";
+ private static final String SOURCES = "account_draft_authorization_sources";
+ private static final String READBACKS = "account_draft_authorization_owner_readbacks";
+ private static final String CHANGES = "account_draft_authorization_source_changes";
+ private static final String CHANGED = "account_draft_authorization_changed_scopes";
+ private final DSLContext dsl;
+
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification =
+ "Injected DSLContext is an internal owner-transaction persistence collaborator.")
+ public DraftAuthorizationFenceRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl);
+ }
+
+ public enum Ordering {
+ RESERVED,
+ COMMIT_ORDER,
+ REVOKE_ORDER
+ }
+
+ public enum Settlement {
+ PENDING,
+ COMMITTED,
+ FAILED_NONPUBLICATION
+ }
+
+ /** Terminal reason for an Account source change that made no source mutation. */
+ public enum SourceChangeAbortReason {
+ EXPIRED,
+ DEFINITIVE_ABORT
+ }
+
+ 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 record SourceChangeSnapshot(
+ UUID changeId,
+ byte[] binding,
+ String status,
+ OffsetDateTime requestedAt,
+ OffsetDateTime committedAt,
+ OffsetDateTime abortedAt,
+ SourceChangeAbortReason abortReason) {
+ public SourceChangeSnapshot {
+ binding = binding.clone();
+ }
+
+ @Override
+ public byte[] binding() {
+ return binding.clone();
+ }
+ }
+
+ /** Full exact mutation intent and independently captured affected source vector. */
+ public record SourceChange(UUID changeId, List sources, byte[] mutation) {
+ public SourceChange {
+ DraftAuthorizationFenceBinding.requireUuid(changeId);
+ sources =
+ List.copyOf(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 affected sources required");
+ }
+ mutation = DraftAuthorizationFenceBinding.bytes(mutation);
+ }
+
+ @Override
+ public List sources() {
+ return List.copyOf(sources);
+ }
+
+ @Override
+ public byte[] mutation() {
+ return mutation.clone();
+ }
+
+ public byte[] canonicalBytes() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ DraftAuthorizationFenceBinding.frame(out, "account-draft-source-change/v1");
+ DraftAuthorizationFenceBinding.frame(out, changeId.toString());
+ DraftAuthorizationFenceBinding.frame(out, Integer.toString(sources.size()));
+ for (SourceEvidence source : sources) {
+ DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes());
+ }
+ DraftAuthorizationFenceBinding.frame(out, mutation);
+ return out.toByteArray();
+ }
+
+ /**
+ * Exact recovery of the original vector; callers must never replace it with a fresh capture.
+ */
+ public static SourceChange fromStored(byte[] stored) {
+ var reader = new DraftAuthorizationFenceBinding.FrameReader(stored);
+ reader.expect("account-draft-source-change/v1");
+ String id = reader.text();
+ DraftAuthorizationFenceBinding.canonicalUuid(id);
+ String count = reader.text();
+ DraftAuthorizationFenceBinding.decimal(count, false);
+ final int size;
+ try {
+ size = Integer.parseInt(count);
+ } catch (NumberFormatException invalid) {
+ throw new IllegalArgumentException("Stored source count is out of range", invalid);
+ }
+ if (size > reader.remaining() / Integer.BYTES) {
+ throw new IllegalArgumentException("Incomplete stored source vector");
+ }
+ java.util.ArrayList sources = new java.util.ArrayList<>();
+ for (int i = 0; i < size; i++) {
+ sources.add(SourceEvidence.fromStored(reader.bytes()));
+ }
+ SourceChange change = new SourceChange(UUID.fromString(id), sources, reader.bytes());
+ reader.requireEnd();
+ if (!Arrays.equals(stored, change.canonicalBytes())) {
+ throw new IllegalArgumentException("Noncanonical stored source change");
+ }
+ return change;
+ }
+ }
+
+ /**
+ * Already-existing source capture only. Future producer must establish completeness/currentness.
+ */
+ public FenceSnapshot reserve(DraftAuthorizationFenceBinding binding) {
+ requireTransaction();
+ lockSources(binding.sources());
+ Record existing = readOperation(binding.operationId());
+ if (existing != null) {
+ return snapshot(requireExact(existing, binding));
+ }
+ if (hasWaitingChange(binding.sources())) {
+ throw new IllegalStateException("Applicable authority source change is waiting");
+ }
+ requireNoAuthorizedDisclosure(binding.sources());
+ dsl.execute(
+ "INSERT INTO "
+ + FENCES
+ + " (operation_id, request_id, commit_id, fence_id, binding, ordering) VALUES (?, ?, ?, ?, ?, 'RESERVED')",
+ binding.operationId(),
+ binding.requestId(),
+ binding.commitId(),
+ binding.fenceId(),
+ 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));
+ }
+
+ /**
+ * Irrevocable exact operation order; revalidate actual source state under its locks before
+ * calling.
+ */
+ public FenceSnapshot claimCommitOrder(DraftAuthorizationFenceBinding 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 owner commit");
+ }
+ requireNoAuthorizedDisclosure(binding.sources());
+ 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));
+ }
+
+ /**
+ * Serializes an exact disclosure preparation against existing Draft captures and owner
+ * settlement. The caller must persist its immutable handoff in this same transaction. This is
+ * deliberately a non-revoking check: it never changes RESERVED, COMMIT_ORDER, or REVOKE_ORDER,
+ * and it does not install a blanket block on ordinary authoring.
+ *
+ * The lock order is the canonical sorted source-key vector followed by affected operation
+ * UUIDs in canonical order, matching capture, commit-order, source-change, and owner-readback
+ * paths. No lock obtained here may be held across an RPC.
+ */
+ public void requireDisclosurePreparation(List exactSources) {
+ lockDisclosureSources(exactSources);
+ List sources = List.copyOf(exactSources);
+ if (hasWaitingChange(sources)) {
+ throw new IllegalStateException("Applicable Account source change is unresolved");
+ }
+ requireNoPendingPublication(sources);
+ requireNoPendingGameLogicIntake(sources);
+ for (UUID operationId : affectedOperations(sources)) {
+ Record row = readOperation(operationId);
+ if (row == null) {
+ throw new IllegalStateException("Affected original Draft operation disappeared");
+ }
+ DraftAuthorizationFenceBinding original = originalBinding(row);
+ Ordering ordering = Ordering.valueOf(row.get("ordering", String.class));
+ if (ordering == Ordering.RESERVED || settlement(original, ordering) == Settlement.PENDING) {
+ throw new IllegalStateException(
+ "Disclosure deadline cannot pass an unsettled original Draft operation");
+ }
+ }
+ }
+
+ /** Locks the complete sorted vector before any disclosure journal or operation row lock. */
+ public void lockDisclosureSources(List exactSources) {
+ requireTransaction();
+ List sources =
+ List.copyOf(Objects.requireNonNull(exactSources, "exact disclosure sources")).stream()
+ .sorted(Comparator.comparing(SourceEvidence::key))
+ .toList();
+ if (sources.isEmpty()
+ || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) {
+ throw new IllegalArgumentException("Distinct exact disclosure source evidence required");
+ }
+ for (SourceEvidence source : sources) {
+ if (source.key().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 512) {
+ throw new IllegalArgumentException(
+ "Disclosure source key exceeds the existing Account source-lock bound");
+ }
+ }
+ lockSources(sources);
+ }
+
+ private void requireNoAuthorizedDisclosure(List sources) {
+ for (SourceEvidence source : sources) {
+ if (source.kind() == SourceKind.HOSTED_TERMS
+ && !dsl.fetch(
+ "SELECT 1 FROM account_hosted_terms_disclosure_handoffs h "
+ + "JOIN account_hosted_terms_disclosure_sources s ON s.handoff_id = h.handoff_id "
+ + "WHERE h.source_key = ? AND s.source_key = h.source_key "
+ + "AND s.source_evidence = ? "
+ + "AND h.status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS', 'DISCLOSED')",
+ source.key(),
+ source.canonicalBytes())
+ .isEmpty()) {
+ throw new IllegalStateException("Exact hosted terms source has authorized disclosure");
+ }
+ }
+ }
+
+ /** Distinct publication admission after authenticated source capture and sorted source locks. */
+ public void requirePublicationAdmission(List sources) {
+ requireTransaction();
+ lockProducerSourcesNowait(sources);
+ if (hasWaitingChange(sources)) {
+ throw new IllegalStateException("Applicable authority source change is waiting");
+ }
+ requireNoAuthorizedDisclosure(sources);
+ }
+
+ /** Distinct rule-intake acquisition uses the same current source/disclosure ordering. */
+ public void requireGameLogicIntakeAdmission(
+ List sources, DraftCommitBinding selected) {
+ requirePublicationAdmission(sources);
+ Record originalRow =
+ dsl.fetchOne(
+ "SELECT * FROM " + FENCES + " WHERE request_id = ? AND commit_id = ? FOR UPDATE",
+ selected.requestId(),
+ selected.commitId());
+ if (originalRow == null) {
+ throw new IllegalStateException("Selected author operation is unavailable");
+ }
+ DraftAuthorizationFenceBinding original = originalBinding(originalRow);
+ if (!Arrays.equals(original.gameDesignBinding(), selected.canonicalBytes())
+ || settlement(original, Ordering.valueOf(originalRow.get("ordering", String.class)))
+ != Settlement.COMMITTED) {
+ throw new IllegalStateException(
+ "Exact selected author operation has not committed and settled");
+ }
+ }
+
+ private boolean hasPendingGameLogicIntake(List sources) {
+ for (SourceEvidence source : sources) {
+ if (!dsl.fetch(
+ "SELECT operation_id FROM account_game_logic_intake_sources WHERE source_key = ?"
+ + " AND NOT account_game_logic_intake_is_settled(operation_id)"
+ + " UNION ALL SELECT operation_id FROM account_game_logic_intake_source_read_sources s"
+ + " WHERE source_key = ? AND account_game_logic_intake_source_read_is_pending(s.operation_id)",
+ source.key(),
+ source.key())
+ .isEmpty()) return true;
+ }
+ return false;
+ }
+
+ private void requireNoPendingGameLogicIntake(List sources) {
+ if (hasPendingGameLogicIntake(sources)) {
+ throw new IllegalStateException("Distinct Game Logic intake remains pending");
+ }
+ }
+
+ private boolean hasPendingPublication(List sources) {
+ for (SourceEvidence source : sources) {
+ if (!dsl.fetch(
+ "SELECT operation_id FROM account_selected_publication_sources"
+ + " WHERE source_key = ? AND NOT account_selected_publication_is_settled(operation_id)",
+ source.key())
+ .isEmpty()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void requireNoPendingPublication(List sources) {
+ if (hasPendingPublication(sources)) {
+ throw new IllegalStateException("Distinct selected-publication operation remains pending");
+ }
+ }
+
+ /**
+ * Commit this WAITING result even when false: rolling back would lose revocation intent. True
+ * means settled or an exact SOURCE_COMMITTED replay; call sourceMutationPermitted before writing.
+ * A distinct request overlapping an already pending source change is not admitted: it must not
+ * retain a second old-state capture that becomes stale when the first source change commits.
+ */
+ public boolean requestSourceChange(SourceChange change) {
+ requireTransaction();
+ lockChangedAccounts(change.sources());
+ lockSources(change.sources());
+ Record prior = readChange(change.changeId());
+ if (prior != null) {
+ requireChange(prior, change);
+ String priorStatus = prior.get("status", String.class);
+ if ("SOURCE_COMMITTED".equals(priorStatus)) {
+ return true;
+ }
+ if ("SOURCE_ABORTED".equals(priorStatus)) {
+ throw new IllegalStateException("Aborted source change cannot be requested again");
+ }
+ if (!"WAITING".equals(priorStatus)) {
+ throw new IllegalStateException("Source change has an unsupported terminal state");
+ }
+ } else {
+ if (hasWaitingChange(change.sources())) {
+ throw new IllegalStateException("Another authority source change is already pending");
+ }
+ dsl.execute(
+ "INSERT INTO " + CHANGES + " (change_id, binding, status) VALUES (?, ?, 'WAITING')",
+ change.changeId(),
+ change.canonicalBytes());
+ for (SourceEvidence source : change.sources()) {
+ dsl.execute(
+ "INSERT INTO " + CHANGED + " (change_id, source_key) VALUES (?, ?)",
+ change.changeId(),
+ source.key());
+ }
+ }
+ for (UUID operation : affectedOperations(change.sources())) {
+ Record row = readOperation(operation);
+ if ("RESERVED".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);
+ }
+ }
+ return allAffectedSettled(change.sources());
+ }
+
+ /** Verify before the first source mutation and retain the transaction through source commit. */
+ public boolean sourceMutationPermitted(SourceChange change) {
+ requireTransaction();
+ lockSources(change.sources());
+ Record row = readChange(change.changeId());
+ requireChange(row, change);
+ return "WAITING".equals(row.get("status", String.class))
+ && allAffectedSettled(change.sources());
+ }
+
+ /** A no-mutation cancellation is safe only after every affected owner operation is settled. */
+ public boolean sourceAbortPermitted(SourceChange change) {
+ requireTransaction();
+ lockSources(change.sources());
+ Record row = readChange(change.changeId());
+ requireChange(row, change);
+ return "WAITING".equals(row.get("status", String.class))
+ && allAffectedSettled(change.sources());
+ }
+
+ /**
+ * Same transaction as actual source mutation/event/readback. No RPC or fake source write here.
+ */
+ public void markSourceCommitted(SourceChange change) {
+ requireTransaction();
+ lockSources(change.sources());
+ Record row = readChange(change.changeId());
+ requireChange(row, change);
+ String status = row.get("status", String.class);
+ if ("SOURCE_COMMITTED".equals(status)) {
+ return;
+ }
+ if ("SOURCE_ABORTED".equals(status)) {
+ throw new IllegalStateException("Aborted source change cannot be committed");
+ }
+ if (!"WAITING".equals(status)) {
+ throw new IllegalStateException("Source change is not waiting");
+ }
+ if (!allAffectedSettled(change.sources())) {
+ throw new IllegalStateException("Owner outcomes unresolved");
+ }
+ int updated =
+ dsl.execute(
+ "UPDATE "
+ + CHANGES
+ + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP"
+ + " WHERE change_id = ? AND status = 'WAITING'",
+ change.changeId());
+ if (updated != 1) {
+ throw new IllegalStateException("Draft source change did not commit exactly once");
+ }
+ }
+
+ /**
+ * Records a terminal no-mutation result. The same ordering-aware settlement predicate used for
+ * source commit applies: revoke order requires two definitive aborts; commit order requires two
+ * exact terminal owner readbacks, including a mixed vector.
+ */
+ public void markSourceAborted(SourceChange change, SourceChangeAbortReason reason) {
+ requireTransaction();
+ Objects.requireNonNull(reason, "source-change abort reason");
+ lockSources(change.sources());
+ Record row = readChange(change.changeId());
+ requireChange(row, change);
+ String status = row.get("status", String.class);
+ if ("SOURCE_ABORTED".equals(status)) {
+ if (!reason.name().equals(row.get("abort_reason", String.class))) {
+ throw new IllegalArgumentException("Source change abort reason differs from readback");
+ }
+ return;
+ }
+ if ("SOURCE_COMMITTED".equals(status)) {
+ throw new IllegalStateException("Committed source change cannot be aborted");
+ }
+ if (!"WAITING".equals(status)) {
+ throw new IllegalStateException("Source change is not waiting");
+ }
+ if (!allAffectedSettled(change.sources())) {
+ throw new IllegalStateException("Owner outcomes unresolved");
+ }
+ int updated =
+ dsl.execute(
+ "UPDATE "
+ + CHANGES
+ + " SET status = 'SOURCE_ABORTED', aborted_at = CURRENT_TIMESTAMP, abort_reason = ?"
+ + " WHERE change_id = ? AND status = 'WAITING'",
+ reason.name(),
+ change.changeId());
+ if (updated != 1) {
+ throw new IllegalStateException("Draft source change did not abort exactly once");
+ }
+ }
+
+ /** Exact durable owner readback, supplied only by the future authenticated owner verifier. */
+ public void recordOwnerReadback(DraftAuthorizationFenceBinding binding, OwnerReadback readback) {
+ requireTransaction();
+ readback.requireBinding(binding);
+ if (!binding.requiredOwners().contains(readback.owner())) {
+ throw new IllegalArgumentException("Owner is not required by the original Draft operation");
+ }
+ lockSources(binding.sources());
+ Record row = requireExact(readOperation(binding.operationId()), binding);
+ if ("RESERVED".equals(row.get("ordering", String.class))) {
+ throw new IllegalStateException("Reservation alone cannot produce terminal owner 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, outcome, readback) VALUES (?, ?, ?, ?)",
+ binding.operationId(),
+ readback.owner().name(),
+ readback.outcome().name(),
+ readback.canonicalBytes());
+ }
+
+ public FenceSnapshot read(DraftAuthorizationFenceBinding binding) {
+ requireTransaction();
+ return snapshot(requireExact(readOperation(binding.operationId()), binding));
+ }
+
+ /** Derived exact settlement only; original ordering and owner readbacks remain immutable. */
+ public Settlement readSettlement(DraftAuthorizationFenceBinding binding) {
+ requireTransaction();
+ Record row = requireExact(readOperation(binding.operationId()), binding);
+ return settlement(originalBinding(row), Ordering.valueOf(row.get("ordering", String.class)));
+ }
+
+ /** Original immutable capture only. An absent operation is UNKNOWN, never abort proof. */
+ public Optional readOriginalBinding(UUID operationId) {
+ requireTransaction();
+ DraftAuthorizationFenceBinding.requireUuid(operationId);
+ Record row = readOperation(operationId);
+ return row == null ? Optional.empty() : Optional.of(originalBinding(row));
+ }
+
+ /** Stable keyset position, independent of mutable ordering or participant outcomes. */
+ public record RecoveryCursor(OffsetDateTime reservedAt, UUID operationId) {
+ public RecoveryCursor {
+ Objects.requireNonNull(reservedAt);
+ DraftAuthorizationFenceBinding.requireUuid(operationId);
+ }
+ }
+
+ public record UnresolvedOperation(
+ DraftAuthorizationFenceBinding binding, Ordering ordering, RecoveryCursor cursor) {}
+
+ /**
+ * Bounded discovery of original unsettled operations. Resume after the last returned cursor; an
+ * empty page ends this pass. Later passes start again to revisit still-pending operations.
+ * Discovery grants no owner permission and never captures new sources or infers expiry.
+ * Participant outcomes can advance concurrently: consumers re-read settlement before acting.
+ */
+ public List readUnresolvedOperations(RecoveryCursor after, int limit) {
+ requireTransaction();
+ if (limit < 1 || limit > 100) {
+ throw new IllegalArgumentException("Recovery page limit must be between 1 and 100");
+ }
+ String pending = " NOT account_draft_authorization_is_settled(f.operation_id)";
+ String sql = "SELECT f.* FROM " + FENCES + " f WHERE" + pending;
+ Object[] parameters;
+ if (after == null) {
+ parameters = new Object[] {limit};
+ } else {
+ sql += " AND (f.reserved_at, f.operation_id) > (?::timestamptz, ?::uuid)";
+ parameters = new Object[] {after.reservedAt(), after.operationId(), limit};
+ }
+ sql += " ORDER BY f.reserved_at, f.operation_id LIMIT ? FOR UPDATE OF f";
+ return dsl.fetch(sql, parameters).stream()
+ .map(
+ row ->
+ new UnresolvedOperation(
+ originalBinding(row),
+ Ordering.valueOf(row.get("ordering", String.class)),
+ new RecoveryCursor(
+ row.get("reserved_at", OffsetDateTime.class),
+ row.get("operation_id", UUID.class))))
+ .toList();
+ }
+
+ private DraftAuthorizationFenceBinding originalBinding(Record row) {
+ DraftAuthorizationFenceBinding binding =
+ DraftAuthorizationFenceBinding.fromStored(row.get("binding", byte[].class));
+ requireExact(row, binding);
+ return binding;
+ }
+
+ /** Absence means UNKNOWN, never no-commit proof. */
+ public Optional readOwnerResult(
+ DraftAuthorizationFenceBinding binding, Owner owner) {
+ requireTransaction();
+ requireExact(readOperation(binding.operationId()), binding);
+ Record row =
+ dsl.fetchOne(
+ "SELECT owner, outcome, readback, recorded_at FROM "
+ + READBACKS
+ + " WHERE operation_id = ? AND owner = ?",
+ binding.operationId(),
+ owner.name());
+ if (row != null) {
+ OwnerReadback readback = OwnerReadback.fromStored(row.get("readback", byte[].class));
+ readback.requireBinding(binding);
+ if (!binding.requiredOwners().contains(owner)
+ || readback.owner() != owner
+ || !readback.outcome().name().equals(row.get("outcome", String.class))
+ || !owner.name().equals(row.get("owner", String.class))) {
+ throw new IllegalStateException("Owner readback differs from persisted columns");
+ }
+ }
+ 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)));
+ }
+
+ /** Durable recovery discovery only; no auto-running worker or authority decision. */
+ public List waitingSourceChanges() {
+ requireTransaction();
+ return dsl
+ .fetch("SELECT * FROM " + CHANGES + " WHERE status = 'WAITING' ORDER BY change_id")
+ .stream()
+ .map(
+ row ->
+ new SourceChangeSnapshot(
+ row.get("change_id", UUID.class),
+ row.get("binding", byte[].class),
+ row.get("status", String.class),
+ row.get("requested_at", OffsetDateTime.class),
+ row.get("committed_at", OffsetDateTime.class),
+ row.get("aborted_at", OffsetDateTime.class),
+ abortReason(row.get("abort_reason", String.class))))
+ .toList();
+ }
+
+ public SourceChangeSnapshot readSourceChange(SourceChange change) {
+ requireTransaction();
+ Record row = readChange(change.changeId());
+ requireChange(row, change);
+ return sourceChangeSnapshot(row);
+ }
+
+ /**
+ * Non-locking exact inspection for callers that must preserve Account/envelope/V57 lock order.
+ */
+ public SourceChangeSnapshot inspectSourceChange(SourceChange change) {
+ requireTransaction();
+ Record row =
+ dsl.fetchOne("SELECT * FROM " + CHANGES + " WHERE change_id = ?", change.changeId());
+ if (row == null) {
+ throw new IllegalArgumentException("Absent or changed immutable source mutation intent");
+ }
+ requireChange(row, change);
+ return sourceChangeSnapshot(row);
+ }
+
+ private SourceChangeSnapshot sourceChangeSnapshot(Record row) {
+ return new SourceChangeSnapshot(
+ row.get("change_id", UUID.class),
+ row.get("binding", byte[].class),
+ row.get("status", String.class),
+ row.get("requested_at", OffsetDateTime.class),
+ row.get("committed_at", OffsetDateTime.class),
+ row.get("aborted_at", OffsetDateTime.class),
+ abortReason(row.get("abort_reason", String.class)));
+ }
+
+ private SourceChangeAbortReason abortReason(String value) {
+ return value == null ? null : SourceChangeAbortReason.valueOf(value);
+ }
+
+ /**
+ * Rows-first creator producer acquisition: never wait on a source-first mutation while retaining
+ * Account/tenant/terms locks. Missing rows or contention must roll back the entire owner capture;
+ * neither condition is a terminal authorization outcome. V99 establishes real-source lock rows.
+ */
+ public void lockProducerSourcesNowait(List sources) {
+ requireTransaction();
+ if (sources == null || sources.isEmpty()) {
+ throw new IllegalArgumentException("Complete existing creator sources required");
+ }
+ String previous = null;
+ for (SourceEvidence source : sources) {
+ if (previous != null && previous.compareTo(source.key()) >= 0) {
+ throw new IllegalArgumentException("Distinct sorted creator source vector required");
+ }
+ if (dsl.fetchOne(
+ "SELECT source_key FROM account_draft_authorization_source_locks"
+ + " WHERE source_key = ? FOR UPDATE NOWAIT",
+ source.key())
+ == null) {
+ throw new IllegalStateException("Existing creator source lock row unavailable");
+ }
+ previous = source.key();
+ }
+ }
+
+ private void lockSources(List sources) {
+ for (SourceEvidence source : sources) {
+ dsl.execute(
+ "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT DO NOTHING",
+ source.key());
+ dsl.fetchOne(
+ "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE",
+ source.key());
+ }
+ }
+
+ /** Account-wide negative intent uses Account-before-source/operation lock order. */
+ private void lockChangedAccounts(List sources) {
+ for (UUID account :
+ sources.stream()
+ .filter(s -> s.kind() == SourceKind.ACCOUNT || s.kind() == SourceKind.GLOBAL_ROLES)
+ .map(s -> UUID.fromString(s.scopeId()))
+ .distinct()
+ .sorted(Comparator.comparing(UUID::toString))
+ .toList()) {
+ Record row =
+ dsl.fetchOne(
+ "SELECT account_uuid FROM accounts WHERE account_uuid = ?"
+ + " AND id > 0 AND account_uuid_source_numeric_id = id"
+ + " AND account_uuid_provenance IN ('ACCOUNT_V29_MIGRATION',"
+ + " 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT') FOR UPDATE",
+ account);
+ if (row == null) {
+ throw new IllegalStateException("Source change requires the exact persisted Account row");
+ }
+ }
+ }
+
+ private boolean hasWaitingChange(List sources) {
+ for (SourceEvidence source : sources) {
+ if (!dsl.fetch(
+ "SELECT c.change_id FROM "
+ + CHANGES
+ + " c JOIN "
+ + CHANGED
+ + " s ON s.change_id = c.change_id WHERE s.source_key = ? AND c.status = 'WAITING'",
+ source.key())
+ .isEmpty()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ 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();
+ }
+
+ /**
+ * Every original required owner must report one uniform exact terminal outcome. Missing or mixed
+ * evidence always remains pending.
+ */
+ private boolean allAffectedSettled(List sources) {
+ if (hasPendingPublication(sources) || hasPendingGameLogicIntake(sources)) {
+ return false;
+ }
+ for (UUID operation : affectedOperations(sources)) {
+ Record row = readOperation(operation);
+ if (settlement(originalBinding(row), Ordering.valueOf(row.get("ordering", String.class)))
+ == Settlement.PENDING) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private Settlement settlement(DraftAuthorizationFenceBinding binding, Ordering ordering) {
+ if (ordering == Ordering.RESERVED) {
+ return Settlement.PENDING;
+ }
+ var rows =
+ dsl.fetch(
+ "SELECT owner, outcome, readback FROM " + READBACKS + " WHERE operation_id = ?",
+ binding.operationId());
+ if (rows.size() != binding.requiredOwners().size()) {
+ return Settlement.PENDING;
+ }
+ List outcomes = new java.util.ArrayList<>();
+ var owners = java.util.EnumSet.noneOf(Owner.class);
+ for (Record row : rows) {
+ try {
+ OwnerReadback readback = OwnerReadback.fromStored(row.get("readback", byte[].class));
+ readback.requireBinding(binding);
+ if (!binding.requiredOwners().contains(readback.owner())
+ || !owners.add(readback.owner())
+ || !readback.owner().name().equals(row.get("owner", String.class))
+ || !readback.outcome().name().equals(row.get("outcome", String.class))) {
+ return Settlement.PENDING;
+ }
+ outcomes.add(readback.outcome());
+ } catch (IllegalArgumentException invalidEvidence) {
+ return Settlement.PENDING;
+ }
+ }
+ boolean bothAborted = outcomes.stream().allMatch(o -> o == Outcome.DEFINITIVELY_ABORTED);
+ if (ordering == Ordering.REVOKE_ORDER) {
+ return bothAborted ? Settlement.FAILED_NONPUBLICATION : Settlement.PENDING;
+ }
+ if (outcomes.stream().allMatch(o -> o == Outcome.COMMITTED)) {
+ return Settlement.COMMITTED;
+ }
+ return bothAborted ? Settlement.FAILED_NONPUBLICATION : Settlement.PENDING;
+ }
+
+ private Record readOperation(UUID operation) {
+ return dsl.fetchOne(
+ "SELECT * FROM " + FENCES + " WHERE operation_id = ? FOR UPDATE", operation);
+ }
+
+ private Record readChange(UUID change) {
+ return dsl.fetchOne("SELECT * FROM " + CHANGES + " WHERE change_id = ? FOR UPDATE", change);
+ }
+
+ private Record requireExact(Record row, DraftAuthorizationFenceBinding binding) {
+ if (row == null
+ || !binding.operationId().equals(row.get("operation_id", UUID.class))
+ || !Arrays.equals(row.get("binding", byte[].class), binding.canonicalBytes())
+ || !binding.requestId().equals(row.get("request_id", UUID.class))
+ || !binding.commitId().equals(row.get("commit_id", UUID.class))
+ || !binding.fenceId().equals(row.get("fence_id", UUID.class))) {
+ throw new IllegalArgumentException("Absent or changed immutable Draft operation");
+ }
+ List sourceRows =
+ dsl
+ .fetch(
+ "SELECT source_key, source_evidence FROM " + SOURCES + " WHERE operation_id = ?",
+ binding.operationId())
+ .stream()
+ .sorted(Comparator.comparing(record -> record.get("source_key", String.class)))
+ .toList();
+ if (sourceRows.size() != binding.sources().size()) {
+ throw new IllegalStateException("Incomplete source participation");
+ }
+ for (int i = 0; i < sourceRows.size(); i++) {
+ SourceEvidence source = binding.sources().get(i);
+ if (!source.key().equals(sourceRows.get(i).get("source_key", String.class))
+ || !Arrays.equals(
+ source.canonicalBytes(), sourceRows.get(i).get("source_evidence", byte[].class))) {
+ throw new IllegalStateException("Source participation differs from exact binding");
+ }
+ }
+ return row;
+ }
+
+ private void requireChange(Record row, SourceChange change) {
+ if (row == null || !Arrays.equals(row.get("binding", byte[].class), change.canonicalBytes())) {
+ throw new IllegalArgumentException("Absent or changed immutable source mutation intent");
+ }
+ List stored =
+ dsl
+ .fetch("SELECT source_key FROM " + CHANGED + " WHERE change_id = ?", change.changeId())
+ .getValues("source_key", String.class)
+ .stream()
+ .sorted()
+ .toList();
+ if (!stored.equals(change.sources().stream().map(SourceEvidence::key).toList())) {
+ throw new IllegalStateException("Incomplete source change participation");
+ }
+ }
+
+ 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/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java
new file mode 100644
index 0000000000..f0e3fb957b
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java
@@ -0,0 +1,108 @@
+package net.firedevops.firemud.accountservice.creatorparty;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+import tools.jackson.databind.json.JsonMapper;
+
+/** Closed canonical encodings; every identity, reference and independent version is bound. */
+public final class CreatorPartyEncoding {
+ private CreatorPartyEncoding() {}
+
+ public static byte[] party(IndividualCreatorPartySource source) {
+ Objects.requireNonNull(source);
+ Map fields = new LinkedHashMap<>();
+ fields.put("schema", "account-individual-creator-party-source/v1");
+ fields.put("creatorPartyId", source.creatorPartyId().toString());
+ fields.put("accountId", source.accountId().toString());
+ fields.put("verificationStatus", source.verificationStatus().name());
+ fields.put("identityVersion", Long.toString(source.identityVersion()));
+ fields.put("policyReference", source.policyReference());
+ fields.put("policyVersion", decimal(source.policyVersion()));
+ fields.put("verificationEvidenceReference", source.verificationEvidenceReference());
+ fields.put("verificationEvidenceVersion", decimal(source.verificationEvidenceVersion()));
+ fields.put("sourceVersion", Long.toString(source.sourceVersion()));
+ return canonical(fields);
+ }
+
+ public static byte[] request(
+ UUID requestId, FreshTenantCreatorEvidence creation, IndividualCreatorPartySource party) {
+ requireUuid(requestId);
+ Objects.requireNonNull(creation);
+ Objects.requireNonNull(party);
+ if (!creation.initiatingAccountId().equals(party.accountId())) {
+ throw new IllegalArgumentException("Creator must bind their own individual party");
+ }
+ return canonical(
+ Map.of(
+ "schema",
+ "account-fresh-creator-party-association-request/v1",
+ "requestId",
+ requestId.toString(),
+ "creatorEvidence",
+ new String(creation(creation), StandardCharsets.UTF_8),
+ "individualPartySource",
+ new String(party(party), StandardCharsets.UTF_8)));
+ }
+
+ public static byte[] result(UUID historyId, byte[] request) {
+ requireUuid(historyId);
+ Objects.requireNonNull(request);
+ if (request.length == 0) {
+ throw new IllegalArgumentException("Exact original request is required");
+ }
+ return canonical(
+ Map.of(
+ "schema",
+ "account-fresh-creator-party-association-result/v1",
+ "historyId",
+ historyId.toString(),
+ "associationSourceVersion",
+ "1",
+ "request",
+ new String(request, StandardCharsets.UTF_8)));
+ }
+
+ public static byte[] creation(FreshTenantCreatorEvidence evidence) {
+ return AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence);
+ }
+
+ public static String digest(byte[] bytes) {
+ Objects.requireNonNull(bytes);
+ try {
+ return "sha256:"
+ + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is required", exception);
+ }
+ }
+
+ static void requireUuid(UUID uuid) {
+ if (uuid == null || uuid.equals(new UUID(0, 0))) {
+ throw new IllegalArgumentException("Canonical nonnil identity is required");
+ }
+ }
+
+ private static String decimal(Long value) {
+ return value == null ? null : value.toString();
+ }
+
+ private static byte[] canonical(Map fields) {
+ try {
+ return Rfc8785CanonicalJson.canonicalizeUtf8(
+ JsonMapper.builder().build().writeValueAsString(fields));
+ } catch (IOException exception) {
+ throw new IllegalArgumentException(
+ "Creator-party evidence cannot be canonically encoded", exception);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java
new file mode 100644
index 0000000000..329f1248be
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java
@@ -0,0 +1,453 @@
+package net.firedevops.firemud.accountservice.creatorparty;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation;
+import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Unregistered owner-local persistence prerequisite, not an authenticated association producer.
+ *
+ * No provisioning method is provided. A future protected producer must authenticate the Account,
+ * independently obtain exact Game Design committed readback and approved individual verification,
+ * and participate in current source ordering before invoking this storage primitive. Supplied DTOs
+ * and a V64 receipt alone do not authenticate a caller. These immutable initial sources cannot yet
+ * participate in revocation/terms ordering; hosted authoring currentness remains denied.
+ */
+public final class IndividualCreatorPartyRepository {
+ private final DSLContext dsl;
+ private final FreshTenantIdentityAssociationRepository freshTenants;
+ private final AccountTenantCreationBootstrapOperationRepository bootstraps;
+
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification = "Owner transaction collaborators are retained privately and never exposed.")
+ public IndividualCreatorPartyRepository(
+ DSLContext dsl,
+ FreshTenantIdentityAssociationRepository freshTenants,
+ AccountTenantCreationBootstrapOperationRepository bootstraps) {
+ this.dsl = Objects.requireNonNull(dsl);
+ this.freshTenants = Objects.requireNonNull(freshTenants);
+ this.bootstraps = Objects.requireNonNull(bootstraps);
+ }
+
+ /** Reads complete exact source bytes; local VERIFIED status is not legal provisioning proof. */
+ public IndividualCreatorPartySource readIndividualSource(UUID partyId, UUID accountId) {
+ requireTransaction();
+ CreatorPartyEncoding.requireUuid(partyId);
+ CreatorPartyEncoding.requireUuid(accountId);
+ Record row =
+ dsl.fetchOne(
+ "SELECT * FROM account_individual_creator_party_sources "
+ + "WHERE creator_party_id = ? FOR UPDATE",
+ partyId);
+ if (row == null) {
+ throw new IllegalStateException("Individual party source is absent");
+ }
+ IndividualCreatorPartySource source =
+ new IndividualCreatorPartySource(
+ row.get("creator_party_id", UUID.class),
+ row.get("account_uuid", UUID.class),
+ VerificationStatus.valueOf(row.get("verification_status", String.class)),
+ row.get("identity_version", Long.class),
+ row.get("policy_reference", String.class),
+ row.get("policy_version", Long.class),
+ row.get("verification_evidence_reference", String.class),
+ row.get("verification_evidence_version", Long.class),
+ row.get("source_version", Long.class));
+ byte[] payload = CreatorPartyEncoding.party(source);
+ if (!accountId.equals(source.accountId())
+ || !Arrays.equals(payload, row.get("source_payload", byte[].class))
+ || !CreatorPartyEncoding.digest(payload).equals(row.get("source_digest", String.class))) {
+ throw new IllegalStateException(
+ "Individual party source identity or exact evidence conflicts");
+ }
+ return source;
+ }
+
+ /**
+ * Stores an exact initial association under caller-owned Account transaction. The supplied
+ * qualification must match persisted V64 and fresh provenance, but this method authenticates no
+ * caller and is deliberately not registered or exposed. No record is inserted on negative paths.
+ */
+ public AssociationReceipt associateFresh(
+ UUID requestId,
+ FreshTenantCreatorEvidence creator,
+ IndividualCreatorPartySource expectedParty) {
+ requireTransaction();
+ byte[] request = CreatorPartyEncoding.request(requestId, creator, expectedParty);
+ UUID tenantId = creator.creationEvidence().canonicalTenantId();
+ lockTenant(tenantId);
+ Record prior = operation(requestId);
+ if (prior != null) {
+ if (!Arrays.equals(request, prior.get("request_payload", byte[].class))) {
+ throw new AssociationConflictException("Association request identity changed its binding");
+ }
+ return verifyReceipt(prior, requestId, creator, expectedParty);
+ }
+ requireFreshCreation(creator);
+ IndividualCreatorPartySource current =
+ readIndividualSource(expectedParty.creatorPartyId(), creator.initiatingAccountId());
+ if (!current.equals(expectedParty) || !current.locallyVerified()) {
+ throw new IllegalStateException(
+ "Exact independently verified own individual source is absent");
+ }
+ if (historyCount(tenantId) != 0
+ || dsl.fetchOne(
+ "SELECT request_id FROM account_fresh_creator_party_association_operations "
+ + "WHERE tenant_uuid = ?",
+ tenantId)
+ != null) {
+ throw new AssociationConflictException(
+ "Tenant has prior creator-party association or history");
+ }
+ UUID historyId = UUID.randomUUID();
+ byte[] result = CreatorPartyEncoding.result(historyId, request);
+ String resultDigest = CreatorPartyEncoding.digest(result);
+ dsl.execute(
+ "INSERT INTO account_tenant_creator_party_history "
+ + "(history_id, tenant_uuid, origin, creator_party_id, source_version, "
+ + "evidence_payload, evidence_digest) VALUES (?, ?, 'FRESH_INITIAL', ?, 1, ?, ?)",
+ historyId,
+ tenantId,
+ current.creatorPartyId(),
+ result,
+ resultDigest);
+ dsl.execute(
+ "INSERT INTO account_fresh_creator_party_association_operations "
+ + "(request_id, tenant_uuid, initiating_account_uuid, creator_party_id, "
+ + "creation_operation_id, creator_evidence_payload, party_source_payload, "
+ + "request_payload, request_digest, history_id, result_payload, result_digest) "
+ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ requestId,
+ tenantId,
+ creator.initiatingAccountId(),
+ current.creatorPartyId(),
+ creator.creationEvidence().operationId(),
+ CreatorPartyEncoding.creation(creator),
+ CreatorPartyEncoding.party(current),
+ request,
+ CreatorPartyEncoding.digest(request),
+ historyId,
+ result,
+ resultDigest);
+ return verifyReceipt(operation(requestId), requestId, creator, current);
+ }
+
+ /**
+ * Exact local initial association readback; later retained/tombstone state denies this reader.
+ */
+ public AssociationReceipt readInitialAssociation(
+ UUID requestId,
+ FreshTenantCreatorEvidence creator,
+ IndividualCreatorPartySource expectedParty) {
+ requireTransaction();
+ lockTenant(creator.creationEvidence().canonicalTenantId());
+ requireFreshCreation(creator);
+ IndividualCreatorPartySource source =
+ readIndividualSource(expectedParty.creatorPartyId(), creator.initiatingAccountId());
+ if (!source.equals(expectedParty) || !source.locallyVerified()) {
+ throw new IllegalStateException("Current exact individual source is unavailable");
+ }
+ AssociationReceipt receipt = verifyReceipt(operation(requestId), requestId, creator, source);
+ if (historyCount(receipt.tenantId()) != 1) {
+ throw new IllegalStateException(
+ "Initial association reader cannot resolve later party history");
+ }
+ return receipt;
+ }
+
+ /**
+ * Resolves the one persisted fresh initial association from its canonical tenant scope.
+ *
+ *
The initiating Account, original creator qualification, association operation, and party are
+ * all derived from owner rows. The canonical tenant claim serializes an absent-row read with the
+ * initial-association writer; no caller-selected party or operation can redirect the readback.
+ * This is immutable source evidence only and grants no caller, content, or gameplay permission. A
+ * composing source read acquires this tenant fence before the bootstrap and Account-source locks
+ * to preserve the initial-association writer's lock order.
+ */
+ public InitialAssociationReadback readExistingInitialAssociation(UUID tenantUuid) {
+ requireTransaction();
+ CreatorPartyEncoding.requireUuid(tenantUuid);
+ lockTenant(tenantUuid);
+
+ FreshTenantCreationEvidence creation =
+ freshTenants
+ .read(tenantUuid)
+ .orElseThrow(
+ () -> new IllegalStateException("Exact fresh tenant creation source is absent"));
+ UUID bootstrapRequestId =
+ bootstraps
+ .findRequestIdByTenantForUpdate(tenantUuid)
+ .orElseThrow(
+ () -> new IllegalStateException("Committed creator-bootstrap receipt is absent"));
+ StoredOperation bootstrap =
+ bootstraps
+ .findForUpdate(bootstrapRequestId)
+ .orElseThrow(
+ () -> new IllegalStateException("Committed creator-bootstrap receipt is absent"));
+ if (!"COMMITTED".equals(bootstrap.status())
+ || !bootstrapRequestId.equals(bootstrap.requestId())
+ || !bootstrapRequestId.equals(bootstrap.accountAuthorizationOperationId())
+ || !tenantUuid.equals(bootstrap.tenantUuid())
+ || !creation.creationRequestId().equals(bootstrap.creationRequestId())
+ || !creation.operationId().equals(bootstrap.creationOperationId())) {
+ throw new IllegalStateException(
+ "Committed creator-bootstrap receipt differs from exact fresh tenant provenance");
+ }
+
+ FreshTenantCreatorEvidence creator =
+ new FreshTenantCreatorEvidence(
+ 1,
+ creation,
+ bootstrap.initiatingAccountUuid(),
+ bootstrap.accountAuthorizationOperationId(),
+ bootstrap.accountAuthorizationDigest(),
+ bootstrap.creatorEvidenceDigest());
+ // Re-read the persisted bootstrap through the existing exact creator-evidence verifier. This
+ // also binds the original creator payload and authorization digest to the fresh association.
+ requireFreshCreation(creator);
+
+ Record association =
+ dsl.fetchOne(
+ "SELECT * FROM account_fresh_creator_party_association_operations "
+ + "WHERE tenant_uuid = ? FOR UPDATE",
+ tenantUuid);
+ if (association == null) {
+ throw new IllegalStateException(
+ "Immutable fresh initial creator-party association is absent");
+ }
+ UUID associationRequestId = association.get("request_id", UUID.class);
+ UUID partyId = association.get("creator_party_id", UUID.class);
+ if (associationRequestId == null || partyId == null) {
+ throw new IllegalStateException(
+ "Immutable fresh initial creator-party association identity is incomplete");
+ }
+
+ IndividualCreatorPartySource party =
+ readIndividualSource(partyId, creator.initiatingAccountId());
+ if (!party.locallyVerified()) {
+ throw new IllegalStateException(
+ "Fresh initial association does not identify its own verified individual party");
+ }
+ AssociationReceipt receipt = readInitialAssociation(associationRequestId, creator, party);
+ if (!tenantUuid.equals(receipt.tenantId())
+ || !partyId.equals(receipt.creatorPartyId())
+ || !associationRequestId.equals(receipt.requestId())) {
+ throw new IllegalStateException(
+ "Exact initial association readback differs from its persisted tenant row");
+ }
+ return new InitialAssociationReadback(creator, receipt, party);
+ }
+
+ /**
+ * Locks only the canonical tenant claim and derives candidate identities from existing owner
+ * rows. Bootstrap and party locks are deliberately deferred so a composer can acquire Account
+ * sources and the environment head first. The complete association must subsequently be read back
+ * with {@link #readExistingInitialAssociation(UUID)} in this same transaction.
+ */
+ public InitialAssociationScope lockExistingInitialAssociationScope(UUID tenantUuid) {
+ requireTransaction();
+ lockTenant(tenantUuid);
+ Record association =
+ dsl.fetchOne(
+ "SELECT request_id, tenant_uuid, initiating_account_uuid, creator_party_id "
+ + "FROM account_fresh_creator_party_association_operations WHERE tenant_uuid = ?",
+ tenantUuid);
+ if (association == null) {
+ throw new IllegalStateException(
+ "Immutable fresh initial creator-party association is absent");
+ }
+ InitialAssociationScope scope =
+ new InitialAssociationScope(
+ association.get("tenant_uuid", UUID.class),
+ association.get("request_id", UUID.class),
+ association.get("initiating_account_uuid", UUID.class),
+ association.get("creator_party_id", UUID.class));
+ if (!tenantUuid.equals(scope.tenantId())) {
+ throw new IllegalStateException("Initial association scope differs from canonical tenant");
+ }
+ return scope;
+ }
+
+ /** Candidate persisted identities only; not authenticated caller or association proof. */
+ public record InitialAssociationScope(
+ UUID tenantId, UUID associationRequestId, UUID accountId, UUID creatorPartyId) {
+ public InitialAssociationScope {
+ CreatorPartyEncoding.requireUuid(tenantId);
+ CreatorPartyEncoding.requireUuid(associationRequestId);
+ CreatorPartyEncoding.requireUuid(accountId);
+ CreatorPartyEncoding.requireUuid(creatorPartyId);
+ }
+ }
+
+ /** This slice never provides commit-bound party/terms authorization. */
+ public void requireHostedAuthoringCurrentness() {
+ throw new IllegalStateException(
+ "Authenticated caller, approved provisioning, party source ordering and hosted terms are unavailable");
+ }
+
+ private void lockTenant(UUID tenantId) {
+ CreatorPartyEncoding.requireUuid(tenantId);
+ Record isolation = dsl.fetchOne("SHOW transaction_isolation");
+ if (isolation == null) {
+ throw new IllegalStateException("Account transaction isolation readback is unavailable");
+ }
+ if (!"read committed".equals(isolation.get(0, String.class))) {
+ throw new IllegalStateException(
+ "Initial party association requires READ COMMITTED owner transaction");
+ }
+ Record claim =
+ dsl.fetchOne(
+ "SELECT identity_kind FROM account_canonical_tenant_identity_claims "
+ + "WHERE canonical_tenant_id = ? FOR UPDATE",
+ tenantId);
+ if (claim == null || !"FRESH_GAME_DESIGN".equals(claim.get("identity_kind", String.class))) {
+ throw new IllegalStateException("Fresh canonical tenant provenance is absent");
+ }
+ }
+
+ private void requireFreshCreation(FreshTenantCreatorEvidence creator) {
+ if (!freshTenants
+ .read(creator.creationEvidence().canonicalTenantId())
+ .filter(creator.creationEvidence()::equals)
+ .isPresent()) {
+ throw new IllegalStateException("Exact committed fresh tenant provenance is absent");
+ }
+ StoredOperation bootstrap =
+ bootstraps
+ .findForUpdate(creator.accountAuthorizationOperationId())
+ .orElseThrow(
+ () -> new IllegalStateException("Persisted creator qualification is absent"));
+ if (!"COMMITTED".equals(bootstrap.status())
+ || !creator.initiatingAccountId().equals(bootstrap.initiatingAccountUuid())
+ || !creator.creationEvidence().canonicalTenantId().equals(bootstrap.tenantUuid())
+ || !creator.creationEvidence().creationRequestId().equals(bootstrap.creationRequestId())
+ || !creator.creationEvidence().operationId().equals(bootstrap.creationOperationId())
+ || !creator
+ .accountAuthorizationOperationId()
+ .equals(bootstrap.accountAuthorizationOperationId())
+ || !creator.accountAuthorizationDigest().equals(bootstrap.accountAuthorizationDigest())
+ || !creator.evidenceDigest().equals(bootstrap.creatorEvidenceDigest())
+ || !Arrays.equals(
+ CreatorPartyEncoding.creation(creator), bootstrap.creatorEvidencePayload())) {
+ throw new IllegalStateException("Persisted committed creator qualification conflicts");
+ }
+ }
+
+ private Record operation(UUID requestId) {
+ CreatorPartyEncoding.requireUuid(requestId);
+ return dsl.fetchOne(
+ "SELECT * FROM account_fresh_creator_party_association_operations WHERE request_id = ?",
+ requestId);
+ }
+
+ private long historyCount(UUID tenantId) {
+ Record history =
+ dsl.fetchOne(
+ "SELECT count(*) AS count FROM account_tenant_creator_party_history WHERE tenant_uuid = ?",
+ tenantId);
+ if (history == null) {
+ throw new IllegalStateException("Creator-party history count readback is unavailable");
+ }
+ Long count = history.get("count", Long.class);
+ if (count == null || count < 0) {
+ throw new IllegalStateException("Creator-party history count is incomplete or invalid");
+ }
+ return count;
+ }
+
+ private AssociationReceipt verifyReceipt(
+ Record row,
+ UUID requestId,
+ FreshTenantCreatorEvidence creator,
+ IndividualCreatorPartySource party) {
+ if (row == null) {
+ throw new IllegalStateException("Immutable association receipt is absent");
+ }
+ UUID historyId = row.get("history_id", UUID.class);
+ byte[] request = CreatorPartyEncoding.request(requestId, creator, party);
+ byte[] result = CreatorPartyEncoding.result(historyId, request);
+ UUID tenantId = creator.creationEvidence().canonicalTenantId();
+ String resultDigest = CreatorPartyEncoding.digest(result);
+ Record history =
+ dsl.fetchOne(
+ "SELECT * FROM account_tenant_creator_party_history WHERE history_id = ?", historyId);
+ if (!requestId.equals(row.get("request_id", UUID.class))
+ || !tenantId.equals(row.get("tenant_uuid", UUID.class))
+ || !creator.initiatingAccountId().equals(row.get("initiating_account_uuid", UUID.class))
+ || !party.creatorPartyId().equals(row.get("creator_party_id", UUID.class))
+ || !creator
+ .creationEvidence()
+ .operationId()
+ .equals(row.get("creation_operation_id", UUID.class))
+ || !Arrays.equals(
+ CreatorPartyEncoding.creation(creator),
+ row.get("creator_evidence_payload", byte[].class))
+ || !Arrays.equals(
+ CreatorPartyEncoding.party(party), row.get("party_source_payload", byte[].class))
+ || !Arrays.equals(request, row.get("request_payload", byte[].class))
+ || !CreatorPartyEncoding.digest(request).equals(row.get("request_digest", String.class))
+ || !Arrays.equals(result, row.get("result_payload", byte[].class))
+ || !resultDigest.equals(row.get("result_digest", String.class))
+ || row.get("committed_at") == null
+ || history == null
+ || !"FRESH_INITIAL".equals(history.get("origin", String.class))
+ || !tenantId.equals(history.get("tenant_uuid", UUID.class))
+ || !party.creatorPartyId().equals(history.get("creator_party_id", UUID.class))
+ || !Long.valueOf(1).equals(history.get("source_version", Long.class))
+ || !Arrays.equals(result, history.get("evidence_payload", byte[].class))
+ || !resultDigest.equals(history.get("evidence_digest", String.class))) {
+ throw new IllegalStateException(
+ "Immutable association readback is incomplete or contradictory");
+ }
+ return new AssociationReceipt(
+ requestId, tenantId, party.creatorPartyId(), historyId, resultDigest);
+ }
+
+ private static void requireTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException("Caller-owned writable Account transaction is required");
+ }
+ }
+
+ /** Historical immutable result only; grants no caller, content or gameplay permission. */
+ public record AssociationReceipt(
+ UUID requestId, UUID tenantId, UUID creatorPartyId, UUID historyId, String resultDigest) {}
+
+ /** Owner-derived fresh creator qualification, association receipt, and current party source. */
+ public record InitialAssociationReadback(
+ FreshTenantCreatorEvidence creatorEvidence,
+ AssociationReceipt receipt,
+ IndividualCreatorPartySource partySource) {
+ public InitialAssociationReadback {
+ Objects.requireNonNull(creatorEvidence);
+ Objects.requireNonNull(receipt);
+ Objects.requireNonNull(partySource);
+ if (!creatorEvidence.creationEvidence().canonicalTenantId().equals(receipt.tenantId())
+ || !creatorEvidence.initiatingAccountId().equals(partySource.accountId())
+ || !receipt.creatorPartyId().equals(partySource.creatorPartyId())
+ || !partySource.locallyVerified()) {
+ throw new IllegalArgumentException(
+ "Initial association readback must retain exact fresh creator and own-party identity");
+ }
+ }
+ }
+
+ public static final class AssociationConflictException extends IllegalStateException {
+ public AssociationConflictException(String message) {
+ super(message);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartySource.java
new file mode 100644
index 0000000000..847641abe9
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartySource.java
@@ -0,0 +1,52 @@
+package net.firedevops.firemud.accountservice.creatorparty;
+
+import java.util.UUID;
+
+/** Opaque owner evidence, not legal identity facts or a caller-supplied verification decision. */
+public record IndividualCreatorPartySource(
+ UUID creatorPartyId,
+ UUID accountId,
+ VerificationStatus verificationStatus,
+ long identityVersion,
+ String policyReference,
+ Long policyVersion,
+ String verificationEvidenceReference,
+ Long verificationEvidenceVersion,
+ long sourceVersion) {
+ public enum VerificationStatus {
+ UNVERIFIED,
+ VERIFIED,
+ UNSUPPORTED
+ }
+
+ public IndividualCreatorPartySource {
+ CreatorPartyEncoding.requireUuid(creatorPartyId);
+ CreatorPartyEncoding.requireUuid(accountId);
+ java.util.Objects.requireNonNull(verificationStatus);
+ if (identityVersion <= 0 || sourceVersion != 1) {
+ throw new IllegalArgumentException(
+ "Only a positive identity and initial source are supported");
+ }
+ requireReference(policyReference, policyVersion);
+ requireReference(verificationEvidenceReference, verificationEvidenceVersion);
+ if (verificationStatus == VerificationStatus.VERIFIED
+ && (policyReference == null || verificationEvidenceReference == null)) {
+ throw new IllegalArgumentException("Verified individual requires exact policy and evidence");
+ }
+ }
+
+ public boolean locallyVerified() {
+ return verificationStatus == VerificationStatus.VERIFIED;
+ }
+
+ private static void requireReference(String reference, Long version) {
+ if ((reference == null) != (version == null)
+ || (reference != null
+ && (reference.isBlank() || reference.length() > 512 || version <= 0))) {
+ throw new IllegalArgumentException("Opaque reference requires its exact positive version");
+ }
+ if (reference != null) {
+ net.firedevops.firemud.common.tenant.GameTenantCreationDigest.utf8ByteLength(reference);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java
new file mode 100644
index 0000000000..029c6bf10f
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java
@@ -0,0 +1,116 @@
+package net.firedevops.firemud.accountservice.dto;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.UUID;
+
+/** Canonical, bounded request digests for the two Account token-logout operations. */
+public final class AccountLogoutRequestDigest {
+ private static final String DOMAIN = "requestDigest/v1";
+ private static final HexFormat HEX = HexFormat.of();
+
+ private AccountLogoutRequestDigest() {}
+
+ public static String tokenLogout(UUID subjectAccountId, String tokenProfile, String tokenHash) {
+ return digest(OperationKind.TOKEN_LOGOUT, subjectAccountId, tokenProfile, tokenHash);
+ }
+
+ public static String accountLogoutAll(
+ UUID subjectAccountId, String tokenProfile, String presentedTokenHash) {
+ return digest(
+ OperationKind.ACCOUNT_LOGOUT_ALL, subjectAccountId, tokenProfile, presentedTokenHash);
+ }
+
+ /** Validates the exact closed token-profile vocabulary accepted by logout request bindings. */
+ public static void validateTokenProfile(String tokenProfile) {
+ if (!"control-ui".equals(tokenProfile) && !"player-bootstrap".equals(tokenProfile)) {
+ throw new IllegalArgumentException(
+ "Logout request token profile must be control-ui or player-bootstrap");
+ }
+ }
+
+ /** Validates a SHA-256 token identity rendered as lowercase hexadecimal without a prefix. */
+ public static void validateTokenHash(String tokenHash) {
+ if (tokenHash == null || !tokenHash.matches("[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Logout request token hash must be lowercase SHA-256 hex");
+ }
+ }
+
+ public static String tokenLogoutPreimageHex(
+ UUID subjectAccountId, String tokenProfile, String tokenHash) {
+ validateBindings(subjectAccountId, tokenProfile, tokenHash);
+ return HEX.formatHex(
+ preimage(OperationKind.TOKEN_LOGOUT, subjectAccountId, tokenProfile, tokenHash));
+ }
+
+ public static String accountLogoutAllPreimageHex(
+ UUID subjectAccountId, String tokenProfile, String presentedTokenHash) {
+ validateBindings(subjectAccountId, tokenProfile, presentedTokenHash);
+ return HEX.formatHex(
+ preimage(
+ OperationKind.ACCOUNT_LOGOUT_ALL, subjectAccountId, tokenProfile, presentedTokenHash));
+ }
+
+ private static String digest(
+ OperationKind operationKind, UUID subjectAccountId, String tokenProfile, String tokenHash) {
+ validateBindings(subjectAccountId, tokenProfile, tokenHash);
+ Objects.requireNonNull(operationKind, "A closed logout operation kind is required");
+ byte[] preimage = preimage(operationKind, subjectAccountId, tokenProfile, tokenHash);
+ try {
+ return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(preimage));
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is unavailable", exception);
+ }
+ }
+
+ private static void validateBindings(
+ UUID subjectAccountId, String tokenProfile, String tokenHash) {
+ if (subjectAccountId == null || new UUID(0L, 0L).equals(subjectAccountId)) {
+ throw new IllegalArgumentException("A canonical non-nil Account UUID is required");
+ }
+ validateTokenProfile(tokenProfile);
+ validateTokenHash(tokenHash);
+ }
+
+ private static byte[] preimage(
+ OperationKind operationKind, UUID subjectAccountId, String tokenProfile, String tokenHash) {
+ String tokenIdentityField =
+ operationKind == OperationKind.ACCOUNT_LOGOUT_ALL ? "presentedTokenHash" : "tokenHash";
+ ByteArrayOutputStream output = new ByteArrayOutputStream(256);
+ appendSegment(output, DOMAIN);
+ appendStringField(output, "operationKind", operationKind.wireValue);
+ appendStringField(output, "subjectAccountId", subjectAccountId.toString());
+ appendStringField(output, "tokenProfile", tokenProfile);
+ appendStringField(output, tokenIdentityField, tokenHash);
+ return output.toByteArray();
+ }
+
+ private static void appendStringField(ByteArrayOutputStream output, String name, String value) {
+ appendSegment(output, name);
+ appendSegment(output, "string");
+ output.write('1');
+ appendSegment(output, value);
+ }
+
+ private static void appendSegment(ByteArrayOutputStream output, String value) {
+ byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
+ output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII));
+ output.write(':');
+ output.writeBytes(bytes);
+ }
+
+ private enum OperationKind {
+ TOKEN_LOGOUT("TOKEN_LOGOUT"),
+ ACCOUNT_LOGOUT_ALL("ACCOUNT_LOGOUT_ALL");
+
+ private final String wireValue;
+
+ OperationKind(String wireValue) {
+ this.wireValue = wireValue;
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.java
new file mode 100644
index 0000000000..e5f1b42d60
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.java
@@ -0,0 +1,197 @@
+package net.firedevops.firemud.accountservice.dto;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+
+/** Exact owner-local fresh-birth evidence; this value grants no admission or activation. */
+public record AccountPlatformRestrictionBirthSource(
+ UUID accountId,
+ long accountSourceNumericId,
+ long accountInsertTransactionId,
+ ScopeState birthAuthority,
+ ScopeState currentAuthority,
+ CategorySource accountSecurityLock,
+ CategorySource platformAccessBan) {
+ public AccountPlatformRestrictionBirthSource {
+ Objects.requireNonNull(accountId, "Account UUID is required");
+ if (accountId.version() != 4
+ || accountId.variant() != 2
+ || accountSourceNumericId <= 0
+ || accountInsertTransactionId <= 0) {
+ throw new IllegalArgumentException("Exact fresh Account identity is required");
+ }
+ requireAccountAuthority(accountId, birthAuthority);
+ requireAccountAuthority(accountId, currentAuthority);
+ if (birthAuthority.generation() != 1
+ || birthAuthority.sourceVersion() != 1
+ || birthAuthority.issuanceFence().value() != 1
+ || birthAuthority.issuanceFence().sourceVersion() != 1) {
+ throw new IllegalArgumentException("Fresh birth requires the initial Account authority");
+ }
+ requireCategory(accountId, accountSecurityLock, Category.ACCOUNT_SECURITY_LOCK);
+ requireCategory(accountId, platformAccessBan, Category.PLATFORM_ACCESS_BAN);
+ for (CategorySource source : new CategorySource[] {accountSecurityLock, platformAccessBan}) {
+ if (!source
+ .payloadDigest()
+ .equals(
+ birthDigest(
+ accountId,
+ accountSourceNumericId,
+ accountInsertTransactionId,
+ birthAuthority,
+ source.category(),
+ source.operationId(),
+ source.resultId(),
+ source.eventId()))) {
+ throw new IllegalArgumentException("Restriction birth payload digest differs");
+ }
+ }
+ if (accountSecurityLock.operationId().equals(platformAccessBan.operationId())
+ || accountSecurityLock.resultId().equals(platformAccessBan.resultId())
+ || accountSecurityLock.eventId().equals(platformAccessBan.eventId())) {
+ throw new IllegalArgumentException("Category birth identities must be independent");
+ }
+ }
+
+ private static void requireAccountAuthority(UUID accountId, ScopeState authority) {
+ Objects.requireNonNull(authority, "Account authority is required");
+ if (!AuthorityScope.account(accountId).equals(authority.scope())
+ || authority.issuanceFence() == null
+ || !accountId.equals(authority.issuanceFence().accountId())) {
+ throw new IllegalArgumentException("Account authority identity differs");
+ }
+ }
+
+ private static void requireCategory(UUID accountId, CategorySource source, Category expected) {
+ Objects.requireNonNull(source, "Explicit category source is required");
+ if (source.category() != expected
+ || !source.outboxStreamKey().equals(streamKey(accountId, expected))) {
+ throw new IllegalArgumentException("Exact category scope is required");
+ }
+ }
+
+ public static String streamKey(UUID accountId, Category category) {
+ return "account:restriction-birth:v1:" + accountId + "/" + category.storageValue();
+ }
+
+ /**
+ * Closed UTF-8 newline-separated birth preimage, with one final newline. Exact order: schema,
+ * account UUID, private numeric source ID, provenance, insert txid, category, source kind,
+ * restriction state, revision, enforcement epoch, birth generation, generation source version,
+ * fence, fence source version, operation ID, result ID, event ID, stream key, outbox sequence.
+ * Every variable field is a canonical UUID, positive decimal, or fixed closed vocabulary.
+ */
+ public static String birthDigest(
+ UUID accountId,
+ long numericId,
+ long transactionId,
+ ScopeState birth,
+ Category category,
+ UUID operationId,
+ UUID resultId,
+ UUID eventId) {
+ String preimage =
+ String.join(
+ "\n",
+ "account-restriction-birth/v1",
+ accountId.toString(),
+ Long.toString(numericId),
+ "ACCOUNT_REPOSITORY_INSERT",
+ Long.toString(transactionId),
+ category.storageValue(),
+ "CATEGORY",
+ "NONRESTRICTED",
+ "1",
+ "1",
+ Long.toString(birth.generation()),
+ Long.toString(birth.sourceVersion()),
+ Long.toString(birth.issuanceFence().value()),
+ Long.toString(birth.issuanceFence().sourceVersion()),
+ operationId.toString(),
+ resultId.toString(),
+ eventId.toString(),
+ streamKey(accountId, category),
+ "1")
+ + "\n";
+ try {
+ return HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256")
+ .digest(preimage.getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException unavailable) {
+ throw new IllegalStateException("Required SHA-256 digest is unavailable", unavailable);
+ }
+ }
+
+ public enum Category {
+ ACCOUNT_SECURITY_LOCK("account_security_lock"),
+ PLATFORM_ACCESS_BAN("platform_access_ban");
+
+ private final String storageValue;
+
+ Category(String storageValue) {
+ this.storageValue = storageValue;
+ }
+
+ public String storageValue() {
+ return storageValue;
+ }
+ }
+
+ public enum SourceKind {
+ CATEGORY
+ }
+
+ public enum RestrictionState {
+ NONRESTRICTED
+ }
+
+ /** A positive, explicit category revision/result, never inferred from absent rows. */
+ public record CategorySource(
+ Category category,
+ SourceKind sourceKind,
+ RestrictionState restrictionState,
+ long revision,
+ long enforcementEpoch,
+ UUID operationId,
+ UUID resultId,
+ UUID eventId,
+ String payloadDigest,
+ String outboxStreamKey,
+ long outboxSequence) {
+ public CategorySource {
+ Objects.requireNonNull(category, "Category is required");
+ Objects.requireNonNull(sourceKind, "Explicit source kind is required");
+ Objects.requireNonNull(restrictionState, "Explicit restriction state is required");
+ requireUuid(operationId);
+ requireUuid(resultId);
+ requireUuid(eventId);
+ if (payloadDigest == null || !payloadDigest.matches("[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Canonical restriction birth digest is required");
+ }
+ Objects.requireNonNull(outboxStreamKey, "Restriction outbox stream is required");
+ if (revision != 1
+ || enforcementEpoch != 1
+ || outboxSequence != 1
+ || operationId.equals(resultId)
+ || operationId.equals(eventId)
+ || resultId.equals(eventId)) {
+ throw new IllegalArgumentException(
+ "Exact independent birth result and outbox are required");
+ }
+ }
+
+ private static void requireUuid(UUID value) {
+ Objects.requireNonNull(value, "Server-generated birth identity is required");
+ if (value.version() != 4 || value.variant() != 2) {
+ throw new IllegalArgumentException("Canonical version-four birth identity is required");
+ }
+ }
+ }
+}
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..97a6d7aefd
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java
@@ -0,0 +1,180 @@
+package net.firedevops.firemud.accountservice.dto;
+
+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;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.core.type.TypeReference;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+/** 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 JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .build();
+ 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 | tools.jackson.core.JacksonException 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 (tools.jackson.core.JacksonException 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.propertyNames().forEach(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 | tools.jackson.core.JacksonException 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/dto/AccountTenantCreationBootstrapResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountTenantCreationBootstrapResult.java
new file mode 100644
index 0000000000..467461750d
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountTenantCreationBootstrapResult.java
@@ -0,0 +1,49 @@
+package net.firedevops.firemud.accountservice.dto;
+
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+/** Immutable historical Account owner result for one source-bound creator membership bootstrap. */
+public record AccountTenantCreationBootstrapResult(
+ UUID operationId,
+ String requestDigest,
+ UUID initiatingAccountUuid,
+ UUID tenantUuid,
+ String creatorEvidenceDigest,
+ String sourceSnapshotDigest,
+ Map membershipVersion,
+ String membershipAuthorityGeneration,
+ List roles,
+ boolean gameplayAdmissionAllowed,
+ String eventStreamKey,
+ String eventRequestId,
+ long eventSequence,
+ String eventId,
+ String eventDigest,
+ UUID auditEventId,
+ String auditEventType,
+ String auditPayloadDigest,
+ String resultDigest) {
+ public AccountTenantCreationBootstrapResult {
+ if (operationId == null
+ || initiatingAccountUuid == null
+ || tenantUuid == null
+ || membershipVersion == null
+ || membershipAuthorityGeneration == null
+ || roles == null
+ || eventStreamKey == null
+ || eventRequestId == null
+ || eventSequence <= 0L
+ || eventId == null
+ || eventDigest == null
+ || auditEventId == null
+ || auditEventType == null
+ || auditPayloadDigest == null
+ || resultDigest == null) {
+ throw new IllegalArgumentException("Committed creator-bootstrap result is incomplete");
+ }
+ membershipVersion = Map.copyOf(membershipVersion);
+ roles = List.copyOf(roles);
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProvider.java
new file mode 100644
index 0000000000..78e672c713
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProvider.java
@@ -0,0 +1,74 @@
+package net.firedevops.firemud.accountservice.hostedterms;
+
+import java.util.Objects;
+
+/**
+ * Adapts one fixed deployment boundary and its supplied owner evidence to Account's
+ * current-boundary interface.
+ *
+ * This adapter does not authenticate, obtain, or refresh deployment evidence and does not
+ * observe an external environment. Its inputs must come from trusted deployment-evidence delivery
+ * and must already have passed that owner's machine validation. This class is intentionally
+ * unregistered; runtime composition remains disabled until that trusted input source is supplied.
+ * Account still independently locks and checks its current environment binding, catalog, operator,
+ * and acceptance sources when authorizing a mutation.
+ */
+public final class AccountDeploymentEnvironmentBoundaryProvider
+ implements AccountHostedTermsService.CurrentEnvironmentBoundaryAuthority {
+ private final HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary capturedBoundary;
+
+ /**
+ * Captures a server-selected deployment boundary and its exact supplied owner evidence.
+ *
+ * @param environmentBoundary fixed environment boundary selected by server deployment policy
+ * @param authenticatedOwnerIdentity expected identity of the deployment evidence owner
+ * @param observationEventIdentity expected identity of the deployment observation event
+ * @param ownerEvidenceDigest expected digest of the exact owner evidence
+ * @param validatedDeploymentEvidence already machine-validated immutable evidence delivered by a
+ * trusted deployment source; this adapter only checks its exact binding and defensive-copies
+ * it
+ * @throws IllegalArgumentException if any required expected value is absent or the supplied
+ * evidence does not exactly match the fixed deployment values
+ * @throws NullPointerException if the supplied evidence record is absent
+ */
+ public AccountDeploymentEnvironmentBoundaryProvider(
+ String environmentBoundary,
+ String authenticatedOwnerIdentity,
+ String observationEventIdentity,
+ String ownerEvidenceDigest,
+ HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary validatedDeploymentEvidence) {
+ String expectedBoundary = HostedTermsEncoding.requireText(environmentBoundary, 512);
+ String expectedOwner = HostedTermsEncoding.requireText(authenticatedOwnerIdentity, 512);
+ String expectedEvent = HostedTermsEncoding.requireText(observationEventIdentity, 512);
+ String expectedDigest = HostedTermsEncoding.requireDigest(ownerEvidenceDigest);
+ Objects.requireNonNull(
+ validatedDeploymentEvidence, "validated deployment evidence is required");
+
+ byte[] exactOwnerEvidence = validatedDeploymentEvidence.exactOwnerEvidence();
+ if (!expectedBoundary.equals(validatedDeploymentEvidence.environmentBoundary())
+ || !expectedOwner.equals(validatedDeploymentEvidence.authenticatedOwnerIdentity())
+ || !expectedEvent.equals(validatedDeploymentEvidence.observationEventIdentity())
+ || !expectedDigest.equals(validatedDeploymentEvidence.ownerEvidenceDigest())
+ || !expectedDigest.equals(HostedTermsEncoding.digest(exactOwnerEvidence))) {
+ throw new IllegalArgumentException(
+ "Deployment environment evidence differs from the fixed server boundary");
+ }
+
+ // Reconstruct through the existing immutable evidence record so its exact-byte and digest
+ // validation remains the canonical shape check, and the provider owns an independent snapshot.
+ this.capturedBoundary =
+ new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary(
+ expectedBoundary, expectedOwner, expectedEvent, exactOwnerEvidence, expectedDigest);
+ }
+
+ /** Returns the fixed captured boundary; request data cannot select or change its scope. */
+ @Override
+ public HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary currentBoundary() {
+ return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary(
+ capturedBoundary.environmentBoundary(),
+ capturedBoundary.authenticatedOwnerIdentity(),
+ capturedBoundary.observationEventIdentity(),
+ capturedBoundary.exactOwnerEvidence(),
+ capturedBoundary.ownerEvidenceDigest());
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java
new file mode 100644
index 0000000000..5f9cabaa4a
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java
@@ -0,0 +1,1151 @@
+package net.firedevops.firemud.accountservice.hostedterms;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.time.Instant;
+import java.time.OffsetDateTime;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository;
+import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding;
+import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository;
+import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource;
+import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/**
+ * Unregistered Account owner workflow for hosted terms publication, individual acceptance and
+ * currentness. Its typed collaborators are trusted-owner boundaries, not caller DTO authority.
+ *
+ *
This does not prove live legal publication or identity verification, add a route/bean, or
+ * authorize Game Design commits. Currentness includes any disclosed future effective deadline; the
+ * commit consumer must recheck that deadline at its own linearization point.
+ */
+public final class AccountHostedTermsService {
+ private final HostedTermsRepository repository;
+ private final IndividualCreatorPartyRepository individualParties;
+ private final DraftAuthorizationFenceRepository draftFences;
+ private final OperatorPublicationAuthority publicationAuthority;
+ private final IndividualAcceptanceAuthority acceptanceAuthority;
+ private final HostedTermsEnvironmentBindingRepository environmentBindings;
+ private final EnvironmentBindingPublicationAuthority environmentBindingPublicationAuthority;
+ private final CurrentEnvironmentBoundaryAuthority currentEnvironmentBoundaryAuthority;
+ private final TransactionTemplate ownerTransaction;
+
+ public AccountHostedTermsService(
+ PlatformTransactionManager transactionManager,
+ HostedTermsRepository repository,
+ IndividualCreatorPartyRepository individualParties,
+ DraftAuthorizationFenceRepository draftFences,
+ OperatorPublicationAuthority publicationAuthority,
+ IndividualAcceptanceAuthority acceptanceAuthority) {
+ this(
+ transactionManager,
+ repository,
+ individualParties,
+ draftFences,
+ publicationAuthority,
+ acceptanceAuthority,
+ null,
+ null,
+ null);
+ }
+
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification = "Trusted owner collaborators are retained privately and never exposed.")
+ public AccountHostedTermsService(
+ PlatformTransactionManager transactionManager,
+ HostedTermsRepository repository,
+ IndividualCreatorPartyRepository individualParties,
+ DraftAuthorizationFenceRepository draftFences,
+ OperatorPublicationAuthority publicationAuthority,
+ IndividualAcceptanceAuthority acceptanceAuthority,
+ HostedTermsEnvironmentBindingRepository environmentBindings,
+ EnvironmentBindingPublicationAuthority environmentBindingPublicationAuthority,
+ CurrentEnvironmentBoundaryAuthority currentEnvironmentBoundaryAuthority) {
+ this.repository = Objects.requireNonNull(repository);
+ this.individualParties = Objects.requireNonNull(individualParties);
+ this.draftFences = Objects.requireNonNull(draftFences);
+ this.publicationAuthority = Objects.requireNonNull(publicationAuthority);
+ this.acceptanceAuthority = Objects.requireNonNull(acceptanceAuthority);
+ this.environmentBindings = environmentBindings;
+ this.environmentBindingPublicationAuthority = environmentBindingPublicationAuthority;
+ this.currentEnvironmentBoundaryAuthority = currentEnvironmentBoundaryAuthority;
+ ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager));
+ ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
+ ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
+ }
+
+ /** Resolves publication solely from the trusted operator owner before opening an Account tx. */
+ public PublicationResult publish(UUID requestId) {
+ HostedTermsEncoding.requireUuid(requestId, "publication request");
+ PublicationEvidence evidence =
+ Objects.requireNonNull(
+ publicationAuthority.resolve(requestId), "operator publication evidence");
+ byte[] requestPayload = HostedTermsEncoding.publication(requestId, evidence);
+ return Objects.requireNonNull(
+ ownerTransaction.execute(
+ ignored -> publishInTransaction(requestId, evidence, requestPayload)),
+ "Account publication transaction result");
+ }
+
+ /**
+ * Resolves the authenticated environment-owner handoff before opening the Account transaction,
+ * then exact-validates its catalog and predecessor while holding owner-local locks.
+ */
+ public EnvironmentBindingPublicationResult publishEnvironmentBinding(UUID requestId) {
+ requireEnvironmentBindingPublicationAuthority();
+ HostedTermsEncoding.requireUuid(requestId, "environment binding publication request");
+ HostedTermsEnvironmentBinding.PublicationEvidence evidence =
+ Objects.requireNonNull(
+ environmentBindingPublicationAuthority.resolve(requestId),
+ "authenticated environment-owner publication evidence");
+ byte[] requestPayload = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence);
+ return Objects.requireNonNull(
+ ownerTransaction.execute(
+ ignored -> publishEnvironmentBindingInTransaction(requestId, evidence, requestPayload)),
+ "Account environment binding publication result");
+ }
+
+ /** Resumes only the exact durable environment-binding publication and source-change intent. */
+ public EnvironmentBindingPublicationResult resumeEnvironmentBinding(UUID requestId) {
+ requireEnvironmentBindingRepository();
+ HostedTermsEncoding.requireUuid(requestId, "environment binding publication request");
+ return Objects.requireNonNull(
+ ownerTransaction.execute(
+ ignored -> {
+ HostedTermsEnvironmentBindingRepository.PublicationOperation operation =
+ environmentBindings
+ .readPublication(requestId, true)
+ .orElseThrow(
+ () ->
+ new IllegalArgumentException(
+ "Original environment binding publication is absent"));
+ return advanceEnvironmentBinding(operation);
+ }),
+ "Account environment binding recovery result");
+ }
+
+ /**
+ * Derives the official environment boundary from a trusted owner collaborator, then reads the
+ * exact binding, current catalog, verified individual party and acceptance in one Account
+ * READ_COMMITTED owner transaction. The result is currentness/source evidence, not permission.
+ */
+ public EnvironmentBoundCurrentness requireCurrentnessForCurrentEnvironment(UUID creatorPartyId) {
+ HostedTermsEncoding.requireUuid(creatorPartyId, "creator party");
+ CapturedEnvironmentBoundary captured = captureCurrentEnvironmentBoundary();
+ return Objects.requireNonNull(
+ ownerTransaction.execute(
+ ignored -> requireCurrentnessInOwnerTransaction(captured, creatorPartyId)),
+ "Account environment-bound currentness result");
+ }
+
+ /**
+ * Obtains the trusted environment observation before any Account transaction begins. This
+ * service-issued handle is source material only and cannot authorize a Draft mutation.
+ */
+ public CapturedEnvironmentBoundary captureCurrentEnvironmentBoundary() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw new IllegalStateException(
+ "Current environment boundary must be captured outside an Account transaction");
+ }
+ requireCurrentEnvironmentBoundaryAuthority();
+ HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment =
+ Objects.requireNonNull(
+ currentEnvironmentBoundaryAuthority.currentBoundary(),
+ "authenticated current environment boundary");
+ return new CapturedEnvironmentBoundary(this, environment);
+ }
+
+ /**
+ * Locks and rereads the persisted mapping, catalog, party, acceptance and deadline in the
+ * caller's writable READ_COMMITTED Account transaction. No external owner is called here; the
+ * returned evidence is not a commit token or proof of later external environment continuity.
+ */
+ public EnvironmentBoundCurrentness requireCurrentnessInOwnerTransaction(
+ CapturedEnvironmentBoundary captured, UUID creatorPartyId) {
+ if (captured == null || captured.owner != this) {
+ throw new IllegalArgumentException("Current environment capture belongs to another owner");
+ }
+ HostedTermsEncoding.requireUuid(creatorPartyId, "creator party");
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException("Writable Account owner transaction required");
+ }
+ // lockHead performs the physical connection's writable READ_COMMITTED check before reading.
+ return currentnessForEnvironmentInTransaction(captured.environment, creatorPartyId);
+ }
+
+ /** Opaque, immutable observation scoped to the issuing service instance. */
+ public static final class CapturedEnvironmentBoundary {
+ private final AccountHostedTermsService owner;
+ private final HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment;
+
+ private CapturedEnvironmentBoundary(
+ AccountHostedTermsService owner,
+ HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment) {
+ this.owner = owner;
+ this.environment = environment;
+ }
+ }
+
+ /** Recovery uses the already durable exact publication and never remints operator evidence. */
+ public PublicationResult resumePublication(UUID requestId) {
+ HostedTermsEncoding.requireUuid(requestId, "publication request");
+ return Objects.requireNonNull(
+ ownerTransaction.execute(
+ ignored -> {
+ HostedTermsRepository.PublicationOperation operation =
+ repository
+ .readPublication(requestId, true)
+ .orElseThrow(
+ () ->
+ new IllegalArgumentException(
+ "Original publication request is absent"));
+ return advancePublication(operation, null);
+ }),
+ "Account publication recovery result");
+ }
+
+ /**
+ * Records only a trusted upstream-authenticated individual's exact affirmative UI/action
+ * evidence. The accepting account/party comes from that collaborator, then Account independently
+ * reads and locks the persisted local VERIFIED party source.
+ */
+ public IndividualHostedTermsAcceptance accept(UUID actionRequestId) {
+ HostedTermsEncoding.requireUuid(actionRequestId, "acceptance action request");
+ AcceptanceAction action =
+ Objects.requireNonNull(
+ acceptanceAuthority.resolve(actionRequestId), "authenticated individual action");
+ if (!actionRequestId.equals(action.actionRequestId())) {
+ throw new IllegalArgumentException(
+ "Trusted acceptance action has a changed request identity");
+ }
+ if (!action.affirmative()) {
+ throw new IllegalArgumentException("Affirmative hosted-terms acceptance is required");
+ }
+ byte[] actionBytes = HostedTermsEncoding.affirmativeAction(action);
+ return Objects.requireNonNull(
+ ownerTransaction.execute(ignored -> acceptInTransaction(action, actionBytes)),
+ "Account acceptance transaction result");
+ }
+
+ /**
+ * Fresh Account evidence for one hosted scope and party. A scheduled deadline is included even
+ * before it is due; at/after it, old terms are denied even if a source-change fence is
+ * unresolved.
+ */
+ public CurrentnessEvidence requireCurrentness(UUID hostedScopeId, UUID creatorPartyId) {
+ HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope");
+ HostedTermsEncoding.requireUuid(creatorPartyId, "creator party");
+ return Objects.requireNonNull(
+ ownerTransaction.execute(
+ ignored -> currentnessInTransaction(hostedScopeId, creatorPartyId)),
+ "Account hosted terms currentness result");
+ }
+
+ private EnvironmentBindingPublicationResult publishEnvironmentBindingInTransaction(
+ UUID requestId,
+ HostedTermsEnvironmentBinding.PublicationEvidence evidence,
+ byte[] requestPayload) {
+ environmentBindings.ensureHead(evidence.environmentBoundary());
+ var operation =
+ environmentBindings.claimPublication(
+ requestId, evidence.environmentBoundary(), requestPayload);
+ if (operation.status() == HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED) {
+ return environmentBindingResult(operation, environmentBindings.readCandidate(operation));
+ }
+ if (operation.status()
+ == HostedTermsEnvironmentBindingRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT) {
+ if (!Arrays.equals(operation.requestPayload(), requestPayload)) {
+ throw new IllegalArgumentException("Binding retry differs from exact owner publication");
+ }
+ return advanceEnvironmentBinding(operation);
+ }
+
+ HostedTermsEnvironmentBindingRepository.HeadSnapshot head =
+ environmentBindings.lockHead(evidence.environmentBoundary());
+ if (head.unsettledPublication() != null
+ && !head.unsettledPublication().requestId().equals(requestId)) {
+ throw new IllegalStateException("Another environment binding change is pending");
+ }
+ HostedTermsEnvironmentBinding predecessor = head.current();
+ if (!Objects.equals(
+ evidence.predecessorBindingId(), predecessor == null ? null : predecessor.bindingId())
+ || !Objects.equals(
+ evidence.predecessorSourceVersion(),
+ predecessor == null ? null : predecessor.sourceVersion())) {
+ throw new IllegalArgumentException(
+ "Authenticated environment publication does not extend exact current binding");
+ }
+ Map catalogScopes =
+ lockBindingCatalogScopes(predecessor, evidence.hostedScopeId());
+ if (predecessor != null && catalogScopes.get(predecessor.hostedScopeId()).current() == null) {
+ throw new IllegalStateException("Prior environment binding catalog source is unavailable");
+ }
+ HostedTermsRepository.ScopeSnapshot targetScope = catalogScopes.get(evidence.hostedScopeId());
+ HostedTermsCatalogVersion targetCatalog = targetScope.current();
+ requireExactBindingCatalog(evidence, targetCatalog, targetScope.databaseNow());
+
+ boolean introducesFutureDeadline =
+ hasFutureScheduledDeadline(targetScope)
+ && (predecessor == null
+ || !predecessor.hostedScopeId().equals(evidence.hostedScopeId()));
+ if (introducesFutureDeadline) {
+ List protectedSources =
+ predecessor == null
+ ? List.of(catalogSourceEvidence(targetCatalog))
+ : bindingSourceEvidence(predecessor, catalogScopes);
+ draftFences.requireDisclosurePreparation(protectedSources);
+ }
+ HostedTermsEnvironmentBinding candidate =
+ environmentBindings.insertCandidate(UUID.randomUUID(), requestId, evidence, predecessor);
+ DraftAuthorizationFenceRepository.SourceChange change =
+ predecessor == null
+ ? null
+ : bindingSourceChange(requestId, predecessor, catalogScopes, candidate);
+ if (change != null) {
+ boolean settled = draftFences.requestSourceChange(change);
+ if (!settled || !draftFences.sourceMutationPermitted(change)) {
+ environmentBindings.markOwnerSettlementPending(
+ requestId, candidate, change.canonicalBytes());
+ return environmentBindingResult(
+ HostedTermsEnvironmentBindingRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT,
+ candidate);
+ }
+ environmentBindings.completePublication(
+ requestId, candidate, change.canonicalBytes(), predecessor);
+ draftFences.markSourceCommitted(change);
+ return environmentBindingResult(
+ HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED, candidate);
+ }
+ environmentBindings.completePublication(requestId, candidate, null, null);
+ return environmentBindingResult(
+ HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED, candidate);
+ }
+
+ private EnvironmentBindingPublicationResult advanceEnvironmentBinding(
+ HostedTermsEnvironmentBindingRepository.PublicationOperation operation) {
+ if (operation.status() == HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED) {
+ return environmentBindingResult(operation, environmentBindings.readCandidate(operation));
+ }
+ if (operation.status() == HostedTermsEnvironmentBindingRepository.PublicationStatus.RECEIVED) {
+ throw new IllegalStateException(
+ "Binding publication intent is incomplete; retry the original trusted request");
+ }
+ if (operation.sourceChangeBinding() == null) {
+ throw new IllegalStateException("Pending binding lacks its durable source-change intent");
+ }
+ HostedTermsEnvironmentBindingRepository.HeadSnapshot head =
+ environmentBindings.lockHead(operation.environmentBoundary());
+ HostedTermsEnvironmentBinding candidate = environmentBindings.readCandidate(operation);
+ HostedTermsEnvironmentBinding predecessor = head.current();
+ if (head.unsettledPublication() == null
+ || !head.unsettledPublication().requestId().equals(operation.requestId())
+ || !Objects.equals(
+ candidate.predecessorBindingId(), predecessor == null ? null : predecessor.bindingId())
+ || !Objects.equals(
+ candidate.predecessorSourceVersion(),
+ predecessor == null ? null : predecessor.sourceVersion())) {
+ throw new IllegalStateException("Pending binding no longer matches exact environment head");
+ }
+ HostedTermsRepository.ScopeSnapshot targetScope =
+ repository.lockScope(candidate.hostedScopeId());
+ requireBindingCatalog(candidate, targetScope.current(), targetScope.databaseNow());
+ DraftAuthorizationFenceRepository.SourceChange change =
+ DraftAuthorizationFenceRepository.SourceChange.fromStored(operation.sourceChangeBinding());
+ boolean settled = draftFences.requestSourceChange(change);
+ if (!settled || !draftFences.sourceMutationPermitted(change)) {
+ return environmentBindingResult(
+ HostedTermsEnvironmentBindingRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT,
+ candidate);
+ }
+ environmentBindings.completePublication(
+ operation.requestId(), candidate, change.canonicalBytes(), predecessor);
+ draftFences.markSourceCommitted(change);
+ return environmentBindingResult(
+ HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED, candidate);
+ }
+
+ private Map lockBindingCatalogScopes(
+ HostedTermsEnvironmentBinding predecessor, UUID targetScopeId) {
+ Map snapshots = new LinkedHashMap<>();
+ java.util.stream.Stream.of(
+ predecessor == null ? targetScopeId : predecessor.hostedScopeId(), targetScopeId)
+ .distinct()
+ .sorted(Comparator.comparing(UUID::toString))
+ .forEach(scopeId -> snapshots.put(scopeId, repository.lockScope(scopeId)));
+ return Map.copyOf(snapshots);
+ }
+
+ private DraftAuthorizationFenceRepository.SourceChange bindingSourceChange(
+ UUID changeId,
+ HostedTermsEnvironmentBinding predecessor,
+ Map catalogScopes,
+ HostedTermsEnvironmentBinding candidate) {
+ return new DraftAuthorizationFenceRepository.SourceChange(
+ changeId,
+ bindingSourceEvidence(predecessor, catalogScopes),
+ HostedTermsEnvironmentBindingEncoding.receipt(candidate));
+ }
+
+ private List bindingSourceEvidence(
+ HostedTermsEnvironmentBinding predecessor,
+ Map catalogScopes) {
+ Map sources = new LinkedHashMap<>();
+ SourceEvidence bindingSource = predecessor.sourceEvidence();
+ sources.put(bindingSource.key(), bindingSource);
+ catalogScopes.values().stream()
+ .map(HostedTermsRepository.ScopeSnapshot::current)
+ .filter(Objects::nonNull)
+ .map(this::catalogSourceEvidence)
+ .forEach(source -> sources.put(source.key(), source));
+ return sources.values().stream().sorted(Comparator.comparing(SourceEvidence::key)).toList();
+ }
+
+ private SourceEvidence catalogSourceEvidence(HostedTermsCatalogVersion catalog) {
+ return new SourceEvidence(
+ SourceKind.HOSTED_TERMS,
+ catalog.hostedScopeId().toString(),
+ Long.toString(catalog.materialGeneration()),
+ Long.toString(catalog.sourceVersion()),
+ null,
+ null,
+ HostedTermsEncoding.catalog(catalog));
+ }
+
+ private boolean hasFutureScheduledDeadline(HostedTermsRepository.ScopeSnapshot scope) {
+ HostedTermsRepository.PublicationOperation pending = scope.unsettledPublication();
+ if (pending == null || pending.status() != HostedTermsRepository.PublicationStatus.SCHEDULED) {
+ return false;
+ }
+ return repository.readCandidate(pending).effectiveAt().isAfter(scope.databaseNow().toInstant());
+ }
+
+ private void requireExactBindingCatalog(
+ HostedTermsEnvironmentBinding.PublicationEvidence evidence,
+ HostedTermsCatalogVersion current,
+ OffsetDateTime databaseNow) {
+ if (current == null || current.effectiveAt().isAfter(databaseNow.toInstant())) {
+ throw new IllegalStateException("Environment binding requires a current due terms catalog");
+ }
+ if (!current.versionId().equals(evidence.catalogVersionId())
+ || !current.hostedScopeId().equals(evidence.hostedScopeId())
+ || current.sourceVersion() != evidence.catalogSourceVersion()
+ || !current.operatorLegalIdentity().equals(evidence.operatorLegalIdentity())
+ || current.operatorIdentityVersion() != evidence.operatorIdentityVersion()) {
+ throw new IllegalArgumentException(
+ "Environment publication differs from exact current catalog and legal operator");
+ }
+ }
+
+ private void requireBindingCatalog(
+ HostedTermsEnvironmentBinding binding,
+ HostedTermsCatalogVersion current,
+ OffsetDateTime databaseNow) {
+ if (current == null || current.effectiveAt().isAfter(databaseNow.toInstant())) {
+ throw new IllegalStateException("Environment binding catalog is not currently operative");
+ }
+ if (!current.versionId().equals(binding.catalogVersionId())
+ || !current.hostedScopeId().equals(binding.hostedScopeId())
+ || current.sourceVersion() != binding.catalogSourceVersion()
+ || !current.operatorLegalIdentity().equals(binding.operatorLegalIdentity())
+ || current.operatorIdentityVersion() != binding.operatorIdentityVersion()) {
+ throw new IllegalStateException("Environment binding points at changed catalog authority");
+ }
+ }
+
+ private EnvironmentBoundCurrentness currentnessForEnvironmentInTransaction(
+ HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment, UUID creatorPartyId) {
+ HostedTermsEnvironmentBindingRepository.HeadSnapshot head =
+ environmentBindings.lockHead(environment.environmentBoundary());
+ if (head.unsettledPublication() != null) {
+ throw new IllegalStateException("Environment binding source change is unresolved");
+ }
+ HostedTermsEnvironmentBinding binding = head.current();
+ if (binding == null) {
+ throw new IllegalStateException(
+ "No authenticated environment-to-hosted-scope binding exists");
+ }
+ CurrentnessEvidence terms = currentnessInTransaction(binding.hostedScopeId(), creatorPartyId);
+ HostedTermsRepository.ScopeSnapshot lockedScope = repository.lockScope(binding.hostedScopeId());
+ HostedTermsCatalogVersion catalog = lockedScope.current();
+ requireBindingCatalog(binding, catalog, lockedScope.databaseNow());
+ if (!catalog.versionId().equals(terms.currentVersionId())) {
+ throw new IllegalStateException("Currentness and locked catalog readback differ");
+ }
+ IndividualCreatorPartySource party =
+ individualParties.readIndividualSource(terms.creatorPartyId(), terms.accountId());
+ if (!party.locallyVerified()) {
+ throw new IllegalStateException(
+ "Current individual party source is unavailable or unverified");
+ }
+ IndividualHostedTermsAcceptance acceptance =
+ repository
+ .readCurrentAcceptance(terms.creatorPartyId(), binding.hostedScopeId(), catalog)
+ .orElseThrow(
+ () -> new IllegalStateException("Current affirmative acceptance is unavailable"));
+ if (!acceptance.evidenceId().equals(terms.acceptanceEvidenceId())) {
+ throw new IllegalStateException("Current acceptance readback changed during capture");
+ }
+ byte[] exactTermsSource =
+ HostedTermsEncoding.currentnessSource(catalog, acceptance, terms.disclosedDeadline());
+ if (!Arrays.equals(exactTermsSource, terms.exactCurrentnessSource())) {
+ throw new IllegalStateException(
+ "Currentness source differs from exact locked acceptance and deadline evidence");
+ }
+ SourceEvidence partySource =
+ new SourceEvidence(
+ SourceKind.CREATOR_PARTY,
+ party.creatorPartyId().toString(),
+ Long.toString(party.identityVersion()),
+ Long.toString(party.sourceVersion()),
+ null,
+ null,
+ CreatorPartyEncoding.party(party));
+ SourceEvidence termsSource =
+ new SourceEvidence(
+ SourceKind.HOSTED_TERMS,
+ catalog.hostedScopeId().toString(),
+ Long.toString(catalog.materialGeneration()),
+ Long.toString(catalog.sourceVersion()),
+ null,
+ null,
+ exactTermsSource);
+ List sources =
+ java.util.stream.Stream.of(binding.sourceEvidence(), termsSource, partySource)
+ .sorted(Comparator.comparing(SourceEvidence::key))
+ .toList();
+ return new EnvironmentBoundCurrentness(environment, binding, terms, sources);
+ }
+
+ private EnvironmentBindingPublicationResult environmentBindingResult(
+ HostedTermsEnvironmentBindingRepository.PublicationOperation operation,
+ HostedTermsEnvironmentBinding candidate) {
+ return environmentBindingResult(operation.status(), candidate);
+ }
+
+ private EnvironmentBindingPublicationResult environmentBindingResult(
+ HostedTermsEnvironmentBindingRepository.PublicationStatus status,
+ HostedTermsEnvironmentBinding candidate) {
+ return new EnvironmentBindingPublicationResult(
+ status, candidate, HostedTermsEnvironmentBindingEncoding.receipt(candidate));
+ }
+
+ private void requireEnvironmentBindingRepository() {
+ if (environmentBindings == null) {
+ throw new IllegalStateException("Account environment-binding persistence is unavailable");
+ }
+ }
+
+ private void requireEnvironmentBindingPublicationAuthority() {
+ requireEnvironmentBindingRepository();
+ if (environmentBindingPublicationAuthority == null) {
+ throw new IllegalStateException(
+ "Authenticated environment publication authority is unavailable");
+ }
+ }
+
+ private void requireCurrentEnvironmentBoundaryAuthority() {
+ requireEnvironmentBindingRepository();
+ if (currentEnvironmentBoundaryAuthority == null) {
+ throw new IllegalStateException("Authenticated current environment boundary is unavailable");
+ }
+ }
+
+ private PublicationResult publishInTransaction(
+ UUID requestId, PublicationEvidence evidence, byte[] requestPayload) {
+ repository.ensureScope(evidence.hostedScopeId());
+ HostedTermsRepository.PublicationOperation operation =
+ repository.claimPublication(requestId, evidence.hostedScopeId(), requestPayload);
+ if (operation.status() != HostedTermsRepository.PublicationStatus.RECEIVED) {
+ return advancePublication(operation, evidence);
+ }
+ HostedTermsRepository.ScopeSnapshot scope = repository.lockScope(evidence.hostedScopeId());
+ if (scope.unsettledPublication() != null
+ && !scope.unsettledPublication().requestId().equals(requestId)) {
+ throw new IllegalStateException("Another hosted terms publication is scheduled or pending");
+ }
+ HostedTermsCatalogVersion candidate = candidate(evidence, scope.current());
+ if (candidate.effectiveAt().isAfter(scope.databaseNow().toInstant())) {
+ if (scope.current() != null) {
+ draftFences.requireDisclosurePreparation(List.of(catalogSourceEvidence(scope.current())));
+ }
+ repository.insertCandidate(candidate);
+ repository.markScheduled(requestId, candidate);
+ return result(HostedTermsRepository.PublicationStatus.SCHEDULED, candidate);
+ }
+ repository.insertCandidate(candidate);
+ return activate(operation, candidate, scope.current(), null, scope.databaseNow());
+ }
+
+ private PublicationResult advancePublication(
+ HostedTermsRepository.PublicationOperation operation, PublicationEvidence suppliedEvidence) {
+ if (operation.status() == HostedTermsRepository.PublicationStatus.COMMITTED) {
+ return result(operation, repository.readCandidate(operation));
+ }
+ if (operation.status() == HostedTermsRepository.PublicationStatus.RECEIVED) {
+ throw new IllegalStateException(
+ "Publication intent is incomplete; retry the original trusted publication request");
+ }
+ if (suppliedEvidence != null) {
+ byte[] supplied = HostedTermsEncoding.publication(operation.requestId(), suppliedEvidence);
+ if (!Arrays.equals(operation.requestPayload(), supplied)) {
+ throw new IllegalArgumentException(
+ "Publication request identity conflicts with exact prior intent");
+ }
+ }
+ HostedTermsRepository.ScopeSnapshot scope = repository.lockScope(operation.hostedScopeId());
+ HostedTermsCatalogVersion candidate = repository.readCandidate(operation);
+ if (candidate.effectiveAt().isAfter(scope.databaseNow().toInstant())) {
+ if (operation.status() != HostedTermsRepository.PublicationStatus.SCHEDULED) {
+ throw new IllegalStateException(
+ "Owner-pending publication cannot precede its effective date");
+ }
+ return result(operation, candidate);
+ }
+ if (operation.status() == HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT) {
+ DraftAuthorizationFenceRepository.SourceChange change =
+ DraftAuthorizationFenceRepository.SourceChange.fromStored(
+ operation.sourceChangeBinding());
+ boolean settled = draftFences.requestSourceChange(change);
+ if (!settled || !draftFences.sourceMutationPermitted(change)) {
+ return result(operation, candidate);
+ }
+ repository.completePublication(
+ operation.requestId(),
+ candidate,
+ HostedTermsEncoding.catalog(candidate),
+ change.canonicalBytes());
+ draftFences.markSourceCommitted(change);
+ return result(HostedTermsRepository.PublicationStatus.COMMITTED, candidate);
+ }
+ return activate(operation, candidate, scope.current(), null, scope.databaseNow());
+ }
+
+ private PublicationResult activate(
+ HostedTermsRepository.PublicationOperation operation,
+ HostedTermsCatalogVersion candidate,
+ HostedTermsCatalogVersion current,
+ byte[] priorChangeBinding,
+ OffsetDateTime databaseNow) {
+ if (candidate.effectiveAt().isAfter(databaseNow.toInstant())) {
+ throw new IllegalStateException("A future catalog version cannot become operative early");
+ }
+ byte[] changeBinding = priorChangeBinding;
+ if (current != null) {
+ DraftAuthorizationFenceRepository.SourceChange change =
+ changeBinding == null
+ ? sourceChange(operation.requestId(), current, candidate)
+ : DraftAuthorizationFenceRepository.SourceChange.fromStored(changeBinding);
+ if (changeBinding == null) {
+ changeBinding = change.canonicalBytes();
+ }
+ boolean settled = draftFences.requestSourceChange(change);
+ if (!settled || !draftFences.sourceMutationPermitted(change)) {
+ if (operation.status()
+ != HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT) {
+ repository.markOwnerSettlementPending(operation.requestId(), candidate, changeBinding);
+ }
+ return result(HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT, candidate);
+ }
+ if (operation.status() == HostedTermsRepository.PublicationStatus.RECEIVED) {
+ repository.markScheduled(operation.requestId(), candidate);
+ }
+ repository.completePublication(
+ operation.requestId(), candidate, HostedTermsEncoding.catalog(candidate), changeBinding);
+ draftFences.markSourceCommitted(change);
+ return result(HostedTermsRepository.PublicationStatus.COMMITTED, candidate);
+ }
+ if (operation.status() == HostedTermsRepository.PublicationStatus.RECEIVED) {
+ repository.markScheduled(operation.requestId(), candidate);
+ }
+ repository.completePublication(
+ operation.requestId(), candidate, HostedTermsEncoding.catalog(candidate), null);
+ return result(HostedTermsRepository.PublicationStatus.COMMITTED, candidate);
+ }
+
+ private HostedTermsCatalogVersion candidate(
+ PublicationEvidence evidence, HostedTermsCatalogVersion predecessor) {
+ HostedTermsCatalogVersion.Materiality materiality =
+ predecessor == null
+ ? HostedTermsCatalogVersion.Materiality.INITIAL
+ : evidence.materiality();
+ if (predecessor == null
+ && evidence.materiality() != HostedTermsCatalogVersion.Materiality.INITIAL) {
+ throw new IllegalArgumentException(
+ "Initial catalog birth must not claim a prior materiality change");
+ }
+ if (predecessor != null
+ && evidence.materiality() == HostedTermsCatalogVersion.Materiality.INITIAL) {
+ throw new IllegalArgumentException(
+ "A catalog update requires an audited materiality classification");
+ }
+ boolean operatorChanged =
+ predecessor != null
+ && (!predecessor.operatorLegalIdentity().equals(evidence.operatorLegalIdentity())
+ || predecessor.operatorIdentityVersion() != evidence.operatorIdentityVersion());
+ if (operatorChanged && materiality != HostedTermsCatalogVersion.Materiality.MATERIAL) {
+ throw new IllegalArgumentException(
+ "Operator identity change requires material classification");
+ }
+ long sourceVersion = predecessor == null ? 1 : Math.addExact(predecessor.sourceVersion(), 1);
+ long generation =
+ predecessor == null
+ ? 1
+ : Math.addExact(
+ predecessor.materialGeneration(),
+ materiality == HostedTermsCatalogVersion.Materiality.MATERIAL ? 1 : 0);
+ UUID versionId = UUID.randomUUID();
+ return new HostedTermsCatalogVersion(
+ versionId,
+ evidence.hostedScopeId(),
+ predecessor == null ? null : predecessor.versionId(),
+ evidence.operatorLegalIdentity(),
+ evidence.operatorIdentityVersion(),
+ evidence.documentBytes(),
+ HostedTermsEncoding.digest(evidence.documentBytes()),
+ sourceVersion,
+ generation,
+ materiality,
+ evidence.materialityEvidenceReference(),
+ evidence.materialityEvidenceVersion(),
+ evidence.publicationEvidenceReference(),
+ evidence.publicationEvidenceVersion(),
+ evidence.noticeEvidenceReference(),
+ evidence.noticeEvidenceVersion(),
+ evidence.effectiveAt());
+ }
+
+ private IndividualHostedTermsAcceptance acceptInTransaction(
+ AcceptanceAction action, byte[] actionBytes) {
+ IndividualHostedTermsAcceptance prior =
+ repository.readAcceptanceByRequest(action.actionRequestId()).orElse(null);
+ if (prior != null) {
+ if (!prior.accountId().equals(action.accountId())
+ || !prior.creatorPartyId().equals(action.creatorPartyId())
+ || !prior.hostedScopeId().equals(action.hostedScopeId())
+ || !prior.termsVersionId().equals(action.shownVersionId())
+ || !prior.documentDigest().equals(action.shownDocumentDigest())
+ || !prior.operatorLegalIdentity().equals(action.shownOperatorLegalIdentity())
+ || prior.operatorIdentityVersion() != action.shownOperatorIdentityVersion()
+ || !Arrays.equals(prior.affirmativeActionEvidence(), actionBytes)) {
+ throw new IllegalArgumentException(
+ "Acceptance request identity conflicts with prior evidence");
+ }
+ return prior;
+ }
+ IndividualCreatorPartySource party =
+ individualParties.readIndividualSource(action.creatorPartyId(), action.accountId());
+ requireOwnVerifiedIndividual(action, party);
+ HostedTermsRepository.ScopeSnapshot scope = repository.lockScope(action.hostedScopeId());
+ HostedTermsCatalogVersion shown =
+ repository.readCatalog(action.hostedScopeId(), action.shownVersionId());
+ if (!action.shownVersionId().equals(shown.versionId())
+ || !action.hostedScopeId().equals(shown.hostedScopeId())
+ || !action.shownDocumentDigest().equals(shown.documentDigest())
+ || !action.shownOperatorLegalIdentity().equals(shown.operatorLegalIdentity())
+ || action.shownOperatorIdentityVersion() != shown.operatorIdentityVersion()) {
+ throw new IllegalArgumentException(
+ "Affirmative action differs from exact shown catalog version");
+ }
+ boolean current =
+ scope.current() != null && scope.current().versionId().equals(shown.versionId());
+ boolean scheduled =
+ scope.unsettledPublication() != null
+ && Objects.equals(scope.unsettledPublication().candidateVersionId(), shown.versionId());
+ if (!current && !scheduled) {
+ throw new IllegalStateException(
+ "Shown hosted terms version is neither operative nor scheduled");
+ }
+ IndividualHostedTermsAcceptance accepted =
+ repository.insertAcceptance(UUID.randomUUID(), action, party, shown, actionBytes);
+ return accepted;
+ }
+
+ private CurrentnessEvidence currentnessInTransaction(UUID scopeId, UUID partyId) {
+ UUID accountId = repository.lockPartyAccount(partyId);
+ IndividualCreatorPartySource party = individualParties.readIndividualSource(partyId, accountId);
+ if (!party.locallyVerified()) {
+ throw new IllegalStateException(
+ "Current individual identity evidence is unavailable or unverified");
+ }
+ HostedTermsRepository.ScopeSnapshot scope = repository.lockScope(scopeId);
+ HostedTermsCatalogVersion current = scope.current();
+ if (current == null || current.effectiveAt().isAfter(scope.databaseNow().toInstant())) {
+ throw new IllegalStateException("No operative hosted terms version is available");
+ }
+ Instant validUntil = null;
+ HostedTermsCatalogVersion disclosedDeadline = null;
+ HostedTermsRepository.PublicationOperation pending = scope.unsettledPublication();
+ if (pending != null) {
+ HostedTermsCatalogVersion next = repository.readCandidate(pending);
+ validUntil = next.effectiveAt();
+ disclosedDeadline = next;
+ if (pending.status() == HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT
+ || !next.effectiveAt().isAfter(scope.databaseNow().toInstant())) {
+ throw new IllegalStateException(
+ "Disclosed hosted-terms effective date has arrived; currentness is unavailable until owner settlement");
+ }
+ }
+ IndividualHostedTermsAcceptance acceptance =
+ repository
+ .readCurrentAcceptance(partyId, scopeId, current)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "No current affirmative party-wide hosted terms acceptance"));
+ byte[] currentParty = HostedTermsEncoding.individualParty(party);
+ if (!acceptance.accountId().equals(accountId)
+ || !acceptance.creatorPartyId().equals(partyId)
+ || !acceptance.hostedScopeId().equals(scopeId)
+ || !Arrays.equals(acceptance.individualPartySource(), currentParty)
+ || !CreatorPartyEncoding.digest(currentParty)
+ .equals(acceptance.individualPartySourceDigest())
+ || acceptance.materialGeneration() != current.materialGeneration()
+ || !acceptance.operatorLegalIdentity().equals(current.operatorLegalIdentity())
+ || acceptance.operatorIdentityVersion() != current.operatorIdentityVersion()) {
+ throw new IllegalStateException(
+ "Acceptance or individual identity source is stale or changed");
+ }
+ byte[] exactCurrentnessSource =
+ HostedTermsEncoding.currentnessSource(current, acceptance, disclosedDeadline);
+ return new CurrentnessEvidence(
+ scopeId,
+ partyId,
+ accountId,
+ current.versionId(),
+ current.documentDigest(),
+ current.operatorLegalIdentity(),
+ current.operatorIdentityVersion(),
+ current.sourceVersion(),
+ current.materialGeneration(),
+ acceptance.evidenceId(),
+ acceptance.termsVersionId(),
+ acceptance.documentDigest(),
+ validUntil,
+ disclosedDeadline,
+ exactCurrentnessSource);
+ }
+
+ private void requireOwnVerifiedIndividual(
+ AcceptanceAction action, IndividualCreatorPartySource party) {
+ if (!party.creatorPartyId().equals(action.creatorPartyId())
+ || !party.accountId().equals(action.accountId())
+ || party.verificationStatus() != VerificationStatus.VERIFIED) {
+ throw new IllegalStateException(
+ "Only the authenticated owner of their own locally verified individual party may accept");
+ }
+ }
+
+ private DraftAuthorizationFenceRepository.SourceChange sourceChange(
+ UUID changeId, HostedTermsCatalogVersion prior, HostedTermsCatalogVersion next) {
+ SourceEvidence source =
+ new SourceEvidence(
+ SourceKind.HOSTED_TERMS,
+ prior.hostedScopeId().toString(),
+ Long.toString(prior.materialGeneration()),
+ Long.toString(prior.sourceVersion()),
+ null,
+ null,
+ HostedTermsEncoding.catalog(prior));
+ return new DraftAuthorizationFenceRepository.SourceChange(
+ changeId, List.of(source), HostedTermsEncoding.catalog(next));
+ }
+
+ private PublicationResult result(
+ HostedTermsRepository.PublicationStatus status, HostedTermsCatalogVersion candidate) {
+ return new PublicationResult(status, candidate, HostedTermsEncoding.catalog(candidate));
+ }
+
+ private PublicationResult result(
+ HostedTermsRepository.PublicationOperation operation, HostedTermsCatalogVersion candidate) {
+ return result(operation.status(), candidate);
+ }
+
+ public interface OperatorPublicationAuthority {
+ PublicationEvidence resolve(UUID stableRequestId);
+ }
+
+ public interface IndividualAcceptanceAuthority {
+ AcceptanceAction resolve(UUID stableActionRequestId);
+ }
+
+ /** Authenticated owner handoff; the result is obtained before any Account DB lock is taken. */
+ public interface EnvironmentBindingPublicationAuthority {
+ HostedTermsEnvironmentBinding.PublicationEvidence resolve(UUID stableRequestId);
+ }
+
+ /** Current official boundary source; no boundary identifier is accepted from the caller. */
+ public interface CurrentEnvironmentBoundaryAuthority {
+ HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary currentBoundary();
+ }
+
+ /** Typed result of an independently trusted operator publication/audit owner. */
+ public record PublicationEvidence(
+ UUID hostedScopeId,
+ String operatorLegalIdentity,
+ long operatorIdentityVersion,
+ byte[] documentBytes,
+ HostedTermsCatalogVersion.Materiality materiality,
+ String materialityEvidenceReference,
+ Long materialityEvidenceVersion,
+ String publicationEvidenceReference,
+ long publicationEvidenceVersion,
+ String noticeEvidenceReference,
+ long noticeEvidenceVersion,
+ Instant effectiveAt) {
+ public PublicationEvidence {
+ HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope");
+ operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048);
+ if (operatorIdentityVersion <= 0) {
+ throw new IllegalArgumentException("Positive exact operator identity version required");
+ }
+ documentBytes = HostedTermsEncoding.requireDocument(documentBytes);
+ Objects.requireNonNull(materiality, "audited materiality classification is required");
+ if (materiality == HostedTermsCatalogVersion.Materiality.INITIAL) {
+ if (materialityEvidenceReference != null || materialityEvidenceVersion != null) {
+ throw new IllegalArgumentException(
+ "Initial catalog birth has no fabricated materiality predecessor");
+ }
+ } else {
+ materialityEvidenceReference =
+ HostedTermsEncoding.requireText(materialityEvidenceReference, 512);
+ if (materialityEvidenceVersion == null || materialityEvidenceVersion <= 0) {
+ throw new IllegalArgumentException(
+ "Audited materiality evidence requires a positive version");
+ }
+ }
+ publicationEvidenceReference =
+ HostedTermsEncoding.requireText(publicationEvidenceReference, 512);
+ noticeEvidenceReference = HostedTermsEncoding.requireText(noticeEvidenceReference, 512);
+ if (publicationEvidenceVersion <= 0 || noticeEvidenceVersion <= 0) {
+ throw new IllegalArgumentException(
+ "Publication and notice evidence versions must be positive");
+ }
+ Objects.requireNonNull(effectiveAt, "explicit disclosed effective instant is required");
+ if (effectiveAt.getNano() % 1_000 != 0) {
+ throw new IllegalArgumentException(
+ "Disclosed effective instant must preserve PostgreSQL microsecond precision");
+ }
+ }
+
+ @Override
+ public byte[] documentBytes() {
+ return documentBytes.clone();
+ }
+ }
+
+ /** Typed action returned only by an authenticated individual-action owner. */
+ public record AcceptanceAction(
+ UUID actionRequestId,
+ boolean affirmative,
+ UUID accountId,
+ UUID creatorPartyId,
+ UUID hostedScopeId,
+ UUID shownVersionId,
+ String shownDocumentDigest,
+ String shownOperatorLegalIdentity,
+ long shownOperatorIdentityVersion,
+ String authenticatedActionReference,
+ long authenticatedActionVersion,
+ OffsetDateTime actionCreatedAt) {
+ public AcceptanceAction {
+ HostedTermsEncoding.requireUuid(actionRequestId, "acceptance action request");
+ HostedTermsEncoding.requireUuid(accountId, "authenticated Account");
+ HostedTermsEncoding.requireUuid(creatorPartyId, "authenticated creator party");
+ HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope");
+ HostedTermsEncoding.requireUuid(shownVersionId, "shown catalog version");
+ shownDocumentDigest = HostedTermsEncoding.requireDigest(shownDocumentDigest);
+ shownOperatorLegalIdentity =
+ HostedTermsEncoding.requireText(shownOperatorLegalIdentity, 2048);
+ if (shownOperatorIdentityVersion <= 0 || authenticatedActionVersion <= 0) {
+ throw new IllegalArgumentException(
+ "Positive shown operator and action evidence versions required");
+ }
+ authenticatedActionReference =
+ HostedTermsEncoding.requireText(authenticatedActionReference, 512);
+ Objects.requireNonNull(actionCreatedAt, "trusted action evidence time is required");
+ }
+ }
+
+ public record PublicationResult(
+ HostedTermsRepository.PublicationStatus status,
+ HostedTermsCatalogVersion candidate,
+ byte[] exactCandidateEvidence) {
+ public PublicationResult {
+ Objects.requireNonNull(status);
+ Objects.requireNonNull(candidate);
+ exactCandidateEvidence = HostedTermsEncoding.requireBytes(exactCandidateEvidence);
+ if (!Arrays.equals(exactCandidateEvidence, HostedTermsEncoding.catalog(candidate))) {
+ throw new IllegalArgumentException(
+ "Publication result differs from exact immutable catalog");
+ }
+ }
+
+ @Override
+ public byte[] exactCandidateEvidence() {
+ return exactCandidateEvidence.clone();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof PublicationResult that
+ && status == that.status
+ && candidate.equals(that.candidate)
+ && Arrays.equals(exactCandidateEvidence, that.exactCandidateEvidence);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(status, candidate, Arrays.hashCode(exactCandidateEvidence));
+ }
+ }
+
+ /** Immutable binding receipt result; PENDING_OWNER_SETTLEMENT is never current permission. */
+ public record EnvironmentBindingPublicationResult(
+ HostedTermsEnvironmentBindingRepository.PublicationStatus status,
+ HostedTermsEnvironmentBinding candidate,
+ byte[] exactReceipt) {
+ public EnvironmentBindingPublicationResult {
+ Objects.requireNonNull(status);
+ Objects.requireNonNull(candidate);
+ exactReceipt = HostedTermsEncoding.requireBytes(exactReceipt);
+ if (!Arrays.equals(exactReceipt, HostedTermsEnvironmentBindingEncoding.receipt(candidate))) {
+ throw new IllegalArgumentException("Binding result differs from exact immutable receipt");
+ }
+ }
+
+ @Override
+ public byte[] exactReceipt() {
+ return exactReceipt.clone();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof EnvironmentBindingPublicationResult that
+ && status == that.status
+ && candidate.equals(that.candidate)
+ && Arrays.equals(exactReceipt, that.exactReceipt);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(status, candidate, Arrays.hashCode(exactReceipt));
+ }
+ }
+
+ /** Combined currentness and exact independent source vector; not a Game Design commit token. */
+ public record EnvironmentBoundCurrentness(
+ HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment,
+ HostedTermsEnvironmentBinding binding,
+ CurrentnessEvidence terms,
+ List sourceEvidence) {
+ public EnvironmentBoundCurrentness {
+ Objects.requireNonNull(environment);
+ Objects.requireNonNull(binding);
+ Objects.requireNonNull(terms);
+ sourceEvidence =
+ List.copyOf(Objects.requireNonNull(sourceEvidence)).stream()
+ .sorted(Comparator.comparing(SourceEvidence::key))
+ .toList();
+ if (!environment.environmentBoundary().equals(binding.environmentBoundary())
+ || !terms.hostedScopeId().equals(binding.hostedScopeId())
+ || !terms.currentVersionId().equals(binding.catalogVersionId())
+ || terms.sourceVersion() != binding.catalogSourceVersion()
+ || !terms.operatorLegalIdentity().equals(binding.operatorLegalIdentity())
+ || terms.operatorIdentityVersion() != binding.operatorIdentityVersion()) {
+ throw new IllegalArgumentException(
+ "Environment binding, current catalog and party acceptance do not agree");
+ }
+ if (sourceEvidence.size() != 3
+ || sourceEvidence.stream().map(SourceEvidence::key).distinct().count() != 3
+ || sourceEvidence.stream()
+ .noneMatch(
+ source ->
+ source.key().equals(binding.sourceEvidence().key())
+ && Arrays.equals(
+ source.canonicalBytes(), binding.sourceEvidence().canonicalBytes()))
+ || sourceEvidence.stream()
+ .noneMatch(
+ source ->
+ source.kind() == SourceKind.HOSTED_TERMS
+ && source.scopeId().equals(terms.hostedScopeId().toString())
+ && Objects.equals(
+ source.generation(), Long.toString(terms.materialGeneration()))
+ && source.sourceVersion().equals(Long.toString(terms.sourceVersion()))
+ && Arrays.equals(source.evidence(), terms.exactCurrentnessSource()))
+ || sourceEvidence.stream()
+ .noneMatch(
+ source ->
+ source.kind() == SourceKind.CREATOR_PARTY
+ && source.scopeId().equals(terms.creatorPartyId().toString())
+ && source.generation() != null
+ && source.sourceVersion() != null)) {
+ throw new IllegalArgumentException(
+ "Bound currentness must retain exact binding, catalog/acceptance and party sources");
+ }
+ }
+
+ public List sourceEvidence() {
+ return List.copyOf(sourceEvidence);
+ }
+ }
+
+ /** Not an owner commit token; deadline must be rechecked at consumer commit linearization. */
+ public record CurrentnessEvidence(
+ UUID hostedScopeId,
+ UUID creatorPartyId,
+ UUID accountId,
+ UUID currentVersionId,
+ String currentDocumentDigest,
+ String operatorLegalIdentity,
+ long operatorIdentityVersion,
+ long sourceVersion,
+ long materialGeneration,
+ UUID acceptanceEvidenceId,
+ UUID acceptedVersionId,
+ String acceptedDocumentDigest,
+ Instant validUntil,
+ HostedTermsCatalogVersion disclosedDeadline,
+ byte[] exactCurrentnessSource) {
+ public CurrentnessEvidence {
+ HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope");
+ HostedTermsEncoding.requireUuid(creatorPartyId, "creator party");
+ HostedTermsEncoding.requireUuid(accountId, "party-owning Account");
+ HostedTermsEncoding.requireUuid(currentVersionId, "current terms version");
+ currentDocumentDigest = HostedTermsEncoding.requireDigest(currentDocumentDigest);
+ operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048);
+ HostedTermsEncoding.requireUuid(acceptanceEvidenceId, "acceptance evidence");
+ HostedTermsEncoding.requireUuid(acceptedVersionId, "accepted terms version");
+ acceptedDocumentDigest = HostedTermsEncoding.requireDigest(acceptedDocumentDigest);
+ exactCurrentnessSource = HostedTermsEncoding.requireBytes(exactCurrentnessSource);
+ if (operatorIdentityVersion <= 0 || sourceVersion <= 0 || materialGeneration <= 0) {
+ throw new IllegalArgumentException("Positive current hosted terms source required");
+ }
+ if ((validUntil == null) != (disclosedDeadline == null)
+ || (disclosedDeadline != null
+ && (!validUntil.equals(disclosedDeadline.effectiveAt())
+ || !disclosedDeadline.hostedScopeId().equals(hostedScopeId)))) {
+ throw new IllegalArgumentException(
+ "Disclosed deadline time and exact immutable catalog evidence must agree");
+ }
+ }
+
+ @Override
+ public byte[] exactCurrentnessSource() {
+ return exactCurrentnessSource.clone();
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsCatalogVersion.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsCatalogVersion.java
new file mode 100644
index 0000000000..0523a33f6e
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsCatalogVersion.java
@@ -0,0 +1,144 @@
+package net.firedevops.firemud.accountservice.hostedterms;
+
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.UUID;
+
+/**
+ * Immutable Account-owned document and source version; publication is not proof of legal review.
+ */
+public record HostedTermsCatalogVersion(
+ UUID versionId,
+ UUID hostedScopeId,
+ UUID predecessorVersionId,
+ String operatorLegalIdentity,
+ long operatorIdentityVersion,
+ byte[] documentBytes,
+ String documentDigest,
+ long sourceVersion,
+ long materialGeneration,
+ Materiality materiality,
+ String materialityEvidenceReference,
+ Long materialityEvidenceVersion,
+ String publicationEvidenceReference,
+ long publicationEvidenceVersion,
+ String noticeEvidenceReference,
+ long noticeEvidenceVersion,
+ Instant effectiveAt) {
+
+ public enum Materiality {
+ INITIAL,
+ MATERIAL,
+ NONMATERIAL
+ }
+
+ public HostedTermsCatalogVersion {
+ HostedTermsEncoding.requireUuid(versionId, "terms version");
+ HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope");
+ if (predecessorVersionId != null) {
+ HostedTermsEncoding.requireUuid(predecessorVersionId, "predecessor version");
+ }
+ operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048);
+ if (operatorIdentityVersion <= 0 || sourceVersion <= 0 || materialGeneration <= 0) {
+ throw new IllegalArgumentException(
+ "Positive independent source and identity versions required");
+ }
+ documentBytes = HostedTermsEncoding.requireDocument(documentBytes);
+ documentDigest = HostedTermsEncoding.requireDigest(documentDigest);
+ if (!HostedTermsEncoding.digest(documentBytes).equals(documentDigest)) {
+ throw new IllegalArgumentException(
+ "Document digest must bind the exact stored document bytes");
+ }
+ Objects.requireNonNull(materiality, "materiality classification is required");
+ Objects.requireNonNull(effectiveAt, "disclosed effective instant is required");
+ if (effectiveAt.getNano() % 1_000 != 0) {
+ throw new IllegalArgumentException(
+ "Effective instant must preserve PostgreSQL microsecond precision");
+ }
+ publicationEvidenceReference =
+ HostedTermsEncoding.requireText(publicationEvidenceReference, 512);
+ if (publicationEvidenceVersion <= 0) {
+ throw new IllegalArgumentException("Positive publication evidence version required");
+ }
+ noticeEvidenceReference = HostedTermsEncoding.requireText(noticeEvidenceReference, 512);
+ if (noticeEvidenceVersion <= 0) {
+ throw new IllegalArgumentException("Positive disclosed-notice evidence version required");
+ }
+ if (predecessorVersionId == null) {
+ if (materiality != Materiality.INITIAL
+ || sourceVersion != 1
+ || materialGeneration != 1
+ || materialityEvidenceReference != null
+ || materialityEvidenceVersion != null) {
+ throw new IllegalArgumentException(
+ "Initial catalog birth cannot fabricate predecessor state");
+ }
+ } else {
+ materialityEvidenceReference =
+ HostedTermsEncoding.requireText(materialityEvidenceReference, 512);
+ if (materialityEvidenceVersion == null
+ || materialityEvidenceVersion <= 0
+ || materiality == Materiality.INITIAL) {
+ throw new IllegalArgumentException("Audited materiality classification is required");
+ }
+ }
+ }
+
+ @Override
+ public byte[] documentBytes() {
+ return documentBytes.clone();
+ }
+
+ public boolean hasOperatorIdentityOf(HostedTermsCatalogVersion other) {
+ return other != null
+ && operatorIdentityVersion == other.operatorIdentityVersion
+ && operatorLegalIdentity.equals(other.operatorLegalIdentity);
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof HostedTermsCatalogVersion that)) {
+ return false;
+ }
+ return versionId.equals(that.versionId)
+ && hostedScopeId.equals(that.hostedScopeId)
+ && Objects.equals(predecessorVersionId, that.predecessorVersionId)
+ && operatorLegalIdentity.equals(that.operatorLegalIdentity)
+ && operatorIdentityVersion == that.operatorIdentityVersion
+ && Arrays.equals(documentBytes, that.documentBytes)
+ && documentDigest.equals(that.documentDigest)
+ && sourceVersion == that.sourceVersion
+ && materialGeneration == that.materialGeneration
+ && materiality == that.materiality
+ && Objects.equals(materialityEvidenceReference, that.materialityEvidenceReference)
+ && Objects.equals(materialityEvidenceVersion, that.materialityEvidenceVersion)
+ && publicationEvidenceReference.equals(that.publicationEvidenceReference)
+ && publicationEvidenceVersion == that.publicationEvidenceVersion
+ && noticeEvidenceReference.equals(that.noticeEvidenceReference)
+ && noticeEvidenceVersion == that.noticeEvidenceVersion
+ && effectiveAt.equals(that.effectiveAt);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(
+ versionId,
+ hostedScopeId,
+ predecessorVersionId,
+ operatorLegalIdentity,
+ operatorIdentityVersion,
+ Arrays.hashCode(documentBytes),
+ documentDigest,
+ sourceVersion,
+ materialGeneration,
+ materiality,
+ materialityEvidenceReference,
+ materialityEvidenceVersion,
+ publicationEvidenceReference,
+ publicationEvidenceVersion,
+ noticeEvidenceReference,
+ noticeEvidenceVersion,
+ effectiveAt);
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java
new file mode 100644
index 0000000000..c74a8d55c4
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java
@@ -0,0 +1,248 @@
+package net.firedevops.firemud.accountservice.hostedterms;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding;
+import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import tools.jackson.databind.json.JsonMapper;
+
+/** Exact closed encodings for Account-owned hosted terms, publication requests and acceptance. */
+public final class HostedTermsEncoding {
+ private HostedTermsEncoding() {}
+
+ public static byte[] publication(
+ UUID requestId, AccountHostedTermsService.PublicationEvidence publication) {
+ requireUuid(requestId, "publication request");
+ Objects.requireNonNull(publication);
+ Map fields = new LinkedHashMap<>();
+ fields.put("schema", "account-hosted-terms-publication/v1");
+ fields.put("requestId", requestId.toString());
+ fields.put("hostedScopeId", publication.hostedScopeId().toString());
+ fields.put("operatorLegalIdentity", publication.operatorLegalIdentity());
+ fields.put("operatorIdentityVersion", Long.toString(publication.operatorIdentityVersion()));
+ fields.put("document", Base64.getEncoder().encodeToString(publication.documentBytes()));
+ fields.put("documentDigest", digest(publication.documentBytes()));
+ fields.put("materiality", publication.materiality().name());
+ fields.put("materialityEvidenceReference", publication.materialityEvidenceReference());
+ fields.put(
+ "materialityEvidenceVersion",
+ publication.materialityEvidenceVersion() == null
+ ? null
+ : publication.materialityEvidenceVersion().toString());
+ fields.put("publicationEvidenceReference", publication.publicationEvidenceReference());
+ fields.put(
+ "publicationEvidenceVersion", Long.toString(publication.publicationEvidenceVersion()));
+ fields.put("noticeEvidenceReference", publication.noticeEvidenceReference());
+ fields.put("noticeEvidenceVersion", Long.toString(publication.noticeEvidenceVersion()));
+ fields.put("effectiveAt", publication.effectiveAt().toString());
+ return canonical(fields);
+ }
+
+ public static byte[] catalog(HostedTermsCatalogVersion version) {
+ Objects.requireNonNull(version);
+ Map fields = new LinkedHashMap<>();
+ fields.put("schema", "account-hosted-terms-catalog-version/v1");
+ fields.put("versionId", version.versionId().toString());
+ fields.put("hostedScopeId", version.hostedScopeId().toString());
+ fields.put(
+ "predecessorVersionId",
+ version.predecessorVersionId() == null ? null : version.predecessorVersionId().toString());
+ fields.put("operatorLegalIdentity", version.operatorLegalIdentity());
+ fields.put("operatorIdentityVersion", Long.toString(version.operatorIdentityVersion()));
+ fields.put("document", Base64.getEncoder().encodeToString(version.documentBytes()));
+ fields.put("documentDigest", version.documentDigest());
+ fields.put("sourceVersion", Long.toString(version.sourceVersion()));
+ fields.put("materialGeneration", Long.toString(version.materialGeneration()));
+ fields.put("materiality", version.materiality().name());
+ fields.put("materialityEvidenceReference", version.materialityEvidenceReference());
+ fields.put(
+ "materialityEvidenceVersion",
+ version.materialityEvidenceVersion() == null
+ ? null
+ : version.materialityEvidenceVersion().toString());
+ fields.put("publicationEvidenceReference", version.publicationEvidenceReference());
+ fields.put("publicationEvidenceVersion", Long.toString(version.publicationEvidenceVersion()));
+ fields.put("noticeEvidenceReference", version.noticeEvidenceReference());
+ fields.put("noticeEvidenceVersion", Long.toString(version.noticeEvidenceVersion()));
+ fields.put("effectiveAt", version.effectiveAt().toString());
+ return canonical(fields);
+ }
+
+ public static byte[] individualParty(IndividualCreatorPartySource source) {
+ return CreatorPartyEncoding.party(Objects.requireNonNull(source));
+ }
+
+ public static byte[] affirmativeAction(AccountHostedTermsService.AcceptanceAction action) {
+ Objects.requireNonNull(action);
+ Map fields = new LinkedHashMap<>();
+ fields.put("schema", "account-hosted-terms-affirmative-action/v1");
+ fields.put("actionRequestId", action.actionRequestId().toString());
+ fields.put("affirmative", Boolean.toString(action.affirmative()));
+ fields.put("accountId", action.accountId().toString());
+ fields.put("creatorPartyId", action.creatorPartyId().toString());
+ fields.put("hostedScopeId", action.hostedScopeId().toString());
+ fields.put("shownVersionId", action.shownVersionId().toString());
+ fields.put("shownDocumentDigest", action.shownDocumentDigest());
+ fields.put("shownOperatorLegalIdentity", action.shownOperatorLegalIdentity());
+ fields.put(
+ "shownOperatorIdentityVersion", Long.toString(action.shownOperatorIdentityVersion()));
+ fields.put("authenticatedActionReference", action.authenticatedActionReference());
+ fields.put("authenticatedActionVersion", Long.toString(action.authenticatedActionVersion()));
+ fields.put("createdAt", action.actionCreatedAt().toString());
+ return canonical(fields);
+ }
+
+ public static byte[] acceptance(IndividualHostedTermsAcceptance acceptance) {
+ Objects.requireNonNull(acceptance);
+ Map fields = new LinkedHashMap<>();
+ fields.put("schema", "account-individual-hosted-terms-acceptance/v1");
+ fields.put("evidenceId", acceptance.evidenceId().toString());
+ fields.put("actionRequestId", acceptance.actionRequestId().toString());
+ fields.put("creatorPartyId", acceptance.creatorPartyId().toString());
+ fields.put("accountId", acceptance.accountId().toString());
+ fields.put("hostedScopeId", acceptance.hostedScopeId().toString());
+ fields.put("termsVersionId", acceptance.termsVersionId().toString());
+ fields.put("documentDigest", acceptance.documentDigest());
+ fields.put("operatorLegalIdentity", acceptance.operatorLegalIdentity());
+ fields.put("operatorIdentityVersion", Long.toString(acceptance.operatorIdentityVersion()));
+ fields.put("sourceVersion", Long.toString(acceptance.sourceVersion()));
+ fields.put("materialGeneration", Long.toString(acceptance.materialGeneration()));
+ fields.put(
+ "individualPartySource",
+ Base64.getEncoder().encodeToString(acceptance.individualPartySource()));
+ fields.put("individualPartySourceDigest", acceptance.individualPartySourceDigest());
+ fields.put(
+ "affirmativeActionEvidence",
+ Base64.getEncoder().encodeToString(acceptance.affirmativeActionEvidence()));
+ fields.put("affirmativeActionDigest", acceptance.affirmativeActionDigest());
+ fields.put("acceptedAt", acceptance.acceptedAt().toString());
+ return canonical(fields);
+ }
+
+ /** Exact hosted source bytes include the catalog head and the affirmative acceptance receipt. */
+ public static byte[] currentnessSource(
+ HostedTermsCatalogVersion catalog, IndividualHostedTermsAcceptance acceptance) {
+ return currentnessSource(catalog, acceptance, null);
+ }
+
+ /**
+ * Exact currentness source also retains any disclosed future catalog and its immutable deadline.
+ */
+ public static byte[] currentnessSource(
+ HostedTermsCatalogVersion catalog,
+ IndividualHostedTermsAcceptance acceptance,
+ HostedTermsCatalogVersion disclosedDeadline) {
+ Objects.requireNonNull(catalog);
+ Objects.requireNonNull(acceptance);
+ if (!catalog.hostedScopeId().equals(acceptance.hostedScopeId())
+ || catalog.materialGeneration() != acceptance.materialGeneration()
+ || !catalog.operatorLegalIdentity().equals(acceptance.operatorLegalIdentity())
+ || catalog.operatorIdentityVersion() != acceptance.operatorIdentityVersion()) {
+ throw new IllegalArgumentException(
+ "Currentness source requires one exact catalog and affirmative acceptance");
+ }
+ if (disclosedDeadline != null) {
+ long expectedGeneration =
+ Math.addExact(
+ catalog.materialGeneration(),
+ disclosedDeadline.materiality() == HostedTermsCatalogVersion.Materiality.MATERIAL
+ ? 1
+ : 0);
+ if (!catalog.hostedScopeId().equals(disclosedDeadline.hostedScopeId())
+ || !Objects.equals(disclosedDeadline.predecessorVersionId(), catalog.versionId())
+ || disclosedDeadline.sourceVersion() != Math.addExact(catalog.sourceVersion(), 1)
+ || disclosedDeadline.materialGeneration() != expectedGeneration
+ || (disclosedDeadline.materiality() != HostedTermsCatalogVersion.Materiality.MATERIAL
+ && !disclosedDeadline.hasOperatorIdentityOf(catalog))
+ || !disclosedDeadline.effectiveAt().isAfter(catalog.effectiveAt())) {
+ throw new IllegalArgumentException(
+ "Disclosed deadline must be the exact immutable next catalog version");
+ }
+ }
+ byte[] catalogBytes = catalog(catalog);
+ byte[] acceptanceBytes = acceptance(acceptance);
+ Map fields = new LinkedHashMap<>();
+ fields.put("schema", "account-hosted-terms-currentness-source/v2");
+ fields.put("hostedScopeId", catalog.hostedScopeId().toString());
+ fields.put("catalog", Base64.getEncoder().encodeToString(catalogBytes));
+ fields.put("catalogDigest", digest(catalogBytes));
+ fields.put("acceptance", Base64.getEncoder().encodeToString(acceptanceBytes));
+ fields.put("acceptanceDigest", digest(acceptanceBytes));
+ byte[] deadlineBytes = disclosedDeadline == null ? null : catalog(disclosedDeadline);
+ fields.put(
+ "disclosedDeadlineCatalog",
+ deadlineBytes == null ? null : Base64.getEncoder().encodeToString(deadlineBytes));
+ fields.put(
+ "disclosedDeadlineCatalogDigest", deadlineBytes == null ? null : digest(deadlineBytes));
+ return canonical(fields);
+ }
+
+ public static String digest(byte[] bytes) {
+ Objects.requireNonNull(bytes);
+ try {
+ return "sha256:"
+ + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException("SHA-256 is required", impossible);
+ }
+ }
+
+ public static UUID requireUuid(UUID value, String description) {
+ if (value == null || value.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException("Canonical nonnil " + description + " UUID is required");
+ }
+ return value;
+ }
+
+ public static byte[] requireDocument(byte[] value) {
+ return requireBytes(value);
+ }
+
+ public static byte[] requireBytes(byte[] value) {
+ if (value == null || value.length == 0) {
+ throw new IllegalArgumentException("Nonempty exact evidence bytes are required");
+ }
+ return value.clone();
+ }
+
+ public static String requireText(String value, int maxUtf8Bytes) {
+ if (value == null
+ || value.isBlank()
+ || value.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes) {
+ throw new IllegalArgumentException("Required exact reference or identity text is invalid");
+ }
+ return value;
+ }
+
+ public static String requireDigest(String value) {
+ if (value == null || !value.matches("sha256:[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Canonical SHA-256 digest is required");
+ }
+ return value;
+ }
+
+ public static long requirePositive(long value, String description) {
+ if (value <= 0) {
+ throw new IllegalArgumentException("Positive " + description + " is required");
+ }
+ return value;
+ }
+
+ private static byte[] canonical(Map fields) {
+ try {
+ return Rfc8785CanonicalJson.canonicalizeUtf8(
+ JsonMapper.builder().build().writeValueAsString(fields));
+ } catch (IOException failure) {
+ throw new IllegalArgumentException("Hosted-terms evidence cannot be encoded", failure);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBinding.java
new file mode 100644
index 0000000000..c00e5507fd
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBinding.java
@@ -0,0 +1,147 @@
+package net.firedevops.firemud.accountservice.hostedterms;
+
+import java.util.UUID;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+
+/**
+ * Immutable Account receipt binding one canonical environment boundary to an exact hosted terms
+ * source. This is owner evidence only; it does not establish production publisher custody.
+ */
+public record HostedTermsEnvironmentBinding(
+ UUID bindingId,
+ UUID publicationRequestId,
+ String environmentBoundary,
+ UUID hostedScopeId,
+ String operatorLegalIdentity,
+ long operatorIdentityVersion,
+ UUID catalogVersionId,
+ long catalogSourceVersion,
+ String authenticatedPublisherIdentity,
+ String publicationEventIdentity,
+ String publicationEvidenceDigest,
+ UUID predecessorBindingId,
+ Long predecessorSourceVersion,
+ long sourceVersion) {
+
+ public HostedTermsEnvironmentBinding {
+ HostedTermsEncoding.requireUuid(bindingId, "environment-binding receipt");
+ HostedTermsEncoding.requireUuid(
+ publicationRequestId, "environment-binding publication request");
+ environmentBoundary = requireBoundary(environmentBoundary);
+ HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope");
+ operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048);
+ HostedTermsEncoding.requirePositive(operatorIdentityVersion, "operator identity version");
+ HostedTermsEncoding.requireUuid(catalogVersionId, "catalog version");
+ HostedTermsEncoding.requirePositive(catalogSourceVersion, "catalog source version");
+ authenticatedPublisherIdentity =
+ HostedTermsEncoding.requireText(authenticatedPublisherIdentity, 512);
+ publicationEventIdentity = HostedTermsEncoding.requireText(publicationEventIdentity, 512);
+ publicationEvidenceDigest = HostedTermsEncoding.requireDigest(publicationEvidenceDigest);
+ if ((predecessorBindingId == null) != (predecessorSourceVersion == null)) {
+ throw new IllegalArgumentException(
+ "Binding predecessor identity and source version must be present together");
+ }
+ if (predecessorBindingId == null) {
+ if (sourceVersion != 1) {
+ throw new IllegalArgumentException(
+ "Initial environment binding cannot fabricate a predecessor source");
+ }
+ } else {
+ HostedTermsEncoding.requireUuid(predecessorBindingId, "predecessor binding");
+ HostedTermsEncoding.requirePositive(predecessorSourceVersion, "predecessor source version");
+ if (sourceVersion != Math.addExact(predecessorSourceVersion, 1)) {
+ throw new IllegalArgumentException(
+ "Environment binding source must advance from its exact predecessor");
+ }
+ }
+ HostedTermsEncoding.requirePositive(sourceVersion, "environment binding source version");
+ }
+
+ /**
+ * Exact independent fence key for this environment mapping. Its namespace is disjoint from the
+ * UUID hosted-scope key; its sourceVersion is the binding counter, not catalog materiality.
+ */
+ public String sourceScopeId() {
+ return "environment-boundary/" + environmentBoundary;
+ }
+
+ public SourceEvidence sourceEvidence() {
+ byte[] bytes = HostedTermsEnvironmentBindingEncoding.receipt(this);
+ return new SourceEvidence(
+ SourceKind.HOSTED_TERMS,
+ sourceScopeId(),
+ null,
+ Long.toString(sourceVersion),
+ null,
+ null,
+ bytes);
+ }
+
+ /**
+ * Exact result supplied by the trusted environment/secrets owner outside the Account transaction.
+ * The Account workflow separately checks it against the current local catalog and binding head.
+ */
+ public record PublicationEvidence(
+ String environmentBoundary,
+ UUID hostedScopeId,
+ String operatorLegalIdentity,
+ long operatorIdentityVersion,
+ UUID catalogVersionId,
+ long catalogSourceVersion,
+ String authenticatedPublisherIdentity,
+ String publicationEventIdentity,
+ UUID predecessorBindingId,
+ Long predecessorSourceVersion) {
+ public PublicationEvidence {
+ environmentBoundary = requireBoundary(environmentBoundary);
+ HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope");
+ operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048);
+ HostedTermsEncoding.requirePositive(operatorIdentityVersion, "operator identity version");
+ HostedTermsEncoding.requireUuid(catalogVersionId, "catalog version");
+ HostedTermsEncoding.requirePositive(catalogSourceVersion, "catalog source version");
+ authenticatedPublisherIdentity =
+ HostedTermsEncoding.requireText(authenticatedPublisherIdentity, 512);
+ publicationEventIdentity = HostedTermsEncoding.requireText(publicationEventIdentity, 512);
+ if ((predecessorBindingId == null) != (predecessorSourceVersion == null)) {
+ throw new IllegalArgumentException(
+ "Binding predecessor identity and source version must be present together");
+ }
+ if (predecessorBindingId != null) {
+ HostedTermsEncoding.requireUuid(predecessorBindingId, "predecessor binding");
+ HostedTermsEncoding.requirePositive(predecessorSourceVersion, "predecessor source version");
+ }
+ }
+ }
+
+ /**
+ * Fresh canonical environment-boundary observation supplied by the trusted environment owner;
+ * callers do not select a boundary UUID or name.
+ */
+ public record CurrentEnvironmentBoundary(
+ String environmentBoundary,
+ String authenticatedOwnerIdentity,
+ String observationEventIdentity,
+ byte[] exactOwnerEvidence,
+ String ownerEvidenceDigest) {
+ public CurrentEnvironmentBoundary {
+ environmentBoundary = requireBoundary(environmentBoundary);
+ authenticatedOwnerIdentity = HostedTermsEncoding.requireText(authenticatedOwnerIdentity, 512);
+ observationEventIdentity = HostedTermsEncoding.requireText(observationEventIdentity, 512);
+ exactOwnerEvidence = HostedTermsEncoding.requireBytes(exactOwnerEvidence);
+ ownerEvidenceDigest = HostedTermsEncoding.requireDigest(ownerEvidenceDigest);
+ if (!HostedTermsEncoding.digest(exactOwnerEvidence).equals(ownerEvidenceDigest)) {
+ throw new IllegalArgumentException("Environment-owner evidence digest conflicts");
+ }
+ }
+
+ @Override
+ public byte[] exactOwnerEvidence() {
+ return exactOwnerEvidence.clone();
+ }
+ }
+
+ private static String requireBoundary(String value) {
+ return HostedTermsEncoding.requireText(value, 512);
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java
new file mode 100644
index 0000000000..c46c2052c4
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java
@@ -0,0 +1,87 @@
+package net.firedevops.firemud.accountservice.hostedterms;
+
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import tools.jackson.databind.json.JsonMapper;
+
+/** Closed canonical encodings for trusted environment-owner binding publications and receipts. */
+public final class HostedTermsEnvironmentBindingEncoding {
+ private HostedTermsEnvironmentBindingEncoding() {}
+
+ public static byte[] publication(
+ UUID requestId, HostedTermsEnvironmentBinding.PublicationEvidence evidence) {
+ HostedTermsEncoding.requireUuid(requestId, "environment binding publication request");
+ Objects.requireNonNull(evidence);
+ Map fields = new LinkedHashMap<>();
+ fields.put("schema", "account-hosted-terms-environment-binding-publication/v1");
+ fields.put("requestId", requestId.toString());
+ fields.put("environmentBoundary", evidence.environmentBoundary());
+ fields.put("hostedScopeId", evidence.hostedScopeId().toString());
+ fields.put("operatorLegalIdentity", evidence.operatorLegalIdentity());
+ fields.put("operatorIdentityVersion", Long.toString(evidence.operatorIdentityVersion()));
+ fields.put("catalogVersionId", evidence.catalogVersionId().toString());
+ fields.put("catalogSourceVersion", Long.toString(evidence.catalogSourceVersion()));
+ fields.put("authenticatedPublisherIdentity", evidence.authenticatedPublisherIdentity());
+ fields.put("publicationEventIdentity", evidence.publicationEventIdentity());
+ fields.put(
+ "predecessorBindingId",
+ evidence.predecessorBindingId() == null
+ ? null
+ : evidence.predecessorBindingId().toString());
+ fields.put(
+ "predecessorSourceVersion",
+ evidence.predecessorSourceVersion() == null
+ ? null
+ : Long.toString(evidence.predecessorSourceVersion()));
+ return canonical(fields);
+ }
+
+ public static byte[] receipt(HostedTermsEnvironmentBinding binding) {
+ Objects.requireNonNull(binding);
+ Map fields = new LinkedHashMap<>();
+ fields.put("schema", "account-hosted-terms-environment-binding-receipt/v1");
+ fields.put("bindingId", binding.bindingId().toString());
+ fields.put("publicationRequestId", binding.publicationRequestId().toString());
+ fields.put("environmentBoundary", binding.environmentBoundary());
+ fields.put("hostedScopeId", binding.hostedScopeId().toString());
+ fields.put("operatorLegalIdentity", binding.operatorLegalIdentity());
+ fields.put("operatorIdentityVersion", Long.toString(binding.operatorIdentityVersion()));
+ fields.put("catalogVersionId", binding.catalogVersionId().toString());
+ fields.put("catalogSourceVersion", Long.toString(binding.catalogSourceVersion()));
+ fields.put("authenticatedPublisherIdentity", binding.authenticatedPublisherIdentity());
+ fields.put("publicationEventIdentity", binding.publicationEventIdentity());
+ fields.put("publicationEvidenceDigest", binding.publicationEvidenceDigest());
+ fields.put(
+ "predecessorBindingId",
+ binding.predecessorBindingId() == null ? null : binding.predecessorBindingId().toString());
+ fields.put(
+ "predecessorSourceVersion",
+ binding.predecessorSourceVersion() == null
+ ? null
+ : Long.toString(binding.predecessorSourceVersion()));
+ fields.put("sourceVersion", Long.toString(binding.sourceVersion()));
+ return canonical(fields);
+ }
+
+ public static String publicationDigest(
+ UUID requestId, HostedTermsEnvironmentBinding.PublicationEvidence evidence) {
+ return HostedTermsEncoding.digest(publication(requestId, evidence));
+ }
+
+ public static String receiptDigest(HostedTermsEnvironmentBinding binding) {
+ return HostedTermsEncoding.digest(receipt(binding));
+ }
+
+ private static byte[] canonical(Map fields) {
+ try {
+ return Rfc8785CanonicalJson.canonicalizeUtf8(
+ JsonMapper.builder().build().writeValueAsString(fields));
+ } catch (IOException failure) {
+ throw new IllegalArgumentException("Environment-binding evidence cannot be encoded", failure);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java
new file mode 100644
index 0000000000..cec24c3388
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java
@@ -0,0 +1,422 @@
+package net.firedevops.firemud.accountservice.hostedterms;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.sql.Connection;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding.PublicationEvidence;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Owner-local immutable binding receipt/head and exact retry storage. */
+public final class HostedTermsEnvironmentBindingRepository {
+ private static final String HEADS = "account_hosted_terms_environment_binding_heads";
+ private static final String BINDINGS = "account_hosted_terms_environment_bindings";
+ private static final String PUBLICATIONS =
+ "account_hosted_terms_environment_binding_publications";
+ private final DSLContext dsl;
+
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification = "Owner DSLContext is retained privately and never exposed.")
+ public HostedTermsEnvironmentBindingRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl);
+ }
+
+ public enum PublicationStatus {
+ RECEIVED,
+ PENDING_OWNER_SETTLEMENT,
+ COMMITTED
+ }
+
+ public record PublicationOperation(
+ UUID requestId,
+ String environmentBoundary,
+ byte[] requestPayload,
+ String requestDigest,
+ PublicationStatus status,
+ UUID candidateBindingId,
+ byte[] sourceChangeBinding,
+ byte[] resultPayload,
+ String resultDigest) {
+ public PublicationOperation {
+ requestPayload = requestPayload.clone();
+ sourceChangeBinding = sourceChangeBinding == null ? null : sourceChangeBinding.clone();
+ resultPayload = resultPayload == null ? null : resultPayload.clone();
+ }
+
+ @Override
+ public byte[] requestPayload() {
+ return requestPayload.clone();
+ }
+
+ @Override
+ public byte[] sourceChangeBinding() {
+ return sourceChangeBinding == null ? null : sourceChangeBinding.clone();
+ }
+
+ @Override
+ public byte[] resultPayload() {
+ return resultPayload == null ? null : resultPayload.clone();
+ }
+ }
+
+ public record HeadSnapshot(
+ String environmentBoundary,
+ HostedTermsEnvironmentBinding current,
+ PublicationOperation unsettledPublication) {}
+
+ /** Creates only an empty serialization row; it does not invent a binding baseline. */
+ public void ensureHead(String environmentBoundary) {
+ requireWriteTransaction();
+ String boundary = requireBoundary(environmentBoundary);
+ if (dsl.fetchOne("SELECT 1 FROM " + HEADS + " WHERE environment_boundary = ?", boundary)
+ != null) {
+ return;
+ }
+ dsl.execute(
+ "INSERT INTO " + HEADS + " (environment_boundary) VALUES (?) ON CONFLICT DO NOTHING",
+ boundary);
+ }
+
+ /** Stable publication request identity binds every owner-authenticated field and predecessor. */
+ public PublicationOperation claimPublication(
+ UUID requestId, String environmentBoundary, byte[] exactRequestPayload) {
+ requireWriteTransaction();
+ HostedTermsEncoding.requireUuid(requestId, "environment binding publication request");
+ String boundary = requireBoundary(environmentBoundary);
+ byte[] request = HostedTermsEncoding.requireBytes(exactRequestPayload);
+ String digest = HostedTermsEncoding.digest(request);
+ dsl.execute(
+ "INSERT INTO "
+ + PUBLICATIONS
+ + " (request_id, environment_boundary, request_payload, request_digest, status) "
+ + "VALUES (?, ?, ?, ?, 'RECEIVED') ON CONFLICT (request_id) DO NOTHING",
+ requestId,
+ boundary,
+ request,
+ digest);
+ PublicationOperation stored =
+ readPublication(requestId, true)
+ .orElseThrow(
+ () -> new IllegalStateException("Binding publication intent readback is absent"));
+ if (!stored.environmentBoundary().equals(boundary)
+ || !Arrays.equals(stored.requestPayload(), request)
+ || !stored.requestDigest().equals(digest)) {
+ throw new IllegalArgumentException(
+ "Environment binding request identity conflicts with exact prior evidence");
+ }
+ return stored;
+ }
+
+ /** Locks the canonical environment head before catalog and Draft source participation locks. */
+ public HeadSnapshot lockHead(String environmentBoundary) {
+ requireWriteTransaction();
+ String boundary = requireBoundary(environmentBoundary);
+ Record head =
+ dsl.fetchOne(
+ "SELECT * FROM " + HEADS + " WHERE environment_boundary = ? FOR UPDATE", boundary);
+ if (head == null) {
+ throw new IllegalStateException("Environment binding head is unavailable");
+ }
+ UUID bindingId = head.get("current_binding_id", UUID.class);
+ Long sourceVersion = head.get("current_source_version", Long.class);
+ if ((bindingId == null) != (sourceVersion == null)) {
+ throw new IllegalStateException("Environment binding head is incomplete");
+ }
+ HostedTermsEnvironmentBinding current =
+ bindingId == null ? null : readBinding(boundary, bindingId);
+ if (current != null && current.sourceVersion() != sourceVersion) {
+ throw new IllegalStateException("Environment binding head differs from immutable history");
+ }
+ return new HeadSnapshot(boundary, current, readUnsettledPublication(boundary).orElse(null));
+ }
+
+ public Optional readPublication(UUID requestId, boolean forUpdate) {
+ requireTransaction();
+ HostedTermsEncoding.requireUuid(requestId, "environment binding publication request");
+ Record row =
+ dsl.fetchOne(
+ "SELECT * FROM "
+ + PUBLICATIONS
+ + " WHERE request_id = ?"
+ + (forUpdate ? " FOR UPDATE" : ""),
+ requestId);
+ return row == null ? Optional.empty() : Optional.of(publication(row));
+ }
+
+ public Optional readUnsettledPublication(String environmentBoundary) {
+ requireTransaction();
+ String boundary = requireBoundary(environmentBoundary);
+ Record row =
+ dsl.fetchOne(
+ "SELECT * FROM "
+ + PUBLICATIONS
+ + " WHERE environment_boundary = ? AND status IN ('RECEIVED', 'PENDING_OWNER_SETTLEMENT')"
+ + " ORDER BY requested_at, request_id LIMIT 1",
+ boundary);
+ return row == null ? Optional.empty() : Optional.of(publication(row));
+ }
+
+ public HostedTermsEnvironmentBinding readCandidate(PublicationOperation operation) {
+ requireTransaction();
+ Objects.requireNonNull(operation);
+ if (operation.candidateBindingId() == null) {
+ throw new IllegalStateException("Environment binding candidate is absent");
+ }
+ return readBinding(operation.environmentBoundary(), operation.candidateBindingId());
+ }
+
+ public HostedTermsEnvironmentBinding readBinding(String environmentBoundary, UUID bindingId) {
+ requireTransaction();
+ String boundary = requireBoundary(environmentBoundary);
+ HostedTermsEncoding.requireUuid(bindingId, "environment binding receipt");
+ Record row =
+ dsl.fetchOne(
+ "SELECT * FROM " + BINDINGS + " WHERE environment_boundary = ? AND binding_id = ?",
+ boundary,
+ bindingId);
+ if (row == null) {
+ throw new IllegalStateException("Exact environment binding receipt is unavailable");
+ }
+ HostedTermsEnvironmentBinding binding = binding(row);
+ byte[] payload = HostedTermsEnvironmentBindingEncoding.receipt(binding);
+ if (!Arrays.equals(payload, row.get("binding_payload", byte[].class))
+ || !HostedTermsEncoding.digest(payload).equals(row.get("binding_digest", String.class))) {
+ throw new IllegalStateException("Environment binding payload or digest conflicts");
+ }
+ return binding;
+ }
+
+ /** Candidate insertion follows the exact current head, and SQL independently enforces it. */
+ public HostedTermsEnvironmentBinding insertCandidate(
+ UUID bindingId,
+ UUID requestId,
+ PublicationEvidence evidence,
+ HostedTermsEnvironmentBinding predecessor) {
+ requireWriteTransaction();
+ HostedTermsEncoding.requireUuid(bindingId, "environment binding receipt");
+ HostedTermsEncoding.requireUuid(requestId, "environment binding publication request");
+ Objects.requireNonNull(evidence);
+ if (!Objects.equals(
+ evidence.predecessorBindingId(), predecessor == null ? null : predecessor.bindingId())
+ || !Objects.equals(
+ evidence.predecessorSourceVersion(),
+ predecessor == null ? null : predecessor.sourceVersion())) {
+ throw new IllegalArgumentException(
+ "Candidate must extend the exact authenticated environment predecessor");
+ }
+ byte[] request = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence);
+ long version = predecessor == null ? 1 : Math.addExact(predecessor.sourceVersion(), 1);
+ HostedTermsEnvironmentBinding binding =
+ new HostedTermsEnvironmentBinding(
+ bindingId,
+ requestId,
+ evidence.environmentBoundary(),
+ evidence.hostedScopeId(),
+ evidence.operatorLegalIdentity(),
+ evidence.operatorIdentityVersion(),
+ evidence.catalogVersionId(),
+ evidence.catalogSourceVersion(),
+ evidence.authenticatedPublisherIdentity(),
+ evidence.publicationEventIdentity(),
+ HostedTermsEncoding.digest(request),
+ predecessor == null ? null : predecessor.bindingId(),
+ predecessor == null ? null : predecessor.sourceVersion(),
+ version);
+ byte[] payload = HostedTermsEnvironmentBindingEncoding.receipt(binding);
+ dsl.execute(
+ "INSERT INTO "
+ + BINDINGS
+ + " (binding_id, publication_request_id, environment_boundary, hosted_scope_id, operator_legal_identity, "
+ + "operator_identity_version, catalog_version_id, catalog_source_version, "
+ + "authenticated_publisher_identity, publication_event_identity, "
+ + "publication_evidence_digest, predecessor_binding_id, predecessor_source_version, "
+ + "source_version, binding_payload, binding_digest) "
+ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ binding.bindingId(),
+ binding.publicationRequestId(),
+ binding.environmentBoundary(),
+ binding.hostedScopeId(),
+ binding.operatorLegalIdentity(),
+ binding.operatorIdentityVersion(),
+ binding.catalogVersionId(),
+ binding.catalogSourceVersion(),
+ binding.authenticatedPublisherIdentity(),
+ binding.publicationEventIdentity(),
+ binding.publicationEvidenceDigest(),
+ binding.predecessorBindingId(),
+ binding.predecessorSourceVersion(),
+ binding.sourceVersion(),
+ payload,
+ HostedTermsEncoding.digest(payload));
+ return readBinding(binding.environmentBoundary(), binding.bindingId());
+ }
+
+ public void markOwnerSettlementPending(
+ UUID requestId, HostedTermsEnvironmentBinding candidate, byte[] sourceChangeBinding) {
+ transitionPublication(
+ requestId,
+ candidate,
+ "PENDING_OWNER_SETTLEMENT",
+ HostedTermsEncoding.requireBytes(sourceChangeBinding));
+ }
+
+ private void transitionPublication(
+ UUID requestId,
+ HostedTermsEnvironmentBinding candidate,
+ String status,
+ byte[] sourceChangeBinding) {
+ requireWriteTransaction();
+ Objects.requireNonNull(candidate);
+ int updated =
+ dsl.execute(
+ "UPDATE "
+ + PUBLICATIONS
+ + " SET candidate_binding_id = ?, source_change_binding = ?, status = ?"
+ + " WHERE request_id = ? AND status = 'RECEIVED'",
+ candidate.bindingId(),
+ sourceChangeBinding,
+ status,
+ requestId);
+ if (updated != 1) {
+ PublicationOperation prior =
+ readPublication(requestId, true)
+ .orElseThrow(() -> new IllegalStateException("Binding publication disappeared"));
+ if (!Objects.equals(prior.candidateBindingId(), candidate.bindingId())
+ || prior.status() != PublicationStatus.valueOf(status)
+ || !Arrays.equals(prior.sourceChangeBinding(), sourceChangeBinding)) {
+ throw new IllegalStateException("Binding publication transition differs from intent");
+ }
+ }
+ }
+
+ /** Commits the head and exact result in the same transaction as Draft source settlement. */
+ public void completePublication(
+ UUID requestId,
+ HostedTermsEnvironmentBinding candidate,
+ byte[] sourceChangeBinding,
+ HostedTermsEnvironmentBinding predecessor) {
+ requireWriteTransaction();
+ Objects.requireNonNull(candidate);
+ byte[] payload = HostedTermsEnvironmentBindingEncoding.receipt(candidate);
+ int operationUpdated =
+ dsl.execute(
+ "UPDATE "
+ + PUBLICATIONS
+ + " SET candidate_binding_id = ?, source_change_binding = ?, status = 'COMMITTED', "
+ + "result_payload = ?, result_digest = ?, committed_at = clock_timestamp() "
+ + "WHERE request_id = ? AND status IN ('RECEIVED', 'PENDING_OWNER_SETTLEMENT')",
+ candidate.bindingId(),
+ sourceChangeBinding,
+ payload,
+ HostedTermsEncoding.digest(payload),
+ requestId);
+ if (operationUpdated != 1) {
+ throw new IllegalStateException("Binding publication did not commit exactly once");
+ }
+ int headUpdated =
+ dsl.execute(
+ "UPDATE "
+ + HEADS
+ + " SET current_binding_id = ?, current_source_version = ? "
+ + "WHERE environment_boundary = ? AND current_binding_id IS NOT DISTINCT FROM ? "
+ + "AND current_source_version IS NOT DISTINCT FROM ?",
+ candidate.bindingId(),
+ candidate.sourceVersion(),
+ candidate.environmentBoundary(),
+ predecessor == null ? null : predecessor.bindingId(),
+ predecessor == null ? null : predecessor.sourceVersion());
+ if (headUpdated != 1) {
+ throw new IllegalStateException("Environment binding head changed from exact predecessor");
+ }
+ }
+
+ private PublicationOperation publication(Record row) {
+ byte[] request = row.get("request_payload", byte[].class);
+ String digest = row.get("request_digest", String.class);
+ if (!HostedTermsEncoding.digest(request).equals(digest)) {
+ throw new IllegalStateException("Stored binding publication request digest conflicts");
+ }
+ PublicationOperation operation =
+ new PublicationOperation(
+ row.get("request_id", UUID.class),
+ row.get("environment_boundary", String.class),
+ request,
+ digest,
+ PublicationStatus.valueOf(row.get("status", String.class)),
+ row.get("candidate_binding_id", UUID.class),
+ row.get("source_change_binding", byte[].class),
+ row.get("result_payload", byte[].class),
+ row.get("result_digest", String.class));
+ if ((operation.candidateBindingId() == null)
+ != (operation.status() == PublicationStatus.RECEIVED)) {
+ throw new IllegalStateException("Stored binding publication candidate state conflicts");
+ }
+ if (operation.status() == PublicationStatus.COMMITTED) {
+ HostedTermsEnvironmentBinding result = readCandidate(operation);
+ if (!Arrays.equals(
+ operation.resultPayload(), HostedTermsEnvironmentBindingEncoding.receipt(result))
+ || !HostedTermsEncoding.digest(operation.resultPayload())
+ .equals(operation.resultDigest())) {
+ throw new IllegalStateException("Stored binding publication result conflicts");
+ }
+ }
+ return operation;
+ }
+
+ private HostedTermsEnvironmentBinding binding(Record row) {
+ HostedTermsEnvironmentBinding binding =
+ new HostedTermsEnvironmentBinding(
+ row.get("binding_id", UUID.class),
+ row.get("publication_request_id", UUID.class),
+ row.get("environment_boundary", String.class),
+ row.get("hosted_scope_id", UUID.class),
+ row.get("operator_legal_identity", String.class),
+ row.get("operator_identity_version", Long.class),
+ row.get("catalog_version_id", UUID.class),
+ row.get("catalog_source_version", Long.class),
+ row.get("authenticated_publisher_identity", String.class),
+ row.get("publication_event_identity", String.class),
+ row.get("publication_evidence_digest", String.class),
+ row.get("predecessor_binding_id", UUID.class),
+ row.get("predecessor_source_version", Long.class),
+ row.get("source_version", Long.class));
+ if (!binding.environmentBoundary().equals(row.get("environment_boundary", String.class))
+ || !binding.hostedScopeId().equals(row.get("hosted_scope_id", UUID.class))
+ || !Objects.equals(
+ binding.predecessorBindingId(), row.get("predecessor_binding_id", UUID.class))) {
+ throw new IllegalStateException("Environment binding columns conflict with exact receipt");
+ }
+ return binding;
+ }
+
+ private static String requireBoundary(String boundary) {
+ return HostedTermsEncoding.requireText(boundary, 512);
+ }
+
+ private void requireTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException(
+ "Environment binding repository requires an owner transaction");
+ }
+ }
+
+ private void requireWriteTransaction() {
+ requireTransaction();
+ if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException("Writable owner transaction required");
+ }
+ dsl.connection(
+ connection -> {
+ if (connection.getAutoCommit()
+ || connection.isReadOnly()
+ || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
+ throw new IllegalStateException("Writable READ_COMMITTED Account transaction required");
+ }
+ });
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java
new file mode 100644
index 0000000000..b23696c6b5
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java
@@ -0,0 +1,550 @@
+package net.firedevops.firemud.accountservice.hostedterms;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.time.OffsetDateTime;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Owner-local PostgreSQL persistence; it authenticates no publisher, signer or legal evidence. */
+public final class HostedTermsRepository {
+ private static final String SCOPES = "account_hosted_terms_scopes";
+ private static final String VERSIONS = "account_hosted_terms_catalog_versions";
+ private static final String PUBLICATIONS = "account_hosted_terms_publication_operations";
+ private static final String ACCEPTANCES = "account_individual_hosted_terms_acceptances";
+ private final DSLContext dsl;
+
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification = "The owner DSLContext is retained privately and never exposed.")
+ public HostedTermsRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl);
+ }
+
+ public enum PublicationStatus {
+ RECEIVED,
+ SCHEDULED,
+ PENDING_OWNER_SETTLEMENT,
+ COMMITTED
+ }
+
+ public record PublicationOperation(
+ UUID requestId,
+ UUID hostedScopeId,
+ byte[] requestPayload,
+ String requestDigest,
+ PublicationStatus status,
+ UUID candidateVersionId,
+ byte[] sourceChangeBinding,
+ byte[] resultPayload,
+ String resultDigest,
+ OffsetDateTime committedAt) {
+ public PublicationOperation {
+ requestPayload = requestPayload.clone();
+ sourceChangeBinding = sourceChangeBinding == null ? null : sourceChangeBinding.clone();
+ resultPayload = resultPayload == null ? null : resultPayload.clone();
+ }
+
+ @Override
+ public byte[] requestPayload() {
+ return requestPayload.clone();
+ }
+
+ @Override
+ public byte[] sourceChangeBinding() {
+ return sourceChangeBinding == null ? null : sourceChangeBinding.clone();
+ }
+
+ @Override
+ public byte[] resultPayload() {
+ return resultPayload == null ? null : resultPayload.clone();
+ }
+ }
+
+ public record ScopeSnapshot(
+ UUID hostedScopeId,
+ HostedTermsCatalogVersion current,
+ OffsetDateTime databaseNow,
+ PublicationOperation unsettledPublication) {}
+
+ /** Creates only an empty serialization row; it never seeds a catalog/source baseline. */
+ public void ensureScope(UUID scopeId) {
+ requireWriteTransaction();
+ HostedTermsEncoding.requireUuid(scopeId, "hosted scope");
+ if (dsl.fetchOne("SELECT 1 FROM " + SCOPES + " WHERE hosted_scope_id = ?", scopeId) != null) {
+ return;
+ }
+ dsl.execute(
+ "INSERT INTO " + SCOPES + " (hosted_scope_id) VALUES (?) ON CONFLICT DO NOTHING", scopeId);
+ }
+
+ /** Claims a stable request identity before scope locking, then returns its immutable intent. */
+ public PublicationOperation claimPublication(
+ UUID requestId, UUID scopeId, byte[] requestPayload) {
+ requireWriteTransaction();
+ HostedTermsEncoding.requireUuid(requestId, "publication request");
+ HostedTermsEncoding.requireUuid(scopeId, "hosted scope");
+ byte[] bytes = HostedTermsEncoding.requireBytes(requestPayload);
+ String digest = HostedTermsEncoding.digest(bytes);
+ dsl.execute(
+ "INSERT INTO "
+ + PUBLICATIONS
+ + " (request_id, hosted_scope_id, request_payload, request_digest, status)"
+ + " VALUES (?, ?, ?, ?, 'RECEIVED') ON CONFLICT (request_id) DO NOTHING",
+ requestId,
+ scopeId,
+ bytes,
+ digest);
+ PublicationOperation operation =
+ readPublication(requestId, true)
+ .orElseThrow(
+ () -> new IllegalStateException("Publication request readback is unavailable"));
+ if (!operation.hostedScopeId().equals(scopeId)
+ || !Arrays.equals(operation.requestPayload(), bytes)
+ || !operation.requestDigest().equals(digest)) {
+ throw new IllegalArgumentException(
+ "Publication request identity conflicts with prior evidence");
+ }
+ return operation;
+ }
+
+ /** Locks the canonical hosted-scope source before any sorted Draft-fence participation. */
+ public ScopeSnapshot lockScope(UUID scopeId) {
+ requireWriteTransaction();
+ HostedTermsEncoding.requireUuid(scopeId, "hosted scope");
+ Record scope =
+ dsl.fetchOne("SELECT * FROM " + SCOPES + " WHERE hosted_scope_id = ? FOR UPDATE", scopeId);
+ if (scope == null) {
+ throw new IllegalStateException("Hosted terms scope serialization row is unavailable");
+ }
+ UUID currentId = scope.get("current_version_id", UUID.class);
+ Long sourceVersion = scope.get("current_source_version", Long.class);
+ Long generation = scope.get("current_material_generation", Long.class);
+ if ((currentId == null) != (sourceVersion == null)
+ || (currentId == null) != (generation == null)) {
+ throw new IllegalStateException("Hosted terms current source is incomplete");
+ }
+ HostedTermsCatalogVersion current = currentId == null ? null : readCatalog(scopeId, currentId);
+ if (current != null
+ && (current.sourceVersion() != sourceVersion
+ || current.materialGeneration() != generation)) {
+ throw new IllegalStateException(
+ "Hosted terms scope head differs from immutable catalog evidence");
+ }
+ OffsetDateTime now = databaseNow();
+ PublicationOperation pending = readUnsettledPublication(scopeId).orElse(null);
+ return new ScopeSnapshot(scopeId, current, now, pending);
+ }
+
+ public Optional readPublication(UUID requestId, boolean forUpdate) {
+ requireTransaction();
+ HostedTermsEncoding.requireUuid(requestId, "publication request");
+ Record row =
+ dsl.fetchOne(
+ "SELECT * FROM "
+ + PUBLICATIONS
+ + " WHERE request_id = ?"
+ + (forUpdate ? " FOR UPDATE" : ""),
+ requestId);
+ return row == null ? Optional.empty() : Optional.of(publication(row));
+ }
+
+ public Optional readUnsettledPublication(UUID scopeId) {
+ requireTransaction();
+ Record row =
+ dsl.fetchOne(
+ "SELECT * FROM "
+ + PUBLICATIONS
+ + " WHERE hosted_scope_id = ? AND status IN ('SCHEDULED', 'PENDING_OWNER_SETTLEMENT')"
+ + " ORDER BY requested_at, request_id LIMIT 1",
+ scopeId);
+ return row == null ? Optional.empty() : Optional.of(publication(row));
+ }
+
+ public HostedTermsCatalogVersion readCandidate(PublicationOperation operation) {
+ requireTransaction();
+ Objects.requireNonNull(operation);
+ if (operation.candidateVersionId() == null) {
+ throw new IllegalStateException("Publication candidate is absent");
+ }
+ return readCatalog(operation.hostedScopeId(), operation.candidateVersionId());
+ }
+
+ public HostedTermsCatalogVersion readCatalog(UUID scopeId, UUID versionId) {
+ requireTransaction();
+ Record row =
+ dsl.fetchOne(
+ "SELECT * FROM " + VERSIONS + " WHERE hosted_scope_id = ? AND version_id = ?",
+ scopeId,
+ versionId);
+ if (row == null) {
+ throw new IllegalStateException("Exact hosted terms catalog version is unavailable");
+ }
+ HostedTermsCatalogVersion version = catalog(row);
+ byte[] payload = HostedTermsEncoding.catalog(version);
+ if (!Arrays.equals(payload, row.get("version_payload", byte[].class))
+ || !HostedTermsEncoding.digest(payload).equals(row.get("version_digest", String.class))) {
+ throw new IllegalStateException(
+ "Hosted terms catalog payload or digest conflicts with exact columns");
+ }
+ return version;
+ }
+
+ public void insertCandidate(HostedTermsCatalogVersion candidate) {
+ requireWriteTransaction();
+ Objects.requireNonNull(candidate);
+ byte[] payload = HostedTermsEncoding.catalog(candidate);
+ dsl.execute(
+ "INSERT INTO "
+ + VERSIONS
+ + " (version_id, hosted_scope_id, predecessor_version_id, operator_legal_identity, "
+ + "operator_identity_version, document_bytes, document_digest, source_version, "
+ + "material_generation, materiality, materiality_evidence_reference, "
+ + "materiality_evidence_version, publication_evidence_reference, "
+ + "publication_evidence_version, notice_evidence_reference, notice_evidence_version, "
+ + "effective_at, version_payload, version_digest) "
+ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, ?, ?)",
+ candidate.versionId(),
+ candidate.hostedScopeId(),
+ candidate.predecessorVersionId(),
+ candidate.operatorLegalIdentity(),
+ candidate.operatorIdentityVersion(),
+ candidate.documentBytes(),
+ candidate.documentDigest(),
+ candidate.sourceVersion(),
+ candidate.materialGeneration(),
+ candidate.materiality().name(),
+ candidate.materialityEvidenceReference(),
+ candidate.materialityEvidenceVersion(),
+ candidate.publicationEvidenceReference(),
+ candidate.publicationEvidenceVersion(),
+ candidate.noticeEvidenceReference(),
+ candidate.noticeEvidenceVersion(),
+ OffsetDateTime.ofInstant(candidate.effectiveAt(), java.time.ZoneOffset.UTC),
+ payload,
+ HostedTermsEncoding.digest(payload));
+ }
+
+ public void markScheduled(UUID requestId, HostedTermsCatalogVersion candidate) {
+ transitionPublication(requestId, candidate, "SCHEDULED", null);
+ }
+
+ public void markOwnerSettlementPending(
+ UUID requestId, HostedTermsCatalogVersion candidate, byte[] sourceChangeBinding) {
+ transitionPublication(
+ requestId,
+ candidate,
+ "PENDING_OWNER_SETTLEMENT",
+ HostedTermsEncoding.requireBytes(sourceChangeBinding));
+ }
+
+ private void transitionPublication(
+ UUID requestId,
+ HostedTermsCatalogVersion candidate,
+ String status,
+ byte[] sourceChangeBinding) {
+ requireWriteTransaction();
+ Objects.requireNonNull(candidate);
+ int updated =
+ dsl.execute(
+ "UPDATE "
+ + PUBLICATIONS
+ + " SET candidate_version_id = ?, source_change_binding = ?, status = ?"
+ + " WHERE request_id = ? AND status IN ('RECEIVED', 'SCHEDULED')",
+ candidate.versionId(),
+ sourceChangeBinding,
+ status,
+ requestId);
+ if (updated != 1) {
+ PublicationOperation prior =
+ readPublication(requestId, true)
+ .orElseThrow(() -> new IllegalStateException("Publication intent disappeared"));
+ if (!Objects.equals(prior.candidateVersionId(), candidate.versionId())
+ || prior.status() != PublicationStatus.valueOf(status)
+ || !Arrays.equals(prior.sourceChangeBinding(), sourceChangeBinding)) {
+ throw new IllegalStateException(
+ "Publication candidate transition differs from exact intent");
+ }
+ }
+ }
+
+ /** Advances operative head only after effectiveAt and every required owner terminal result. */
+ public void completePublication(
+ UUID requestId,
+ HostedTermsCatalogVersion candidate,
+ byte[] resultPayload,
+ byte[] sourceChangeBinding) {
+ requireWriteTransaction();
+ Objects.requireNonNull(candidate);
+ byte[] result = HostedTermsEncoding.requireBytes(resultPayload);
+ if (!Arrays.equals(result, HostedTermsEncoding.catalog(candidate))) {
+ throw new IllegalArgumentException(
+ "Publication result must be exact candidate catalog bytes");
+ }
+ int headUpdated =
+ dsl.execute(
+ "UPDATE "
+ + SCOPES
+ + " SET current_version_id = ?, current_source_version = ?, "
+ + "current_material_generation = ? WHERE hosted_scope_id = ? "
+ + "AND current_version_id IS NOT DISTINCT FROM ? "
+ + "AND current_source_version IS NOT DISTINCT FROM ? "
+ + "AND current_material_generation IS NOT DISTINCT FROM ?",
+ candidate.versionId(),
+ candidate.sourceVersion(),
+ candidate.materialGeneration(),
+ candidate.hostedScopeId(),
+ candidate.predecessorVersionId(),
+ candidate.predecessorVersionId() == null ? null : candidate.sourceVersion() - 1,
+ candidate.predecessorVersionId() == null
+ ? null
+ : candidate.materialGeneration()
+ - (candidate.materiality() == HostedTermsCatalogVersion.Materiality.MATERIAL
+ ? 1
+ : 0));
+ if (headUpdated != 1) {
+ throw new IllegalStateException("Hosted terms operative head changed from exact predecessor");
+ }
+ int operationUpdated =
+ dsl.execute(
+ "UPDATE "
+ + PUBLICATIONS
+ + " SET candidate_version_id = ?, source_change_binding = ?, status = 'COMMITTED', "
+ + "result_payload = ?, result_digest = ?, committed_at = CURRENT_TIMESTAMP "
+ + "WHERE request_id = ? AND status IN ('RECEIVED', 'SCHEDULED', 'PENDING_OWNER_SETTLEMENT')",
+ candidate.versionId(),
+ sourceChangeBinding,
+ result,
+ HostedTermsEncoding.digest(result),
+ requestId);
+ if (operationUpdated != 1) {
+ throw new IllegalStateException("Publication operation did not commit exactly once");
+ }
+ }
+
+ public UUID lockPartyAccount(UUID creatorPartyId) {
+ requireWriteTransaction();
+ HostedTermsEncoding.requireUuid(creatorPartyId, "creator party");
+ Record row =
+ dsl.fetchOne(
+ "SELECT account_uuid FROM account_individual_creator_party_sources "
+ + "WHERE creator_party_id = ? FOR UPDATE",
+ creatorPartyId);
+ if (row == null) {
+ throw new IllegalStateException("Current individual creator party source is unavailable");
+ }
+ UUID accountId = row.get("account_uuid", UUID.class);
+ return HostedTermsEncoding.requireUuid(accountId, "party-owning Account");
+ }
+
+ public Optional readAcceptanceByRequest(UUID actionRequestId) {
+ requireTransaction();
+ Record row =
+ dsl.fetchOne(
+ "SELECT * FROM " + ACCEPTANCES + " WHERE action_request_id = ?", actionRequestId);
+ return row == null ? Optional.empty() : Optional.of(acceptance(row));
+ }
+
+ /** Latest acceptance on the active catalog ancestry for this party and material generation. */
+ public Optional readCurrentAcceptance(
+ UUID creatorPartyId, UUID hostedScopeId, HostedTermsCatalogVersion current) {
+ requireTransaction();
+ Record row =
+ dsl.fetchOne(
+ "WITH RECURSIVE active_terms(version_id, predecessor_version_id) AS ("
+ + " SELECT version_id, predecessor_version_id FROM "
+ + VERSIONS
+ + " WHERE hosted_scope_id = ? AND version_id = ?"
+ + " UNION ALL SELECT prior.version_id, prior.predecessor_version_id FROM "
+ + VERSIONS
+ + " prior JOIN active_terms active ON prior.version_id = active.predecessor_version_id"
+ + " WHERE prior.hosted_scope_id = ?)"
+ + " SELECT acceptance.* FROM "
+ + ACCEPTANCES
+ + " acceptance JOIN active_terms active ON active.version_id = acceptance.terms_version_id"
+ + " WHERE acceptance.creator_party_id = ? AND acceptance.hosted_scope_id = ?"
+ + " AND acceptance.material_generation = ? AND acceptance.operator_legal_identity = ?"
+ + " AND acceptance.operator_identity_version = ?"
+ + " ORDER BY acceptance.accepted_at DESC, acceptance.evidence_id LIMIT 1",
+ hostedScopeId,
+ current.versionId(),
+ hostedScopeId,
+ creatorPartyId,
+ hostedScopeId,
+ current.materialGeneration(),
+ current.operatorLegalIdentity(),
+ current.operatorIdentityVersion());
+ return row == null ? Optional.empty() : Optional.of(acceptance(row));
+ }
+
+ /** Inserts acceptance from owner-read sources; accepted_at is assigned by PostgreSQL. */
+ public IndividualHostedTermsAcceptance insertAcceptance(
+ UUID evidenceId,
+ AccountHostedTermsService.AcceptanceAction action,
+ IndividualCreatorPartySource party,
+ HostedTermsCatalogVersion shownVersion,
+ byte[] actionEvidence) {
+ requireWriteTransaction();
+ HostedTermsEncoding.requireUuid(evidenceId, "acceptance evidence");
+ Objects.requireNonNull(action);
+ Objects.requireNonNull(party);
+ Objects.requireNonNull(shownVersion);
+ byte[] sourceBytes = HostedTermsEncoding.individualParty(party);
+ byte[] actionBytes = HostedTermsEncoding.requireBytes(actionEvidence);
+ dsl.execute(
+ "INSERT INTO "
+ + ACCEPTANCES
+ + " (evidence_id, action_request_id, creator_party_id, account_uuid, hosted_scope_id, "
+ + "terms_version_id, document_digest, operator_legal_identity, operator_identity_version, "
+ + "source_version, material_generation, individual_party_source, "
+ + "individual_party_source_digest, affirmative_action_evidence, affirmative_action_digest) "
+ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "
+ + "ON CONFLICT (action_request_id) DO NOTHING",
+ evidenceId,
+ action.actionRequestId(),
+ party.creatorPartyId(),
+ party.accountId(),
+ shownVersion.hostedScopeId(),
+ shownVersion.versionId(),
+ shownVersion.documentDigest(),
+ shownVersion.operatorLegalIdentity(),
+ shownVersion.operatorIdentityVersion(),
+ shownVersion.sourceVersion(),
+ shownVersion.materialGeneration(),
+ sourceBytes,
+ HostedTermsEncoding.digest(sourceBytes),
+ actionBytes,
+ HostedTermsEncoding.digest(actionBytes));
+ IndividualHostedTermsAcceptance stored =
+ readAcceptanceByRequest(action.actionRequestId())
+ .orElseThrow(() -> new IllegalStateException("Affirmative acceptance did not persist"));
+ if (!stored.creatorPartyId().equals(party.creatorPartyId())
+ || !stored.accountId().equals(party.accountId())
+ || !stored.hostedScopeId().equals(shownVersion.hostedScopeId())
+ || !stored.termsVersionId().equals(shownVersion.versionId())
+ || !stored.documentDigest().equals(shownVersion.documentDigest())
+ || !stored.operatorLegalIdentity().equals(shownVersion.operatorLegalIdentity())
+ || stored.operatorIdentityVersion() != shownVersion.operatorIdentityVersion()
+ || stored.sourceVersion() != shownVersion.sourceVersion()
+ || stored.materialGeneration() != shownVersion.materialGeneration()
+ || !Arrays.equals(stored.individualPartySource(), sourceBytes)
+ || !stored.individualPartySourceDigest().equals(HostedTermsEncoding.digest(sourceBytes))
+ || !Arrays.equals(stored.affirmativeActionEvidence(), actionBytes)
+ || !stored.affirmativeActionDigest().equals(HostedTermsEncoding.digest(actionBytes))) {
+ throw new IllegalArgumentException(
+ "Acceptance request identity conflicts with stored evidence");
+ }
+ return stored;
+ }
+
+ private OffsetDateTime databaseNow() {
+ // Transaction timestamp can predate a row-lock wait and incorrectly grandfather an expired
+ // terms version. Sample PostgreSQL wall time only after the source locks are held.
+ Record row = dsl.fetchOne("SELECT clock_timestamp() AS database_now");
+ if (row == null || row.get("database_now", OffsetDateTime.class) == null) {
+ throw new IllegalStateException("Account database time is unavailable");
+ }
+ return row.get("database_now", OffsetDateTime.class);
+ }
+
+ private PublicationOperation publication(Record row) {
+ byte[] request = row.get("request_payload", byte[].class);
+ String requestDigest = row.get("request_digest", String.class);
+ if (!HostedTermsEncoding.digest(request).equals(requestDigest)) {
+ throw new IllegalStateException("Stored publication request digest conflicts");
+ }
+ PublicationOperation operation =
+ new PublicationOperation(
+ row.get("request_id", UUID.class),
+ row.get("hosted_scope_id", UUID.class),
+ request,
+ requestDigest,
+ PublicationStatus.valueOf(row.get("status", String.class)),
+ row.get("candidate_version_id", UUID.class),
+ row.get("source_change_binding", byte[].class),
+ row.get("result_payload", byte[].class),
+ row.get("result_digest", String.class),
+ row.get("committed_at", OffsetDateTime.class));
+ if (operation.status() == PublicationStatus.COMMITTED) {
+ HostedTermsCatalogVersion candidate = readCandidate(operation);
+ if (!Arrays.equals(operation.resultPayload(), HostedTermsEncoding.catalog(candidate))
+ || !HostedTermsEncoding.digest(operation.resultPayload())
+ .equals(operation.resultDigest())) {
+ throw new IllegalStateException(
+ "Committed publication result differs from immutable catalog");
+ }
+ }
+ return operation;
+ }
+
+ private HostedTermsCatalogVersion catalog(Record row) {
+ HostedTermsCatalogVersion version =
+ new HostedTermsCatalogVersion(
+ row.get("version_id", UUID.class),
+ row.get("hosted_scope_id", UUID.class),
+ row.get("predecessor_version_id", UUID.class),
+ row.get("operator_legal_identity", String.class),
+ row.get("operator_identity_version", Long.class),
+ row.get("document_bytes", byte[].class),
+ row.get("document_digest", String.class),
+ row.get("source_version", Long.class),
+ row.get("material_generation", Long.class),
+ HostedTermsCatalogVersion.Materiality.valueOf(row.get("materiality", String.class)),
+ row.get("materiality_evidence_reference", String.class),
+ row.get("materiality_evidence_version", Long.class),
+ row.get("publication_evidence_reference", String.class),
+ row.get("publication_evidence_version", Long.class),
+ row.get("notice_evidence_reference", String.class),
+ row.get("notice_evidence_version", Long.class),
+ row.get("effective_at", OffsetDateTime.class).toInstant());
+ return version;
+ }
+
+ private IndividualHostedTermsAcceptance acceptance(Record row) {
+ IndividualHostedTermsAcceptance acceptance =
+ new IndividualHostedTermsAcceptance(
+ row.get("evidence_id", UUID.class),
+ row.get("action_request_id", UUID.class),
+ row.get("creator_party_id", UUID.class),
+ row.get("account_uuid", UUID.class),
+ row.get("hosted_scope_id", UUID.class),
+ row.get("terms_version_id", UUID.class),
+ row.get("document_digest", String.class),
+ row.get("operator_legal_identity", String.class),
+ row.get("operator_identity_version", Long.class),
+ row.get("source_version", Long.class),
+ row.get("material_generation", Long.class),
+ row.get("individual_party_source", byte[].class),
+ row.get("individual_party_source_digest", String.class),
+ row.get("affirmative_action_evidence", byte[].class),
+ row.get("affirmative_action_digest", String.class),
+ row.get("accepted_at", OffsetDateTime.class));
+ if (!Arrays.equals(
+ acceptance.affirmativeActionEvidence(),
+ row.get("affirmative_action_evidence", byte[].class))
+ || !HostedTermsEncoding.digest(acceptance.individualPartySource())
+ .equals(row.get("individual_party_source_digest", String.class))) {
+ throw new IllegalStateException("Stored acceptance evidence digest conflicts");
+ }
+ return acceptance;
+ }
+
+ private void requireTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException("Hosted terms repository requires an owner transaction");
+ }
+ }
+
+ private void requireWriteTransaction() {
+ requireTransaction();
+ Record isolation = dsl.fetchOne("SHOW transaction_isolation");
+ if (isolation == null || !"read committed".equals(isolation.get(0, String.class))) {
+ throw new IllegalStateException("Hosted terms owner writes require READ COMMITTED isolation");
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/IndividualHostedTermsAcceptance.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/IndividualHostedTermsAcceptance.java
new file mode 100644
index 0000000000..69dfc6df53
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/IndividualHostedTermsAcceptance.java
@@ -0,0 +1,105 @@
+package net.firedevops.firemud.accountservice.hostedterms;
+
+import java.time.OffsetDateTime;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.UUID;
+
+/**
+ * Append-only party-wide affirmative acceptance with the exact local individual source captured.
+ */
+public record IndividualHostedTermsAcceptance(
+ UUID evidenceId,
+ UUID actionRequestId,
+ UUID creatorPartyId,
+ UUID accountId,
+ UUID hostedScopeId,
+ UUID termsVersionId,
+ String documentDigest,
+ String operatorLegalIdentity,
+ long operatorIdentityVersion,
+ long sourceVersion,
+ long materialGeneration,
+ byte[] individualPartySource,
+ String individualPartySourceDigest,
+ byte[] affirmativeActionEvidence,
+ String affirmativeActionDigest,
+ OffsetDateTime acceptedAt) {
+
+ public IndividualHostedTermsAcceptance {
+ HostedTermsEncoding.requireUuid(evidenceId, "acceptance evidence");
+ HostedTermsEncoding.requireUuid(actionRequestId, "acceptance action request");
+ HostedTermsEncoding.requireUuid(creatorPartyId, "creator party");
+ HostedTermsEncoding.requireUuid(accountId, "accepting Account");
+ HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope");
+ HostedTermsEncoding.requireUuid(termsVersionId, "accepted terms version");
+ documentDigest = HostedTermsEncoding.requireDigest(documentDigest);
+ operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048);
+ if (operatorIdentityVersion <= 0 || sourceVersion <= 0 || materialGeneration <= 0) {
+ throw new IllegalArgumentException("Positive operator and currentness versions required");
+ }
+ individualPartySource = HostedTermsEncoding.requireBytes(individualPartySource);
+ individualPartySourceDigest = HostedTermsEncoding.requireDigest(individualPartySourceDigest);
+ affirmativeActionEvidence = HostedTermsEncoding.requireBytes(affirmativeActionEvidence);
+ affirmativeActionDigest = HostedTermsEncoding.requireDigest(affirmativeActionDigest);
+ Objects.requireNonNull(acceptedAt, "database acceptance time is required");
+ if (!HostedTermsEncoding.digest(individualPartySource).equals(individualPartySourceDigest)
+ || !HostedTermsEncoding.digest(affirmativeActionEvidence).equals(affirmativeActionDigest)) {
+ throw new IllegalArgumentException("Acceptance evidence digest does not match exact bytes");
+ }
+ }
+
+ @Override
+ public byte[] individualPartySource() {
+ return individualPartySource.clone();
+ }
+
+ @Override
+ public byte[] affirmativeActionEvidence() {
+ return affirmativeActionEvidence.clone();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof IndividualHostedTermsAcceptance that)) {
+ return false;
+ }
+ return evidenceId.equals(that.evidenceId)
+ && actionRequestId.equals(that.actionRequestId)
+ && creatorPartyId.equals(that.creatorPartyId)
+ && accountId.equals(that.accountId)
+ && hostedScopeId.equals(that.hostedScopeId)
+ && termsVersionId.equals(that.termsVersionId)
+ && documentDigest.equals(that.documentDigest)
+ && operatorLegalIdentity.equals(that.operatorLegalIdentity)
+ && operatorIdentityVersion == that.operatorIdentityVersion
+ && sourceVersion == that.sourceVersion
+ && materialGeneration == that.materialGeneration
+ && Arrays.equals(individualPartySource, that.individualPartySource)
+ && individualPartySourceDigest.equals(that.individualPartySourceDigest)
+ && Arrays.equals(affirmativeActionEvidence, that.affirmativeActionEvidence)
+ && affirmativeActionDigest.equals(that.affirmativeActionDigest)
+ && acceptedAt.equals(that.acceptedAt);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(
+ evidenceId,
+ actionRequestId,
+ creatorPartyId,
+ accountId,
+ hostedScopeId,
+ termsVersionId,
+ documentDigest,
+ operatorLegalIdentity,
+ operatorIdentityVersion,
+ sourceVersion,
+ materialGeneration,
+ Arrays.hashCode(individualPartySource),
+ individualPartySourceDigest,
+ Arrays.hashCode(affirmativeActionEvidence),
+ affirmativeActionDigest,
+ acceptedAt);
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java
index 1d7d6dec6c..34f9e93da8 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java
@@ -7,6 +7,7 @@
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
+import net.firedevops.firemud.accountservice.entity.Account;
import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes;
import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
@@ -14,8 +15,14 @@
import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence;
import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind;
import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint;
import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event;
import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence;
+import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback;
+import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback.RetainedEventEvidence;
+import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot;
+import net.firedevops.firemud.accountservice.service.AccountGenerationProjection;
+import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection;
import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec;
import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountEvent;
import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountPreimage;
@@ -29,6 +36,7 @@
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Owns explicit fresh source baselines and exact Account/issuer authority event append/readback.
@@ -79,14 +87,20 @@ public CurrentSourceEvidence initializeIssuerIfAbsent(String exactIssuerId) {
@Transactional(propagation = Propagation.MANDATORY)
public void initializeFreshAccount(AccountRepository.FreshAccountInsert proof) {
Objects.requireNonNull(proof, "fresh Account repository insert proof is required");
- initializeIssuerIfAbsent(ACCOUNT_ISSUER);
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new SourceEvidenceUnavailableException();
+ }
long accountInsertTransactionId = requireFreshAccountReadback(proof);
+ initializeIssuerIfAbsent(ACCOUNT_ISSUER);
ScopeState accountState = generations.initializeAccountForFreshRepositoryInsert(proof);
insertFreshBaseline(
AuthorityScope.account(proof.accountUuid()),
accountState,
new AccountIdentitySource(proof.accountId(), accountInsertTransactionId));
readCurrentSource(AuthorityScope.account(proof.accountUuid()), accountState);
+ new AccountPlatformRestrictionBirthRepository(dsl)
+ .initializeFreshAccount(proof, accountInsertTransactionId, accountState);
}
/**
@@ -195,7 +209,203 @@ public IssuerAccountSourceSnapshot readCurrentIssuerAccountSources(
|| !account.issuanceFence().equals(snapshot.account().issuanceFence())) {
throw new SourceEvidenceUnavailableException();
}
- return new IssuerAccountSourceSnapshot(issuer, account, snapshot.issuanceFence());
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot closedSource =
+ closedEventReadback()
+ .requireCurrentLatest(
+ readAccountIdentityForClosedReadback(accountUuid), snapshot.account());
+ if (closedSource.outboxSequence() != account.checkpoint().sequence()) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ if (closedSource.outboxSequence() == 0L) {
+ if (closedSource.latestEvent().isPresent()
+ || account.checkpoint().sourceEventId().isPresent()
+ || account.checkpoint().sourceEventDigest().isPresent()) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ } else {
+ Event closedEvent = closedSource.latestEvent().orElseThrow();
+ if (closedEvent.outboxSequence() != account.checkpoint().sequence()
+ || !closedEvent.eventId().equals(account.checkpoint().sourceEventId().orElseThrow())
+ || !closedEvent
+ .eventDigest()
+ .equals(account.checkpoint().sourceEventDigest().orElseThrow())) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ }
+ AccountGenerationProjection accountProjection =
+ AccountGenerationProjection.fromSource(
+ new AccountSourceSnapshot(
+ accountUuid,
+ snapshot.account(),
+ account.checkpoint().outboxStreamKey(),
+ account.checkpoint().sequence(),
+ closedSource.latestEvent()));
+ return new IssuerAccountSourceSnapshot(
+ issuer,
+ account,
+ snapshot.issuanceFence(),
+ accountProjection,
+ IssuerGenerationProjection.fromSource(
+ new CanonicalIssuerSourceSnapshot(
+ issuer,
+ issuer.checkpoint().sequence() == 0L
+ ? Optional.empty()
+ : Optional.of(
+ outbox
+ .findEvent(
+ issuer.checkpoint().outboxStreamKey(),
+ issuer.checkpoint().sequence())
+ .orElseThrow(SourceEvidenceUnavailableException::new)))));
+ }
+
+ /**
+ * Prepares exactly one Account-local advance against the complete current source readback. This
+ * is not authorization or a committed receipt. The closed event, immutable operation receipt and
+ * source head must all complete in this same owner transaction; deferred SQL consistency guards
+ * reject an incomplete transaction.
+ */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public ScopeState prepareClosedAccountAdvance(UUID accountUuid, CurrentSourceEvidence expected) {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()
+ || accountUuid == null
+ || accountUuid.equals(new UUID(0L, 0L))
+ || expected == null
+ || !AuthorityScope.account(accountUuid).equals(expected.scope())
+ || expected.issuanceFence() == null) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ AuthorityScope scope = AuthorityScope.account(accountUuid);
+ ScopeState current = generations.read(scope);
+ CurrentSourceEvidence actual = readCurrentSource(scope, current);
+ if (!expected.equals(actual) || !expected.issuanceFence().equals(current.issuanceFence())) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ long nextGeneration = Math.addExact(current.generation(), 1L);
+ long nextSourceVersion = Math.addExact(current.sourceVersion(), 1L);
+ long nextFence = Math.addExact(current.issuanceFence().value(), 1L);
+ long nextFenceVersion = Math.addExact(current.issuanceFence().sourceVersion(), 1L);
+ ScopeState advanced = generations.advanceForSourceEvidence(current, current.issuanceFence());
+ if (!scope.equals(advanced.scope())
+ || advanced.generation() != nextGeneration
+ || advanced.sourceVersion() != nextSourceVersion
+ || advanced.issuanceFence() == null
+ || !accountUuid.equals(advanced.issuanceFence().accountId())
+ || advanced.issuanceFence().value() != nextFence
+ || advanced.issuanceFence().sourceVersion() != nextFenceVersion) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ return advanced;
+ }
+
+ /**
+ * Advances the canonical Account source head only after a closed operation's immutable owner
+ * receipt and exact outbox event have been stored in this same owner transaction.
+ */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public CurrentSourceEvidence advanceClosedAccountHead(
+ UUID accountUuid, ScopeState expected, ScopeState advanced, Event event) {
+ Objects.requireNonNull(accountUuid, "Account UUID is required");
+ Objects.requireNonNull(expected, "expected Account source state is required");
+ Objects.requireNonNull(advanced, "advanced Account source state is required");
+ Objects.requireNonNull(event, "closed Account source event is required");
+ AuthorityScope scope = AuthorityScope.account(accountUuid);
+ if (!scope.equals(expected.scope())
+ || !scope.equals(advanced.scope())
+ || expected.issuanceFence() == null
+ || advanced.issuanceFence() == null
+ || advanced.generation() != Math.addExact(expected.generation(), 1L)
+ || advanced.sourceVersion() != Math.addExact(expected.sourceVersion(), 1L)
+ || advanced.issuanceFence().value() != Math.addExact(expected.issuanceFence().value(), 1L)
+ || advanced.issuanceFence().sourceVersion()
+ != Math.addExact(expected.issuanceFence().sourceVersion(), 1L)) {
+ throw new SourceEvidenceUnavailableException();
+ }
+
+ // The typed producer has already appended the event, but source_records must still contain
+ // the exact old head. Read and authenticate that previous head while allowing only this one
+ // pending outbox append; a normal current-source read would correctly reject the transaction's
+ // temporarily advanced stream checkpoint.
+ CurrentSourceEvidence before = readPreviousSourceForClosedAppend(scope, expected, event);
+ long expectedSequence = Math.addExact(before.checkpoint().sequence(), 1L);
+ RetainedEventEvidence receiptEvidence =
+ closedEventReadback()
+ .requireRetainedEvent(
+ readAccountIdentityForClosedReadback(accountUuid), event, advanced);
+ if (!streamKey(scope).equals(event.outboxStreamKey())
+ || event.outboxSequence() != expectedSequence
+ || advanced.generation() != receiptEvidence.accountAuthorityGeneration()
+ || advanced.sourceVersion() != receiptEvidence.sourceVersion()
+ || receiptEvidence.issuanceFence() != advanced.issuanceFence().value()
+ || receiptEvidence.issuanceFenceSourceVersion()
+ != advanced.issuanceFence().sourceVersion()) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ Event bySequence =
+ outbox
+ .findEvent(event.outboxStreamKey(), event.outboxSequence())
+ .orElseThrow(SourceEvidenceUnavailableException::new);
+ Event byRequest =
+ outbox
+ .findEvent(event.outboxStreamKey(), event.requestId())
+ .orElseThrow(SourceEvidenceUnavailableException::new);
+ if (!event.equals(bySequence) || !event.equals(byRequest)) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ Checkpoint checkpoint =
+ outbox
+ .readCheckpoint(event.outboxStreamKey())
+ .orElseThrow(SourceEvidenceUnavailableException::new);
+ if (checkpoint.outboxSequence() != expectedSequence
+ || !checkpoint.sourceEventId().equals(event.eventId())
+ || !checkpoint.sourceEventDigest().equals(event.eventDigest())) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ var typedCutoff = receiptEvidence.accountSecurityCutoff();
+ updateSourceHead(
+ before,
+ event,
+ new AccountSecurityCutoff(
+ typedCutoff.accountAuthorityGeneration(),
+ typedCutoff.outboxStreamKey(),
+ typedCutoff.outboxSequence()),
+ advanced,
+ advanced.issuanceFence());
+ CurrentSourceEvidence current = readCurrentSource(scope, advanced);
+ if (current.checkpoint().sequence() != event.outboxSequence()
+ || !current.checkpoint().sourceEventId().orElseThrow().equals(event.eventId())
+ || !current.checkpoint().sourceEventDigest().orElseThrow().equals(event.eventDigest())) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ Account latestAccount = readAccountIdentityForClosedReadback(accountUuid);
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest =
+ closedEventReadback().requireCurrentLatest(latestAccount, advanced);
+ if (latest.outboxSequence() != event.outboxSequence()
+ || latest.latestEvent().isEmpty()
+ || !event.equals(latest.latestEvent().orElseThrow())) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ return current;
+ }
+
+ /** Returns the actual current issuer source and its retained terminal event without mutation. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public CanonicalIssuerSourceSnapshot readCurrentCanonicalIssuerSource(String exactIssuerId) {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ AuthorityScope scope = AuthorityScope.issuer(exactIssuerId);
+ CurrentSourceEvidence current = readCurrentSource(scope, generations.read(scope));
+ Optional latest =
+ current.checkpoint().sequence() == 0L
+ ? Optional.empty()
+ : Optional.of(
+ outbox
+ .findEvent(
+ current.checkpoint().outboxStreamKey(), current.checkpoint().sequence())
+ .orElseThrow(SourceEvidenceUnavailableException::new));
+ return new CanonicalIssuerSourceSnapshot(current, latest);
}
/** Records an explicit issuer-wide mutation with exact event readback and no Account cutoff. */
@@ -287,13 +497,42 @@ private void insertFreshBaseline(
}
private CurrentSourceEvidence readCurrentSource(AuthorityScope scope, ScopeState authority) {
- return readCurrentSource(scope, authority, Optional.empty());
+ return readCurrentSource(scope, authority, Optional.empty(), false);
}
private CurrentSourceEvidence readCurrentSource(
AuthorityScope scope,
ScopeState authority,
Optional expectedPreUpdateAccountState) {
+ return readCurrentSource(scope, authority, expectedPreUpdateAccountState, false);
+ }
+
+ private CurrentSourceEvidence readPreviousSourceForClosedAppend(
+ AuthorityScope scope, ScopeState authority, Event pendingEvent) {
+ CurrentSourceEvidence before = readCurrentSource(scope, authority, Optional.empty(), true);
+ if (!streamKey(scope).equals(pendingEvent.outboxStreamKey())
+ || pendingEvent.outboxSequence() != Math.addExact(before.checkpoint().sequence(), 1L)) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ Event exactPending =
+ outbox
+ .findEvent(pendingEvent.outboxStreamKey(), pendingEvent.outboxSequence())
+ .orElseThrow(SourceEvidenceUnavailableException::new);
+ Event requestMatch =
+ outbox
+ .findEvent(pendingEvent.outboxStreamKey(), pendingEvent.requestId())
+ .orElseThrow(SourceEvidenceUnavailableException::new);
+ if (!pendingEvent.equals(exactPending) || !pendingEvent.equals(requestMatch)) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ return before;
+ }
+
+ private CurrentSourceEvidence readCurrentSource(
+ AuthorityScope scope,
+ ScopeState authority,
+ Optional expectedPreUpdateAccountState,
+ boolean allowOnePendingAppend) {
String key = streamKey(scope);
Record source =
dsl.fetchOne(
@@ -337,12 +576,25 @@ private CurrentSourceEvidence readCurrentSource(
"SELECT last_sequence FROM account_authority_outbox_streams "
+ "WHERE outbox_stream_key = ? FOR SHARE",
key);
- if (stream == null || nonnegative(stream, "last_sequence") != sequence) {
+ long expectedStreamSequence = allowOnePendingAppend ? Math.addExact(sequence, 1L) : sequence;
+ if (stream == null || nonnegative(stream, "last_sequence") != expectedStreamSequence) {
throw new SourceEvidenceUnavailableException();
}
+ if (scope.kind() == ScopeKind.ACCOUNT) {
+ Record eventCountRow =
+ dsl.fetchOne(
+ "SELECT count(*) AS event_count FROM account_authority_outbox_events "
+ + "WHERE outbox_stream_key = ?",
+ key);
+ Long eventCount = eventCountRow == null ? null : eventCountRow.get("event_count", Long.class);
+ if (eventCount == null || eventCount != expectedStreamSequence) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ }
+
SourceCheckpoint checkpoint;
- Optional cutoff = Optional.empty();
- SourceEvent latest = null;
+ Optional cutoff = Optional.empty();
+ VerifiedSourceHistory history = null;
if (sequence == 0L) {
if (source.get("last_event_id", String.class) != null
|| source.get("last_event_digest", String.class) != null
@@ -355,17 +607,27 @@ private CurrentSourceEvidence readCurrentSource(
}
checkpoint = new SourceCheckpoint(key, 0L, Optional.empty(), Optional.empty());
} else {
- latest = verifyLatestEvent(scope, key, sequence, authority, fence);
- if (!latest.eventId().equals(source.get("last_event_id", String.class))
- || !latest.eventDigest().equals(source.get("last_event_digest", String.class))) {
+ if (scope.kind() == ScopeKind.ISSUER) {
+ history = verifyLatestEvent(scope, key, sequence, authority, fence);
+ } else {
+ history = verifyEventHistory(scope, key, sequence, authority, fence);
+ }
+ Event latestEvent = history.latestEvent();
+ if (!latestEvent.eventId().equals(source.get("last_event_id", String.class))
+ || !latestEvent.eventDigest().equals(source.get("last_event_digest", String.class))) {
throw new SourceEvidenceUnavailableException();
}
checkpoint =
new SourceCheckpoint(
- key, sequence, Optional.of(latest.eventId()), Optional.of(latest.eventDigest()));
+ key,
+ sequence,
+ Optional.of(latestEvent.eventId()),
+ Optional.of(latestEvent.eventDigest()));
if (scope.kind() == ScopeKind.ACCOUNT) {
- AccountEvent accountEvent = (AccountEvent) latest;
- AccountSecurityCutoff exactCutoff = accountEvent.accountSecurityCutoff();
+ AccountSecurityCutoff exactCutoff =
+ history
+ .accountSecurityCutoff()
+ .orElseThrow(() -> new SourceEvidenceUnavailableException());
if (positive(source, "cutoff_generation") != currentGeneration
|| !key.equals(source.get("cutoff_stream_key", String.class))
|| positive(source, "cutoff_sequence") != sequence
@@ -383,7 +645,8 @@ private CurrentSourceEvidence readCurrentSource(
}
if (scope.kind() == ScopeKind.ACCOUNT) {
requireAccountSourceIdentity(source, scope);
- if (latest instanceof AccountEvent accountEvent) {
+ if (history != null && history.latestLegacyAccountEvent().isPresent()) {
+ AccountEvent accountEvent = history.latestLegacyAccountEvent().orElseThrow();
AccountState expectedAccountState =
expectedPreUpdateAccountState.orElseGet(() -> readAccountState(scope.accountId()));
if (!accountEvent.accountState().equals(expectedAccountState)) {
@@ -405,7 +668,7 @@ private CurrentSourceEvidence readCurrentSource(
source.get("account_repository_insert_transaction_id", Long.class));
}
- private SourceEvent verifyLatestEvent(
+ private VerifiedSourceHistory verifyLatestEvent(
AuthorityScope scope,
String streamKey,
long sequence,
@@ -459,7 +722,103 @@ private SourceEvent verifyLatestEvent(
|| fence.sourceVersion() != sequence + 1L))) {
throw new SourceEvidenceUnavailableException();
}
- return latest;
+ return new VerifiedSourceHistory(stored, Optional.empty(), Optional.empty());
+ }
+
+ private VerifiedSourceHistory verifyEventHistory(
+ AuthorityScope scope,
+ String streamKey,
+ long sequence,
+ ScopeState authority,
+ IssuanceFence fence) {
+ Event latest = null;
+ AccountEvent latestLegacyAccountEvent = null;
+ AccountSecurityCutoff latestCutoff = null;
+ Account sourceAccount =
+ scope.kind() == ScopeKind.ACCOUNT
+ ? readAccountIdentityForClosedReadback(scope.accountId())
+ : null;
+ for (long current = 1L; current <= sequence; current++) {
+ Event stored =
+ outbox
+ .findEvent(streamKey, current)
+ .orElseThrow(() -> new SourceEvidenceUnavailableException());
+ SourceEvent event = null;
+ try {
+ event =
+ AccountAuthoritySourceEventV1Codec.verify(
+ new String(stored.payload(), StandardCharsets.UTF_8));
+ } catch (RuntimeException notLegacyEvent) {
+ // Closed RESET/LOGOUT/security events are verified by their operation-specific receipts
+ // below. Generic source history remains readable but is not accepted as current authority.
+ }
+ if (event != null) {
+ if (!stored.eventId().equals(event.eventId())
+ || !stored.requestId().equals(event.requestId())
+ || !stored.outboxStreamKey().equals(event.outboxStreamKey())
+ || stored.outboxSequence() != Long.parseLong(event.outboxSequence())
+ || !stored.eventDigest().equals(event.eventDigest())
+ || (scope.kind() == ScopeKind.ISSUER && !(event instanceof IssuerEvent))
+ || (scope.kind() == ScopeKind.ACCOUNT && !(event instanceof AccountEvent))) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ if (event instanceof IssuerEvent issuer
+ && (!issuer.issuerId().equals(scope.issuerId())
+ || Long.parseLong(issuer.issuerAuthGeneration()) != current + 1L
+ || Long.parseLong(issuer.sourceVersion()) != current + 1L)) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ if (event instanceof AccountEvent account
+ && (!account.accountId().equals(scope.accountId().toString())
+ || Long.parseLong(account.accountAuthorityGeneration()) != current + 1L
+ || Long.parseLong(account.sourceVersion()) != current + 1L
+ || Long.parseLong(account.issuanceFence()) != current + 1L
+ || Long.parseLong(account.issuanceFenceSourceVersion()) != current + 1L)) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ latestLegacyAccountEvent = event instanceof AccountEvent account ? account : null;
+ latestCutoff =
+ event instanceof AccountEvent account ? account.accountSecurityCutoff() : null;
+ } else if (scope.kind() == ScopeKind.ACCOUNT) {
+ final RetainedEventEvidence receiptEvidence;
+ try {
+ receiptEvidence =
+ closedEventReadback().requireRetainedEvent(sourceAccount, stored, authority);
+ } catch (RuntimeException missingOrInvalidReceipt) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ if (!streamKey.equals(receiptEvidence.outboxStreamKey())
+ || receiptEvidence.outboxSequence() != current
+ || receiptEvidence.accountAuthorityGeneration() != current + 1L
+ || receiptEvidence.sourceVersion() != current + 1L
+ || receiptEvidence.issuanceFence() != current + 1L
+ || receiptEvidence.issuanceFenceSourceVersion() != current + 1L) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ var typedCutoff = receiptEvidence.accountSecurityCutoff();
+ latestCutoff =
+ new AccountSecurityCutoff(
+ typedCutoff.accountAuthorityGeneration(),
+ typedCutoff.outboxStreamKey(),
+ typedCutoff.outboxSequence());
+ latestLegacyAccountEvent = null;
+ } else {
+ throw new SourceEvidenceUnavailableException();
+ }
+ latest = stored;
+ }
+ if (latest == null
+ || latest.outboxSequence() != sequence
+ || authority.generation() != sequence + 1L
+ || authority.sourceVersion() != sequence + 1L
+ || (scope.kind() == ScopeKind.ACCOUNT
+ && (fence == null
+ || fence.value() != sequence + 1L
+ || fence.sourceVersion() != sequence + 1L))) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ return new VerifiedSourceHistory(
+ latest, Optional.ofNullable(latestLegacyAccountEvent), Optional.ofNullable(latestCutoff));
}
private void updateSourceHead(
@@ -469,6 +828,40 @@ private void updateSourceHead(
IssuanceFence advancedFence) {
AccountSecurityCutoff cutoff =
event instanceof AccountEvent account ? account.accountSecurityCutoff() : null;
+ updateSourceHead(
+ before,
+ event.outboxSequence(),
+ event.eventId(),
+ event.eventDigest(),
+ cutoff,
+ advanced,
+ advancedFence);
+ }
+
+ private void updateSourceHead(
+ CurrentSourceEvidence before,
+ Event event,
+ AccountSecurityCutoff cutoff,
+ ScopeState advanced,
+ IssuanceFence advancedFence) {
+ updateSourceHead(
+ before,
+ Long.toString(event.outboxSequence()),
+ event.eventId(),
+ event.eventDigest(),
+ cutoff,
+ advanced,
+ advancedFence);
+ }
+
+ private void updateSourceHead(
+ CurrentSourceEvidence before,
+ String sequenceText,
+ String eventId,
+ String eventDigest,
+ AccountSecurityCutoff cutoff,
+ ScopeState advanced,
+ IssuanceFence advancedFence) {
Record changed =
dsl.fetchOne(
"UPDATE "
@@ -486,9 +879,9 @@ private void updateSourceHead(
advanced.sourceVersion(),
advancedFence == null ? null : advancedFence.value(),
advancedFence == null ? null : advancedFence.sourceVersion(),
- Long.parseLong(event.outboxSequence()),
- event.eventId(),
- event.eventDigest(),
+ Long.parseLong(sequenceText),
+ eventId,
+ eventDigest,
cutoff == null ? null : Long.parseLong(cutoff.accountAuthorityGeneration()),
cutoff == null ? null : cutoff.outboxStreamKey(),
cutoff == null ? null : Long.parseLong(cutoff.outboxSequence()),
@@ -628,6 +1021,34 @@ private AccountState readAccountState(UUID accountUuid) {
return accountState(account);
}
+ private Account readAccountIdentityForClosedReadback(UUID accountUuid) {
+ Record row =
+ dsl.fetchOne(
+ "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id, "
+ + "password_hash FROM accounts WHERE account_uuid = ? FOR SHARE",
+ accountUuid);
+ if (row == null) throw new SourceEvidenceUnavailableException();
+ Account account = new Account();
+ account.setId(positive(row, "id"));
+ account.setAccountUuid(row.get("account_uuid", UUID.class));
+ account.setAccountUuidProvenance(
+ AccountIdentityProvenance.fromStorageValue(
+ row.get("account_uuid_provenance", String.class)));
+ account.setAccountUuidSourceNumericId(positive(row, "account_uuid_source_numeric_id"));
+ account.setPasswordHash(row.get("password_hash", String.class));
+ return account;
+ }
+
+ private AccountAuthoritySourceEventReadback closedEventReadback() {
+ // Construct at use, not in the repository constructor: the security-state storage owner
+ // itself depends on this source owner. Every invocation still requires every exact receipt.
+ return new AccountAuthoritySourceEventReadback(
+ outbox,
+ new AccountPasswordResetOperationRepository(dsl),
+ new AccountLogoutAllOperationRepository(dsl),
+ new AccountSecurityStateOperationRepository(dsl));
+ }
+
private void requireAccountReadback(
UUID accountUuid, long accountId, AccountRepository.AccountAuthorityState expected) {
Record account =
@@ -800,6 +1221,17 @@ public record SourceCheckpoint(
}
}
+ private record VerifiedSourceHistory(
+ Event latestEvent,
+ Optional latestLegacyAccountEvent,
+ Optional accountSecurityCutoff) {
+ private VerifiedSourceHistory {
+ Objects.requireNonNull(latestEvent);
+ Objects.requireNonNull(latestLegacyAccountEvent);
+ Objects.requireNonNull(accountSecurityCutoff);
+ }
+ }
+
public record CurrentSourceEvidence(
AuthorityScope scope,
long generation,
@@ -872,8 +1304,61 @@ public record CurrentSourceEvidence(
}
}
+ public record CanonicalIssuerSourceSnapshot(
+ CurrentSourceEvidence source, Optional latestEvent) {
+ public CanonicalIssuerSourceSnapshot {
+ Objects.requireNonNull(source);
+ Objects.requireNonNull(latestEvent);
+ if (source.scope().kind() != ScopeKind.ISSUER
+ || (source.checkpoint().sequence() == 0L) != latestEvent.isEmpty()) {
+ throw new SourceEvidenceUnavailableException();
+ }
+ }
+ }
+
public record IssuerAccountSourceSnapshot(
- CurrentSourceEvidence issuer, CurrentSourceEvidence account, IssuanceFence issuanceFence) {
+ CurrentSourceEvidence issuer,
+ CurrentSourceEvidence account,
+ IssuanceFence issuanceFence,
+ AccountGenerationProjection canonicalAccountProjection,
+ IssuerGenerationProjection canonicalIssuerProjection) {
+ public IssuerAccountSourceSnapshot(
+ CurrentSourceEvidence issuer,
+ CurrentSourceEvidence account,
+ IssuanceFence issuanceFence,
+ AccountGenerationProjection canonicalAccountProjection) {
+ this(
+ issuer,
+ account,
+ issuanceFence,
+ canonicalAccountProjection,
+ issuer != null && issuer.checkpoint().sequence() == 0L
+ ? IssuerGenerationProjection.fromSource(issuer)
+ : null);
+ }
+
+ /**
+ * Preserves lightweight source-state fixtures while refusing to invent advanced event bytes.
+ * Production snapshots are created by {@link #readCurrentIssuerAccountSources} with the exact
+ * receipt-verified latest event from that same composite owner read.
+ */
+ public IssuerAccountSourceSnapshot(
+ CurrentSourceEvidence issuer, CurrentSourceEvidence account, IssuanceFence issuanceFence) {
+ this(
+ issuer,
+ account,
+ issuanceFence,
+ account != null && account.checkpoint().sequence() == 0L
+ ? new AccountGenerationProjection(
+ account.scope().accountId().toString(),
+ Long.toString(account.generation()),
+ Long.toString(account.sourceVersion()),
+ account.checkpoint().outboxStreamKey(),
+ "0",
+ Optional.empty())
+ : null);
+ }
+
public IssuerAccountSourceSnapshot {
Objects.requireNonNull(issuer);
Objects.requireNonNull(account);
@@ -884,6 +1369,44 @@ public record IssuerAccountSourceSnapshot(
|| !account.issuanceFence().equals(issuanceFence)) {
throw new IllegalArgumentException("Issuer/Account source snapshot scope is invalid");
}
+ if (canonicalAccountProjection != null
+ && (!account.scope().accountId().toString().equals(canonicalAccountProjection.accountId())
+ || !Long.toString(account.generation())
+ .equals(canonicalAccountProjection.accountAuthorityGeneration())
+ || !Long.toString(account.sourceVersion())
+ .equals(canonicalAccountProjection.sourceVersion())
+ || !account
+ .checkpoint()
+ .outboxStreamKey()
+ .equals(canonicalAccountProjection.outboxStreamKey())
+ || !Long.toString(account.checkpoint().sequence())
+ .equals(canonicalAccountProjection.outboxSequence()))) {
+ throw new IllegalArgumentException(
+ "Canonical Account source projection differs from its snapshot");
+ }
+ if (canonicalIssuerProjection != null
+ && (!issuer.scope().issuerId().equals(canonicalIssuerProjection.issuerId())
+ || !Long.toString(issuer.generation())
+ .equals(canonicalIssuerProjection.issuerAuthGeneration())
+ || !Long.toString(issuer.sourceVersion())
+ .equals(canonicalIssuerProjection.sourceVersion())
+ || !issuer
+ .checkpoint()
+ .outboxStreamKey()
+ .equals(canonicalIssuerProjection.outboxStreamKey())
+ || !Long.toString(issuer.checkpoint().sequence())
+ .equals(canonicalIssuerProjection.lastAppliedSourceOutboxSequence())
+ || !issuer
+ .checkpoint()
+ .sourceEventId()
+ .equals(canonicalIssuerProjection.lastAppliedSourceEventId())
+ || !issuer
+ .checkpoint()
+ .sourceEventDigest()
+ .equals(canonicalIssuerProjection.lastAppliedSourceEventDigest()))) {
+ throw new IllegalArgumentException(
+ "Canonical issuer source projection differs from its snapshot");
+ }
}
}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java
new file mode 100644
index 0000000000..0ce98e77e2
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java
@@ -0,0 +1,321 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Stores immutable source and lifecycle-result evidence for one Account logout-all operation. */
+@Repository
+@SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification = "Injected DSLContext is an internal Spring collaborator.")
+public class AccountLogoutAllOperationRepository {
+ private static final String TABLE = "account_logout_all_operation_receipts";
+ private static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:";
+ private static final String LIFECYCLE_RESULT = "LOGOUT_ALL_COMMITTED";
+ private static final String SELECT_COLUMNS =
+ "request_id, account_id, account_uuid, operation_kind, request_digest_version, "
+ + "request_digest, presented_token_hash, token_profile, outbox_stream_key, outbox_sequence, "
+ + "event_id, event_digest, account_authority_generation, account_source_version, "
+ + "issuance_fence, issuance_fence_source_version, lifecycle_result";
+ private static final HexFormat HEX = HexFormat.of();
+
+ private final DSLContext dsl;
+
+ public AccountLogoutAllOperationRepository(DSLContext dsl) {
+ this.dsl = dsl;
+ }
+
+ /** Exact request lookup; callers compare every immutable request binding before recovery. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional findByRequestId(UUID requestId) {
+ requireOwnerTransaction();
+ requireRequestId(requestId);
+ Record row =
+ dsl.fetchOne(
+ "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE request_id = ?", requestId);
+ return Optional.ofNullable(row == null ? null : toReceipt(row));
+ }
+
+ /**
+ * Token identity lookup prevents an old presented token from being rebound to another request.
+ */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional findByPresentedTokenHash(String tokenHash) {
+ requireOwnerTransaction();
+ byte[] hash = decodeDigest(tokenHash, "presented token hash");
+ Record row =
+ dsl.fetchOne(
+ "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE presented_token_hash = ?",
+ hash);
+ return Optional.ofNullable(row == null ? null : toReceipt(row));
+ }
+
+ /** Inserts the one immutable lifecycle receipt for the source event. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public LogoutAllReceipt insert(LogoutAllReceipt receipt) {
+ requireOwnerTransaction();
+ validateReceipt(receipt);
+ int inserted =
+ dsl.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (request_id, account_id, account_uuid, operation_kind, "
+ + "request_digest_version, request_digest, presented_token_hash, token_profile, "
+ + "outbox_stream_key, outbox_sequence, event_id, event_digest, "
+ + "account_authority_generation, account_source_version, issuance_fence, "
+ + "issuance_fence_source_version, lifecycle_result) "
+ + "VALUES (?, ?, ?, 'ACCOUNT_LOGOUT_ALL', 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'LOGOUT_ALL_COMMITTED')",
+ receipt.requestId(),
+ receipt.accountId(),
+ receipt.accountUuid(),
+ decodeDigest(receipt.requestDigest(), "request digest"),
+ decodeDigest(receipt.presentedTokenHash(), "presented token hash"),
+ receipt.tokenProfile(),
+ receipt.outboxStreamKey(),
+ receipt.outboxSequence(),
+ receipt.eventId(),
+ receipt.eventDigest(),
+ receipt.accountAuthorityGeneration(),
+ receipt.accountSourceVersion(),
+ receipt.issuanceFence(),
+ receipt.issuanceFenceSourceVersion());
+ if (inserted != 1) {
+ throw new IllegalStateException("Logout-all operation receipt was not inserted");
+ }
+ return receipt;
+ }
+
+ private LogoutAllReceipt toReceipt(Record row) {
+ return new LogoutAllReceipt(
+ requiredUuid(row.get("request_id", UUID.class), "request ID"),
+ requiredPositive(row.get("account_id", Long.class), "Account association"),
+ requiredUuid(row.get("account_uuid", UUID.class), "Account UUID"),
+ requireText(row.get("operation_kind", String.class), "operation kind"),
+ requiredPositive(row.get("request_digest_version", Integer.class), "digest version"),
+ encodeDigest(row.get("request_digest", byte[].class), "request digest"),
+ encodeDigest(row.get("presented_token_hash", byte[].class), "presented token hash"),
+ requireText(row.get("token_profile", String.class), "token profile"),
+ requireText(row.get("outbox_stream_key", String.class), "outbox stream key"),
+ requiredPositive(row.get("outbox_sequence", Long.class), "outbox sequence"),
+ requireText(row.get("event_id", String.class), "event ID"),
+ requireText(row.get("event_digest", String.class), "event digest"),
+ requiredPositive(
+ row.get("account_authority_generation", Long.class), "Account authority generation"),
+ requiredPositive(row.get("account_source_version", Long.class), "Account source version"),
+ requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"),
+ requiredPositive(
+ row.get("issuance_fence_source_version", Long.class), "issuance-fence source version"),
+ requireText(row.get("lifecycle_result", String.class), "lifecycle result"));
+ }
+
+ private static void validateReceipt(LogoutAllReceipt receipt) {
+ Objects.requireNonNull(receipt, "logout-all receipt is required");
+ requireRequestId(receipt.requestId());
+ decodeDigest(receipt.requestDigest(), "request digest");
+ decodeDigest(receipt.presentedTokenHash(), "presented token hash");
+ AccountLogoutRequestDigest.validateTokenProfile(receipt.tokenProfile());
+ if (receipt.accountId() <= 0L
+ || receipt.accountUuid() == null
+ || isNil(receipt.accountUuid())
+ || receipt.requestDigestVersion() != 1
+ || !AccountLogoutRequestDigest.accountLogoutAll(
+ receipt.accountUuid(), receipt.tokenProfile(), receipt.presentedTokenHash())
+ .equals(receipt.requestDigest())
+ || receipt.outboxSequence() <= 0L
+ || receipt.accountAuthorityGeneration() <= 0L
+ || receipt.accountSourceVersion() <= 0L
+ || receipt.issuanceFence() <= 0L
+ || receipt.issuanceFenceSourceVersion() <= 0L
+ || !accountStreamKey(receipt.accountUuid()).equals(receipt.outboxStreamKey())
+ || !expectedEventId(receipt.requestId()).equals(receipt.eventId())
+ || receipt.eventDigest() == null
+ || !receipt.eventDigest().matches("sha256:[0-9a-f]{64}")
+ || !LIFECYCLE_RESULT.equals(receipt.lifecycleResult())) {
+ throw new IllegalArgumentException("Logout-all operation receipt is malformed");
+ }
+ requireBoundedText(receipt.operationKind(), "operation kind", 32);
+ if (!"ACCOUNT_LOGOUT_ALL".equals(receipt.operationKind())) {
+ throw new IllegalArgumentException("Logout-all operation kind is invalid");
+ }
+ }
+
+ private static void requireOwnerTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException(
+ "Logout-all operation storage requires an active Account transaction");
+ }
+ }
+
+ private static UUID requiredUuid(UUID value, String field) {
+ if (value == null || isNil(value)) {
+ throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid");
+ }
+ return value;
+ }
+
+ private static long requiredPositive(Long value, String field) {
+ if (value == null || value <= 0L) {
+ throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid");
+ }
+ return value;
+ }
+
+ private static int requiredPositive(Integer value, String field) {
+ if (value == null || value <= 0) {
+ throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid");
+ }
+ return value;
+ }
+
+ private static String requireText(String value, String field) {
+ if (value == null || value.isBlank()) {
+ throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid");
+ }
+ return value;
+ }
+
+ private static void requireBoundedText(String value, String field, int maximumLength) {
+ if (value == null || value.isBlank() || value.length() > maximumLength) {
+ throw new IllegalArgumentException(
+ "Logout-all receipt " + field + " must contain 1 to " + maximumLength + " characters");
+ }
+ }
+
+ private static void requireRequestId(UUID requestId) {
+ if (requestId == null || isNil(requestId)) {
+ throw new IllegalArgumentException("A canonical non-nil logout-all request UUID is required");
+ }
+ }
+
+ private static byte[] decodeDigest(String value, String field) {
+ if (value == null || !value.matches("[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Logout-all receipt " + field + " is malformed");
+ }
+ return HEX.parseHex(value);
+ }
+
+ private static String encodeDigest(byte[] value, String field) {
+ if (value == null || value.length != 32) {
+ throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid");
+ }
+ return HEX.formatHex(value);
+ }
+
+ private static String accountStreamKey(UUID accountUuid) {
+ return "account:auth-authority:v1:account/" + accountUuid;
+ }
+
+ private static String expectedEventId(UUID requestId) {
+ return EVENT_ID_PREFIX + requestId;
+ }
+
+ private static boolean isNil(UUID value) {
+ return new UUID(0L, 0L).equals(value);
+ }
+
+ /** Immutable committed request binding, source checkpoint and lifecycle-only result. */
+ public record LogoutAllReceipt(
+ UUID requestId,
+ long accountId,
+ UUID accountUuid,
+ String operationKind,
+ int requestDigestVersion,
+ String requestDigest,
+ String presentedTokenHash,
+ String tokenProfile,
+ String outboxStreamKey,
+ long outboxSequence,
+ String eventId,
+ String eventDigest,
+ long accountAuthorityGeneration,
+ long accountSourceVersion,
+ long issuanceFence,
+ long issuanceFenceSourceVersion,
+ String lifecycleResult) {
+ public LogoutAllReceipt {
+ requireRequestId(requestId);
+ decodeDigest(requestDigest, "request digest");
+ decodeDigest(presentedTokenHash, "presented token hash");
+ AccountLogoutRequestDigest.validateTokenProfile(tokenProfile);
+ if (accountId <= 0L
+ || accountUuid == null
+ || isNil(accountUuid)
+ || requestDigestVersion != 1
+ || !AccountLogoutRequestDigest.accountLogoutAll(
+ accountUuid, tokenProfile, presentedTokenHash)
+ .equals(requestDigest)
+ || outboxSequence <= 0L
+ || accountAuthorityGeneration <= 0L
+ || accountSourceVersion <= 0L
+ || issuanceFence <= 0L
+ || issuanceFenceSourceVersion <= 0L
+ || !accountStreamKey(accountUuid).equals(outboxStreamKey)
+ || !expectedEventId(requestId).equals(eventId)
+ || eventDigest == null
+ || !eventDigest.matches("sha256:[0-9a-f]{64}")
+ || !LIFECYCLE_RESULT.equals(lifecycleResult)) {
+ throw new IllegalArgumentException("Logout-all operation receipt is malformed");
+ }
+ requireBoundedText(operationKind, "operation kind", 32);
+ if (!"ACCOUNT_LOGOUT_ALL".equals(operationKind)) {
+ throw new IllegalArgumentException("Logout-all operation kind is invalid");
+ }
+ }
+
+ public static LogoutAllReceipt committed(
+ UUID requestId,
+ long accountId,
+ UUID accountUuid,
+ String requestDigest,
+ String presentedTokenHash,
+ String tokenProfile,
+ String outboxStreamKey,
+ long outboxSequence,
+ String eventId,
+ String eventDigest,
+ ScopeState accountAuthority,
+ IssuanceFence issuanceFence) {
+ if (accountAuthority == null
+ || issuanceFence == null
+ || accountAuthority.issuanceFence() == null
+ || !issuanceFence.equals(accountAuthority.issuanceFence())) {
+ throw new IllegalArgumentException(
+ "Committed logout-all authority and issuance fence must match exactly");
+ }
+ return new LogoutAllReceipt(
+ requestId,
+ accountId,
+ accountUuid,
+ "ACCOUNT_LOGOUT_ALL",
+ 1,
+ requestDigest,
+ presentedTokenHash,
+ tokenProfile,
+ outboxStreamKey,
+ outboxSequence,
+ eventId,
+ eventDigest,
+ accountAuthority.generation(),
+ accountAuthority.sourceVersion(),
+ issuanceFence.value(),
+ issuanceFence.sourceVersion(),
+ LIFECYCLE_RESULT);
+ }
+
+ public IssuanceFence issuanceFenceEvidence() {
+ return new IssuanceFence(accountUuid, issuanceFence, issuanceFenceSourceVersion);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java
new file mode 100644
index 0000000000..700668e747
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java
@@ -0,0 +1,316 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Stores immutable proof for one Account-owned password-reset source commit. */
+@Repository
+@SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification = "Injected DSLContext is an internal Spring collaborator.")
+public class AccountPasswordResetOperationRepository {
+ private static final String TABLE = "account_password_reset_operation_receipts";
+ private static final String REQUEST_ID_PREFIX = "account-password-reset-request-v1:";
+ private static final String EVENT_ID_PREFIX = "account-password-reset-event-v1:";
+ private static final String SELECT_COLUMNS =
+ "token_hash, account_id, account_uuid, operation_kind, request_id, "
+ + "request_digest_version, request_digest, token_expires_at, "
+ + "password_verifier_digest, outbox_stream_key, outbox_sequence, event_id, "
+ + "event_digest, account_authority_generation, account_source_version, "
+ + "issuance_fence, issuance_fence_source_version";
+ private static final HexFormat HEX = HexFormat.of();
+
+ private final DSLContext dsl;
+
+ public AccountPasswordResetOperationRepository(DSLContext dsl) {
+ this.dsl = dsl;
+ }
+
+ /** Read-only lookup by the SHA-256 identity of the token, including after token consumption. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional findByTokenHash(String tokenHash) {
+ requireOwnerTransaction();
+ byte[] tokenHashBytes = decodeDigest(tokenHash, "token hash");
+ Record row =
+ dsl.fetchOne(
+ "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE token_hash = ?",
+ tokenHashBytes);
+ return Optional.ofNullable(row == null ? null : toReceipt(row));
+ }
+
+ /** Read-only source-history lookup used to prove a progressed Account stream. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional findByRequestId(String requestId) {
+ requireOwnerTransaction();
+ requireBoundedText(requestId, "request ID", 128);
+ Record row =
+ dsl.fetchOne(
+ "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE request_id = ?", requestId);
+ return Optional.ofNullable(row == null ? null : toReceipt(row));
+ }
+
+ /** Inserts the one immutable receipt for this token hash. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public PasswordResetReceipt insert(PasswordResetReceipt receipt) {
+ requireOwnerTransaction();
+ validateReceipt(receipt);
+ int inserted =
+ dsl.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (token_hash, account_id, account_uuid, operation_kind, request_id, "
+ + "request_digest_version, request_digest, token_expires_at, "
+ + "password_verifier_digest, outbox_stream_key, outbox_sequence, event_id, "
+ + "event_digest, account_authority_generation, account_source_version, "
+ + "issuance_fence, issuance_fence_source_version) "
+ + "VALUES (?, ?, ?, 'PASSWORD_RESET', ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ decodeDigest(receipt.tokenHash(), "token hash"),
+ receipt.accountId(),
+ receipt.accountUuid(),
+ receipt.requestId(),
+ decodeDigest(receipt.requestDigest(), "request digest"),
+ receipt.tokenExpiresAt(),
+ decodeDigest(receipt.passwordVerifierDigest(), "password verifier digest"),
+ receipt.outboxStreamKey(),
+ receipt.outboxSequence(),
+ receipt.eventId(),
+ receipt.eventDigest(),
+ receipt.accountAuthorityGeneration(),
+ receipt.accountSourceVersion(),
+ receipt.issuanceFence(),
+ receipt.issuanceFenceSourceVersion());
+ if (inserted != 1) {
+ throw new IllegalStateException("Password-reset operation receipt was not inserted");
+ }
+ return receipt;
+ }
+
+ private PasswordResetReceipt toReceipt(Record row) {
+ return new PasswordResetReceipt(
+ requiredPositive(row.get("account_id", Long.class), "Account association"),
+ Objects.requireNonNull(row.get("account_uuid", UUID.class), "receipt Account UUID"),
+ encodeDigest(row.get("token_hash", byte[].class), "token hash"),
+ requireText(row.get("operation_kind", String.class), "operation kind"),
+ requireText(row.get("request_id", String.class), "request ID"),
+ requiredPositive(row.get("request_digest_version", Integer.class), "digest version"),
+ encodeDigest(row.get("request_digest", byte[].class), "request digest"),
+ Objects.requireNonNull(
+ row.get("token_expires_at", java.time.LocalDateTime.class), "token deadline"),
+ encodeDigest(row.get("password_verifier_digest", byte[].class), "password verifier digest"),
+ requireText(row.get("outbox_stream_key", String.class), "outbox stream key"),
+ requiredPositive(row.get("outbox_sequence", Long.class), "outbox sequence"),
+ requireText(row.get("event_id", String.class), "event ID"),
+ requireText(row.get("event_digest", String.class), "event digest"),
+ requiredPositive(
+ row.get("account_authority_generation", Long.class), "Account authority generation"),
+ requiredPositive(row.get("account_source_version", Long.class), "Account source version"),
+ requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"),
+ requiredPositive(
+ row.get("issuance_fence_source_version", Long.class), "issuance-fence source version"));
+ }
+
+ private static void validateReceipt(PasswordResetReceipt receipt) {
+ Objects.requireNonNull(receipt, "password-reset receipt is required");
+ decodeDigest(receipt.tokenHash(), "token hash");
+ decodeDigest(receipt.requestDigest(), "request digest");
+ decodeDigest(receipt.passwordVerifierDigest(), "password verifier digest");
+ if (receipt.accountId() <= 0L
+ || receipt.accountUuid() == null
+ || new UUID(0L, 0L).equals(receipt.accountUuid())
+ || receipt.requestDigestVersion() != 1
+ || receipt.tokenExpiresAt() == null
+ || receipt.outboxSequence() <= 0L
+ || receipt.accountAuthorityGeneration() <= 0L
+ || receipt.accountSourceVersion() <= 0L
+ || receipt.issuanceFence() <= 0L
+ || receipt.issuanceFenceSourceVersion() <= 0L
+ || !accountStreamKey(receipt.accountUuid()).equals(receipt.outboxStreamKey())
+ || receipt.eventDigest() == null
+ || !receipt.eventDigest().matches("sha256:[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Password-reset operation receipt is malformed");
+ }
+ requireBoundedText(receipt.operationKind(), "operation kind", 32);
+ if (!"PASSWORD_RESET".equals(receipt.operationKind())) {
+ throw new IllegalArgumentException("Password-reset operation kind is invalid");
+ }
+ requireBoundedText(receipt.requestId(), "request ID", 128);
+ requireBoundedText(receipt.eventId(), "event ID", 128);
+ if (!(REQUEST_ID_PREFIX + receipt.tokenHash()).equals(receipt.requestId())
+ || !(EVENT_ID_PREFIX + receipt.tokenHash()).equals(receipt.eventId())) {
+ throw new IllegalArgumentException(
+ "Password-reset operation IDs must be derived from the token hash");
+ }
+ }
+
+ private static void requireOwnerTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException(
+ "Password-reset operation storage requires an active Account transaction");
+ }
+ }
+
+ private static long requiredPositive(Long value, String field) {
+ if (value == null || value <= 0L) {
+ throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid");
+ }
+ return value;
+ }
+
+ private static int requiredPositive(Integer value, String field) {
+ if (value == null || value <= 0) {
+ throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid");
+ }
+ return value;
+ }
+
+ private static String requireText(String value, String field) {
+ if (value == null || value.isBlank()) {
+ throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid");
+ }
+ return value;
+ }
+
+ private static void requireBoundedText(String value, String field, int maximumLength) {
+ if (value == null || value.isBlank() || value.length() > maximumLength) {
+ throw new IllegalArgumentException(
+ "Password-reset receipt "
+ + field
+ + " must contain 1 to "
+ + maximumLength
+ + " characters");
+ }
+ }
+
+ private static byte[] decodeDigest(String value, String field) {
+ if (value == null || !value.matches("[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Password-reset receipt " + field + " is malformed");
+ }
+ return HEX.parseHex(value);
+ }
+
+ private static String encodeDigest(byte[] value, String field) {
+ if (value == null || value.length != 32) {
+ throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid");
+ }
+ return HEX.formatHex(value);
+ }
+
+ private static String accountStreamKey(UUID accountUuid) {
+ return "account:auth-authority:v1:account/" + accountUuid;
+ }
+
+ /** Immutable commit and retry evidence; digest values are lowercase SHA-256 hex strings. */
+ public record PasswordResetReceipt(
+ long accountId,
+ UUID accountUuid,
+ String tokenHash,
+ String operationKind,
+ String requestId,
+ int requestDigestVersion,
+ String requestDigest,
+ java.time.LocalDateTime tokenExpiresAt,
+ String passwordVerifierDigest,
+ String outboxStreamKey,
+ long outboxSequence,
+ String eventId,
+ String eventDigest,
+ long accountAuthorityGeneration,
+ long accountSourceVersion,
+ long issuanceFence,
+ long issuanceFenceSourceVersion) {
+ public PasswordResetReceipt {
+ decodeDigest(tokenHash, "token hash");
+ decodeDigest(requestDigest, "request digest");
+ decodeDigest(passwordVerifierDigest, "password verifier digest");
+ if (accountId <= 0L
+ || accountUuid == null
+ || new UUID(0L, 0L).equals(accountUuid)
+ || requestDigestVersion != 1
+ || tokenExpiresAt == null
+ || outboxSequence <= 0L
+ || accountAuthorityGeneration <= 0L
+ || accountSourceVersion <= 0L
+ || issuanceFence <= 0L
+ || issuanceFenceSourceVersion <= 0L
+ || !accountStreamKey(accountUuid).equals(outboxStreamKey)
+ || eventDigest == null
+ || !eventDigest.matches("sha256:[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Password-reset operation receipt is malformed");
+ }
+ requireBoundedText(operationKind, "operation kind", 32);
+ if (!"PASSWORD_RESET".equals(operationKind)) {
+ throw new IllegalArgumentException("Password-reset operation kind is invalid");
+ }
+ requireBoundedText(requestId, "request ID", 128);
+ requireBoundedText(eventId, "event ID", 128);
+ if (!(REQUEST_ID_PREFIX + tokenHash).equals(requestId)
+ || !(EVENT_ID_PREFIX + tokenHash).equals(eventId)) {
+ throw new IllegalArgumentException(
+ "Password-reset operation IDs must be derived from the token hash");
+ }
+ }
+
+ public static PasswordResetReceipt committed(
+ long accountId,
+ UUID accountUuid,
+ String tokenHash,
+ String requestId,
+ String requestDigest,
+ java.time.LocalDateTime tokenExpiresAt,
+ String passwordVerifierDigest,
+ String outboxStreamKey,
+ long outboxSequence,
+ String eventId,
+ String eventDigest,
+ ScopeState accountAuthority,
+ IssuanceFence issuanceFence) {
+ if (accountAuthority == null
+ || issuanceFence == null
+ || accountAuthority.issuanceFence() == null
+ || !issuanceFence.equals(accountAuthority.issuanceFence())) {
+ throw new IllegalArgumentException(
+ "Committed password-reset authority and issuance fence must match exactly");
+ }
+ return new PasswordResetReceipt(
+ accountId,
+ accountUuid,
+ tokenHash,
+ "PASSWORD_RESET",
+ requestId,
+ 1,
+ requestDigest,
+ tokenExpiresAt,
+ passwordVerifierDigest,
+ outboxStreamKey,
+ outboxSequence,
+ eventId,
+ eventDigest,
+ accountAuthority.generation(),
+ accountAuthority.sourceVersion(),
+ issuanceFence.value(),
+ issuanceFence.sourceVersion());
+ }
+
+ public IssuanceFence issuanceFenceEvidence() {
+ return new IssuanceFence(accountUuid, issuanceFence, issuanceFenceSourceVersion);
+ }
+ }
+
+ /** A token identity was already committed with a different supplied password. */
+ 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/AccountPlatformRestrictionBirthRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepository.java
new file mode 100644
index 0000000000..abb4585c1a
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepository.java
@@ -0,0 +1,325 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource;
+import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category;
+import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.CategorySource;
+import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.RestrictionState;
+import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.SourceKind;
+import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Fresh source prerequisite only. Retained Accounts and later moderation writes are not enrolled.
+ */
+@Repository
+public class AccountPlatformRestrictionBirthRepository {
+ private final DSLContext dsl;
+
+ @SuppressFBWarnings(
+ value = "CT_CONSTRUCTOR_THROW",
+ justification = "Preserve required DSLContext; Spring must proxy this repository.")
+ public AccountPlatformRestrictionBirthRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl, "DSLContext is required");
+ }
+
+ /** Called only after the existing fresh-insert capability and sequence-zero source readback. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ void initializeFreshAccount(
+ AccountRepository.FreshAccountInsert proof, long insertTransactionId, ScopeState birth) {
+ requireTransaction();
+ Objects.requireNonNull(proof, "Fresh Account insert proof is required");
+ Record account = lockAccount(proof.accountUuid());
+ if (positive(account, "id") != proof.accountId()
+ || positive(account, "account_repository_insert_transaction_id") != insertTransactionId
+ || positive(account, "current_xid") != insertTransactionId
+ || !"active".equals(account.get("lifecycle_state", String.class))) {
+ throw new BirthSourceUnavailableException();
+ }
+ ScopeState current = currentAuthority(proof.accountUuid());
+ if (!current.equals(birth)
+ || birth.generation() != 1
+ || birth.sourceVersion() != 1
+ || birth.issuanceFence() == null
+ || birth.issuanceFence().value() != 1
+ || birth.issuanceFence().sourceVersion() != 1) {
+ throw new BirthSourceUnavailableException();
+ }
+ CategorySource lock =
+ insertCategory(
+ proof.accountUuid(),
+ proof.accountId(),
+ insertTransactionId,
+ birth,
+ Category.ACCOUNT_SECURITY_LOCK);
+ CategorySource ban =
+ insertCategory(
+ proof.accountUuid(),
+ proof.accountId(),
+ insertTransactionId,
+ birth,
+ Category.PLATFORM_ACCESS_BAN);
+ AccountPlatformRestrictionBirthSource expected =
+ new AccountPlatformRestrictionBirthSource(
+ proof.accountUuid(), proof.accountId(), insertTransactionId, birth, current, lock, ban);
+ if (!expected.equals(readCurrentBirthSource(proof.accountUuid()))) {
+ throw new BirthSourceUnavailableException();
+ }
+ }
+
+ /**
+ * Locks Account first and requires both explicit CATEGORY projections, exact immutable birth
+ * results and their distinct restriction outbox evidence. Missing or changed evidence denies.
+ * NONRESTRICTED is the historical birth result, not proof of current protective-lock absence.
+ * This source read does not authorize a player or manufacture an auth-authority event.
+ */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public AccountPlatformRestrictionBirthSource readCurrentBirthSource(UUID accountId) {
+ requireTransaction();
+ Record account = lockAccount(accountId);
+ ScopeState current = currentAuthority(accountId);
+ CategoryReadback lock = readCategory(accountId, Category.ACCOUNT_SECURITY_LOCK, account);
+ CategoryReadback ban = readCategory(accountId, Category.PLATFORM_ACCESS_BAN, account);
+ if (!lock.birthAuthority().equals(ban.birthAuthority())) {
+ throw new BirthSourceUnavailableException();
+ }
+ try {
+ return new AccountPlatformRestrictionBirthSource(
+ accountId,
+ positive(account, "id"),
+ positive(account, "account_repository_insert_transaction_id"),
+ lock.birthAuthority(),
+ current,
+ lock.source(),
+ ban.source());
+ } catch (IllegalArgumentException malformed) {
+ throw new BirthSourceUnavailableException();
+ }
+ }
+
+ private CategorySource insertCategory(
+ UUID accountId, long numericId, long transactionId, ScopeState birth, Category category) {
+ // No upsert or retry minting: this method is reachable only inside the exact new row's tx.
+ // Committed readback always returns the original retained identities.
+ UUID operationId = UUID.randomUUID();
+ UUID resultId = UUID.randomUUID();
+ UUID eventId = UUID.randomUUID();
+ String stream = AccountPlatformRestrictionBirthSource.streamKey(accountId, category);
+ String digest =
+ AccountPlatformRestrictionBirthSource.birthDigest(
+ accountId, numericId, transactionId, birth, category, operationId, resultId, eventId);
+ int inserted =
+ dsl.execute(
+ "INSERT INTO account_platform_restriction_births (account_uuid, category, revision, "
+ + "enforcement_epoch, source_kind, restriction_state, operation_id, result_id, event_id, payload_digest, "
+ + "account_source_numeric_id, account_insert_transaction_id, account_generation, "
+ + "account_source_version, issuance_fence, fence_source_version) "
+ + "VALUES (?, ?, 1, 1, 'CATEGORY', 'NONRESTRICTED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ accountId,
+ category.storageValue(),
+ operationId,
+ resultId,
+ eventId,
+ digest,
+ numericId,
+ transactionId,
+ birth.generation(),
+ birth.sourceVersion(),
+ birth.issuanceFence().value(),
+ birth.issuanceFence().sourceVersion());
+ int projected =
+ dsl.execute(
+ "INSERT INTO account_platform_restriction_projections "
+ + "(account_uuid, category, revision, enforcement_epoch, result_id) VALUES (?, ?, 1, 1, ?)",
+ accountId,
+ category.storageValue(),
+ resultId);
+ int emitted =
+ dsl.execute(
+ "INSERT INTO account_platform_restriction_birth_outbox "
+ + "(account_uuid, category, revision, enforcement_epoch, operation_id, result_id, "
+ + "event_id, payload_digest, outbox_stream_key, outbox_sequence, source_kind, restriction_state) "
+ + "VALUES (?, ?, 1, 1, ?, ?, ?, ?, ?, 1, 'CATEGORY', 'NONRESTRICTED')",
+ accountId,
+ category.storageValue(),
+ operationId,
+ resultId,
+ eventId,
+ digest,
+ stream);
+ if (inserted != 1 || projected != 1 || emitted != 1) {
+ throw new BirthSourceUnavailableException();
+ }
+ return new CategorySource(
+ category,
+ SourceKind.CATEGORY,
+ RestrictionState.NONRESTRICTED,
+ 1,
+ 1,
+ operationId,
+ resultId,
+ eventId,
+ digest,
+ stream,
+ 1);
+ }
+
+ private CategoryReadback readCategory(UUID accountId, Category category, Record account) {
+ Record birth =
+ dsl.fetchOne(
+ "SELECT * FROM account_platform_restriction_births "
+ + "WHERE account_uuid = ? AND category = ? FOR SHARE",
+ accountId,
+ category.storageValue());
+ Record projection =
+ dsl.fetchOne(
+ "SELECT * FROM account_platform_restriction_projections "
+ + "WHERE account_uuid = ? AND category = ? FOR SHARE",
+ accountId,
+ category.storageValue());
+ Record event =
+ dsl.fetchOne(
+ "SELECT * FROM account_platform_restriction_birth_outbox "
+ + "WHERE account_uuid = ? AND category = ? FOR SHARE",
+ accountId,
+ category.storageValue());
+ if (birth == null
+ || projection == null
+ || event == null
+ || positive(birth, "account_source_numeric_id") != positive(account, "id")
+ || positive(birth, "account_insert_transaction_id")
+ != positive(account, "account_repository_insert_transaction_id")) {
+ throw new BirthSourceUnavailableException();
+ }
+ for (String field :
+ new String[] {"account_uuid", "category", "revision", "enforcement_epoch", "result_id"}) {
+ if (!Objects.equals(birth.get(field), projection.get(field))
+ || !Objects.equals(birth.get(field), event.get(field))) {
+ throw new BirthSourceUnavailableException();
+ }
+ }
+ for (String field :
+ new String[] {
+ "operation_id", "event_id", "payload_digest", "source_kind", "restriction_state"
+ }) {
+ if (!Objects.equals(birth.get(field), event.get(field))) {
+ throw new BirthSourceUnavailableException();
+ }
+ }
+ if (!accountId.equals(birth.get("account_uuid", UUID.class))
+ || !category.storageValue().equals(birth.get("category", String.class))
+ || !"CATEGORY".equals(birth.get("source_kind", String.class))
+ || !"NONRESTRICTED".equals(birth.get("restriction_state", String.class))
+ || positive(birth, "revision") != 1
+ || positive(birth, "enforcement_epoch") != 1
+ || positive(event, "outbox_sequence") != 1
+ || !AccountPlatformRestrictionBirthSource.streamKey(accountId, category)
+ .equals(event.get("outbox_stream_key", String.class))) {
+ throw new BirthSourceUnavailableException();
+ }
+ try {
+ var fence =
+ new AccountAuthorityGenerationRepository.IssuanceFence(
+ accountId,
+ positive(birth, "issuance_fence"),
+ positive(birth, "fence_source_version"));
+ var authority =
+ new ScopeState(
+ AuthorityScope.account(accountId),
+ positive(birth, "account_generation"),
+ positive(birth, "account_source_version"),
+ fence);
+ if (authority.generation() != 1
+ || authority.sourceVersion() != 1
+ || fence.value() != 1
+ || fence.sourceVersion() != 1) {
+ throw new BirthSourceUnavailableException();
+ }
+ UUID operationId = birth.get("operation_id", UUID.class);
+ UUID resultId = birth.get("result_id", UUID.class);
+ UUID eventId = event.get("event_id", UUID.class);
+ if (operationId == null || resultId == null || eventId == null) {
+ throw new BirthSourceUnavailableException();
+ }
+ return new CategoryReadback(
+ authority,
+ new CategorySource(
+ category,
+ SourceKind.CATEGORY,
+ RestrictionState.NONRESTRICTED,
+ 1,
+ 1,
+ operationId,
+ resultId,
+ eventId,
+ birth.get("payload_digest", String.class),
+ event.get("outbox_stream_key", String.class),
+ 1));
+ } catch (IllegalArgumentException malformed) {
+ throw new BirthSourceUnavailableException();
+ }
+ }
+
+ private Record lockAccount(UUID accountId) {
+ if (accountId == null || accountId.version() != 4 || accountId.variant() != 2) {
+ throw new BirthSourceUnavailableException();
+ }
+ Record account =
+ dsl.fetchOne(
+ "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id, lifecycle_state, "
+ + "account_repository_insert_transaction_id, txid_current() AS current_xid "
+ + "FROM accounts WHERE account_uuid = ? FOR UPDATE",
+ accountId);
+ if (account == null
+ || !accountId.equals(account.get("account_uuid", UUID.class))
+ || !AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT
+ .name()
+ .equals(account.get("account_uuid_provenance", String.class))
+ || positive(account, "id") != positive(account, "account_uuid_source_numeric_id")) {
+ throw new BirthSourceUnavailableException();
+ }
+ positive(account, "account_repository_insert_transaction_id");
+ return account;
+ }
+
+ private ScopeState currentAuthority(UUID accountId) {
+ ScopeState state =
+ new AccountAuthorityGenerationRepository(dsl).read(AuthorityScope.account(accountId));
+ if (state.issuanceFence() == null || !accountId.equals(state.issuanceFence().accountId())) {
+ throw new BirthSourceUnavailableException();
+ }
+ return state;
+ }
+
+ private static long positive(Record row, String field) {
+ Long value = row.get(field, Long.class);
+ if (value == null || value <= 0) throw new BirthSourceUnavailableException();
+ return value;
+ }
+
+ private static void requireTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException("Restriction birth source requires an Account transaction");
+ }
+ }
+
+ private record CategoryReadback(ScopeState birthAuthority, CategorySource source) {}
+
+ public static final class BirthSourceUnavailableException extends IllegalStateException {
+ private static final long serialVersionUID = 1L;
+
+ public BirthSourceUnavailableException() {
+ super("Exact Account restriction birth source is unavailable");
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java
index 532b660843..3282040440 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java
@@ -16,7 +16,9 @@
import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountState;
import org.jooq.DSLContext;
import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
@Repository
public class AccountRepository {
@@ -52,6 +54,55 @@ public Optional findById(Long id) {
dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).fetchOne(this::toEntity));
}
+ /** Locks one exact persisted Account row before an owner-local authority mutation. */
+ @Transactional
+ public Optional findByIdForUpdate(Long id) {
+ if (id == null || id <= 0L) {
+ throw new IllegalArgumentException("A positive persisted Account ID is required");
+ }
+ return Optional.ofNullable(
+ dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).forUpdate().fetchOne(this::toEntity));
+ }
+
+ /**
+ * Replaces the verifier for one exact locked owner; the caller appends the closed reset event.
+ */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Account updatePasswordHashForLockedAccount(Account expected, String passwordHash) {
+ requireWritableOwnerTransaction();
+ if (expected == null
+ || expected.getId() == null
+ || expected.getAccountUuid() == null
+ || expected.getAccountUuidProvenance() == null
+ || expected.getAccountUuidSourceNumericId() == null
+ || passwordHash == null
+ || passwordHash.isBlank()) {
+ throw new IllegalArgumentException(
+ "A locked Account identity and password verifier are required");
+ }
+ AccountsRecord updated =
+ dsl.update(ACCOUNTS)
+ .set(ACCOUNTS.PASSWORD_HASH, passwordHash)
+ .where(ACCOUNTS.ID.eq(expected.getId()))
+ .and(ACCOUNTS.ACCOUNT_UUID.eq(expected.getAccountUuid()))
+ .and(ACCOUNTS.ACCOUNT_UUID_PROVENANCE.eq(expected.getAccountUuidProvenance().name()))
+ .and(
+ ACCOUNTS.ACCOUNT_UUID_SOURCE_NUMERIC_ID.eq(
+ expected.getAccountUuidSourceNumericId()))
+ .and(ACCOUNTS.PASSWORD_HASH.isNotDistinctFrom(expected.getPasswordHash()))
+ .returning()
+ .fetchOne();
+ if (updated == null) {
+ throw JooqAccountRepositorySupport.staleWrite("accounts", expected.getId());
+ }
+ requireExactIdentityReadback(
+ updated, expected.getAccountUuid(), expected.getAccountUuidProvenance());
+ if (!Objects.equals(updated.getPasswordHash(), passwordHash)) {
+ throw new IllegalStateException("Account password verifier readback did not match its write");
+ }
+ return toEntity(updated);
+ }
+
public Optional findByAccountUuid(UUID accountUuid) {
Objects.requireNonNull(accountUuid, "accountUuid must not be null");
return Optional.ofNullable(
@@ -60,6 +111,20 @@ public Optional findByAccountUuid(UUID accountUuid) {
.fetchOne(this::toEntity));
}
+ /** Locks one exact Account UUID inside a writable owner transaction. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional findByAccountUuidForUpdate(UUID accountUuid) {
+ if (accountUuid == null || accountUuid.equals(new UUID(0L, 0L))) {
+ throw new IllegalArgumentException("A non-nil Account UUID is required");
+ }
+ requireWritableOwnerTransaction();
+ return Optional.ofNullable(
+ dsl.selectFrom(ACCOUNTS)
+ .where(ACCOUNTS.ACCOUNT_UUID.eq(accountUuid))
+ .forUpdate()
+ .fetchOne(this::toEntity));
+ }
+
public Optional findByUsername(String username) {
return Optional.ofNullable(
dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.USERNAME.eq(username)).fetchOne(this::toEntity));
@@ -219,6 +284,14 @@ private String normalizedLoginAuthModes(Account entity) {
return AccountLoginAuthModes.normalize(entity.getLoginAuthModes());
}
+ private void requireWritableOwnerTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException(
+ "Account authority mutation requires an active writable owner transaction");
+ }
+ }
+
private static AccountAuthorityState authorityState(AccountsRecord record) {
return new AccountAuthorityState(
record.getPasswordHash(),
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..25076a2630
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java
@@ -0,0 +1,693 @@
+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.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 net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+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;
+ private final AccountAuthoritySourceEvidenceRepository sourceEvidence;
+
+ @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);
+ sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox);
+ }
+
+ /** 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) {
+ return findByRequestId(requestId, false);
+ }
+
+ /** Reads only complete immutable receipts without upgrading a source reader's Account lock. */
+ public Optional findCommittedByRequestIdShared(UUID requestId) {
+ return findByRequestId(requestId, true);
+ }
+
+ private Optional findByRequestId(UUID requestId, boolean sharedCommittedRead) {
+ 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)),
+ sharedCommittedRead);
+ Optional stored = readOperation(requestId, sharedCommittedRead);
+ if (sharedCommittedRead && stored.isPresent() && stored.orElseThrow().receipt().isEmpty()) {
+ throw new IllegalStateException("Complete committed security-state receipt is required");
+ }
+ 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(),
+ true);
+ Operation stored = findCommittedByRequestIdShared(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");
+ }
+ sourceEvidence.advanceClosedAccountHead(
+ request.accountUuid(), original.capture().sourceState(), result, event);
+ return stored;
+ }
+
+ private Optional readForUpdate(UUID requestId) {
+ return readOperation(requestId, false);
+ }
+
+ private Optional readOperation(UUID requestId, boolean shared) {
+ Record row =
+ dsl.fetchOne(
+ "SELECT * FROM "
+ + TABLE
+ + " WHERE request_id = ?"
+ + (shared ? " FOR SHARE" : " 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) {
+ lockAssociation(numericId, accountUuid, provenance, false);
+ }
+
+ private void lockAssociation(
+ long numericId, UUID accountUuid, AccountIdentityProvenance provenance, boolean shared) {
+ Record account =
+ dsl.fetchOne(
+ "SELECT id, account_uuid, account_uuid_source_numeric_id, account_uuid_provenance FROM accounts WHERE id = ?"
+ + (shared ? " FOR SHARE" : " 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/repository/AccountTenantCreationBootstrapDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java
new file mode 100644
index 0000000000..e17c784be8
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java
@@ -0,0 +1,251 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.PrivateRealmGrantVersion;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+
+/** Canonical complete-map encodings and digests for immutable creator-bootstrap owner evidence. */
+public final class AccountTenantCreationBootstrapDigest {
+ private static final String REQUEST_DOMAIN =
+ "firemud/account/tenant-creation-bootstrap/request/v1";
+ private static final String RESULT_DOMAIN = "firemud/account/tenant-creation-bootstrap/result/v1";
+
+ private AccountTenantCreationBootstrapDigest() {}
+
+ public static byte[] creatorEvidencePayload(FreshTenantCreatorEvidence evidence) {
+ Objects.requireNonNull(evidence, "creator evidence is required");
+ Map creator = new LinkedHashMap<>();
+ creator.put("schemaVersion", Integer.toString(evidence.schemaVersion()));
+ creator.put("creationEvidence", creationEvidenceMap(evidence.creationEvidence()));
+ creator.put("initiatingAccountId", evidence.initiatingAccountId().toString());
+ creator.put(
+ "accountAuthorizationOperationId", evidence.accountAuthorizationOperationId().toString());
+ creator.put("accountAuthorizationDigest", evidence.accountAuthorizationDigest());
+ creator.put("evidenceDigest", evidence.evidenceDigest());
+ return canonicalJson(creator);
+ }
+
+ public static byte[] sourceSnapshotPayload(NeverJoinedMembershipSnapshot snapshot) {
+ Objects.requireNonNull(snapshot, "Account baseline snapshot is required");
+ Map source = new LinkedHashMap<>();
+ source.put("accountId", snapshot.accountId());
+ source.put("tenantId", snapshot.tenantId());
+ source.put("membershipExists", snapshot.membershipExists());
+ source.put("membershipLifecycleState", snapshot.membershipLifecycleState());
+ source.put("gameplayAdmissionAllowed", snapshot.gameplayAdmissionAllowed());
+ source.put("roles", snapshot.roles());
+ source.put("membershipVersion", snapshot.membershipVersion());
+ source.put("membershipAuthorityGeneration", snapshot.membershipAuthorityGeneration());
+ source.put("authorityTuple", authorityTupleMap(snapshot.authorityTuple()));
+ source.put("issuanceFence", snapshot.issuanceFence());
+ source.put("evaluatedAt", snapshot.evaluatedAt().toString());
+ source.put("outboxStreamKey", snapshot.outboxStreamKey());
+ source.put(
+ "outboxCheckpoints",
+ snapshot.outboxCheckpoints().stream()
+ .map(
+ checkpoint ->
+ Map.of(
+ "outboxStreamKey", checkpoint.outboxStreamKey(),
+ "outboxSequence", checkpoint.outboxSequence()))
+ .toList());
+ source.put(
+ "outboxSourceEvidence",
+ snapshot.outboxSourceEvidence().stream()
+ .map(
+ evidence ->
+ Map.of(
+ "outboxStreamKey", evidence.outboxStreamKey(),
+ "outboxSequence", evidence.outboxSequence(),
+ "eventId", evidence.eventId(),
+ "eventDigest", evidence.eventDigest(),
+ "canonicalEventJson", evidence.canonicalEventJson()))
+ .toList());
+ return canonicalJson(source);
+ }
+
+ public static byte[] requestPayload(byte[] creatorEvidencePayload, byte[] sourceSnapshotPayload) {
+ return frameBytes(
+ REQUEST_DOMAIN.getBytes(StandardCharsets.UTF_8),
+ creatorEvidencePayload,
+ sourceSnapshotPayload);
+ }
+
+ public static byte[] resultPayload(
+ String requestId,
+ String requestDigest,
+ String sourceSnapshotDigest,
+ UUID tenantUuid,
+ Map membershipVersion,
+ String membershipAuthorityGeneration,
+ String eventStreamKey,
+ String eventRequestId,
+ long eventSequence,
+ String eventId,
+ String eventDigest,
+ byte[] eventPayload,
+ UUID auditEventId,
+ String auditEventType,
+ String auditOccurredAt,
+ String auditPayloadDigest,
+ byte[] auditPayload,
+ byte[] creatorEvidencePayload,
+ byte[] sourceSnapshotPayload) {
+ Objects.requireNonNull(tenantUuid, "result tenant UUID is required");
+ Objects.requireNonNull(membershipVersion, "result membership-version map is required");
+ String tenantKey = tenantUuid.toString();
+ if (membershipVersion.size() != 1 || !membershipVersion.containsKey(tenantKey)) {
+ throw new IllegalArgumentException(
+ "Creator-bootstrap result requires exactly its tenant membership-version entry");
+ }
+ String version = membershipVersion.get(tenantKey);
+ try {
+ if (version == null
+ || !Long.toString(Long.parseLong(version)).equals(version)
+ || Long.parseLong(version) <= 0L) {
+ throw new IllegalArgumentException("Creator-bootstrap membership version is invalid");
+ }
+ } catch (NumberFormatException failure) {
+ throw new IllegalArgumentException(
+ "Creator-bootstrap membership version is invalid", failure);
+ }
+ Map result = new LinkedHashMap<>();
+ result.put("schemaVersion", "account-tenant-creation-bootstrap-result/v1");
+ result.put("requestId", requestId);
+ result.put("requestDigest", requestDigest);
+ result.put("sourceSnapshotDigest", sourceSnapshotDigest);
+ result.put("membershipVersion", membershipVersion);
+ result.put("membershipAuthorityGeneration", membershipAuthorityGeneration);
+ result.put("eventStreamKey", eventStreamKey);
+ result.put("eventRequestId", eventRequestId);
+ result.put("eventSequence", Long.toString(eventSequence));
+ result.put("eventId", eventId);
+ result.put("eventDigest", eventDigest);
+ result.put("eventPayload", Base64.getEncoder().encodeToString(eventPayload));
+ result.put("auditEventId", auditEventId.toString());
+ result.put("auditEventType", auditEventType);
+ result.put("auditOccurredAt", auditOccurredAt);
+ result.put("auditPayloadDigest", auditPayloadDigest);
+ result.put("auditPayload", Base64.getEncoder().encodeToString(auditPayload));
+ result.put("creatorEvidence", Base64.getEncoder().encodeToString(creatorEvidencePayload));
+ result.put("sourceSnapshot", Base64.getEncoder().encodeToString(sourceSnapshotPayload));
+ return frameBytes(RESULT_DOMAIN.getBytes(StandardCharsets.UTF_8), canonicalJson(result));
+ }
+
+ public static String sha256(byte[] payload) {
+ Objects.requireNonNull(payload, "digest payload is required");
+ try {
+ return "sha256:"
+ + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload));
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException("SHA-256 is unavailable", impossible);
+ }
+ }
+
+ public static byte[] authorityTuplePayload(AuthorityTuple tuple) {
+ return canonicalJson(authorityTupleMap(tuple));
+ }
+
+ public static Map authorityTupleMap(AuthorityTuple tuple) {
+ Objects.requireNonNull(tuple, "authority tuple is required");
+ Map result = new LinkedHashMap<>();
+ result.put("issuerAuthGeneration", tuple.issuerAuthGeneration());
+ result.put("accountAuthorityGeneration", tuple.accountAuthorityGeneration());
+ result.put("tenantAuthorityGeneration", tuple.tenantAuthorityGeneration());
+ result.put("membershipAuthorityGeneration", tuple.membershipAuthorityGeneration());
+ result.put(
+ "privateRealmGrantVersions",
+ tuple.privateRealmGrantVersions().stream()
+ .map(AccountTenantCreationBootstrapDigest::grantMap)
+ .toList());
+ tuple
+ .accountSecurityCutoff()
+ .ifPresent(cutoff -> result.put("accountSecurityCutoff", cutoffMap(cutoff)));
+ tuple
+ .tenantBillingCutoff()
+ .ifPresent(
+ cutoffs -> {
+ Map encodedCutoffs = new LinkedHashMap<>();
+ cutoffs.forEach(
+ (tenantId, cutoff) -> encodedCutoffs.put(tenantId, cutoffMap(cutoff)));
+ result.put("tenantBillingCutoff", encodedCutoffs);
+ });
+ return result;
+ }
+
+ private static Map creationEvidenceMap(FreshTenantCreationEvidence evidence) {
+ Map result = new LinkedHashMap<>();
+ result.put("schemaVersion", Integer.toString(evidence.schemaVersion()));
+ result.put("targetNamespace", evidence.targetNamespace());
+ result.put("creationRequestId", evidence.creationRequestId().toString());
+ result.put("operationId", evidence.operationId().toString());
+ result.put("requestDigest", evidence.requestDigest());
+ result.put("canonicalTenantId", evidence.canonicalTenantId().toString());
+ result.put("sourceGameRowId", Long.toString(evidence.sourceGameRowId()));
+ result.put("sourceGameTenantKey", evidence.sourceGameTenantKey());
+ result.put("provenanceKind", evidence.provenanceKind());
+ result.put("evidenceDigest", evidence.evidenceDigest());
+ return result;
+ }
+
+ private static Map grantMap(PrivateRealmGrantVersion grant) {
+ return Map.of(
+ "tenantId", grant.tenantId(),
+ "worldSlug", grant.worldSlug(),
+ "realmSlug", grant.realmSlug(),
+ "playtestLifecycleId", grant.playtestLifecycleId(),
+ "grantVersion", grant.grantVersion());
+ }
+
+ private static Map cutoffMap(AccountSecurityCutoff cutoff) {
+ return Map.of(
+ "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(),
+ "outboxStreamKey", cutoff.outboxStreamKey(),
+ "outboxSequence", cutoff.outboxSequence());
+ }
+
+ private static Map cutoffMap(TenantBillingCutoff cutoff) {
+ return Map.of(
+ "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(),
+ "tenantBillingSequence", cutoff.tenantBillingSequence(),
+ "outboxStreamKey", cutoff.outboxStreamKey(),
+ "outboxSequence", cutoff.outboxSequence());
+ }
+
+ private static byte[] canonicalJson(Object value) {
+ try {
+ return Rfc8785CanonicalJson.canonicalizeUtf8(
+ tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(value));
+ } catch (IOException | RuntimeException failure) {
+ throw new IllegalStateException(
+ "Creator-bootstrap canonical JSON serialization failed", failure);
+ }
+ }
+
+ private static byte[] frameBytes(byte[]... values) {
+ ByteArrayOutputStream framed = new ByteArrayOutputStream();
+ for (byte[] value : values) {
+ Objects.requireNonNull(value, "framed value is required");
+ framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array());
+ framed.writeBytes(value);
+ }
+ return framed.toByteArray();
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java
new file mode 100644
index 0000000000..f2912cbdcf
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java
@@ -0,0 +1,573 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.time.Instant;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+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.dto.AccountTenantCreationBootstrapResult;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+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;
+
+/** Immutable Account owner request, source snapshot, and result receipt for creator bootstrap. */
+@Repository
+public class AccountTenantCreationBootstrapOperationRepository {
+ private static final String TABLE = "account_tenant_creation_bootstrap_operations";
+
+ private final DSLContext dsl;
+
+ @SuppressFBWarnings(
+ value = "CT_CONSTRUCTOR_THROW",
+ justification =
+ "Spring transaction proxy requires a non-final class; constructor only validates its internal collaborator and publishes no partial instance.")
+ public AccountTenantCreationBootstrapOperationRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl, "DSLContext is required");
+ }
+
+ /** Claims one source and baseline, or returns its exact immutable original result. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Claim claim(
+ FreshTenantCreatorEvidence evidence,
+ byte[] creatorEvidencePayload,
+ byte[] sourceSnapshotPayload,
+ String sourceSnapshotDigest,
+ byte[] requestPayload,
+ String requestDigest,
+ long baselineMembershipVersion,
+ long baselineMembershipAuthorityGeneration) {
+ requireWriteTransaction();
+ Objects.requireNonNull(evidence, "creator evidence is required");
+ requireBytes(creatorEvidencePayload, "creator evidence payload");
+ requireBytes(sourceSnapshotPayload, "Account source snapshot payload");
+ requireBytes(requestPayload, "creator-bootstrap request payload");
+ requireDigest(sourceSnapshotDigest, "source snapshot digest");
+ requireDigest(requestDigest, "request digest");
+ if (baselineMembershipVersion <= 0L || baselineMembershipAuthorityGeneration <= 0L) {
+ throw new IllegalArgumentException("Creator-bootstrap baseline counters must be positive");
+ }
+ var creation = evidence.creationEvidence();
+ UUID requestId = evidence.accountAuthorizationOperationId();
+ int inserted =
+ dsl.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (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, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'IN_PROGRESS') "
+ + "ON CONFLICT DO NOTHING",
+ requestId,
+ evidence.initiatingAccountId(),
+ creation.canonicalTenantId(),
+ creation.creationRequestId(),
+ creation.operationId(),
+ evidence.accountAuthorizationOperationId(),
+ evidence.accountAuthorizationDigest(),
+ evidence.evidenceDigest(),
+ creatorEvidencePayload,
+ sourceSnapshotPayload,
+ sourceSnapshotDigest,
+ requestPayload,
+ requestDigest,
+ baselineMembershipVersion,
+ baselineMembershipAuthorityGeneration);
+ if (inserted == 1) {
+ StoredOperation stored =
+ findForUpdate(requestId)
+ .orElseThrow(
+ () -> new IllegalStateException("Claimed creator-bootstrap operation is absent"));
+ requireSameInput(
+ stored,
+ evidence,
+ creatorEvidencePayload,
+ sourceSnapshotPayload,
+ sourceSnapshotDigest,
+ requestPayload,
+ requestDigest,
+ baselineMembershipVersion,
+ baselineMembershipAuthorityGeneration);
+ if (!"IN_PROGRESS".equals(stored.status())) {
+ throw new IllegalStateException("New creator-bootstrap claim is not in progress");
+ }
+ return new Claim(true, stored);
+ }
+ if (inserted != 0) {
+ throw new IllegalStateException("Creator-bootstrap operation claim was ambiguous");
+ }
+
+ Optional sameRequest = findForUpdate(requestId);
+ if (sameRequest.isPresent()) {
+ StoredOperation stored = sameRequest.orElseThrow();
+ requireSameInput(
+ stored,
+ evidence,
+ creatorEvidencePayload,
+ sourceSnapshotPayload,
+ sourceSnapshotDigest,
+ requestPayload,
+ requestDigest,
+ baselineMembershipVersion,
+ baselineMembershipAuthorityGeneration);
+ if (!"COMMITTED".equals(stored.status())) {
+ throw new IllegalStateException(
+ "Incomplete creator-bootstrap operation cannot be replayed");
+ }
+ return new Claim(false, stored);
+ }
+
+ Optional tenantOperation = findRequestIdByTenantForUpdate(creation.canonicalTenantId());
+ if (tenantOperation.isPresent()) {
+ throw new OperationConflictException(
+ "Fresh tenant already has a different immutable creator-bootstrap operation");
+ }
+ throw new IllegalStateException("Conflicting creator-bootstrap operation claim disappeared");
+ }
+
+ /** Returns one request under its row lock for exact retry verification. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional findForUpdate(UUID requestId) {
+ requireWriteTransaction();
+ Objects.requireNonNull(requestId, "creator-bootstrap request ID is required");
+ Record row =
+ dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", requestId);
+ return row == null ? Optional.empty() : Optional.of(toStoredOperation(row));
+ }
+
+ /** Locks the tenant's unique original creator operation when a request ID differs. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional findRequestIdByTenantForUpdate(UUID tenantUuid) {
+ requireWriteTransaction();
+ Objects.requireNonNull(tenantUuid, "tenant UUID is required");
+ Record row =
+ dsl.fetchOne(
+ "SELECT request_id FROM " + TABLE + " WHERE tenant_uuid = ? FOR UPDATE", tenantUuid);
+ return row == null ? Optional.empty() : Optional.of(row.get("request_id", UUID.class));
+ }
+
+ /**
+ * Requires no older Account membership receipt or operation history for this exact UUID pair. The
+ * caller already holds the initiator Account row fence and the Account authority snapshot.
+ */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public void assertNoContradictoryMembershipHistory(UUID accountUuid, UUID tenantUuid) {
+ requireWriteTransaction();
+ boolean priorJoinOperation =
+ exists(
+ "SELECT EXISTS (SELECT 1 FROM account_join_operations "
+ + "WHERE account_uuid = ? AND tenant_uuid = ?)",
+ accountUuid,
+ tenantUuid);
+ if (priorJoinOperation) {
+ throw new IllegalStateException(
+ "Fresh creator membership pair has contradictory retained Account JOIN history");
+ }
+ }
+
+ /** Completes the exact claim with the membership event, audit, and immutable result receipt. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public StoredOperation complete(UUID requestId, Completion completion) {
+ requireWriteTransaction();
+ Objects.requireNonNull(requestId, "creator-bootstrap request ID is required");
+ Objects.requireNonNull(completion, "creator-bootstrap completion is required");
+ int updated =
+ dsl.execute(
+ "UPDATE "
+ + TABLE
+ + " SET membership_id = ?, membership_version = ?, "
+ + "membership_authority_generation = ?, membership_lifecycle_state = ?, "
+ + "gameplay_admission_allowed = ?, membership_roles_payload = ?, "
+ + "event_stream_key = ?, event_request_id = ?, event_sequence = ?, event_id = ?, "
+ + "event_digest = ?, caller_bound_authority_invalidated = ?, event_payload = ?, "
+ + "audit_event_id = ?, audit_event_type = ?, audit_occurred_at = CAST(? AS TIMESTAMPTZ), "
+ + "audit_payload_digest = ?, audit_payload = ?, result_payload = ?, result_digest = ?, "
+ + "status = 'COMMITTED' WHERE request_id = ? AND status = 'IN_PROGRESS'",
+ completion.membershipId(),
+ completion.membershipVersion(),
+ completion.membershipAuthorityGeneration(),
+ completion.membershipLifecycleState(),
+ completion.gameplayAdmissionAllowed(),
+ completion.membershipRolesPayload(),
+ completion.eventStreamKey(),
+ completion.eventRequestId(),
+ completion.eventSequence(),
+ completion.eventId(),
+ completion.eventDigest(),
+ completion.callerBoundAuthorityInvalidated(),
+ completion.eventPayload(),
+ completion.auditEventId(),
+ completion.auditEventType(),
+ OffsetDateTime.ofInstant(completion.auditOccurredAt(), ZoneOffset.UTC).toString(),
+ completion.auditPayloadDigest(),
+ completion.auditPayload(),
+ completion.resultPayload(),
+ completion.resultDigest(),
+ requestId);
+ if (updated != 1) {
+ throw new IllegalStateException("Creator-bootstrap operation was not completed exactly once");
+ }
+ StoredOperation stored =
+ findForUpdate(requestId)
+ .orElseThrow(
+ () -> new IllegalStateException("Completed creator-bootstrap receipt is absent"));
+ if (!"COMMITTED".equals(stored.status())
+ || stored.membershipId() != completion.membershipId()
+ || stored.membershipVersion() != completion.membershipVersion()
+ || stored.membershipAuthorityGeneration() != completion.membershipAuthorityGeneration()
+ || !completion.membershipLifecycleState().equals(stored.membershipLifecycleState())
+ || !Boolean.valueOf(completion.gameplayAdmissionAllowed())
+ .equals(stored.gameplayAdmissionAllowed())
+ || !Arrays.equals(stored.membershipRolesPayload(), completion.membershipRolesPayload())
+ || !stored.eventStreamKey().equals(completion.eventStreamKey())
+ || !stored.eventRequestId().equals(completion.eventRequestId())
+ || stored.eventSequence() != completion.eventSequence()
+ || !stored.eventId().equals(completion.eventId())
+ || !stored.eventDigest().equals(completion.eventDigest())
+ || !Arrays.equals(stored.eventPayload(), completion.eventPayload())
+ || !stored.auditEventId().equals(completion.auditEventId())
+ || !stored.auditEventType().equals(completion.auditEventType())
+ || !stored.auditOccurredAt().equals(completion.auditOccurredAt())
+ || !stored.auditPayloadDigest().equals(completion.auditPayloadDigest())
+ || !Arrays.equals(stored.auditPayload(), completion.auditPayload())
+ || !Arrays.equals(stored.resultPayload(), completion.resultPayload())
+ || !stored.resultDigest().equals(completion.resultDigest())) {
+ throw new IllegalStateException("Creator-bootstrap committed receipt readback differs");
+ }
+ return stored;
+ }
+
+ private boolean exists(String query, Object... bindings) {
+ Record result = dsl.fetchOne(query, bindings);
+ return result != null && Boolean.TRUE.equals(result.get(0, Boolean.class));
+ }
+
+ private static void requireSameInput(
+ StoredOperation stored,
+ FreshTenantCreatorEvidence evidence,
+ byte[] creatorEvidencePayload,
+ byte[] sourceSnapshotPayload,
+ String sourceSnapshotDigest,
+ byte[] requestPayload,
+ String requestDigest,
+ long baselineMembershipVersion,
+ long baselineMembershipAuthorityGeneration) {
+ var creation = evidence.creationEvidence();
+ if (!stored.requestId().equals(evidence.accountAuthorizationOperationId())
+ || !stored.initiatingAccountUuid().equals(evidence.initiatingAccountId())
+ || !stored.tenantUuid().equals(creation.canonicalTenantId())
+ || !stored.creationRequestId().equals(creation.creationRequestId())
+ || !stored.creationOperationId().equals(creation.operationId())
+ || !stored
+ .accountAuthorizationOperationId()
+ .equals(evidence.accountAuthorizationOperationId())
+ || !stored.accountAuthorizationDigest().equals(evidence.accountAuthorizationDigest())
+ || !stored.creatorEvidenceDigest().equals(evidence.evidenceDigest())
+ || !Arrays.equals(stored.creatorEvidencePayload(), creatorEvidencePayload)
+ || !Arrays.equals(stored.sourceSnapshotPayload(), sourceSnapshotPayload)
+ || !stored.sourceSnapshotDigest().equals(sourceSnapshotDigest)
+ || !Arrays.equals(stored.requestPayload(), requestPayload)
+ || !stored.requestDigest().equals(requestDigest)
+ || stored.baselineMembershipVersion() != baselineMembershipVersion
+ || stored.baselineMembershipAuthorityGeneration() != baselineMembershipAuthorityGeneration
+ || stored.baselineEventSequence() != 0L) {
+ throw new OperationConflictException(
+ "Creator-bootstrap operation ID was reused with changed source or Account snapshot");
+ }
+ }
+
+ private static StoredOperation toStoredOperation(Record row) {
+ return new StoredOperation(
+ required(row.get("request_id", UUID.class), "request ID"),
+ required(row.get("initiating_account_uuid", UUID.class), "initiating Account UUID"),
+ required(row.get("tenant_uuid", UUID.class), "tenant UUID"),
+ required(row.get("creation_request_id", UUID.class), "creation request ID"),
+ required(row.get("creation_operation_id", UUID.class), "creation operation ID"),
+ required(
+ row.get("account_authorization_operation_id", UUID.class),
+ "Account authorization operation ID"),
+ required(
+ row.get("account_authorization_digest", String.class), "Account authorization digest"),
+ required(row.get("creator_evidence_digest", String.class), "creator evidence digest"),
+ required(row.get("creator_evidence_payload", byte[].class), "creator evidence payload"),
+ required(row.get("source_snapshot_payload", byte[].class), "source snapshot payload"),
+ required(row.get("source_snapshot_digest", String.class), "source snapshot digest"),
+ required(row.get("request_payload", byte[].class), "request payload"),
+ required(row.get("request_digest", String.class), "request digest"),
+ required(row.get("baseline_membership_version", Long.class), "baseline membership version"),
+ required(
+ row.get("baseline_membership_authority_generation", Long.class),
+ "baseline membership authority generation"),
+ required(row.get("baseline_event_sequence", Long.class), "baseline event sequence"),
+ required(row.get("status", String.class), "operation status"),
+ row.get("membership_id", Long.class),
+ row.get("membership_version", Long.class),
+ row.get("membership_authority_generation", Long.class),
+ row.get("membership_lifecycle_state", String.class),
+ row.get("gameplay_admission_allowed", Boolean.class),
+ row.get("membership_roles_payload", byte[].class),
+ row.get("event_stream_key", String.class),
+ row.get("event_request_id", String.class),
+ row.get("event_sequence", Long.class),
+ row.get("event_id", String.class),
+ row.get("event_digest", String.class),
+ row.get("caller_bound_authority_invalidated", Boolean.class),
+ row.get("event_payload", byte[].class),
+ row.get("audit_event_id", UUID.class),
+ row.get("audit_event_type", String.class),
+ toInstant(row.get("audit_occurred_at", OffsetDateTime.class)),
+ row.get("audit_payload_digest", String.class),
+ row.get("audit_payload", byte[].class),
+ row.get("result_payload", byte[].class),
+ row.get("result_digest", String.class),
+ toInstant(row.get("committed_at", OffsetDateTime.class)));
+ }
+
+ private static T required(T value, String label) {
+ if (value == null) {
+ throw new IllegalStateException("Creator-bootstrap stored " + label + " is absent");
+ }
+ return value;
+ }
+
+ private static Instant toInstant(OffsetDateTime value) {
+ return value == null ? null : value.toInstant();
+ }
+
+ private static void requireBytes(byte[] value, String label) {
+ if (value == null || value.length == 0) {
+ throw new IllegalArgumentException("Creator-bootstrap " + label + " is required");
+ }
+ }
+
+ private static void requireDigest(String value, String label) {
+ if (value == null || !value.matches("sha256:[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Creator-bootstrap " + label + " is malformed");
+ }
+ }
+
+ private static void requireWriteTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException(
+ "Creator-bootstrap owner operation requires a write transaction");
+ }
+ }
+
+ public record Claim(boolean claimed, StoredOperation operation) {
+ public Claim {
+ Objects.requireNonNull(operation, "claimed creator-bootstrap operation is required");
+ }
+ }
+
+ public record Completion(
+ long membershipId,
+ long membershipVersion,
+ long membershipAuthorityGeneration,
+ String membershipLifecycleState,
+ boolean gameplayAdmissionAllowed,
+ byte[] membershipRolesPayload,
+ String eventStreamKey,
+ String eventRequestId,
+ long eventSequence,
+ String eventId,
+ String eventDigest,
+ boolean callerBoundAuthorityInvalidated,
+ byte[] eventPayload,
+ UUID auditEventId,
+ String auditEventType,
+ Instant auditOccurredAt,
+ String auditPayloadDigest,
+ byte[] auditPayload,
+ byte[] resultPayload,
+ String resultDigest) {
+ public Completion {
+ if (membershipId <= 0L
+ || membershipVersion <= 0L
+ || membershipAuthorityGeneration <= 0L
+ || membershipLifecycleState == null
+ || membershipRolesPayload == null
+ || eventStreamKey == null
+ || eventRequestId == null
+ || eventSequence <= 0L
+ || eventId == null
+ || eventDigest == null
+ || eventPayload == null
+ || auditEventId == null
+ || auditEventType == null
+ || auditOccurredAt == null
+ || auditPayloadDigest == null
+ || auditPayload == null
+ || resultPayload == null
+ || resultDigest == null) {
+ throw new IllegalArgumentException("Creator-bootstrap completion evidence is incomplete");
+ }
+ membershipRolesPayload = membershipRolesPayload.clone();
+ eventPayload = eventPayload.clone();
+ auditPayload = auditPayload.clone();
+ resultPayload = resultPayload.clone();
+ }
+
+ @Override
+ public byte[] membershipRolesPayload() {
+ return membershipRolesPayload.clone();
+ }
+
+ @Override
+ public byte[] eventPayload() {
+ return eventPayload.clone();
+ }
+
+ @Override
+ public byte[] auditPayload() {
+ return auditPayload.clone();
+ }
+
+ @Override
+ public byte[] resultPayload() {
+ return resultPayload.clone();
+ }
+ }
+
+ public record StoredOperation(
+ UUID requestId,
+ UUID initiatingAccountUuid,
+ UUID tenantUuid,
+ UUID creationRequestId,
+ UUID creationOperationId,
+ UUID accountAuthorizationOperationId,
+ String accountAuthorizationDigest,
+ String creatorEvidenceDigest,
+ byte[] creatorEvidencePayload,
+ byte[] sourceSnapshotPayload,
+ String sourceSnapshotDigest,
+ byte[] requestPayload,
+ String requestDigest,
+ long baselineMembershipVersion,
+ long baselineMembershipAuthorityGeneration,
+ long baselineEventSequence,
+ String status,
+ Long membershipId,
+ Long membershipVersion,
+ Long membershipAuthorityGeneration,
+ String membershipLifecycleState,
+ Boolean gameplayAdmissionAllowed,
+ byte[] membershipRolesPayload,
+ String eventStreamKey,
+ String eventRequestId,
+ Long eventSequence,
+ String eventId,
+ String eventDigest,
+ Boolean callerBoundAuthorityInvalidated,
+ byte[] eventPayload,
+ UUID auditEventId,
+ String auditEventType,
+ Instant auditOccurredAt,
+ String auditPayloadDigest,
+ byte[] auditPayload,
+ byte[] resultPayload,
+ String resultDigest,
+ Instant committedAt) {
+ public StoredOperation {
+ creatorEvidencePayload = cloneBytes(creatorEvidencePayload);
+ sourceSnapshotPayload = cloneBytes(sourceSnapshotPayload);
+ requestPayload = cloneBytes(requestPayload);
+ membershipRolesPayload = cloneBytes(membershipRolesPayload);
+ eventPayload = cloneBytes(eventPayload);
+ auditPayload = cloneBytes(auditPayload);
+ resultPayload = cloneBytes(resultPayload);
+ }
+
+ @Override
+ public byte[] creatorEvidencePayload() {
+ return cloneBytes(creatorEvidencePayload);
+ }
+
+ @Override
+ public byte[] sourceSnapshotPayload() {
+ return cloneBytes(sourceSnapshotPayload);
+ }
+
+ @Override
+ public byte[] requestPayload() {
+ return cloneBytes(requestPayload);
+ }
+
+ @Override
+ public byte[] membershipRolesPayload() {
+ return cloneBytes(membershipRolesPayload);
+ }
+
+ @Override
+ public byte[] eventPayload() {
+ return cloneBytes(eventPayload);
+ }
+
+ @Override
+ public byte[] auditPayload() {
+ return cloneBytes(auditPayload);
+ }
+
+ @Override
+ public byte[] resultPayload() {
+ return cloneBytes(resultPayload);
+ }
+
+ public AccountTenantCreationBootstrapResult result() {
+ if (!"COMMITTED".equals(status)
+ || membershipVersion == null
+ || membershipAuthorityGeneration == null
+ || eventSequence == null
+ || eventStreamKey == null
+ || eventRequestId == null
+ || eventId == null
+ || eventDigest == null
+ || auditEventId == null
+ || auditEventType == null
+ || auditPayloadDigest == null
+ || resultDigest == null) {
+ throw new IllegalStateException("Incomplete creator-bootstrap result is not replayable");
+ }
+ return new AccountTenantCreationBootstrapResult(
+ requestId,
+ requestDigest,
+ initiatingAccountUuid,
+ tenantUuid,
+ creatorEvidenceDigest,
+ sourceSnapshotDigest,
+ java.util.Map.of(tenantUuid.toString(), Long.toString(membershipVersion)),
+ Long.toString(membershipAuthorityGeneration),
+ List.of("tenantAdmin"),
+ false,
+ eventStreamKey,
+ eventRequestId,
+ eventSequence,
+ eventId,
+ eventDigest,
+ auditEventId,
+ auditEventType,
+ auditPayloadDigest,
+ resultDigest);
+ }
+
+ private static byte[] cloneBytes(byte[] bytes) {
+ return bytes == null ? null : bytes.clone();
+ }
+ }
+
+ 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/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java
index 8ece8ba979..6618c17601 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java
@@ -294,6 +294,95 @@ public AccountTenantMembership createFreshMembershipForJoin(UUID accountUuid, UU
return readback;
}
+ /** Account-fenced absence enrollment for the fresh creator owner; creates no membership. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public PairAuthority prepareFreshCreatorAbsence(UUID accountUuid, UUID tenantUuid) {
+ requireOwnerWriteTransaction();
+ Account account = lockCanonicalAccountByUuid(accountUuid);
+ VerifiedTenantProvenance provenance = readFreshProvenance(tenantUuid);
+ if (readCanonicalRow(account.getId(), tenantUuid, true) != null) {
+ throw new IllegalStateException("Fresh creator membership is not absent");
+ }
+ Record retainedRoleHistoryCheck =
+ dsl.fetchOne(
+ "SELECT EXISTS (SELECT 1 FROM account_tenant_membership_role_snapshots roles "
+ + "JOIN account_tenant_membership member ON member.id = roles.membership_id "
+ + "WHERE member.account_id = ? AND member.tenant_uuid = ?)",
+ account.getId(),
+ tenantUuid);
+ if (retainedRoleHistoryCheck == null) {
+ throw new IllegalStateException("Fresh creator role history check is absent");
+ }
+ if (!Boolean.FALSE.equals(retainedRoleHistoryCheck.get(0, Boolean.class))) {
+ throw new IllegalStateException("Fresh creator pair has retained role history");
+ }
+ return pairAuthorityRepository.enrollAbsence(accountUuid, tenantUuid, provenance);
+ }
+
+ /** Exact UUID source row, including a creator write awaiting its same-transaction event. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional findCanonicalMembershipForUpdate(
+ UUID accountUuid, UUID tenantUuid) {
+ requireOwnerWriteTransaction();
+ requireCanonicalUuid(tenantUuid, "tenant UUID");
+ Account account = lockCanonicalAccountByUuid(accountUuid);
+ VerifiedTenantProvenance provenance = readFreshProvenance(tenantUuid);
+ Record row = readCanonicalRow(account.getId(), tenantUuid, true);
+ if (row == null) return Optional.empty();
+ AccountTenantMembership membership = toCanonicalEntity(row, account);
+ requireFreshMembershipIdentity(membership, account, tenantUuid, provenance);
+ return Optional.of(membership);
+ }
+
+ /** Creates only the exact first control-only creator row from its durable absence pair. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public AccountTenantMembership createFreshCreatorMembership(UUID accountUuid, UUID tenantUuid) {
+ requireOwnerWriteTransaction();
+ Account account = lockCanonicalAccountByUuid(accountUuid);
+ VerifiedTenantProvenance provenance = readFreshProvenance(tenantUuid);
+ if (readCanonicalRow(account.getId(), tenantUuid, true) != null) {
+ throw new IllegalStateException("Creator bootstrap cannot overwrite membership");
+ }
+ PairAuthority baseline =
+ pairAuthorityRepository
+ .readForUpdate(accountUuid, tenantUuid)
+ .orElseThrow(() -> new IllegalStateException("Creator absence pair is absent"));
+ if (!new PairAuthority(
+ accountUuid, tenantUuid, provenance, false, 1L, 1L, 0L, null, null, false)
+ .equals(baseline)) {
+ throw new IllegalStateException("Creator pair differs from its exact absence baseline");
+ }
+ Long id =
+ dsl.resultQuery(
+ "INSERT INTO account_tenant_membership (account_id, tenant_id, tenant_uuid, "
+ + "tenant_provenance_kind, tenant_source_operation_id, tenant_provenance_digest, "
+ + "gameplay_admission_allowed, lifecycle_state, membership_version, "
+ + "membership_authority_generation, authority_provenance) "
+ + "VALUES (?, NULL, ?, ?, ?, ?, FALSE, 'ACTIVE', 2, 1, 'TENANT_CREATION') RETURNING id",
+ account.getId(),
+ tenantUuid,
+ provenance.kind().name(),
+ provenance.sourceOperationId(),
+ provenance.digest())
+ .fetchOne(0, Long.class);
+ AccountTenantMembership result =
+ findCanonicalMembershipForUpdate(accountUuid, tenantUuid)
+ .orElseThrow(() -> new IllegalStateException("Creator membership readback is absent"));
+ if (id == null
+ || id <= 0L
+ || !id.equals(result.getId())
+ || result.getMembershipVersion() != 2L
+ || result.getMembershipAuthorityGeneration() != 1L
+ || result.isGameplayAdmissionAllowed()
+ || !"ACTIVE".equals(result.getLifecycleState())
+ || !"TENANT_CREATION".equals(result.getAuthorityProvenance())
+ || !Optional.of(baseline)
+ .equals(pairAuthorityRepository.readForUpdate(accountUuid, tenantUuid))) {
+ throw new IllegalStateException("Creator membership readback differs from its write");
+ }
+ return result;
+ }
+
public boolean existsByAccountIdAndTenantId(Long accountId, Long tenantId) {
requirePositiveNumericTenantId(tenantId);
return dsl.fetchExists(
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java
index 5c509ff3eb..b7a5eb5025 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java
@@ -10,6 +10,8 @@
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;
@Repository
@SuppressFBWarnings(
@@ -61,6 +63,27 @@ public void delete(PasswordResetToken entity) {
}
}
+ /** Atomically consumes the exact still-valid token row under the caller's owner transaction. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public boolean consumeIfUnexpired(PasswordResetToken token, LocalDateTime capturedNow) {
+ if (token == null || token.getId() == null || capturedNow == null) {
+ return false;
+ }
+ return dsl.deleteFrom(PASSWORD_RESET_TOKEN)
+ .where(
+ PASSWORD_RESET_TOKEN
+ .ID
+ .eq(token.getId())
+ .and(PASSWORD_RESET_TOKEN.TOKEN.eq(token.getToken()))
+ .and(
+ PASSWORD_RESET_TOKEN.ACCOUNT_ID.eq(
+ token.getAccount() == null ? null : token.getAccount().getId()))
+ .and(PASSWORD_RESET_TOKEN.EXPIRES_AT.eq(token.getExpiresAt()))
+ .and(PASSWORD_RESET_TOKEN.EXPIRES_AT.gt(capturedNow)))
+ .execute()
+ == 1;
+ }
+
public void deleteByAccountId(Long accountId) {
dsl.deleteFrom(PASSWORD_RESET_TOKEN)
.where(PASSWORD_RESET_TOKEN.ACCOUNT_ID.eq(accountId))
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java
new file mode 100644
index 0000000000..8413b44ed1
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java
@@ -0,0 +1,714 @@
+package net.firedevops.firemud.accountservice.service;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event;
+import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt;
+import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt;
+import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository;
+import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff;
+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;
+import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * 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 JsonMapper SNAPSHOT_JSON =
+ JsonMapper.builder()
+ .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .build();
+ private static final String STREAM_PREFIX = "account:auth-authority:v1:account/";
+ private static final String PASSWORD_RESET_REQUEST_ID_PREFIX =
+ "account-password-reset-request-v1:";
+ private static final String PASSWORD_RESET_EVENT_ID_PREFIX = "account-password-reset-event-v1:";
+ private static final String PASSWORD_RESET_REQUEST_DOMAIN = "account-password-reset-request/v1";
+ private static final String LOGOUT_ALL_EVENT_ID_PREFIX = "account-logout-all-event-v1:";
+ private static final String PASSWORD_RESET_OPERATION_KIND = "PASSWORD_RESET";
+ private static final String LOGOUT_ALL_OPERATION_KIND = "ACCOUNT_LOGOUT_ALL";
+ private static final String LOGOUT_ALL_RESULT = "LOGOUT_ALL_COMMITTED";
+
+ private final AccountAuthorityOutboxRepository outboxRepository;
+ private final AccountPasswordResetOperationRepository passwordResetRepository;
+ private final AccountLogoutAllOperationRepository logoutAllRepository;
+ private final AccountSecurityStateOperationRepository securityStateRepository;
+
+ public AccountAuthoritySourceEventReadback(
+ AccountAuthorityOutboxRepository outboxRepository,
+ AccountPasswordResetOperationRepository passwordResetRepository,
+ AccountLogoutAllOperationRepository logoutAllRepository,
+ AccountSecurityStateOperationRepository securityStateRepository) {
+ this.outboxRepository =
+ Objects.requireNonNull(outboxRepository, "Account authority outbox repository is required");
+ this.passwordResetRepository =
+ Objects.requireNonNull(
+ passwordResetRepository, "Password-reset operation repository is required");
+ this.logoutAllRepository =
+ Objects.requireNonNull(logoutAllRepository, "Logout-all operation repository is required");
+ this.securityStateRepository =
+ Objects.requireNonNull(
+ securityStateRepository, "Security-state operation repository is required");
+ }
+
+ /**
+ * Proves the exact current Account source generation, source version and shared outbox
+ * checkpoint. Sequence zero is valid only for the original positive 1/1 source baseline and
+ * absent history.
+ */
+ public LatestSourceSnapshot requireCurrentLatest(Account account, ScopeState current) {
+ requireAccountAssociation(account);
+ AuthorityScope expectedScope = AuthorityScope.account(account.getAccountUuid());
+ if (current == null
+ || !expectedScope.equals(current.scope())
+ || current.generation() <= 0L
+ || current.sourceVersion() <= 0L) {
+ throw new IllegalStateException("Account source authority scope or counters are invalid");
+ }
+ requireCurrentFence(current.issuanceFence(), account.getAccountUuid());
+
+ String streamKey = streamKey(account.getAccountUuid());
+ Optional checkpoint = outboxRepository.readCheckpoint(streamKey);
+ if (checkpoint.isEmpty()) {
+ if (current.generation() != 1L || current.sourceVersion() != 1L) {
+ throw new IllegalStateException(
+ "Account source sequence zero is not the original positive 1/1 baseline");
+ }
+ return new LatestSourceSnapshot(0L, Optional.empty());
+ }
+
+ Checkpoint latestCheckpoint = checkpoint.orElseThrow();
+ if (current.generation() == 1L && current.sourceVersion() == 1L) {
+ throw new IllegalStateException("Pristine Account source has contradictory event history");
+ }
+ if (current.generation() <= 1L || current.sourceVersion() <= 1L) {
+ throw new IllegalStateException("Account source history is not proven");
+ }
+ // The latest closed receipt cannot make an earlier generic Account mutation authoritative.
+ // Retain generic history for inspection elsewhere, but fail closed for currentness until every
+ // event in this stream has the closed operation-specific receipt/readback contract.
+ for (long sequence = 1L; sequence < latestCheckpoint.outboxSequence(); sequence++) {
+ Event retainedEvent =
+ outboxRepository
+ .findEvent(streamKey, sequence)
+ .orElseThrow(
+ () -> new IllegalStateException("Retained Account source event is missing"));
+ requireRetainedEvent(account, retainedEvent, current);
+ }
+ Event latestEvent =
+ outboxRepository
+ .findEvent(streamKey, latestCheckpoint.outboxSequence())
+ .orElseThrow(() -> new IllegalStateException("Latest Account source event is missing"));
+ requireCheckpointMatches(latestCheckpoint, latestEvent);
+ VerifiedSourceEvent verified = verifyEvent(latestEvent, account.getAccountUuid());
+ if (!Long.toString(current.generation()).equals(verified.accountAuthorityGeneration())
+ || !Long.toString(current.sourceVersion()).equals(verified.sourceVersion())) {
+ throw new IllegalStateException(
+ "Latest Account source event does not match its current generation and source version");
+ }
+
+ if (verified.passwordReset().isPresent()) {
+ PasswordResetReceipt receipt =
+ passwordResetRepository
+ .findByRequestId(verified.requestId())
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Latest Account password-reset event has no immutable operation receipt"));
+ requirePasswordResetReceipt(account, receipt, latestEvent, verified, current);
+ } else if (verified.securityState().isPresent()) {
+ requireSecurityStateReceipt(account, latestEvent, verified, current, true);
+ } else {
+ UUID requestId = parseLogoutAllRequestId(verified.requestId());
+ LogoutAllReceipt receipt =
+ logoutAllRepository
+ .findByRequestId(requestId)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Latest Account logout-all event has no immutable operation receipt"));
+ requireLogoutAllReceipt(account, receipt, latestEvent, verified, current);
+ }
+ return new LatestSourceSnapshot(latestEvent.outboxSequence(), Optional.of(latestEvent));
+ }
+
+ /** Validates one retained logout-all receipt after the account stream has advanced further. */
+ public void requireLogoutAllReceiptRetained(
+ Account account, LogoutAllReceipt receipt, Event event, ScopeState current) {
+ requireAccountAssociation(account);
+ if (current == null
+ || !AuthorityScope.account(account.getAccountUuid()).equals(current.scope())) {
+ throw new IllegalStateException("Logout-all current Account source scope is invalid");
+ }
+ requireCurrentFence(current.issuanceFence(), account.getAccountUuid());
+ VerifiedSourceEvent verified = verifyEvent(event, account.getAccountUuid());
+ requireLogoutAllReceipt(account, receipt, event, verified, current);
+ if (event.outboxSequence() > currentSourceSequence(account)) {
+ throw new IllegalStateException(
+ "Logout-all operation event is ahead of its source checkpoint");
+ }
+ }
+
+ /**
+ * Validates one selected immutable Account event and its receipt against the current local
+ * authority fence. Historical password-reset evidence deliberately does not prove that the old
+ * password verifier remains current or make that reset operation recoverable.
+ */
+ public RetainedEventEvidence requireRetainedEvent(
+ Account account, Event event, ScopeState current) {
+ requireAccountAssociation(account);
+ if (current == null
+ || !AuthorityScope.account(account.getAccountUuid()).equals(current.scope())
+ || current.generation() <= 0L
+ || current.sourceVersion() <= 0L) {
+ throw new IllegalStateException("Retained Account source authority state is invalid");
+ }
+ requireCurrentFence(current.issuanceFence(), account.getAccountUuid());
+ VerifiedSourceEvent verified = verifyEvent(event, account.getAccountUuid());
+ if (event.outboxSequence() > currentSourceSequence(account)) {
+ throw new IllegalStateException("Selected Account source event is ahead of its checkpoint");
+ }
+
+ if (verified.passwordReset().isPresent()) {
+ PasswordResetReceipt receipt =
+ passwordResetRepository
+ .findByRequestId(verified.requestId())
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Selected Account password-reset event has no immutable operation receipt"));
+ requirePasswordResetReceiptBinding(account, receipt, event, verified, current);
+ return retainedEvidence(
+ event, verified, receipt.issuanceFence(), receipt.issuanceFenceSourceVersion());
+ }
+
+ if (verified.securityState().isPresent()) {
+ var operation =
+ securityStateRepository
+ .findCommittedByRequestIdShared(UUID.fromString(verified.requestId()))
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Selected Account security-state event has no immutable operation receipt"));
+ var receipt =
+ operation
+ .receipt()
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Selected Account security-state operation is not COMMITTED"));
+ requireSecurityStateReceipt(account, event, verified, current, false);
+ return retainedEvidence(
+ event,
+ verified,
+ receipt.sourceState().issuanceFence().value(),
+ receipt.sourceState().issuanceFence().sourceVersion());
+ }
+ UUID requestId = parseLogoutAllRequestId(verified.requestId());
+ LogoutAllReceipt receipt =
+ logoutAllRepository
+ .findByRequestId(requestId)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Selected Account logout-all event has no immutable operation receipt"));
+ requireLogoutAllReceipt(account, receipt, event, verified, current);
+ return retainedEvidence(
+ event, verified, receipt.issuanceFence(), receipt.issuanceFenceSourceVersion());
+ }
+
+ private RetainedEventEvidence retainedEvidence(
+ Event event, VerifiedSourceEvent verified, long issuanceFence, long fenceSourceVersion) {
+ return new RetainedEventEvidence(
+ event.outboxStreamKey(),
+ event.outboxSequence(),
+ Long.parseLong(verified.accountAuthorityGeneration()),
+ Long.parseLong(verified.sourceVersion()),
+ issuanceFence,
+ fenceSourceVersion,
+ verified.accountSecurityCutoff());
+ }
+
+ private long currentSourceSequence(Account account) {
+ return outboxRepository
+ .readCheckpoint(streamKey(account.getAccountUuid()))
+ .map(Checkpoint::outboxSequence)
+ .orElse(0L);
+ }
+
+ private void requireSecurityStateReceipt(
+ Account account,
+ Event event,
+ VerifiedSourceEvent verified,
+ ScopeState current,
+ boolean latest) {
+ var operation =
+ securityStateRepository
+ .findCommittedByRequestIdShared(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,
+ Event event,
+ VerifiedSourceEvent verified,
+ ScopeState current) {
+ requirePasswordResetReceiptBinding(account, receipt, event, verified, current);
+ requireCurrentPasswordVerifier(account, receipt);
+ }
+
+ private void requirePasswordResetReceiptBinding(
+ Account account,
+ PasswordResetReceipt receipt,
+ Event event,
+ VerifiedSourceEvent verified,
+ ScopeState current) {
+ if (receipt.accountId() != account.getId()
+ || !account.getAccountUuid().equals(receipt.accountUuid())
+ || !PASSWORD_RESET_OPERATION_KIND.equals(receipt.operationKind())
+ || receipt.requestDigestVersion() != 1
+ || !streamKey(account.getAccountUuid()).equals(receipt.outboxStreamKey())
+ || receipt.outboxSequence() != event.outboxSequence()
+ || !receipt.requestId().equals(event.requestId())
+ || !receipt.eventId().equals(event.eventId())
+ || !receipt.eventDigest().equals(event.eventDigest())
+ || !receipt.eventId().equals(PASSWORD_RESET_EVENT_ID_PREFIX + receipt.tokenHash())
+ || !receipt.requestId().equals(PASSWORD_RESET_REQUEST_ID_PREFIX + receipt.tokenHash())
+ || !Long.toString(receipt.accountAuthorityGeneration())
+ .equals(verified.accountAuthorityGeneration())
+ || !Long.toString(receipt.accountSourceVersion()).equals(verified.sourceVersion())) {
+ throw new IllegalStateException(
+ "Latest Account password-reset receipt does not match its source event");
+ }
+ String expectedDigest =
+ passwordResetRequestDigest(
+ receipt.accountUuid(),
+ receipt.tokenHash(),
+ receipt.tokenExpiresAt().toString(),
+ receipt.passwordVerifierDigest());
+ if (!constantTimeTextEquals(expectedDigest, receipt.requestDigest())) {
+ throw new IllegalStateException(
+ "Latest Account password-reset receipt request digest is inconsistent");
+ }
+ requireReceiptNotAhead(
+ receipt.accountAuthorityGeneration(),
+ receipt.accountSourceVersion(),
+ receipt.issuanceFence(),
+ receipt.issuanceFenceSourceVersion(),
+ current,
+ "Password-reset");
+ }
+
+ private void requireCurrentPasswordVerifier(Account account, PasswordResetReceipt receipt) {
+ String currentVerifier = account.getPasswordHash();
+ if (currentVerifier == null
+ || currentVerifier.isBlank()
+ || !constantTimeTextEquals(sha256Hex(currentVerifier), receipt.passwordVerifierDigest())) {
+ throw new IllegalStateException(
+ "Latest Account password-reset event does not match the current password verifier");
+ }
+ }
+
+ private void requireLogoutAllReceipt(
+ Account account,
+ LogoutAllReceipt receipt,
+ Event event,
+ VerifiedSourceEvent verified,
+ ScopeState current) {
+ UUID requestId = parseLogoutAllRequestId(verified.requestId());
+ if (!requestId.toString().equals(verified.requestId())
+ || !requestId.equals(receipt.requestId())
+ || receipt.accountId() != account.getId()
+ || !account.getAccountUuid().equals(receipt.accountUuid())
+ || !LOGOUT_ALL_OPERATION_KIND.equals(receipt.operationKind())
+ || receipt.requestDigestVersion() != 1
+ || !receipt.lifecycleResult().equals(LOGOUT_ALL_RESULT)
+ || !streamKey(account.getAccountUuid()).equals(receipt.outboxStreamKey())
+ || receipt.outboxSequence() != event.outboxSequence()
+ || !receipt.requestId().toString().equals(event.requestId())
+ || !receipt.eventId().equals(event.eventId())
+ || !receipt.eventDigest().equals(event.eventDigest())
+ || !receipt.eventId().equals(LOGOUT_ALL_EVENT_ID_PREFIX + receipt.requestId())
+ || !Long.toString(receipt.accountAuthorityGeneration())
+ .equals(verified.accountAuthorityGeneration())
+ || !Long.toString(receipt.accountSourceVersion()).equals(verified.sourceVersion())) {
+ throw new IllegalStateException("Latest Account logout-all receipt does not match its event");
+ }
+ String expectedRequestDigest =
+ AccountLogoutRequestDigest.accountLogoutAll(
+ receipt.accountUuid(), receipt.tokenProfile(), receipt.presentedTokenHash());
+ if (!constantTimeTextEquals(expectedRequestDigest, receipt.requestDigest())) {
+ throw new IllegalStateException(
+ "Account logout-all receipt request digest does not match its immutable caller bindings");
+ }
+ requireReceiptNotAhead(
+ receipt.accountAuthorityGeneration(),
+ receipt.accountSourceVersion(),
+ receipt.issuanceFence(),
+ receipt.issuanceFenceSourceVersion(),
+ current,
+ "Logout-all");
+ }
+
+ private UUID parseLogoutAllRequestId(String requestIdText) {
+ UUID requestId;
+ try {
+ requestId = UUID.fromString(requestIdText);
+ } catch (IllegalArgumentException exception) {
+ throw new IllegalStateException("Logout-all source request ID is malformed", exception);
+ }
+ if (!requestId.toString().equals(requestIdText)) {
+ throw new IllegalStateException("Logout-all source request ID is not canonical");
+ }
+ return requestId;
+ }
+
+ private static VerifiedSourceEvent verifyEvent(Event event, UUID accountUuid) {
+ if (event == null) throw new IllegalStateException("Account source event is missing");
+ String payload = new String(event.payload(), StandardCharsets.UTF_8);
+ try {
+ 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 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);
+ }
+ 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 (tools.jackson.core.JacksonException | IllegalArgumentException invalid) {
+ throw new IllegalStateException("Account source event is invalid", invalid);
+ }
+ }
+
+ 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
+ || current == null
+ || !AuthorityScope.account(accountUuid).equals(current.scope())
+ || current.generation() <= 0L
+ || current.sourceVersion() <= 0L) {
+ throw new IllegalStateException("Account source snapshot scope or counters are invalid");
+ }
+ SnapshotCounters verified = verifySnapshotEvent(event, accountUuid);
+ BigInteger eventGeneration = new BigInteger(verified.accountAuthorityGeneration());
+ BigInteger eventSourceVersion = new BigInteger(verified.sourceVersion());
+ BigInteger currentGeneration = BigInteger.valueOf(current.generation());
+ BigInteger currentSourceVersion = BigInteger.valueOf(current.sourceVersion());
+ boolean countersMatch =
+ mustBeCurrentLatest
+ ? eventGeneration.equals(currentGeneration)
+ && eventSourceVersion.equals(currentSourceVersion)
+ : eventGeneration.compareTo(currentGeneration) <= 0
+ && eventSourceVersion.compareTo(currentSourceVersion) <= 0;
+ if (!countersMatch) {
+ throw new IllegalStateException(
+ "Account source event counters contradict or lead the current snapshot");
+ }
+ }
+
+ private static SnapshotCounters verifySnapshotEvent(Event event, UUID accountUuid) {
+ VerifiedSourceEvent verified = verifyEvent(event, accountUuid);
+ return new SnapshotCounters(verified.accountAuthorityGeneration(), verified.sourceVersion());
+ }
+
+ private record SnapshotCounters(String accountAuthorityGeneration, String sourceVersion) {}
+
+ private void requireReceiptNotAhead(
+ long generation,
+ long sourceVersion,
+ long fence,
+ long fenceSourceVersion,
+ ScopeState current,
+ String operation) {
+ IssuanceFence currentFence = current.issuanceFence();
+ if (generation > current.generation()
+ || sourceVersion > current.sourceVersion()
+ || fence > currentFence.value()
+ || fenceSourceVersion > currentFence.sourceVersion()) {
+ throw new IllegalStateException(operation + " receipt is ahead of current Account authority");
+ }
+ }
+
+ private void requireCurrentFence(IssuanceFence fence, UUID accountUuid) {
+ if (fence == null
+ || !accountUuid.equals(fence.accountId())
+ || fence.value() <= 0L
+ || fence.sourceVersion() <= 0L) {
+ throw new IllegalStateException("Account source issuance fence is missing or invalid");
+ }
+ }
+
+ private void requireAccountAssociation(Account account) {
+ AccountIdentityProvenance provenance =
+ account == null ? null : account.getAccountUuidProvenance();
+ if (account == null
+ || account.getId() == null
+ || account.getId() <= 0L
+ || account.getAccountUuid() == null
+ || new UUID(0L, 0L).equals(account.getAccountUuid())
+ || account.getAccountUuidSourceNumericId() == null
+ || !account.getId().equals(account.getAccountUuidSourceNumericId())
+ || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT
+ && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION
+ && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT)) {
+ throw new IllegalStateException("Verified persisted Account association is required");
+ }
+ }
+
+ private void requireCheckpointMatches(Checkpoint checkpoint, Event event) {
+ if (!checkpoint.outboxStreamKey().equals(event.outboxStreamKey())
+ || checkpoint.outboxSequence() != event.outboxSequence()
+ || !checkpoint.sourceEventId().equals(event.eventId())
+ || !checkpoint.sourceEventDigest().equals(event.eventDigest())) {
+ throw new IllegalStateException("Account source checkpoint differs from its latest event");
+ }
+ }
+
+ private String streamKey(UUID accountUuid) {
+ return STREAM_PREFIX + accountUuid;
+ }
+
+ private String passwordResetRequestDigest(
+ UUID accountUuid, String tokenHash, String tokenExpiresAt, String verifierDigest) {
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ updateLengthPrefixed(digest, PASSWORD_RESET_REQUEST_DOMAIN);
+ updateLengthPrefixed(digest, PASSWORD_RESET_OPERATION_KIND);
+ updateLengthPrefixed(digest, accountUuid.toString());
+ updateLengthPrefixed(digest, tokenHash);
+ updateLengthPrefixed(digest, tokenExpiresAt);
+ updateLengthPrefixed(digest, verifierDigest);
+ return HexFormat.of().formatHex(digest.digest());
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is unavailable", exception);
+ }
+ }
+
+ private void updateLengthPrefixed(MessageDigest digest, String value) {
+ if (value == null) {
+ throw new IllegalArgumentException("Password-reset request field is required");
+ }
+ byte[] encoded = value.getBytes(StandardCharsets.UTF_8);
+ digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array());
+ digest.update(encoded);
+ }
+
+ private String sha256Hex(String value) {
+ try {
+ return HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is unavailable", exception);
+ }
+ }
+
+ private boolean constantTimeTextEquals(String left, String right) {
+ return left != null
+ && right != null
+ && MessageDigest.isEqual(
+ left.getBytes(StandardCharsets.US_ASCII), right.getBytes(StandardCharsets.US_ASCII));
+ }
+
+ /** Current exact source checkpoint; empty event is legal only for the proven 1/1 baseline. */
+ public record LatestSourceSnapshot(long outboxSequence, Optional latestEvent) {
+ public LatestSourceSnapshot {
+ latestEvent = Objects.requireNonNull(latestEvent, "latest source event optional is required");
+ if (outboxSequence < 0L
+ || (outboxSequence == 0L && latestEvent.isPresent())
+ || (outboxSequence > 0L
+ && (latestEvent.isEmpty()
+ || latestEvent.orElseThrow().outboxSequence() != outboxSequence))) {
+ throw new IllegalArgumentException("Account latest source snapshot is inconsistent");
+ }
+ }
+ }
+
+ /** Exact closed-schema source counters and cutoff returned only after receipt validation. */
+ public record RetainedEventEvidence(
+ String outboxStreamKey,
+ long outboxSequence,
+ long accountAuthorityGeneration,
+ long sourceVersion,
+ long issuanceFence,
+ long issuanceFenceSourceVersion,
+ AccountSecurityCutoff accountSecurityCutoff) {
+ public RetainedEventEvidence {
+ if (outboxStreamKey == null
+ || outboxSequence <= 0L
+ || accountAuthorityGeneration <= 0L
+ || sourceVersion <= 0L
+ || issuanceFence != accountAuthorityGeneration
+ || issuanceFenceSourceVersion != sourceVersion
+ || accountSecurityCutoff == null
+ || !outboxStreamKey.equals(accountSecurityCutoff.outboxStreamKey())
+ || outboxSequence != Long.parseLong(accountSecurityCutoff.outboxSequence())
+ || accountAuthorityGeneration
+ != Long.parseLong(accountSecurityCutoff.accountAuthorityGeneration())) {
+ throw new IllegalArgumentException("Retained Account source evidence is inconsistent");
+ }
+ }
+ }
+
+ private record VerifiedSourceEvent(
+ String requestId,
+ String accountAuthorityGeneration,
+ String sourceVersion,
+ AccountSecurityCutoff accountSecurityCutoff,
+ Optional passwordReset,
+ Optional
+ securityState) {
+ private static VerifiedSourceEvent passwordReset(PasswordResetAuthorityEvent event) {
+ return new VerifiedSourceEvent(
+ event.requestId(),
+ event.accountAuthorityGeneration(),
+ event.sourceVersion(),
+ new AccountSecurityCutoff(
+ event.accountSecurityCutoff().accountAuthorityGeneration(),
+ event.accountSecurityCutoff().outboxStreamKey(),
+ event.accountSecurityCutoff().outboxSequence()),
+ Optional.of(event),
+ Optional.empty());
+ }
+
+ private static VerifiedSourceEvent logoutAll(AccountLogoutAllAuthorityEvent event) {
+ return new VerifiedSourceEvent(
+ event.requestId(),
+ event.accountAuthorityGeneration(),
+ event.sourceVersion(),
+ new AccountSecurityCutoff(
+ event.accountSecurityCutoff().accountAuthorityGeneration(),
+ event.accountSecurityCutoff().outboxStreamKey(),
+ event.accountSecurityCutoff().outboxSequence()),
+ Optional.empty(),
+ Optional.empty());
+ }
+
+ private static VerifiedSourceEvent securityState(
+ AccountSecurityStateAuthorityEventV1Codec.AccountSecurityStateAuthorityEvent event) {
+ return new VerifiedSourceEvent(
+ event.requestId(),
+ event.accountAuthorityGeneration(),
+ event.sourceVersion(),
+ new AccountSecurityCutoff(
+ event.accountSecurityCutoff().accountAuthorityGeneration(),
+ event.accountSecurityCutoff().outboxStreamKey(),
+ event.accountSecurityCutoff().outboxSequence()),
+ Optional.empty(),
+ Optional.of(event));
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java
new file mode 100644
index 0000000000..104217fe25
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java
@@ -0,0 +1,237 @@
+package net.firedevops.firemud.accountservice.service;
+
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/**
+ * Unwired owner-local reader for current and selected historical Account authority source events.
+ * Returned source evidence is not recipient authority.
+ */
+public final class AccountAuthoritySourceReader {
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+ private static final String ACCOUNT_STREAM_PREFIX = "account:auth-authority:v1:account/";
+
+ private final AccountRepository accountRepository;
+ private final AccountAuthorityGenerationRepository generationRepository;
+ private final AccountAuthorityOutboxRepository outboxRepository;
+ private final AccountAuthoritySourceEventReadback sourceEventReadback;
+ private final TransactionTemplate ownerTransaction;
+
+ public AccountAuthoritySourceReader(
+ AccountRepository accountRepository,
+ AccountAuthorityGenerationRepository generationRepository,
+ AccountAuthorityOutboxRepository outboxRepository,
+ AccountAuthoritySourceEventReadback sourceEventReadback,
+ PlatformTransactionManager transactionManager) {
+ this.accountRepository =
+ Objects.requireNonNull(accountRepository, "Account repository is required");
+ this.generationRepository =
+ Objects.requireNonNull(generationRepository, "authority generation repository is required");
+ this.outboxRepository =
+ Objects.requireNonNull(outboxRepository, "authority outbox repository is required");
+ this.sourceEventReadback =
+ Objects.requireNonNull(sourceEventReadback, "source event readback is required");
+
+ this.ownerTransaction =
+ new TransactionTemplate(
+ Objects.requireNonNull(transactionManager, "Account transaction manager is required"));
+ this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
+ this.ownerTransaction.setReadOnly(false);
+ }
+
+ /** Reads the current positive Account source and its exact latest event, if one exists. */
+ public AccountSourceSnapshot readCurrent(UUID accountId) {
+ requireCanonicalAccountId(accountId);
+ requireNoAmbientTransaction();
+ return requireTransactionResult(
+ ownerTransaction.execute(
+ status -> readCurrentSnapshot(loadLockedAccount(accountId), accountId)));
+ }
+
+ /**
+ * Reads one positive immutable event from this Account stream together with the current source
+ * snapshot that fences its use.
+ */
+ public AccountSourceEventReadback readCommittedEvent(UUID accountId, long outboxSequence) {
+ requireCanonicalAccountId(accountId);
+ if (outboxSequence <= 0L) {
+ throw new IllegalArgumentException("A positive Account source event sequence is required");
+ }
+ requireNoAmbientTransaction();
+ return requireTransactionResult(
+ ownerTransaction.execute(
+ status -> {
+ Account account = loadLockedAccount(accountId);
+ AccountSourceSnapshot current = readCurrentSnapshot(account, accountId);
+ if (outboxSequence > current.outboxSequence()) {
+ throw new IllegalStateException(
+ "Selected Account source event is ahead of its current checkpoint");
+ }
+ Event requested =
+ outboxRepository
+ .findEvent(current.outboxStreamKey(), outboxSequence)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Selected Account source event is missing"));
+ if (!current.outboxStreamKey().equals(requested.outboxStreamKey())
+ || requested.outboxSequence() != outboxSequence) {
+ throw new IllegalStateException(
+ "Selected Account source event identity changed during readback");
+ }
+ sourceEventReadback.requireRetainedEvent(account, requested, current.sourceState());
+ return new AccountSourceEventReadback(current, requested);
+ }));
+ }
+
+ private AccountSourceSnapshot readCurrentSnapshot(Account account, UUID accountId) {
+ AuthorityScope scope = AuthorityScope.account(accountId);
+ ScopeState state = generationRepository.read(scope);
+ if (state == null || !scope.equals(state.scope())) {
+ throw new IllegalStateException("Current Account authority scope changed during readback");
+ }
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest =
+ sourceEventReadback.requireCurrentLatest(account, state);
+ return new AccountSourceSnapshot(
+ accountId,
+ state,
+ accountStreamKey(accountId),
+ latest.outboxSequence(),
+ latest.latestEvent());
+ }
+
+ private Account loadLockedAccount(UUID accountId) {
+ Account associated =
+ accountRepository
+ .findByAccountUuid(accountId)
+ .orElseThrow(
+ () -> new IllegalStateException("Persisted Account UUID association is missing"));
+ requirePersistedAssociation(associated, accountId);
+
+ Account locked =
+ accountRepository
+ .findByIdForUpdate(associated.getId())
+ .orElseThrow(
+ () -> new IllegalStateException("Persisted Account source row is missing"));
+ requirePersistedAssociation(locked, accountId);
+ if (!Objects.equals(associated.getId(), locked.getId())
+ || !Objects.equals(associated.getAccountUuid(), locked.getAccountUuid())
+ || associated.getAccountUuidProvenance() != locked.getAccountUuidProvenance()
+ || !Objects.equals(
+ associated.getAccountUuidSourceNumericId(), locked.getAccountUuidSourceNumericId())) {
+ throw new IllegalStateException(
+ "Locked Account row changed its exact UUID association or provenance");
+ }
+ return locked;
+ }
+
+ private void requirePersistedAssociation(Account account, UUID accountId) {
+ AccountIdentityProvenance provenance =
+ account == null ? null : account.getAccountUuidProvenance();
+ if (account == null
+ || account.getId() == null
+ || account.getId() <= 0L
+ || !accountId.equals(account.getAccountUuid())
+ || account.getAccountUuidSourceNumericId() == null
+ || !account.getId().equals(account.getAccountUuidSourceNumericId())
+ || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT
+ && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION
+ && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT)) {
+ throw new IllegalStateException("Verified persisted Account association is required");
+ }
+ }
+
+ private static void requireCanonicalAccountId(UUID accountId) {
+ if (accountId == null || NIL_UUID.equals(accountId)) {
+ throw new IllegalArgumentException("A canonical non-nil Account UUID is required");
+ }
+ }
+
+ private static void requireNoAmbientTransaction() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException(
+ "Account authority source reader must own its transaction without an ambient transaction");
+ }
+ }
+
+ private static T requireTransactionResult(T result) {
+ if (result == null) {
+ throw new IllegalStateException("Account authority source readback returned no result");
+ }
+ return result;
+ }
+
+ private static String accountStreamKey(UUID accountId) {
+ return ACCOUNT_STREAM_PREFIX + accountId;
+ }
+
+ /** Immutable current owner-local source snapshot; it carries no credential or recipient tuple. */
+ public record AccountSourceSnapshot(
+ UUID accountId,
+ ScopeState sourceState,
+ String outboxStreamKey,
+ long outboxSequence,
+ Optional latestEvent) {
+ public AccountSourceSnapshot {
+ requireCanonicalAccountId(accountId);
+ Objects.requireNonNull(sourceState, "Account source state is required");
+ Objects.requireNonNull(outboxStreamKey, "Account source stream key is required");
+ latestEvent = Objects.requireNonNull(latestEvent, "latest source event optional is required");
+ AuthorityScope expectedScope = AuthorityScope.account(accountId);
+ if (!expectedScope.equals(sourceState.scope())
+ || sourceState.generation() <= 0L
+ || sourceState.sourceVersion() <= 0L
+ || !outboxStreamKey.equals(accountStreamKey(accountId))
+ || sourceState.issuanceFence() == null
+ || !accountId.equals(sourceState.issuanceFence().accountId())
+ || sourceState.issuanceFence().value() <= 0L
+ || sourceState.issuanceFence().sourceVersion() <= 0L
+ || outboxSequence < 0L
+ || (outboxSequence == 0L
+ && (sourceState.generation() != 1L
+ || sourceState.sourceVersion() != 1L
+ || latestEvent.isPresent()))
+ || (outboxSequence > 0L
+ && (sourceState.generation() <= 1L
+ || sourceState.sourceVersion() <= 1L
+ || latestEvent.isEmpty()
+ || latestEvent.orElseThrow().outboxSequence() != outboxSequence
+ || !outboxStreamKey.equals(latestEvent.orElseThrow().outboxStreamKey())))) {
+ throw new IllegalArgumentException("Account source snapshot is inconsistent");
+ }
+ latestEvent.ifPresent(
+ event ->
+ AccountAuthoritySourceEventReadback.requireEventMatchesSnapshot(
+ event, accountId, sourceState, true));
+ }
+ }
+
+ /** Immutable selected event paired with the current Account source fence. */
+ public record AccountSourceEventReadback(
+ AccountSourceSnapshot currentSnapshot, Event requestedEvent) {
+ public AccountSourceEventReadback {
+ Objects.requireNonNull(currentSnapshot, "current Account source snapshot is required");
+ Objects.requireNonNull(requestedEvent, "selected Account source event is required");
+ if (requestedEvent.outboxSequence() <= 0L
+ || requestedEvent.outboxSequence() > currentSnapshot.outboxSequence()
+ || !currentSnapshot.outboxStreamKey().equals(requestedEvent.outboxStreamKey())) {
+ throw new IllegalArgumentException("Selected Account source event is inconsistent");
+ }
+ AccountAuthoritySourceEventReadback.requireEventMatchesSnapshot(
+ requestedEvent, currentSnapshot.accountId(), currentSnapshot.sourceState(), false);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java
new file mode 100644
index 0000000000..12f020dfb5
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java
@@ -0,0 +1,568 @@
+package net.firedevops.firemud.accountservice.service;
+
+import static net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.validatorSnapshot;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.function.Supplier;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
+import net.firedevops.firemud.accountservice.entity.AccountTenantMembership;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event;
+import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot;
+import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot;
+import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository;
+import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources;
+import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot;
+import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry;
+import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent;
+import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Account-owned creator source composition; supplies no caller, authoring or gameplay authority.
+ */
+@Service
+@SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification = "Injected Account repositories are internal transaction collaborators.")
+public class AccountCreatorMembershipSourceReader {
+ private static final String ISSUER = "firemud-account-service";
+ private final AccountRepository accountRepository;
+ private final AccountJoinOperationRepository joinOperationRepository;
+ private final AccountTenantMembershipRepository membershipRepository;
+ private final AccountMembershipPairAuthorityRepository pairAuthorityRepository;
+ private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository;
+ private final FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository;
+ private final AccountAuthorityGenerationRepository authorityGenerationRepository;
+ private final AccountAuthorityOutboxRepository authorityOutboxRepository;
+ private final AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository;
+ private final AccountTenantCreationBootstrapOperationRepository bootstrapOperations;
+
+ @SuppressFBWarnings(
+ value = "CT_CONSTRUCTOR_THROW",
+ justification =
+ "Spring proxies the non-final owner reader; constructor validates private collaborators.")
+ public AccountCreatorMembershipSourceReader(
+ AccountRepository accounts,
+ AccountJoinOperationRepository joins,
+ AccountTenantMembershipRepository memberships,
+ AccountMembershipPairAuthorityRepository pairs,
+ AccountTenantMembershipRoleSnapshotRepository roles,
+ FreshTenantIdentityAssociationRepository fresh,
+ AccountAuthorityGenerationRepository generations,
+ AccountAuthorityOutboxRepository outbox,
+ AccountAuthoritySourceEvidenceRepository sources,
+ AccountTenantCreationBootstrapOperationRepository bootstrapOperations) {
+ this.accountRepository = Objects.requireNonNull(accounts);
+ this.joinOperationRepository = Objects.requireNonNull(joins);
+ this.membershipRepository = Objects.requireNonNull(memberships);
+ this.pairAuthorityRepository = Objects.requireNonNull(pairs);
+ this.roleSnapshotRepository = Objects.requireNonNull(roles);
+ this.freshTenantIdentityAssociationRepository = Objects.requireNonNull(fresh);
+ this.authorityGenerationRepository = Objects.requireNonNull(generations);
+ this.authorityOutboxRepository = Objects.requireNonNull(outbox);
+ this.sourceEvidenceRepository = Objects.requireNonNull(sources);
+ this.bootstrapOperations = Objects.requireNonNull(bootstrapOperations);
+ }
+
+ /** Explicit owner enrollment/readback, never an absent-row authority inference. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public NeverJoinedMembershipSnapshot readFreshNeverJoinedMembershipSnapshot(
+ UUID accountUuid, UUID tenantUuid) {
+ requireWritableOwnerTransaction();
+ requireCanonicalUuidInput(accountUuid, "Account UUID");
+ requireCanonicalUuidInput(tenantUuid, "tenant UUID");
+ Account account =
+ accountRepository
+ .findByAccountUuidForUpdate(accountUuid)
+ .orElseThrow(() -> new IllegalStateException("Fresh Account source is absent"));
+ requirePersistedAccountIdentity(account, accountUuid);
+ FreshTenantCreationEvidence creation =
+ freshTenantIdentityAssociationRepository
+ .read(tenantUuid)
+ .orElseThrow(() -> new IllegalStateException("Fresh tenant source is absent"));
+ CompositeSnapshot upstream =
+ authorityGenerationRepository.readCompositeSnapshot(
+ ISSUER, accountUuid, List.of(tenantUuid), List.of());
+ readCurrentUpstreamSourceEvidence(accountUuid, tenantUuid, upstream);
+ bootstrapOperations.assertNoContradictoryMembershipHistory(accountUuid, tenantUuid);
+ String stream = membershipStreamKey(accountUuid, tenantUuid);
+ if (authorityOutboxRepository.readCheckpoint(stream).isPresent()) {
+ throw new IllegalStateException("Fresh creator membership has committed event history");
+ }
+ ScopeState generation =
+ authorityGenerationRepository.initialize(
+ AuthorityScope.membership(accountUuid, tenantUuid));
+ if (generation.generation() != 1L || generation.sourceVersion() != 1L) {
+ throw new IllegalStateException("Fresh creator membership generation is not pristine");
+ }
+ PairAuthority pair = membershipRepository.prepareFreshCreatorAbsence(accountUuid, tenantUuid);
+ VerifiedTenantProvenance provenance = freshTenantProvenance(creation);
+ if (!new PairAuthority(
+ accountUuid, tenantUuid, provenance, false, 1L, 1L, 0L, null, null, false)
+ .equals(pair)) {
+ throw new IllegalStateException("Fresh creator pair baseline differs");
+ }
+ CompositeSnapshot authority = readSnapshot(accountUuid, tenantUuid);
+ requireMatchingFence(authority, only(authority.memberships(), "membership"), accountUuid);
+ CurrentSourceEvidence sources =
+ readCurrentUpstreamSourceEvidence(accountUuid, tenantUuid, authority);
+ List checkpoints = new ArrayList<>(sources.checkpoints());
+ checkpoints.add(new OutboxCheckpointEntry(stream, "0"));
+ requireUnchangedAccountIdentity(account, accountUuid);
+ if (!Optional.of(creation).equals(freshTenantIdentityAssociationRepository.read(tenantUuid))
+ || authorityOutboxRepository.readCheckpoint(stream).isPresent()) {
+ throw new IllegalStateException("Fresh creator source changed during capture");
+ }
+ return new NeverJoinedMembershipSnapshot(
+ accountUuid.toString(),
+ tenantUuid.toString(),
+ Map.of(tenantUuid.toString(), "1"),
+ "1",
+ currentAuthorityTuple(tenantUuid, authority, sources),
+ decimal(authority.issuanceFence().value()),
+ Instant.now(),
+ stream,
+ orderedCheckpoints(checkpoints),
+ sources.sourceEvidence());
+ }
+
+ @Transactional(propagation = Propagation.MANDATORY)
+ CreatorControlCaptureSources readExistingCreatorControlCaptureSources(
+ UUID accountUuid, UUID tenantUuid, Supplier verifiedOriginalReceipt) {
+ requireWritableOwnerTransaction();
+ requireCanonicalUuidInput(accountUuid, "Account UUID");
+ requireCanonicalUuidInput(tenantUuid, "tenant UUID");
+ Account account =
+ accountRepository
+ .findByAccountUuid(accountUuid)
+ .orElseThrow(() -> new IllegalStateException("Creator Account source is absent"));
+ requirePersistedAccountIdentity(account, accountUuid);
+ joinOperationRepository.lockAccount(account.getId());
+ CompositeSnapshot authority = readSnapshot(accountUuid, tenantUuid);
+ CurrentSourceEvidence upstream =
+ readCurrentUpstreamSourceEvidence(accountUuid, tenantUuid, authority);
+ FreshTenantCreationEvidence creation =
+ freshTenantIdentityAssociationRepository
+ .read(tenantUuid)
+ .orElseThrow(() -> new IllegalStateException("Creator fresh tenant source is absent"));
+ var receipt = Objects.requireNonNull(verifiedOriginalReceipt.get());
+ var provenance = freshTenantProvenance(creation);
+ Identity identity = new Identity(account.getId(), null, accountUuid, tenantUuid, provenance);
+ PairAuthority pair =
+ pairAuthorityRepository
+ .readForUpdate(accountUuid, tenantUuid)
+ .orElseThrow(() -> new IllegalStateException("Creator pair source is absent"));
+ AccountTenantMembership membership =
+ membershipRepository
+ .findCanonicalMembershipForUpdate(accountUuid, tenantUuid)
+ .orElseThrow(
+ () -> new IllegalStateException("Creator control membership source is absent"));
+ if (membership.getAccount() == null) {
+ throw new IllegalStateException("Creator control membership Account is absent");
+ }
+ requirePersistedAccountIdentity(membership.getAccount(), accountUuid);
+ ScopeState memberSource = only(authority.memberships(), "membership");
+ requireMatchingFence(authority, memberSource, accountUuid);
+ if (!"COMMITTED".equals(receipt.status())
+ || !accountUuid.equals(receipt.initiatingAccountUuid())
+ || !tenantUuid.equals(receipt.tenantUuid())
+ || !creation.operationId().equals(receipt.creationOperationId())
+ || !creation.creationRequestId().equals(receipt.creationRequestId())
+ || !Objects.equals(account.getId(), membership.getAccount().getId())
+ || !tenantUuid.equals(membership.getTenantUuid())
+ || membership.getTenantId() != null
+ || !provenance.kind().name().equals(membership.getTenantProvenanceKind())
+ || !provenance.sourceOperationId().equals(membership.getTenantSourceOperationId())
+ || !provenance.digest().equals(membership.getTenantProvenanceDigest())
+ || !"TENANT_CREATION".equals(membership.getAuthorityProvenance())
+ || !"ACTIVE".equals(membership.getLifecycleState())
+ || membership.isGameplayAdmissionAllowed()
+ || !Objects.equals(receipt.membershipId(), membership.getId())
+ || !Objects.equals(receipt.membershipVersion(), membership.getMembershipVersion())
+ || !Objects.equals(
+ receipt.membershipAuthorityGeneration(), membership.getMembershipAuthorityGeneration())
+ || receipt.baselineEventSequence() != 0L
+ || membership.getMembershipVersion()
+ != Math.incrementExact(receipt.baselineMembershipVersion())
+ || membership.getMembershipAuthorityGeneration()
+ != receipt.baselineMembershipAuthorityGeneration()
+ || memberSource.generation() != membership.getMembershipAuthorityGeneration()) {
+ throw new IllegalStateException(
+ "Creator control membership differs from its exact bootstrap source");
+ }
+ RoleSnapshot roles =
+ roleSnapshotRepository
+ .findForCanonicalUpdate(
+ accountUuid,
+ tenantUuid,
+ provenance,
+ membership.getId(),
+ membership.getMembershipVersion())
+ .orElseThrow(() -> new IllegalStateException("Creator control role source is absent"));
+ if (!List.of("tenantAdmin").equals(roles.roles())
+ || roles.accountId() != account.getId()
+ || roles.tenantId() != null
+ || !accountUuid.equals(roles.accountUuid())
+ || !tenantUuid.equals(roles.tenantUuid())
+ || !provenance.equals(roles.tenantProvenance())
+ || roles.membershipId() != membership.getId()
+ || roles.snapshotVersion() != membership.getMembershipVersion()
+ || !Arrays.equals(
+ receipt.membershipRolesPayload(),
+ "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8))) {
+ throw new IllegalStateException(
+ "Creator control roles differ from the exact bootstrap receipt");
+ }
+ String stream = membershipStreamKey(identity);
+ Checkpoint checkpoint =
+ authorityOutboxRepository
+ .readCheckpoint(stream)
+ .orElseThrow(
+ () -> new IllegalStateException("Creator current event checkpoint is absent"));
+ Event event =
+ authorityOutboxRepository
+ .findEvent(stream, checkpoint.outboxSequence())
+ .orElseThrow(() -> new IllegalStateException("Creator current event source is absent"));
+ MembershipEvent verified = verifyStoredEvent(event, identity, receipt.eventRequestId());
+ if (checkpoint.outboxSequence() != 1L
+ || !checkpointMatches(checkpoint, event)
+ || !stream.equals(receipt.eventStreamKey())
+ || !Objects.equals(receipt.eventSequence(), 1L)
+ || !event.eventId().equals(receipt.eventId())
+ || !event.eventDigest().equals(receipt.eventDigest())
+ || !Arrays.equals(event.payload(), receipt.eventPayload())
+ || !pair.equals(
+ new PairAuthority(
+ accountUuid,
+ tenantUuid,
+ provenance,
+ true,
+ membership.getMembershipVersion(),
+ membership.getMembershipAuthorityGeneration(),
+ 1L,
+ event.eventId(),
+ event.eventDigest(),
+ false))) {
+ throw new IllegalStateException(
+ "Creator control event or pair differs from the bootstrap receipt");
+ }
+ List checkpoints = new ArrayList<>(upstream.checkpoints());
+ checkpoints.add(new OutboxCheckpointEntry(stream, "1"));
+ List sources = new ArrayList<>(upstream.sourceEvidence());
+ sources.add(sourceEvidence(checkpoint, event));
+ AuthorityTuple tuple = currentAuthorityTuple(tenantUuid, authority, upstream);
+ Map version =
+ Map.of(tenantUuid.toString(), Long.toString(membership.getMembershipVersion()));
+ var boundEvent =
+ RuntimeMembershipAuthorityEvidenceValidator.validate(
+ validatorSnapshot(
+ accountUuid.toString(),
+ tenantUuid.toString(),
+ true,
+ "ACTIVE",
+ false,
+ version,
+ Long.toString(memberSource.generation()),
+ List.of("tenantAdmin"),
+ tuple,
+ decimal(authority.issuanceFence().value()),
+ orderedCheckpoints(checkpoints),
+ orderedSourceEvidence(sources)));
+ if (boundEvent.isEmpty()
+ || !verified.canonicalJson().equals(boundEvent.orElseThrow().canonicalJson())
+ || verified.callerBoundAuthorityInvalidated()) {
+ throw new IllegalStateException(
+ "Creator control event does not bind the current source capture");
+ }
+ requireUnchangedAccountIdentity(account, accountUuid);
+ if (!Optional.of(creation).equals(freshTenantIdentityAssociationRepository.read(tenantUuid))) {
+ throw new IllegalStateException("Creator fresh tenant source changed during capture");
+ }
+ return new CreatorControlCaptureSources(
+ accountUuid,
+ tenantUuid,
+ authority,
+ version,
+ tuple,
+ decimal(authority.issuanceFence().value()),
+ pair,
+ roles,
+ creation,
+ receipt,
+ verified,
+ orderedCheckpoints(checkpoints),
+ orderedSourceEvidence(sources),
+ Instant.now());
+ }
+
+ private CurrentSourceEvidence readCurrentUpstreamSourceEvidence(
+ UUID accountUuid, UUID tenantUuid, CompositeSnapshot authority) {
+ IssuerAccountSourceSnapshot source =
+ sourceEvidenceRepository.readCurrentIssuerAccountSources(ISSUER, accountUuid);
+ ScopeState tenant = only(authority.tenants(), "tenant");
+ Account account = accountRepository.findByAccountUuid(accountUuid).orElseThrow();
+ requirePersistedAccountIdentity(account, accountUuid);
+ if (!AuthorityScope.issuer(ISSUER).equals(authority.issuer().scope())
+ || !AuthorityScope.account(accountUuid).equals(authority.account().scope())
+ || !AuthorityScope.tenant(tenantUuid).equals(tenant.scope())
+ || !authority.issuanceFence().equals(source.issuanceFence())
+ || !authority.issuanceFence().equals(authority.account().issuanceFence())
+ || !accountUuid.equals(authority.issuanceFence().accountId())
+ || source.account().accountSourceNumericId() == null
+ || !Objects.equals(source.account().accountSourceNumericId(), account.getId())
+ || source.issuer().generation() != authority.issuer().generation()
+ || source.issuer().sourceVersion() != authority.issuer().sourceVersion()
+ || source.account().generation() != authority.account().generation()
+ || source.account().sourceVersion() != authority.account().sourceVersion()
+ || tenant.generation() != 1L
+ || tenant.sourceVersion() != 1L
+ || authorityOutboxRepository
+ .readCheckpoint(
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantUuid)
+ .isPresent()) {
+ throw new IllegalStateException(
+ "Current creator upstream sources are unavailable or mismatched");
+ }
+ // The source repository proves complete retained histories and exact live Account state;
+ // these projections additionally validate their current closed source-event schemas.
+ net.firedevops.firemud.accountservice.service.session
+ .AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source);
+ FreshTenantCreationEvidence fresh =
+ freshTenantIdentityAssociationRepository
+ .read(tenantUuid)
+ .orElseThrow(
+ () -> new IllegalStateException("Current fresh tenant provenance is absent"));
+ if (!tenantUuid.equals(fresh.canonicalTenantId())) {
+ throw new IllegalStateException("Current fresh tenant provenance differs");
+ }
+ List checkpoints = new ArrayList<>();
+ List sources = new ArrayList<>();
+ for (var current : List.of(source.issuer(), source.account())) {
+ var checkpoint = current.checkpoint();
+ checkpoints.add(
+ new OutboxCheckpointEntry(
+ checkpoint.outboxStreamKey(), Long.toString(checkpoint.sequence())));
+ if (checkpoint.sequence() > 0L) {
+ Checkpoint stored =
+ authorityOutboxRepository.readCheckpoint(checkpoint.outboxStreamKey()).orElseThrow();
+ Event event =
+ authorityOutboxRepository
+ .findEvent(checkpoint.outboxStreamKey(), checkpoint.sequence())
+ .orElseThrow();
+ if (stored.outboxSequence() != checkpoint.sequence()
+ || !checkpoint.sourceEventId().orElseThrow().equals(stored.sourceEventId())
+ || !checkpoint.sourceEventDigest().orElseThrow().equals(stored.sourceEventDigest())) {
+ throw new IllegalStateException("Current source checkpoint differs from owner proof");
+ }
+ sources.add(sourceEvidence(stored, event));
+ }
+ }
+ checkpoints.add(
+ new OutboxCheckpointEntry(
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantUuid, "0"));
+ return new CurrentSourceEvidence(
+ orderedCheckpoints(checkpoints),
+ orderedSourceEvidence(sources),
+ source
+ .account()
+ .accountSecurityCutoff()
+ .map(
+ c ->
+ new MembershipAuthorityEventV1Codec.AccountSecurityCutoff(
+ c.accountAuthorityGeneration(), c.outboxStreamKey(), c.outboxSequence())));
+ }
+
+ private CompositeSnapshot readSnapshot(UUID accountUuid, UUID tenantUuid) {
+ return authorityGenerationRepository.readCompositeSnapshot(
+ ISSUER, accountUuid, List.of(tenantUuid), List.of(tenantUuid));
+ }
+
+ private static AuthorityTuple currentAuthorityTuple(
+ UUID tenantUuid, CompositeSnapshot authority, CurrentSourceEvidence sources) {
+ return new AuthorityTuple(
+ decimal(authority.issuer().generation()),
+ decimal(authority.account().generation()),
+ Map.of(tenantUuid.toString(), decimal(only(authority.tenants(), "tenant").generation())),
+ Map.of(
+ tenantUuid.toString(),
+ decimal(only(authority.memberships(), "membership").generation())),
+ List.of(),
+ sources.accountSecurityCutoff(),
+ Optional.empty());
+ }
+
+ private static void requireMatchingFence(
+ CompositeSnapshot authority, ScopeState member, UUID accountUuid) {
+ if (!AuthorityScope.membership(
+ accountUuid, only(authority.tenants(), "tenant").scope().tenantId())
+ .equals(member.scope())
+ || !accountUuid.equals(authority.issuanceFence().accountId())
+ || !authority.issuanceFence().equals(authority.account().issuanceFence())
+ || !authority.issuanceFence().equals(member.issuanceFence())) {
+ throw new IllegalStateException("Creator membership source fence differs");
+ }
+ }
+
+ private static MembershipEvent verifyStoredEvent(
+ Event event, Identity identity, String requestId) {
+ MembershipEvent verified =
+ MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8));
+ if (!requestId.equals(event.requestId())
+ || !requestId.equals(verified.requestId())
+ || !membershipStreamKey(identity).equals(event.outboxStreamKey())
+ || !event.outboxStreamKey().equals(verified.outboxStreamKey())
+ || event.outboxSequence() != 1L
+ || !"1".equals(verified.outboxSequence())
+ || !event.eventId().equals(verified.eventId())
+ || !event.eventDigest().equals(verified.eventDigest())
+ || !UUID.nameUUIDFromBytes(
+ (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + requestId)
+ .getBytes(StandardCharsets.UTF_8))
+ .toString()
+ .equals(verified.eventId())
+ || !identity.accountUuid().toString().equals(verified.accountId())
+ || !identity.tenantUuid().toString().equals(verified.tenantId())
+ || !Arrays.equals(event.payload(), verified.canonicalJsonUtf8())) {
+ throw new IllegalStateException("Creator event differs from its immutable source columns");
+ }
+ return verified;
+ }
+
+ private static boolean checkpointMatches(Checkpoint c, Event e) {
+ return c.outboxStreamKey().equals(e.outboxStreamKey())
+ && c.outboxSequence() == e.outboxSequence()
+ && c.sourceEventId().equals(e.eventId())
+ && c.sourceEventDigest().equals(e.eventDigest());
+ }
+
+ private static OutboxSourceEvidence sourceEvidence(Checkpoint c, Event e) {
+ if (!checkpointMatches(c, e))
+ throw new IllegalStateException("Creator checkpoint differs from event");
+ return new OutboxSourceEvidence(
+ c.outboxStreamKey(),
+ Long.toString(c.outboxSequence()),
+ e.eventId(),
+ e.eventDigest(),
+ new String(e.payload(), StandardCharsets.UTF_8));
+ }
+
+ private static List orderedCheckpoints(
+ List values) {
+ return values.stream()
+ .sorted(Comparator.comparing(OutboxCheckpointEntry::outboxStreamKey))
+ .toList();
+ }
+
+ private static List orderedSourceEvidence(
+ List values) {
+ return values.stream()
+ .sorted(Comparator.comparing(OutboxSourceEvidence::outboxStreamKey))
+ .toList();
+ }
+
+ private static ScopeState only(List values, String label) {
+ if (values.size() != 1)
+ throw new IllegalStateException("Expected exactly one " + label + " source");
+ return values.getFirst();
+ }
+
+ private static VerifiedTenantProvenance freshTenantProvenance(FreshTenantCreationEvidence fresh) {
+ return new VerifiedTenantProvenance(
+ null, TenantProvenanceKind.FRESH_GAME_DESIGN, fresh.operationId(), fresh.evidenceDigest());
+ }
+
+ private static void requireCanonicalUuidInput(UUID uuid, String label) {
+ if (uuid == null || new UUID(0L, 0L).equals(uuid))
+ throw new IllegalArgumentException(label + " must be non-nil");
+ }
+
+ private static void requirePersistedAccountIdentity(Account account, UUID uuid) {
+ if (account == null
+ || account.getId() == null
+ || account.getId() <= 0L
+ || !uuid.equals(account.getAccountUuid())
+ || account.getAccountUuidProvenance() != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT
+ || !account.getId().equals(account.getAccountUuidSourceNumericId())) {
+ throw new IllegalStateException("Creator Account source identity differs");
+ }
+ }
+
+ private void requireUnchangedAccountIdentity(Account before, UUID uuid) {
+ Account after = accountRepository.findByAccountUuid(uuid).orElseThrow();
+ requirePersistedAccountIdentity(after, uuid);
+ if (!before.getId().equals(after.getId()))
+ throw new IllegalStateException("Creator Account identity changed");
+ }
+
+ private static String decimal(long value) {
+ if (value <= 0L) throw new IllegalStateException("Creator source counters must be positive");
+ return Long.toString(value);
+ }
+
+ private static String membershipStreamKey(Identity identity) {
+ return membershipStreamKey(identity.accountUuid(), identity.tenantUuid());
+ }
+
+ private static String membershipStreamKey(UUID account, UUID tenant) {
+ return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX
+ + "membership/"
+ + account
+ + "/"
+ + tenant;
+ }
+
+ private static void requireWritableOwnerTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException(
+ "Creator source capture requires a writable Account owner transaction");
+ }
+ }
+
+ private record Identity(
+ long accountId,
+ Long legacyTenantId,
+ UUID accountUuid,
+ UUID tenantUuid,
+ VerifiedTenantProvenance provenance) {}
+
+ private record CurrentSourceEvidence(
+ List checkpoints,
+ List sourceEvidence,
+ Optional accountSecurityCutoff) {}
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java
new file mode 100644
index 0000000000..767c0be665
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java
@@ -0,0 +1,355 @@
+package net.firedevops.firemud.accountservice.service;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.util.HashSet;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event;
+import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot;
+import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent;
+import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+import tools.jackson.databind.node.ObjectNode;
+
+/** Closed current-snapshot projection of one durable Account account-generation source. */
+public record AccountGenerationProjection(
+ String accountId,
+ String accountAuthorityGeneration,
+ String sourceVersion,
+ String outboxStreamKey,
+ String outboxSequence,
+ Optional sourceEvent) {
+ public static final String SCHEMA_VERSION = "account-auth-account-generation-projection/v1";
+ public static final String KEY_PREFIX = "session:auth:generation:account:";
+ private static final String STREAM_PREFIX = "account:auth-authority:v1:account/";
+ private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*");
+ private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("0|[1-9][0-9]*");
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .build();
+ private static final Set REQUIRED_FIELDS =
+ Set.of(
+ "schemaVersion",
+ "accountId",
+ "accountAuthorityGeneration",
+ "sourceVersion",
+ "outboxStreamKey",
+ "outboxSequence");
+ private static final Set ALL_FIELDS =
+ Set.of(
+ "schemaVersion",
+ "accountId",
+ "accountAuthorityGeneration",
+ "sourceVersion",
+ "outboxStreamKey",
+ "outboxSequence",
+ "sourceEvent");
+
+ public AccountGenerationProjection {
+ requireCanonicalAccountId(accountId);
+ requirePositiveDecimal(accountAuthorityGeneration, "accountAuthorityGeneration");
+ requirePositiveDecimal(sourceVersion, "sourceVersion");
+ requireNonNegativeDecimal(outboxSequence, "outboxSequence");
+ if (!streamKeyForAccount(accountId).equals(outboxStreamKey)) {
+ throw new IllegalArgumentException(
+ "Account generation projection stream key is not canonical");
+ }
+ sourceEvent = Objects.requireNonNull(sourceEvent, "sourceEvent optional is required");
+ BigInteger sequence = new BigInteger(outboxSequence);
+ if (sequence.signum() == 0) {
+ if (!"1".equals(accountAuthorityGeneration)
+ || !"1".equals(sourceVersion)
+ || sourceEvent.isPresent()) {
+ throw new IllegalArgumentException(
+ "Account sequence zero requires the original 1/1 source baseline and no event");
+ }
+ } else {
+ if (new BigInteger(accountAuthorityGeneration).compareTo(BigInteger.ONE) <= 0
+ || new BigInteger(sourceVersion).compareTo(BigInteger.ONE) <= 0
+ || sourceEvent.isEmpty()) {
+ throw new IllegalArgumentException(
+ "Positive Account source sequence requires advanced counters and its exact event");
+ }
+ validateSourceEvent(
+ sourceEvent.orElseThrow(),
+ accountId,
+ accountAuthorityGeneration,
+ sourceVersion,
+ outboxStreamKey,
+ outboxSequence);
+ }
+ }
+
+ /** Builds projection evidence only from Account's owner-local current durable readback. */
+ public static AccountGenerationProjection fromSource(AccountSourceSnapshot source) {
+ Objects.requireNonNull(source, "Account source snapshot is required");
+ AuthorityScope scope = source.sourceState().scope();
+ if (scope.kind() != ScopeKind.ACCOUNT || !source.accountId().equals(scope.accountId())) {
+ throw new IllegalArgumentException("Account source snapshot has a different authority scope");
+ }
+ Optional event =
+ source.latestEvent().map(AccountGenerationProjection::decodeCanonicalEvent);
+ return new AccountGenerationProjection(
+ source.accountId().toString(),
+ Long.toString(source.sourceState().generation()),
+ Long.toString(source.sourceState().sourceVersion()),
+ source.outboxStreamKey(),
+ Long.toString(source.outboxSequence()),
+ event);
+ }
+
+ /**
+ * Parses the closed wire shape and rejects noncanonical JSON and all alternate representations.
+ */
+ public static AccountGenerationProjection parse(String json) {
+ Objects.requireNonNull(json, "projection JSON is required");
+ final JsonNode root;
+ try {
+ root = JSON.readTree(json);
+ } catch (tools.jackson.core.JacksonException exception) {
+ throw new IllegalArgumentException(
+ "Account generation projection JSON is malformed", exception);
+ }
+ if (!(root instanceof ObjectNode object)) {
+ throw new IllegalArgumentException("Account generation projection must be a JSON object");
+ }
+ Set fields = new HashSet<>();
+ object.propertyNames().forEach(fields::add);
+ if (!fields.contains("sourceEvent") && !fields.equals(REQUIRED_FIELDS)) {
+ throw new IllegalArgumentException(
+ "Account generation projection has unknown or missing fields");
+ }
+ if (fields.contains("sourceEvent") && !fields.equals(ALL_FIELDS)) {
+ throw new IllegalArgumentException(
+ "Account generation projection has unknown or missing fields");
+ }
+ if (!SCHEMA_VERSION.equals(requireText(object, "schemaVersion"))) {
+ throw new IllegalArgumentException(
+ "Account generation projection schemaVersion is unsupported");
+ }
+ Optional event =
+ fields.contains("sourceEvent")
+ ? Optional.of(requireText(object, "sourceEvent"))
+ : Optional.empty();
+ AccountGenerationProjection projection =
+ new AccountGenerationProjection(
+ requireText(object, "accountId"),
+ requireText(object, "accountAuthorityGeneration"),
+ requireText(object, "sourceVersion"),
+ requireText(object, "outboxStreamKey"),
+ requireText(object, "outboxSequence"),
+ event);
+ if (!projection.toJson().equals(json)) {
+ throw new IllegalArgumentException("Account generation projection JSON is not canonical");
+ }
+ return projection;
+ }
+
+ public String key() {
+ return KEY_PREFIX + accountId;
+ }
+
+ public String toJson() {
+ ObjectNode object = JSON.createObjectNode();
+ object.put("schemaVersion", SCHEMA_VERSION);
+ object.put("accountId", accountId);
+ object.put("accountAuthorityGeneration", accountAuthorityGeneration);
+ object.put("sourceVersion", sourceVersion);
+ object.put("outboxStreamKey", outboxStreamKey);
+ object.put("outboxSequence", outboxSequence);
+ sourceEvent.ifPresent(value -> object.put("sourceEvent", value));
+ try {
+ return JSON.writeValueAsString(object);
+ } catch (tools.jackson.core.JacksonException exception) {
+ throw new IllegalStateException(
+ "Account generation projection cannot be serialized", exception);
+ }
+ }
+
+ public BigInteger generationValue() {
+ return new BigInteger(accountAuthorityGeneration);
+ }
+
+ public BigInteger sourceVersionValue() {
+ return new BigInteger(sourceVersion);
+ }
+
+ public BigInteger outboxSequenceValue() {
+ return new BigInteger(outboxSequence);
+ }
+
+ static String keyForAccount(UUID accountId) {
+ Objects.requireNonNull(accountId, "Account UUID is required");
+ if (new UUID(0L, 0L).equals(accountId)) {
+ throw new IllegalArgumentException("A canonical non-nil Account UUID is required");
+ }
+ return KEY_PREFIX + accountId;
+ }
+
+ private static String streamKeyForAccount(String accountId) {
+ return STREAM_PREFIX + accountId;
+ }
+
+ private static String decodeCanonicalEvent(Event event) {
+ try {
+ return StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(event.payload()))
+ .toString();
+ } catch (CharacterCodingException exception) {
+ throw new IllegalArgumentException("Account source event is not valid UTF-8", exception);
+ }
+ }
+
+ private static void validateSourceEvent(
+ String eventJson,
+ String accountId,
+ String generation,
+ String sourceVersion,
+ String streamKey,
+ String sequence) {
+ final JsonNode root;
+ try {
+ root = JSON.readTree(eventJson);
+ } catch (tools.jackson.core.JacksonException exception) {
+ throw new IllegalArgumentException("Account source event JSON is malformed", exception);
+ }
+ if (!(root instanceof ObjectNode object)) {
+ throw new IllegalArgumentException("Account source event must be a JSON object");
+ }
+ String canonicalEvent;
+ switch (requireText(object, "schemaVersion")) {
+ case PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION -> {
+ PasswordResetAuthorityEvent reset = PasswordResetAuthorityEventV1Codec.verify(eventJson);
+ canonicalEvent = new String(reset.canonicalJsonUtf8(), StandardCharsets.UTF_8);
+ requireEventBinding(
+ accountId,
+ generation,
+ sourceVersion,
+ streamKey,
+ sequence,
+ reset.accountId(),
+ reset.accountAuthorityGeneration(),
+ reset.sourceVersion(),
+ reset.outboxStreamKey(),
+ reset.outboxSequence());
+ }
+ case AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION -> {
+ AccountLogoutAllAuthorityEvent logout =
+ AccountLogoutAllAuthorityEventV1Codec.verify(eventJson);
+ canonicalEvent = new String(logout.canonicalJsonUtf8(), StandardCharsets.UTF_8);
+ requireEventBinding(
+ accountId,
+ generation,
+ sourceVersion,
+ streamKey,
+ sequence,
+ logout.accountId(),
+ logout.accountAuthorityGeneration(),
+ logout.sourceVersion(),
+ logout.outboxStreamKey(),
+ logout.outboxSequence());
+ }
+ case AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION -> {
+ var security = AccountSecurityStateAuthorityEventV1Codec.verify(eventJson);
+ canonicalEvent = security.canonicalJson();
+ requireEventBinding(
+ accountId,
+ generation,
+ sourceVersion,
+ streamKey,
+ sequence,
+ security.accountId(),
+ security.accountAuthorityGeneration(),
+ security.sourceVersion(),
+ security.outboxStreamKey(),
+ security.outboxSequence());
+ }
+ default -> {
+ throw new IllegalArgumentException(
+ "Account source event is not one of the declared closed schemas");
+ }
+ }
+ if (!canonicalEvent.equals(eventJson)) {
+ throw new IllegalArgumentException("Account source event JSON is not canonical");
+ }
+ }
+
+ private static void requireEventBinding(
+ String expectedAccount,
+ String expectedGeneration,
+ String expectedSourceVersion,
+ String expectedStream,
+ String expectedSequence,
+ String actualAccount,
+ String actualGeneration,
+ String actualSourceVersion,
+ String actualStream,
+ String actualSequence) {
+ if (!expectedAccount.equals(actualAccount)
+ || !expectedGeneration.equals(actualGeneration)
+ || !expectedSourceVersion.equals(actualSourceVersion)
+ || !expectedStream.equals(actualStream)
+ || !expectedSequence.equals(actualSequence)) {
+ throw new IllegalArgumentException(
+ "Account source event does not match its current projection checkpoint");
+ }
+ }
+
+ private static String requireText(ObjectNode object, String field) {
+ JsonNode value = object.get(field);
+ if (value == null || !value.isTextual()) {
+ throw new IllegalArgumentException(
+ "Account generation projection " + field + " must be a string");
+ }
+ return value.textValue();
+ }
+
+ private static void requireCanonicalAccountId(String value) {
+ Objects.requireNonNull(value, "accountId is required");
+ try {
+ UUID parsed = UUID.fromString(value);
+ if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) {
+ throw new IllegalArgumentException(
+ "Account generation projection accountId is not canonical");
+ }
+ } catch (IllegalArgumentException malformed) {
+ throw new IllegalArgumentException(
+ "Account generation projection accountId must be a lowercase canonical non-nil UUID",
+ malformed);
+ }
+ }
+
+ private static void requirePositiveDecimal(String value, String field) {
+ if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) {
+ throw new IllegalArgumentException(field + " must be a positive canonical decimal string");
+ }
+ }
+
+ private static void requireNonNegativeDecimal(String value, String field) {
+ if (value == null || !NON_NEGATIVE_DECIMAL.matcher(value).matches()) {
+ throw new IllegalArgumentException(
+ field + " must be a non-negative canonical decimal string");
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java
new file mode 100644
index 0000000000..406af7927d
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java
@@ -0,0 +1,680 @@
+package net.firedevops.firemud.accountservice.service;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.util.HexFormat;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange;
+import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent;
+import org.jooq.DSLContext;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/**
+ * Unwired source-only Account logout-all mutation and immutable result readback.
+ *
+ * This primitive does not authenticate a caller. Its caller must perform the initial exact token
+ * registry and Account evidence-bundle authorization required by ADR 0036 before invoking a new
+ * operation. It creates no authorization context and is not exposed through a REST, gRPC, or
+ * controller path. Exact committed retries return only the durable lifecycle result.
+ */
+public final class AccountLogoutAllAuthorityEventProducer {
+ private static final String STREAM_PREFIX = "account:auth-authority:v1:account/";
+ private static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:";
+ private static final int DIGEST_VERSION = 1;
+ private static final String OPERATION_KIND = "ACCOUNT_LOGOUT_ALL";
+ private static final HexFormat HEX = HexFormat.of();
+
+ private final AccountRepository accountRepository;
+ private final AccountAuthorityGenerationRepository generationRepository;
+ private final AccountAuthorityOutboxRepository outboxRepository;
+ private final AccountLogoutAllOperationRepository operationRepository;
+ private final AccountAuthoritySourceEventReadback sourceReadback;
+ private final AccountLogoutAllDraftSourceChangeRepository draftSourceChanges;
+ private final TransactionTemplate ownerTransaction;
+
+ public AccountLogoutAllAuthorityEventProducer(
+ AccountRepository accountRepository,
+ AccountAuthorityGenerationRepository generationRepository,
+ AccountAuthorityOutboxRepository outboxRepository,
+ AccountLogoutAllOperationRepository operationRepository,
+ AccountAuthoritySourceEventReadback sourceReadback,
+ DSLContext dsl,
+ PlatformTransactionManager transactionManager) {
+ this.accountRepository =
+ Objects.requireNonNull(accountRepository, "Account repository is required");
+ this.generationRepository =
+ Objects.requireNonNull(generationRepository, "authority-generation repository is required");
+ this.outboxRepository =
+ Objects.requireNonNull(outboxRepository, "authority outbox repository is required");
+ this.operationRepository =
+ Objects.requireNonNull(operationRepository, "logout-all operation repository is required");
+ this.sourceReadback =
+ Objects.requireNonNull(sourceReadback, "Account source-event readback is required");
+ this.draftSourceChanges = new AccountLogoutAllDraftSourceChangeRepository(dsl);
+ Objects.requireNonNull(dsl, "transaction-aware DSLContext is required");
+ Objects.requireNonNull(transactionManager, "Account transaction manager is required");
+
+ this.ownerTransaction = new TransactionTemplate(transactionManager);
+ this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
+ this.ownerTransaction.setReadOnly(false);
+ }
+
+ /**
+ * Commits one account-wide cutoff or recovers that request's exact original lifecycle result.
+ *
+ *
The request digest is recomputed from the exact closed operation tuple and compared with the
+ * supplied lowercase SHA-256 binding. The token profile and digest correlate the receipt; neither
+ * is proof of caller authorization. The supplied Account association and scope state are compared
+ * against locked persisted state for a new request. A pending exact retry recovers its original
+ * server-resolved counters and capture rather than treating a changed retry snapshot as new
+ * caller identity.
+ */
+ public LogoutAllResult commit(
+ UUID requestId,
+ int requestDigestVersion,
+ String requestDigest,
+ String tokenProfile,
+ String presentedTokenHash,
+ Account verifiedAccountAssociation,
+ ScopeState expectedAccountState) {
+ validateRequest(
+ requestId, requestDigestVersion, requestDigest, tokenProfile, presentedTokenHash);
+ validateExpectedInputs(verifiedAccountAssociation, expectedAccountState);
+ requireNoAmbientTransaction();
+
+ CommitAttempt transactionResult =
+ ownerTransaction.execute(
+ status ->
+ commitInOwnerTransaction(
+ requestId,
+ requestDigestVersion,
+ requestDigest,
+ tokenProfile,
+ presentedTokenHash,
+ verifiedAccountAssociation,
+ expectedAccountState));
+ if (transactionResult == null) {
+ throw new IllegalStateException("Logout-all source transaction returned no result");
+ }
+ if (transactionResult.pendingChange() != null) {
+ ownerTransaction.executeWithoutResult(
+ status ->
+ draftSourceChanges.verifyWaiting(
+ requestId,
+ transactionResult.requestPayload(),
+ transactionResult.pendingChange()));
+ throw new AccountLogoutAllDraftSourceChangeRepository.PendingSourceChangeException(
+ transactionResult.pendingChange().changeId());
+ }
+
+ LogoutAllReceipt committedResult =
+ readCommittedOperation(
+ requestId,
+ requestDigestVersion,
+ requestDigest,
+ tokenProfile,
+ presentedTokenHash,
+ verifiedAccountAssociation);
+ if (!transactionResult.receipt().equals(committedResult)) {
+ throw new IllegalStateException(
+ "Post-commit logout-all receipt differs from the source transaction result");
+ }
+ return LogoutAllResult.valueOf(committedResult.lifecycleResult());
+ }
+
+ private CommitAttempt commitInOwnerTransaction(
+ UUID requestId,
+ int requestDigestVersion,
+ String requestDigest,
+ String tokenProfile,
+ String presentedTokenHash,
+ Account requestedAccount,
+ ScopeState expectedAccountState) {
+ Account account = lockVerifiedAccount(requestedAccount);
+ String requestText = requestId.toString();
+
+ // The immutable request and token bindings take precedence over current server-derived
+ // counters.
+ Optional priorRequest = operationRepository.findByRequestId(requestId);
+ Optional priorToken =
+ operationRepository.findByPresentedTokenHash(presentedTokenHash);
+ byte[] requestPayload =
+ draftSourceChanges.requestBinding(
+ requestId,
+ requestDigestVersion,
+ requestDigest,
+ tokenProfile,
+ presentedTokenHash,
+ account);
+ if (priorRequest.isPresent()) {
+ LogoutAllReceipt receipt = priorRequest.orElseThrow();
+ requireExactRetryBinding(
+ receipt,
+ requestId,
+ requestDigestVersion,
+ requestDigest,
+ tokenProfile,
+ presentedTokenHash,
+ account);
+ if (priorToken.isEmpty() || !receipt.equals(priorToken.orElseThrow())) {
+ throw new IllegalStateException("Logout-all token receipt index readback is inconsistent");
+ }
+ Event historicalEvent =
+ outboxRepository
+ .findEvent(receipt.outboxStreamKey(), receipt.outboxSequence())
+ .orElseThrow(
+ () -> new IllegalStateException("Logout-all historical event is missing"));
+ draftSourceChanges.verifyCommittedIfPresent(requestId, requestPayload, historicalEvent);
+ return new CommitAttempt(recoverReceipt(account, receipt), null, requestPayload);
+ }
+ if (priorToken.isPresent()) {
+ throw new OperationConflictException(
+ "Presented token identity is already bound to another logout-all request");
+ }
+
+ Optional originalPending =
+ draftSourceChanges.findPending(
+ requestId,
+ requestDigestVersion,
+ requestDigest,
+ tokenProfile,
+ presentedTokenHash,
+ account);
+
+ if (requestDigestVersion != DIGEST_VERSION) {
+ throw new IllegalArgumentException("Logout-all request digest version must be 1");
+ }
+ String canonicalDigest =
+ AccountLogoutRequestDigest.accountLogoutAll(
+ account.getAccountUuid(), tokenProfile, presentedTokenHash);
+ if (!constantTimeTextEquals(canonicalDigest, requestDigest)) {
+ throw new IllegalArgumentException(
+ "Logout-all request digest does not match its canonical caller bindings");
+ }
+ ScopeState current =
+ generationRepository.read(AuthorityScope.account(account.getAccountUuid()));
+ if (originalPending.isEmpty() && !current.equals(expectedAccountState)) {
+ throw new IllegalStateException("Logout-all Account source compare-and-advance is stale");
+ }
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot source =
+ sourceReadback.requireCurrentLatest(account, current);
+ long nextGeneration = incrementExact(current.generation(), "Account authority generation");
+ long nextSourceVersion = incrementExact(current.sourceVersion(), "Account source version");
+ long nextIssuanceFence =
+ incrementExact(current.issuanceFence().value(), "Account issuance fence");
+ incrementExact(current.issuanceFence().sourceVersion(), "issuance-fence source version");
+ long nextSequence = incrementExact(source.outboxSequence(), "Account source outbox sequence");
+ String streamKey = streamKey(account.getAccountUuid());
+ String eventId = EVENT_ID_PREFIX + requestText;
+
+ AccountLogoutAllDraftSourceChangeRepository.Participation participation =
+ draftSourceChanges.participate(
+ requestId,
+ requestDigestVersion,
+ requestDigest,
+ tokenProfile,
+ presentedTokenHash,
+ account,
+ current,
+ source);
+ SourceChange sourceChange = participation.change();
+ if (!participation.settled()) {
+ return new CommitAttempt(null, sourceChange, requestPayload);
+ }
+ if (!draftSourceChanges.permitted(sourceChange)) {
+ throw new IllegalStateException("Settled logout-all source change is not permitted");
+ }
+
+ ScopeState advanced = generationRepository.advance(current, current.issuanceFence());
+ requireAdvancedState(current, advanced, nextGeneration, nextSourceVersion, nextIssuanceFence);
+
+ Event appended =
+ outboxRepository.append(
+ streamKey,
+ requestText,
+ sequence ->
+ eventEvidence(
+ account.getAccountUuid(),
+ requestId,
+ eventId,
+ sequence,
+ nextGeneration,
+ nextSourceVersion));
+ if (appended.outboxSequence() != nextSequence) {
+ throw new IllegalStateException("Logout-all source outbox sequence did not advance once");
+ }
+ AccountLogoutAllAuthorityEvent event =
+ requireEvent(
+ appended,
+ account.getAccountUuid(),
+ requestId,
+ eventId,
+ nextGeneration,
+ nextSourceVersion);
+ Checkpoint checkpoint =
+ outboxRepository
+ .readCheckpoint(streamKey)
+ .orElseThrow(() -> new IllegalStateException("Logout-all checkpoint is missing"));
+ requireCheckpointMatches(checkpoint, appended);
+
+ LogoutAllReceipt receipt =
+ LogoutAllReceipt.committed(
+ requestId,
+ account.getId(),
+ account.getAccountUuid(),
+ requestDigest,
+ presentedTokenHash,
+ tokenProfile,
+ streamKey,
+ appended.outboxSequence(),
+ event.eventId(),
+ event.eventDigest(),
+ advanced,
+ advanced.issuanceFence());
+ operationRepository.insert(receipt);
+
+ Event requestReadback =
+ outboxRepository
+ .findEvent(streamKey, requestText)
+ .orElseThrow(
+ () -> new IllegalStateException("Logout-all request event readback is missing"));
+ Event sequenceReadback =
+ outboxRepository
+ .findEvent(streamKey, nextSequence)
+ .orElseThrow(
+ () -> new IllegalStateException("Logout-all sequence event readback is missing"));
+ if (!appended.equals(requestReadback) || !appended.equals(sequenceReadback)) {
+ throw new IllegalStateException("Logout-all immutable event readback differs from append");
+ }
+ ScopeState sourceReadbackState =
+ generationRepository.read(AuthorityScope.account(account.getAccountUuid()));
+ if (!advanced.equals(sourceReadbackState)) {
+ throw new IllegalStateException("Logout-all source state readback differs from its commit");
+ }
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest =
+ sourceReadback.requireCurrentLatest(account, sourceReadbackState);
+ if (latest.outboxSequence() != nextSequence
+ || latest.latestEvent().isEmpty()
+ || !appended.equals(latest.latestEvent().orElseThrow())) {
+ throw new IllegalStateException("Logout-all current source checkpoint readback differs");
+ }
+ draftSourceChanges.complete(requestId, requestPayload, sourceChange, appended);
+ requireReceiptReadback(
+ receipt,
+ requestId,
+ requestDigestVersion,
+ requestDigest,
+ tokenProfile,
+ presentedTokenHash,
+ account);
+ return new CommitAttempt(receipt, null, requestPayload);
+ }
+
+ private LogoutAllReceipt recoverReceipt(Account account, LogoutAllReceipt receipt) {
+ ScopeState current =
+ generationRepository.read(AuthorityScope.account(account.getAccountUuid()));
+ sourceReadback.requireCurrentLatest(account, current);
+ Event event =
+ outboxRepository
+ .findEvent(receipt.outboxStreamKey(), receipt.outboxSequence())
+ .orElseThrow(() -> new IllegalStateException("Logout-all historical event is missing"));
+ sourceReadback.requireLogoutAllReceiptRetained(account, receipt, event, current);
+ LogoutAllReceipt readback =
+ operationRepository
+ .findByRequestId(receipt.requestId())
+ .orElseThrow(() -> new IllegalStateException("Logout-all retry receipt is missing"));
+ if (!receipt.equals(readback)) {
+ throw new IllegalStateException("Logout-all retry receipt changed during readback");
+ }
+ Optional tokenReadback =
+ operationRepository.findByPresentedTokenHash(receipt.presentedTokenHash());
+ if (tokenReadback.isEmpty() || !receipt.equals(tokenReadback.orElseThrow())) {
+ throw new IllegalStateException("Logout-all retry token receipt changed during readback");
+ }
+ return readback;
+ }
+
+ private LogoutAllReceipt readCommittedOperation(
+ UUID requestId,
+ int requestDigestVersion,
+ String requestDigest,
+ String tokenProfile,
+ String presentedTokenHash,
+ Account requestedAccount) {
+ requireNoAmbientTransaction();
+ LogoutAllReceipt receipt =
+ ownerTransaction.execute(
+ status -> {
+ Account account = lockVerifiedAccount(requestedAccount);
+ LogoutAllReceipt committed =
+ operationRepository
+ .findByRequestId(requestId)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Post-commit logout-all request receipt is missing"));
+ requireExactRetryBinding(
+ committed,
+ requestId,
+ requestDigestVersion,
+ requestDigest,
+ tokenProfile,
+ presentedTokenHash,
+ account);
+ Event event =
+ outboxRepository
+ .findEvent(committed.outboxStreamKey(), committed.outboxSequence())
+ .orElseThrow(
+ () ->
+ new IllegalStateException("Logout-all historical event is missing"));
+ draftSourceChanges.verifyCommittedIfPresent(
+ requestId,
+ draftSourceChanges.requestBinding(
+ requestId,
+ requestDigestVersion,
+ requestDigest,
+ tokenProfile,
+ presentedTokenHash,
+ account),
+ event);
+ return recoverReceipt(account, committed);
+ });
+ if (receipt == null) {
+ throw new IllegalStateException("Post-commit logout-all receipt readback returned no result");
+ }
+ return receipt;
+ }
+
+ private LogoutAllReceipt requireReceiptReadback(
+ LogoutAllReceipt expected,
+ UUID requestId,
+ int requestDigestVersion,
+ String requestDigest,
+ String tokenProfile,
+ String presentedTokenHash,
+ Account account) {
+ LogoutAllReceipt byRequest =
+ operationRepository
+ .findByRequestId(requestId)
+ .orElseThrow(() -> new IllegalStateException("Logout-all receipt readback is missing"));
+ Optional byToken =
+ operationRepository.findByPresentedTokenHash(presentedTokenHash);
+ requireExactRetryBinding(
+ byRequest,
+ requestId,
+ requestDigestVersion,
+ requestDigest,
+ tokenProfile,
+ presentedTokenHash,
+ account);
+ if (!expected.equals(byRequest)
+ || byToken.isEmpty()
+ || !expected.equals(byToken.orElseThrow())) {
+ throw new IllegalStateException("Logout-all receipt readback differs from its insert");
+ }
+ Event event =
+ outboxRepository
+ .findEvent(expected.outboxStreamKey(), expected.outboxSequence())
+ .orElseThrow(() -> new IllegalStateException("Logout-all event readback is missing"));
+ draftSourceChanges.verifyCommittedIfPresent(
+ requestId,
+ draftSourceChanges.requestBinding(
+ requestId,
+ requestDigestVersion,
+ requestDigest,
+ tokenProfile,
+ presentedTokenHash,
+ account),
+ event);
+ return byRequest;
+ }
+
+ private void requireExactRetryBinding(
+ LogoutAllReceipt receipt,
+ UUID requestId,
+ int requestDigestVersion,
+ String requestDigest,
+ String tokenProfile,
+ String presentedTokenHash,
+ Account account) {
+ if (!receipt.requestId().equals(requestId)
+ || !OPERATION_KIND.equals(receipt.operationKind())
+ || receipt.requestDigestVersion() != requestDigestVersion
+ || !constantTimeTextEquals(receipt.requestDigest(), requestDigest)
+ || !receipt.tokenProfile().equals(tokenProfile)
+ || !constantTimeTextEquals(receipt.presentedTokenHash(), presentedTokenHash)
+ || receipt.accountId() != account.getId()
+ || !receipt.accountUuid().equals(account.getAccountUuid())) {
+ throw new OperationConflictException(
+ "Logout-all request, digest, operation, token, or Account binding conflicts with its receipt");
+ }
+ }
+
+ private Account lockVerifiedAccount(Account requestedAccount) {
+ Account locked =
+ accountRepository
+ .findByIdForUpdate(requestedAccount.getId())
+ .orElseThrow(
+ () ->
+ new OperationConflictException(
+ "Logout-all Account identity binding is absent from persisted Account state"));
+ if (!Objects.equals(requestedAccount.getId(), locked.getId())
+ || !Objects.equals(requestedAccount.getAccountUuid(), locked.getAccountUuid())
+ || !Objects.equals(
+ requestedAccount.getAccountUuidSourceNumericId(),
+ locked.getAccountUuidSourceNumericId())
+ || requestedAccount.getAccountUuidProvenance() != locked.getAccountUuidProvenance()
+ || !isVerifiedProvenance(locked.getAccountUuidProvenance())) {
+ throw new OperationConflictException(
+ "Logout-all Account identity binding conflicts with persisted Account identity");
+ }
+ // The source readback enforces that this is an exact persisted UUID association.
+ if (locked.getId() == null
+ || locked.getId() <= 0L
+ || locked.getAccountUuid() == null
+ || new UUID(0L, 0L).equals(locked.getAccountUuid())
+ || !locked.getId().equals(locked.getAccountUuidSourceNumericId())) {
+ throw new IllegalStateException("Verified persisted Account association is invalid");
+ }
+ return locked;
+ }
+
+ private EventEvidence eventEvidence(
+ UUID accountUuid,
+ UUID requestId,
+ String eventId,
+ long sequence,
+ long generation,
+ long sourceVersion) {
+ String streamKey = streamKey(accountUuid);
+ AccountLogoutAllAuthorityEvent event =
+ AccountLogoutAllAuthorityEventV1Codec.seal(
+ Map.ofEntries(
+ Map.entry("schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION),
+ Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE),
+ Map.entry("eventId", eventId),
+ Map.entry("requestId", requestId.toString()),
+ Map.entry("accountId", accountUuid.toString()),
+ Map.entry("sourceScope", "account/" + accountUuid),
+ Map.entry("outboxStreamKey", streamKey),
+ Map.entry("outboxSequence", Long.toString(sequence)),
+ Map.entry("accountAuthorityGeneration", Long.toString(generation)),
+ Map.entry("sourceVersion", Long.toString(sourceVersion)),
+ Map.entry(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration", Long.toString(generation),
+ "outboxStreamKey", streamKey,
+ "outboxSequence", Long.toString(sequence)))));
+ return new EventEvidence(event.eventId(), event.eventDigest(), event.canonicalJsonUtf8());
+ }
+
+ private AccountLogoutAllAuthorityEvent requireEvent(
+ Event event,
+ UUID accountUuid,
+ UUID requestId,
+ String eventId,
+ long generation,
+ long sourceVersion) {
+ AccountLogoutAllAuthorityEvent verified =
+ AccountLogoutAllAuthorityEventV1Codec.verify(
+ new String(event.payload(), StandardCharsets.UTF_8));
+ if (!MessageDigest.isEqual(event.payload(), verified.canonicalJsonUtf8())
+ || !streamKey(accountUuid).equals(event.outboxStreamKey())
+ || !requestId.toString().equals(event.requestId())
+ || !eventId.equals(event.eventId())
+ || !event.eventDigest().equals(verified.eventDigest())
+ || !accountUuid.toString().equals(verified.accountId())
+ || !Long.toString(event.outboxSequence()).equals(verified.outboxSequence())
+ || !Long.toString(generation).equals(verified.accountAuthorityGeneration())
+ || !Long.toString(sourceVersion).equals(verified.sourceVersion())) {
+ throw new IllegalStateException("Logout-all source event differs from its committed state");
+ }
+ return verified;
+ }
+
+ private void requireAdvancedState(
+ ScopeState previous,
+ ScopeState advanced,
+ long expectedGeneration,
+ long expectedSourceVersion,
+ long expectedFence) {
+ if (advanced == null
+ || !previous.scope().equals(advanced.scope())
+ || advanced.generation() != expectedGeneration
+ || advanced.sourceVersion() != expectedSourceVersion
+ || advanced.issuanceFence() == null
+ || !previous.issuanceFence().accountId().equals(advanced.issuanceFence().accountId())
+ || advanced.issuanceFence().value() != expectedFence
+ || advanced.issuanceFence().sourceVersion()
+ != incrementExact(
+ previous.issuanceFence().sourceVersion(), "issuance-fence source version")) {
+ throw new IllegalStateException(
+ "Logout-all Account source and issuance fence did not advance once");
+ }
+ }
+
+ private void requireCheckpointMatches(Checkpoint checkpoint, Event event) {
+ if (!checkpoint.outboxStreamKey().equals(event.outboxStreamKey())
+ || checkpoint.outboxSequence() != event.outboxSequence()
+ || !checkpoint.sourceEventId().equals(event.eventId())
+ || !checkpoint.sourceEventDigest().equals(event.eventDigest())) {
+ throw new IllegalStateException("Logout-all outbox checkpoint differs from its event");
+ }
+ }
+
+ private void validateRequest(
+ UUID requestId,
+ int requestDigestVersion,
+ String requestDigest,
+ String tokenProfile,
+ String presentedTokenHash) {
+ if (requestId == null || new UUID(0L, 0L).equals(requestId)) {
+ throw new IllegalArgumentException("A canonical non-nil logout-all request UUID is required");
+ }
+ AccountLogoutRequestDigest.validateTokenProfile(tokenProfile);
+ if (requestDigestVersion <= 0) {
+ throw new IllegalArgumentException("Logout-all request digest version must be positive");
+ }
+ decodeDigest(requestDigest, "request digest");
+ AccountLogoutRequestDigest.validateTokenHash(presentedTokenHash);
+ }
+
+ private void validateExpectedInputs(Account account, ScopeState expectedState) {
+ if (account == null
+ || account.getId() == null
+ || account.getId() <= 0L
+ || account.getAccountUuid() == null
+ || new UUID(0L, 0L).equals(account.getAccountUuid())
+ || !isVerifiedProvenance(account.getAccountUuidProvenance())
+ || account.getAccountUuidSourceNumericId() == null
+ || !account.getId().equals(account.getAccountUuidSourceNumericId())) {
+ throw new IllegalArgumentException("Verified persisted Account association is required");
+ }
+ if (expectedState == null
+ || !AuthorityScope.account(account.getAccountUuid()).equals(expectedState.scope())
+ || expectedState.generation() <= 0L
+ || expectedState.sourceVersion() <= 0L
+ || expectedState.issuanceFence() == null
+ || !account.getAccountUuid().equals(expectedState.issuanceFence().accountId())
+ || expectedState.issuanceFence().value() <= 0L
+ || expectedState.issuanceFence().sourceVersion() <= 0L) {
+ throw new IllegalArgumentException("Expected Account authority scope and fence are required");
+ }
+ }
+
+ private boolean isVerifiedProvenance(AccountIdentityProvenance provenance) {
+ return provenance == AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT
+ || provenance == AccountIdentityProvenance.ACCOUNT_V29_MIGRATION
+ || provenance == AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT;
+ }
+
+ private void requireNoAmbientTransaction() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException(
+ "Logout-all source operations must own their Account transaction without an ambient transaction");
+ }
+ }
+
+ private String streamKey(UUID accountUuid) {
+ return STREAM_PREFIX + accountUuid;
+ }
+
+ private static String decodeDigest(String value, String field) {
+ if (value == null || !value.matches("[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Logout-all " + field + " must be lowercase SHA-256 hex");
+ }
+ HEX.parseHex(value);
+ return value;
+ }
+
+ private boolean constantTimeTextEquals(String left, String right) {
+ return left != null
+ && right != null
+ && MessageDigest.isEqual(
+ left.getBytes(StandardCharsets.US_ASCII), right.getBytes(StandardCharsets.US_ASCII));
+ }
+
+ private record CommitAttempt(
+ LogoutAllReceipt receipt, SourceChange pendingChange, byte[] requestPayload) {}
+
+ private long incrementExact(long value, String field) {
+ try {
+ return Math.addExact(value, 1L);
+ } catch (ArithmeticException overflow) {
+ throw new IllegalStateException("Logout-all " + field + " is exhausted", overflow);
+ }
+ }
+
+ /** Caller bindings changed for an existing logout-all request or token identity. */
+ public static final class OperationConflictException extends IllegalStateException {
+ public OperationConflictException(String message) {
+ super(message);
+ }
+ }
+
+ /** The non-authorizing lifecycle outcome returned by both initial commit and exact retry. */
+ public enum LogoutAllResult {
+ LOGOUT_ALL_COMMITTED
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllDraftSourceChangeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllDraftSourceChangeRepository.java
new file mode 100644
index 0000000000..51dd3d7728
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllDraftSourceChangeRepository.java
@@ -0,0 +1,484 @@
+package net.firedevops.firemud.accountservice.service;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.ByteArrayOutputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+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.DraftAuthorizationFenceRepository;
+import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Exact Account logout-all request journal linked to the V76 Draft authorization fence. */
+public final class AccountLogoutAllDraftSourceChangeRepository {
+ private static final String TABLE = "account_logout_all_draft_source_changes";
+ private static final String REQUEST_SCHEMA = "account-logout-all-draft-source-request/v1";
+ private static final String MUTATION_SCHEMA = "account-logout-all-draft-source-mutation/v1";
+ private static final String STREAM_PREFIX = "account:auth-authority:v1:account/";
+ private final DSLContext dsl;
+ private final DraftAuthorizationFenceRepository fences;
+
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification = "The transaction-aware DSLContext is an internal persistence collaborator.")
+ public AccountLogoutAllDraftSourceChangeRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl);
+ this.fences = new DraftAuthorizationFenceRepository(dsl);
+ }
+
+ /** Captures one exact logout request and its already verified current Account source. */
+ Participation participate(
+ UUID requestId,
+ int digestVersion,
+ String digest,
+ String tokenProfile,
+ String tokenHash,
+ Account account,
+ ScopeState current,
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest) {
+ requireTransaction();
+ byte[] request =
+ requestBytes(requestId, digestVersion, digest, tokenProfile, tokenHash, account);
+ SourceEvidence evidence = capture(account, current, latest);
+ Record prior = findByRequestId(requestId);
+ SourceChange change;
+ if (prior != null) {
+ change = requireRequest(prior, request, account);
+ if (!"WAITING".equals(prior.get("status", String.class))) {
+ throw new IllegalStateException("Completed logout-all source request has no receipt");
+ }
+ if (!Arrays.equals(change.sources().getFirst().canonicalBytes(), evidence.canonicalBytes())
+ || !sameState(prior, current)) {
+ throw new IllegalStateException(
+ "Pending logout-all source request no longer matches its original capture");
+ }
+ } else {
+ if (findByTokenHash(tokenHash) != null) {
+ throw new IllegalStateException(
+ "Presented token identity is already bound to another pending logout-all request");
+ }
+ byte[] mutation = mutationBytes(request, current, latest, evidence.canonicalBytes());
+ change = new SourceChange(UUID.randomUUID(), List.of(evidence), mutation);
+ }
+
+ boolean settled = fences.requestSourceChange(change);
+ if (prior == null) {
+ dsl.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (request_id, account_id, account_uuid, request_digest_version, request_digest,"
+ + " token_profile, presented_token_hash, expected_generation, expected_source_version,"
+ + " expected_issuance_fence, expected_issuance_fence_source_version, checkpoint_stream,"
+ + " checkpoint_sequence, capture_evidence, request_payload, source_evidence, source_change_id,"
+ + " source_change_request, source_change_binding, status)"
+ + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'WAITING')",
+ requestId,
+ account.getId(),
+ account.getAccountUuid(),
+ digestVersion,
+ decodeHex(digest),
+ tokenProfile,
+ decodeHex(tokenHash),
+ current.generation(),
+ current.sourceVersion(),
+ current.issuanceFence().value(),
+ current.issuanceFence().sourceVersion(),
+ evidence.checkpointStream(),
+ latest.outboxSequence(),
+ captureEvidence(account, current, latest),
+ request,
+ evidence.canonicalBytes(),
+ change.changeId(),
+ change.mutation(),
+ change.canonicalBytes());
+ }
+ Record stored = findByRequestId(requestId);
+ SourceChange readback = requireRequest(stored, request, account);
+ if (!Arrays.equals(readback.canonicalBytes(), change.canonicalBytes())) {
+ throw new IllegalStateException(
+ "Logout-all source request readback differs from its capture");
+ }
+ return new Participation(change, settled);
+ }
+
+ /** Exact caller-binding lookup used before server-derived counters on retry. */
+ Optional findPending(
+ UUID requestId,
+ int digestVersion,
+ String digest,
+ String tokenProfile,
+ String tokenHash,
+ Account account) {
+ requireTransaction();
+ Record row = findByRequestId(requestId);
+ if (row == null) {
+ Record token = findByTokenHash(tokenHash);
+ if (token != null) {
+ requireRequest(
+ token,
+ requestBytes(requestId, digestVersion, digest, tokenProfile, tokenHash, account),
+ account);
+ }
+ return Optional.empty();
+ }
+ SourceChange change =
+ requireRequest(
+ row,
+ requestBytes(requestId, digestVersion, digest, tokenProfile, tokenHash, account),
+ account);
+ if (!"WAITING".equals(row.get("status", String.class))) {
+ throw new IllegalStateException(
+ "Committed logout-all source intent has no operation receipt");
+ }
+ return Optional.of(change);
+ }
+
+ byte[] requestBinding(
+ UUID requestId,
+ int digestVersion,
+ String digest,
+ String tokenProfile,
+ String tokenHash,
+ Account account) {
+ return requestBytes(requestId, digestVersion, digest, tokenProfile, tokenHash, account);
+ }
+
+ /** Read-only exact journal evidence for owner-local recovery and PostgreSQL proof. */
+ public Optional readPendingIntent(UUID requestId) {
+ requireTransaction();
+ Record row = findByRequestId(requestId);
+ if (row == null) {
+ return Optional.empty();
+ }
+ requireRequest(row, row.get("request_payload", byte[].class), null);
+ return Optional.of(snapshot(row));
+ }
+
+ boolean permitted(SourceChange change) {
+ return fences.sourceMutationPermitted(change);
+ }
+
+ /** Source counters, receipt/outbox and both journal transitions share one owner transaction. */
+ void complete(UUID requestId, byte[] request, SourceChange change, Event event) {
+ requireTransaction();
+ fences.markSourceCommitted(change);
+ int updated =
+ dsl.execute(
+ "UPDATE "
+ + TABLE
+ + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP,"
+ + " event_stream = ?, event_sequence = ?, event_id = ?, event_digest = ?, event_payload = ?"
+ + " WHERE request_id = ? AND source_change_id = ? AND status = 'WAITING'",
+ event.outboxStreamKey(),
+ event.outboxSequence(),
+ event.eventId(),
+ event.eventDigest(),
+ event.payload(),
+ requestId,
+ change.changeId());
+ if (updated != 1) {
+ throw new IllegalStateException("Logout-all source request did not complete exactly once");
+ }
+ verifyCommittedIfPresent(requestId, request, event);
+ }
+
+ void verifyCommittedIfPresent(UUID requestId, byte[] request, Event event) {
+ requireTransaction();
+ Record row = findByRequestId(requestId);
+ if (row == null) return;
+ SourceChange change = requireRequest(row, request, null);
+ if (!"SOURCE_COMMITTED".equals(row.get("status", String.class))
+ || !"SOURCE_COMMITTED".equals(fences.readSourceChange(change).status())
+ || !event.outboxStreamKey().equals(row.get("event_stream", String.class))
+ || !Long.valueOf(event.outboxSequence()).equals(row.get("event_sequence", Long.class))
+ || !event.eventId().equals(row.get("event_id", String.class))
+ || !event.eventDigest().equals(row.get("event_digest", String.class))
+ || !Arrays.equals(event.payload(), row.get("event_payload", byte[].class))) {
+ throw new IllegalStateException("Logout-all source request and retained event differ");
+ }
+ }
+
+ void verifyWaiting(UUID requestId, byte[] request, SourceChange change) {
+ requireTransaction();
+ Record row = findByRequestId(requestId);
+ SourceChange stored = requireRequest(row, request, null);
+ if (!Arrays.equals(stored.canonicalBytes(), change.canonicalBytes())
+ || !"WAITING".equals(row.get("status", String.class))
+ || !"WAITING".equals(fences.readSourceChange(stored).status())) {
+ throw new IllegalStateException(
+ "Logout-all pending intent readback differs from its capture");
+ }
+ }
+
+ private Record findByRequestId(UUID requestId) {
+ return dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", requestId);
+ }
+
+ private Record findByTokenHash(String tokenHash) {
+ return dsl.fetchOne(
+ "SELECT * FROM " + TABLE + " WHERE presented_token_hash = ? FOR UPDATE",
+ decodeHex(tokenHash));
+ }
+
+ private SourceChange requireRequest(Record row, byte[] request, Account account) {
+ if (row == null || !Arrays.equals(request, row.get("request_payload", byte[].class))) {
+ throw new AccountLogoutAllAuthorityEventProducer.OperationConflictException(
+ "Logout-all request, token, or Account binding conflicts with its pending intent");
+ }
+ if (account != null
+ && (!account.getId().equals(row.get("account_id", Long.class))
+ || !account.getAccountUuid().equals(row.get("account_uuid", UUID.class)))) {
+ throw new AccountLogoutAllAuthorityEventProducer.OperationConflictException(
+ "Logout-all Account binding conflicts with its pending intent");
+ }
+ SourceChange change = SourceChange.fromStored(row.get("source_change_binding", byte[].class));
+ byte[] expectedMutation =
+ mutationBytes(
+ row.get("request_payload", byte[].class),
+ row.get("expected_generation", Long.class),
+ row.get("expected_source_version", Long.class),
+ row.get("expected_issuance_fence", Long.class),
+ row.get("expected_issuance_fence_source_version", Long.class),
+ row.get("checkpoint_sequence", Long.class),
+ row.get("source_evidence", byte[].class));
+ if (!change.changeId().equals(row.get("source_change_id", UUID.class))
+ || !Arrays.equals(change.mutation(), row.get("source_change_request", byte[].class))
+ || !Arrays.equals(expectedMutation, change.mutation())
+ || !Arrays.equals(
+ change.sources().getFirst().canonicalBytes(), row.get("source_evidence", byte[].class))
+ || !change
+ .sources()
+ .getFirst()
+ .key()
+ .equals("ACCOUNT:" + row.get("account_uuid", UUID.class))) {
+ throw new IllegalStateException("Logout-all journal differs from its immutable V76 capture");
+ }
+ fences.readSourceChange(change);
+ return change;
+ }
+
+ private PendingIntentSnapshot snapshot(Record row) {
+ return new PendingIntentSnapshot(
+ row.get("request_id", UUID.class),
+ row.get("source_change_id", UUID.class),
+ row.get("request_payload", byte[].class),
+ row.get("capture_evidence", byte[].class),
+ row.get("source_evidence", byte[].class),
+ row.get("source_change_request", byte[].class),
+ row.get("source_change_binding", byte[].class),
+ row.get("status", String.class),
+ row.get("expected_generation", Long.class),
+ row.get("expected_source_version", Long.class),
+ row.get("expected_issuance_fence", Long.class),
+ row.get("expected_issuance_fence_source_version", Long.class),
+ row.get("checkpoint_sequence", Long.class));
+ }
+
+ private boolean sameState(Record row, ScopeState current) {
+ return current.generation() == row.get("expected_generation", Long.class)
+ && current.sourceVersion() == row.get("expected_source_version", Long.class)
+ && current.issuanceFence().value() == row.get("expected_issuance_fence", Long.class)
+ && current.issuanceFence().sourceVersion()
+ == row.get("expected_issuance_fence_source_version", Long.class);
+ }
+
+ private static SourceEvidence capture(
+ Account account,
+ ScopeState current,
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest) {
+ String stream = STREAM_PREFIX + account.getAccountUuid();
+ if (latest.outboxSequence() == 0L && latest.latestEvent().isPresent()) {
+ throw new IllegalStateException("Account source baseline has contradictory event evidence");
+ }
+ if (latest.outboxSequence() > 0L && latest.latestEvent().isEmpty()) {
+ throw new IllegalStateException("Account source checkpoint has no exact latest event");
+ }
+ byte[] evidence = captureEvidence(account, current, latest);
+ return new SourceEvidence(
+ SourceKind.ACCOUNT,
+ account.getAccountUuid().toString(),
+ Long.toString(current.generation()),
+ Long.toString(current.sourceVersion()),
+ stream,
+ Long.toString(latest.outboxSequence()),
+ evidence);
+ }
+
+ private static byte[] captureEvidence(
+ Account account,
+ ScopeState current,
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest) {
+ String stream = STREAM_PREFIX + account.getAccountUuid();
+ return latest
+ .latestEvent()
+ .map(Event::payload)
+ .orElseGet(
+ () ->
+ framed(
+ List.of(
+ "account-draft-source-baseline/v1",
+ account.getAccountUuid().toString(),
+ Long.toString(current.generation()),
+ Long.toString(current.sourceVersion()),
+ stream,
+ "0")));
+ }
+
+ private static byte[] requestBytes(
+ UUID requestId,
+ int digestVersion,
+ String digest,
+ String tokenProfile,
+ String tokenHash,
+ Account account) {
+ return framed(
+ List.of(
+ REQUEST_SCHEMA,
+ requestId.toString(),
+ Long.toString(account.getId()),
+ account.getAccountUuid().toString(),
+ Integer.toString(digestVersion),
+ decodeHex(digest),
+ tokenProfile,
+ decodeHex(tokenHash)));
+ }
+
+ private static byte[] mutationBytes(
+ byte[] request,
+ ScopeState current,
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest,
+ byte[] sourceEvidence) {
+ return mutationBytes(
+ request,
+ current.generation(),
+ current.sourceVersion(),
+ current.issuanceFence().value(),
+ current.issuanceFence().sourceVersion(),
+ latest.outboxSequence(),
+ sourceEvidence);
+ }
+
+ private static byte[] mutationBytes(
+ byte[] request,
+ long generation,
+ long sourceVersion,
+ long issuanceFence,
+ long issuanceFenceSourceVersion,
+ long checkpointSequence,
+ byte[] sourceEvidence) {
+ return framed(
+ List.of(
+ MUTATION_SCHEMA,
+ request,
+ Long.toString(generation),
+ Long.toString(sourceVersion),
+ Long.toString(issuanceFence),
+ Long.toString(issuanceFenceSourceVersion),
+ Long.toString(checkpointSequence),
+ sourceEvidence));
+ }
+
+ private static byte[] framed(List> fields) {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ for (Object field : fields) {
+ byte[] bytes =
+ field instanceof byte[] binary
+ ? binary
+ : field.toString().getBytes(StandardCharsets.UTF_8);
+ output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array());
+ output.writeBytes(bytes);
+ }
+ return output.toByteArray();
+ }
+
+ private static byte[] decodeHex(String value) {
+ if (value == null || !value.matches("[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Logout-all digest binding must be lowercase SHA-256 hex");
+ }
+ return java.util.HexFormat.of().parseHex(value);
+ }
+
+ private static void requireTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException(
+ "Writable Account transaction required for logout-all source fence");
+ }
+ }
+
+ record Participation(SourceChange change, boolean settled) {}
+
+ public record PendingIntentSnapshot(
+ UUID requestId,
+ UUID sourceChangeId,
+ byte[] requestPayload,
+ byte[] captureEvidence,
+ byte[] sourceEvidence,
+ byte[] sourceChangeRequest,
+ byte[] sourceChangeBinding,
+ String status,
+ long expectedGeneration,
+ long expectedSourceVersion,
+ long expectedIssuanceFence,
+ long expectedIssuanceFenceSourceVersion,
+ long checkpointSequence) {
+ public PendingIntentSnapshot {
+ requestPayload = requestPayload.clone();
+ captureEvidence = captureEvidence.clone();
+ sourceEvidence = sourceEvidence.clone();
+ sourceChangeRequest = sourceChangeRequest.clone();
+ sourceChangeBinding = sourceChangeBinding.clone();
+ }
+
+ @Override
+ public byte[] requestPayload() {
+ return requestPayload.clone();
+ }
+
+ @Override
+ public byte[] captureEvidence() {
+ return captureEvidence.clone();
+ }
+
+ @Override
+ public byte[] sourceEvidence() {
+ return sourceEvidence.clone();
+ }
+
+ @Override
+ public byte[] sourceChangeRequest() {
+ return sourceChangeRequest.clone();
+ }
+
+ @Override
+ public byte[] sourceChangeBinding() {
+ return sourceChangeBinding.clone();
+ }
+ }
+
+ /** Pending source intent is durable and carries no permission to advance Account state. */
+ public static final class PendingSourceChangeException extends IllegalStateException {
+ private static final long serialVersionUID = 1L;
+ private final UUID sourceChangeId;
+
+ public PendingSourceChangeException(UUID sourceChangeId) {
+ super("Draft owner outcomes remain pending for logout-all source change " + sourceChangeId);
+ this.sourceChangeId = Objects.requireNonNull(sourceChangeId);
+ }
+
+ public UUID sourceChangeId() {
+ return sourceChangeId;
+ }
+ }
+}
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 c5332db93f..19ca4c3987 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
@@ -2,7 +2,10 @@
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -36,11 +39,16 @@
import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance;
import net.firedevops.firemud.accountservice.repository.AccountRepository;
import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation;
import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository;
import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository;
import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot;
import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple;
import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent;
+import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator;
+import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@@ -54,6 +62,10 @@ public class AccountMembershipAuthorityEventProducer {
private static final String ACCOUNT_JWT_ISSUER = "firemud-account-service";
private static final int MAX_REQUEST_ID_LENGTH = 128;
private static final int MAX_CALLER_BINDING_LENGTH = 128;
+ private static final Comparator OUTBOX_CHECKPOINT_ORDER =
+ Comparator.comparing(
+ OutboxCheckpointEntry::outboxStreamKey,
+ AccountMembershipAuthorityEventProducer::compareUnsignedUtf8);
private final AccountJoinOperationRepository joinOperationRepository;
private final AccountRepository accountRepository;
@@ -824,6 +836,283 @@ private static void requireBoundedText(String value, String label, int maxCodePo
}
}
+ public record OutboxCheckpointEntry(String outboxStreamKey, String outboxSequence) {
+ public OutboxCheckpointEntry {
+ Objects.requireNonNull(outboxStreamKey, "authority outbox stream key is required");
+ Objects.requireNonNull(outboxSequence, "authority outbox sequence is required");
+ if (!outboxStreamKey.startsWith(MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX)
+ || !isNonnegativeCanonicalDecimal(outboxSequence)) {
+ throw new IllegalArgumentException("Account authority checkpoint is not canonical");
+ }
+ }
+ }
+
+ /** Positive committed source-event identity kept outside the two-field checkpoint carrier. */
+ public record OutboxSourceEvidence(
+ String outboxStreamKey,
+ String outboxSequence,
+ String eventId,
+ String eventDigest,
+ String canonicalEventJson) {
+ public OutboxSourceEvidence {
+ Objects.requireNonNull(outboxStreamKey, "authority outbox stream key is required");
+ Objects.requireNonNull(outboxSequence, "authority outbox sequence is required");
+ if (eventId == null || eventId.isBlank()) {
+ throw new IllegalArgumentException("source event ID is required");
+ }
+ Objects.requireNonNull(eventDigest, "source event digest is required");
+ Objects.requireNonNull(canonicalEventJson, "canonical source event JSON is required");
+ if (!outboxStreamKey.startsWith(MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX)
+ || !isPositiveCanonicalDecimal(outboxSequence)
+ || !eventDigest.matches("sha256:[0-9a-f]{64}")
+ || !canonicalEventJson.startsWith("{")
+ || !canonicalEventJson.endsWith("}")) {
+ throw new IllegalArgumentException(
+ "Account authority source event evidence is not canonical");
+ }
+ }
+ }
+
+ /**
+ * Local V36 absence evidence with an exact one-tenant membership-version map. The sequence-zero
+ * checkpoints carry no source event identity or digest and never authorize gameplay.
+ */
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP",
+ justification = "The constructor stores immutable Map.copyOf and List.copyOf values.")
+ public record NeverJoinedMembershipSnapshot(
+ String accountId,
+ String tenantId,
+ Map membershipVersion,
+ String membershipAuthorityGeneration,
+ AuthorityTuple authorityTuple,
+ String issuanceFence,
+ Instant evaluatedAt,
+ String outboxStreamKey,
+ List outboxCheckpoints,
+ List outboxSourceEvidence) {
+ public NeverJoinedMembershipSnapshot {
+ accountId = requireCanonicalUuid(accountId, "canonical Account UUID");
+ tenantId = requireCanonicalUuid(tenantId, "canonical tenant UUID");
+ membershipVersion =
+ requireExactPositiveVersionMap(membershipVersion, tenantId, "membership version");
+ membershipAuthorityGeneration =
+ requirePositiveCanonicalDecimal(
+ membershipAuthorityGeneration, "membership authority generation");
+ Objects.requireNonNull(authorityTuple, "complete authority tuple is required");
+ issuanceFence = requirePositiveCanonicalDecimal(issuanceFence, "Account issuance fence");
+ Objects.requireNonNull(evaluatedAt, "Account evaluation time is required");
+ outboxStreamKey =
+ Objects.requireNonNull(outboxStreamKey, "membership stream key is required");
+ outboxCheckpoints = requireOrderedCheckpointSet(outboxCheckpoints);
+ outboxSourceEvidence = List.copyOf(outboxSourceEvidence);
+
+ if (!"1".equals(membershipAuthorityGeneration)
+ || !membershipAuthorityGeneration.equals(
+ authorityTuple.membershipAuthorityGeneration().get(tenantId))
+ || !"1".equals(membershipVersion.get(tenantId))
+ || !authorityTuple.privateRealmGrantVersions().isEmpty()
+ || authorityTuple.tenantBillingCutoff().isPresent()) {
+ throw new IllegalArgumentException(
+ "Never-joined Account authority tuple is incomplete or mismatched");
+ }
+
+ String expectedStreamKey =
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX
+ + "membership/"
+ + accountId
+ + "/"
+ + tenantId;
+ if (!expectedStreamKey.equals(outboxStreamKey)) {
+ throw new IllegalArgumentException(
+ "Never-joined Account membership stream key is not canonical");
+ }
+ List membershipCheckpoints =
+ outboxCheckpoints.stream()
+ .filter(checkpoint -> checkpoint.outboxStreamKey().equals(expectedStreamKey))
+ .toList();
+ if (membershipCheckpoints.size() != 1
+ || !"0".equals(membershipCheckpoints.getFirst().outboxSequence())) {
+ throw new IllegalArgumentException(
+ "Never-joined Account snapshot must retain a sequence-zero membership checkpoint");
+ }
+ if (RuntimeMembershipAuthorityEvidenceValidator.validate(
+ validatorSnapshot(
+ accountId,
+ tenantId,
+ false,
+ "MISSING",
+ false,
+ membershipVersion,
+ membershipAuthorityGeneration,
+ List.of(),
+ authorityTuple,
+ issuanceFence,
+ outboxCheckpoints,
+ outboxSourceEvidence))
+ .isPresent()) {
+ throw new IllegalArgumentException(
+ "Never-joined Account snapshot cannot contain a membership event");
+ }
+ }
+
+ public boolean membershipExists() {
+ return false;
+ }
+
+ public String membershipLifecycleState() {
+ return "MISSING";
+ }
+
+ public List roles() {
+ return List.of();
+ }
+
+ public boolean gameplayAdmissionAllowed() {
+ return false;
+ }
+ }
+
+ /** Existing control-only source evidence, never a runtime admission or authoring permission. */
+ public record CreatorControlCaptureSources(
+ UUID accountUuid,
+ UUID tenantUuid,
+ CompositeSnapshot authoritySnapshot,
+ Map membershipVersion,
+ AuthorityTuple authorityTuple,
+ String issuanceFence,
+ PairAuthority pairSource,
+ RoleSnapshot roleSource,
+ FreshTenantCreationEvidence creationSource,
+ StoredOperation bootstrapReceipt,
+ MembershipEvent sourceEvent,
+ List outboxCheckpoints,
+ List outboxSourceEvidence,
+ Instant evaluatedAt) {
+ public CreatorControlCaptureSources {
+ membershipVersion = Map.copyOf(membershipVersion);
+ outboxCheckpoints = List.copyOf(outboxCheckpoints);
+ outboxSourceEvidence = List.copyOf(outboxSourceEvidence);
+ }
+ }
+
+ private static String requireCanonicalUuid(String value, String field) {
+ Objects.requireNonNull(value, field + " is required");
+ try {
+ if (!UUID.fromString(value).toString().equals(value)) {
+ throw new IllegalArgumentException(field + " must be a canonical lowercase UUID");
+ }
+ } catch (IllegalArgumentException exception) {
+ throw new IllegalArgumentException(field + " must be a canonical lowercase UUID", exception);
+ }
+ return value;
+ }
+
+ private static String requirePositiveCanonicalDecimal(String value, String field) {
+ Objects.requireNonNull(value, field + " is required");
+ if (!isPositiveCanonicalDecimal(value)) {
+ throw new IllegalArgumentException(
+ field + " must be a positive canonical unsigned decimal string");
+ }
+ return value;
+ }
+
+ private static boolean isPositiveCanonicalDecimal(String value) {
+ return value != null && value.matches("[1-9][0-9]*");
+ }
+
+ private static boolean isNonnegativeCanonicalDecimal(String value) {
+ return value != null && value.matches("0|[1-9][0-9]*");
+ }
+
+ private static Map requireExactPositiveVersionMap(
+ Map value, String tenantId, String field) {
+ Objects.requireNonNull(value, field + " map is required");
+ if (value.size() != 1
+ || !value.containsKey(tenantId)
+ || !isPositiveCanonicalDecimal(value.get(tenantId))) {
+ throw new IllegalArgumentException(field + " must be a positive canonical one-tenant map");
+ }
+ return Map.copyOf(value);
+ }
+
+ private static List requireOrderedCheckpointSet(
+ List checkpoints) {
+ Objects.requireNonNull(checkpoints, "Account authority checkpoints are required");
+ List copy = List.copyOf(checkpoints);
+ ArrayList ordered = new ArrayList<>(copy);
+ ordered.sort(OUTBOX_CHECKPOINT_ORDER);
+ if (!copy.equals(ordered)) {
+ throw new IllegalArgumentException(
+ "Account authority checkpoints must use canonical stream-key order");
+ }
+ for (int index = 1; index < copy.size(); index++) {
+ if (copy.get(index - 1).outboxStreamKey().equals(copy.get(index).outboxStreamKey())) {
+ throw new IllegalArgumentException(
+ "Account authority checkpoint stream keys must be unique");
+ }
+ }
+ return copy;
+ }
+
+ static Snapshot validatorSnapshot(
+ String accountId,
+ String tenantId,
+ boolean membershipExists,
+ String membershipLifecycleState,
+ boolean gameplayAdmissionAllowed,
+ Map membershipVersion,
+ String membershipAuthorityGeneration,
+ List roles,
+ AuthorityTuple authorityTuple,
+ String issuanceFence,
+ List checkpoints,
+ List sourceEvidence) {
+ return new Snapshot(
+ ACCOUNT_JWT_ISSUER,
+ accountId,
+ tenantId,
+ membershipExists,
+ membershipLifecycleState,
+ gameplayAdmissionAllowed,
+ membershipVersion,
+ membershipAuthorityGeneration,
+ roles,
+ authorityTuple,
+ issuanceFence,
+ checkpoints.stream()
+ .map(
+ checkpoint ->
+ new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(
+ checkpoint.outboxStreamKey(), checkpoint.outboxSequence()))
+ .toList(),
+ sourceEvidence.stream()
+ .map(
+ source ->
+ new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence(
+ source.outboxStreamKey(),
+ source.outboxSequence(),
+ source.eventId(),
+ source.eventDigest(),
+ source.canonicalEventJson()))
+ .toList());
+ }
+
+ private static int compareUnsignedUtf8(String left, String right) {
+ byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8);
+ byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8);
+ int commonLength = Math.min(leftBytes.length, rightBytes.length);
+ for (int index = 0; index < commonLength; index++) {
+ int comparison =
+ Integer.compare(
+ Byte.toUnsignedInt(leftBytes[index]), Byte.toUnsignedInt(rightBytes[index]));
+ if (comparison != 0) {
+ return comparison;
+ }
+ }
+ return Integer.compare(leftBytes.length, rightBytes.length);
+ }
+
private static void requireWritableOwnerTransaction() {
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException(
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java
new file mode 100644
index 0000000000..3a52b65be1
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java
@@ -0,0 +1,758 @@
+package net.firedevops.firemud.accountservice.service;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.ByteArrayOutputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository;
+import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange;
+import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChangeAbortReason;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Durable exact Account password-reset intent linked to the V76 Draft source-writer fence. */
+@Repository
+@SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification = "The transaction-aware DSLContext is an internal persistence collaborator.")
+public final class AccountPasswordResetDraftSourceChangeRepository {
+ private static final String TABLE = "account_password_reset_draft_source_changes";
+ private static final String REQUEST_SCHEMA = "account-password-reset-draft-source-request/v1";
+ private static final String MUTATION_SCHEMA = "account-password-reset-draft-source-mutation/v1";
+ private static final String STREAM_PREFIX = "account:auth-authority:v1:account/";
+ private static final String REQUEST_ID_PREFIX = "account-password-reset-request-v1:";
+ private static final String EVENT_ID_PREFIX = "account-password-reset-event-v1:";
+ private static final HexFormat HEX = HexFormat.of();
+
+ private final DSLContext dsl;
+ private final DraftAuthorizationFenceRepository fences;
+
+ public AccountPasswordResetDraftSourceChangeRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl);
+ this.fences = new DraftAuthorizationFenceRepository(dsl);
+ }
+
+ /** Locks and verifies the original immutable request before a retry derives new source state. */
+ public Optional findAccountIdByTokenHash(String tokenHash) {
+ requireTransaction();
+ Record row =
+ dsl.fetchOne(
+ "SELECT account_id FROM " + TABLE + " WHERE token_hash = ?", decodeHex(tokenHash));
+ return Optional.ofNullable(row == null ? null : row.get("account_id", Long.class));
+ }
+
+ public Optional findByTokenHash(String tokenHash) {
+ requireTransaction();
+ Record row =
+ dsl.fetchOne(
+ "SELECT * FROM " + TABLE + " WHERE token_hash = ? FOR UPDATE", decodeHex(tokenHash));
+ return Optional.ofNullable(row == null ? null : requireIntent(row));
+ }
+
+ /**
+ * Persists the exact original capture before returning a waiting result. An existing intent is
+ * always replayed from its stored source change; a retry never replaces the original capture.
+ */
+ public Intent participate(
+ Account account,
+ long tokenId,
+ String tokenHash,
+ LocalDateTime tokenExpiresAt,
+ String requestDigest,
+ String passwordVerifier,
+ ScopeState current,
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest) {
+ requireTransaction();
+ requireAccount(account);
+ requireDigest(tokenHash, "token hash");
+ requireDigest(requestDigest, "request digest");
+ if (tokenId <= 0L
+ || tokenExpiresAt == null
+ || passwordVerifier == null
+ || passwordVerifier.isBlank()
+ || passwordVerifier.length() > 255) {
+ throw new IllegalArgumentException("Exact password-reset request evidence is required");
+ }
+
+ String verifierDigest = sha256Hex(passwordVerifier);
+ byte[] request =
+ requestBytes(account, tokenId, tokenHash, tokenExpiresAt, requestDigest, verifierDigest);
+ Record prior = findRow(tokenHash);
+ if (prior != null) {
+ Intent intent = requireIntent(prior);
+ requireSameRequest(intent, request, account);
+ if (!"WAITING".equals(intent.status())) {
+ throw new IllegalStateException("Terminal password-reset source intent has no receipt");
+ }
+ fences.requestSourceChange(intent.sourceChange());
+ return requireIntent(findRow(tokenHash));
+ }
+
+ SourceEvidence source = capture(account, current, latest);
+ String requestId = REQUEST_ID_PREFIX + tokenHash;
+ String eventId = EVENT_ID_PREFIX + tokenHash;
+ long nextGeneration = Math.addExact(current.generation(), 1L);
+ long nextSourceVersion = Math.addExact(current.sourceVersion(), 1L);
+ long nextFence = Math.addExact(current.issuanceFence().value(), 1L);
+ long nextFenceSourceVersion = Math.addExact(current.issuanceFence().sourceVersion(), 1L);
+ long nextSequence = Math.addExact(latest.outboxSequence(), 1L);
+ byte[] mutation =
+ mutationBytes(
+ request,
+ current.generation(),
+ current.sourceVersion(),
+ current.issuanceFence().value(),
+ current.issuanceFence().sourceVersion(),
+ latest.outboxSequence(),
+ source.canonicalBytes(),
+ nextGeneration,
+ nextSourceVersion,
+ nextFence,
+ nextFenceSourceVersion,
+ nextSequence,
+ requestId,
+ eventId);
+ SourceChange change = new SourceChange(UUID.randomUUID(), List.of(source), mutation);
+ fences.requestSourceChange(change);
+
+ dsl.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (token_hash, account_id, account_uuid, account_uuid_provenance, "
+ + "account_uuid_source_numeric_id, token_id, request_id, event_id, "
+ + "request_digest_version, request_digest, password_verifier, password_verifier_digest, "
+ + "token_expires_at, token_expires_epoch_nanos, expected_generation, expected_source_version, "
+ + "expected_issuance_fence, expected_issuance_fence_source_version, checkpoint_stream, "
+ + "checkpoint_sequence, capture_evidence, request_payload, source_evidence, source_change_id, "
+ + "source_change_request, source_change_binding, status) "
+ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'WAITING')",
+ decodeHex(tokenHash),
+ account.getId(),
+ account.getAccountUuid(),
+ account.getAccountUuidProvenance().name(),
+ account.getAccountUuidSourceNumericId(),
+ tokenId,
+ requestId,
+ eventId,
+ decodeHex(requestDigest),
+ passwordVerifier,
+ decodeHex(verifierDigest),
+ tokenExpiresAt,
+ epochNanos(tokenExpiresAt),
+ current.generation(),
+ current.sourceVersion(),
+ current.issuanceFence().value(),
+ current.issuanceFence().sourceVersion(),
+ source.checkpointStream(),
+ latest.outboxSequence(),
+ captureEvidence(account, current, latest),
+ request,
+ source.canonicalBytes(),
+ change.changeId(),
+ mutation,
+ change.canonicalBytes());
+
+ Intent stored = requireIntent(findRow(tokenHash));
+ if (!Arrays.equals(stored.requestPayload(), request)
+ || !Arrays.equals(stored.sourceChange().canonicalBytes(), change.canonicalBytes())) {
+ throw new IllegalStateException("Password-reset Draft intent readback differs from capture");
+ }
+ return stored;
+ }
+
+ /** Currentness check is separate from immutable-intent recovery and grants no mutation right. */
+ public boolean matchesCapture(
+ Intent intent,
+ Account account,
+ ScopeState current,
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest) {
+ requireTransaction();
+ if (intent.accountId() != account.getId()
+ || !intent.accountUuid().equals(account.getAccountUuid())
+ || current.generation() != intent.expectedGeneration()
+ || current.sourceVersion() != intent.expectedSourceVersion()
+ || current.issuanceFence().value() != intent.expectedIssuanceFence()
+ || current.issuanceFence().sourceVersion() != intent.expectedIssuanceFenceSourceVersion()
+ || latest.outboxSequence() != intent.checkpointSequence()) {
+ return false;
+ }
+ byte[] currentCapture = captureEvidence(account, current, latest);
+ return Arrays.equals(currentCapture, intent.captureEvidence());
+ }
+
+ public boolean sourceMutationPermitted(Intent intent) {
+ requireTransaction();
+ return fences.sourceMutationPermitted(intent.sourceChange());
+ }
+
+ /** V76 transition and immutable operation receipt/event are committed in the same transaction. */
+ public void markSourceCommitted(Intent intent, Event event) {
+ requireTransaction();
+ fences.markSourceCommitted(intent.sourceChange());
+ int updated =
+ dsl.execute(
+ "UPDATE "
+ + TABLE
+ + " SET status = 'SOURCE_COMMITTED', event_stream = ?, event_sequence = ?, "
+ + "event_id = ?, event_digest = ?, event_payload = ? "
+ + "WHERE token_hash = ? AND source_change_id = ? AND status = 'WAITING'",
+ event.outboxStreamKey(),
+ event.outboxSequence(),
+ event.eventId(),
+ event.eventDigest(),
+ event.payload(),
+ decodeHex(intent.tokenHash()),
+ intent.sourceChangeId());
+ if (updated != 1) {
+ throw new IllegalStateException(
+ "Password-reset Draft source intent did not commit exactly once");
+ }
+ Intent readback = requireIntent(findRow(intent.tokenHash()));
+ if (!"SOURCE_COMMITTED".equals(readback.status())
+ || !"SOURCE_COMMITTED".equals(fences.readSourceChange(readback.sourceChange()).status())
+ || !event.equals(readback.event())) {
+ throw new IllegalStateException("Password-reset Draft source commit readback differs");
+ }
+ }
+
+ /** A definitive no-mutation result closes both durable records only after V76 permits it. */
+ public void markSourceAborted(Intent intent, SourceChangeAbortReason reason) {
+ requireTransaction();
+ fences.markSourceAborted(intent.sourceChange(), reason);
+ int updated =
+ dsl.execute(
+ "UPDATE "
+ + TABLE
+ + " SET status = 'SOURCE_ABORTED', abort_reason = ? "
+ + "WHERE token_hash = ? AND source_change_id = ? AND status = 'WAITING'",
+ reason.name(),
+ decodeHex(intent.tokenHash()),
+ intent.sourceChangeId());
+ if (updated != 1) {
+ throw new IllegalStateException(
+ "Password-reset Draft source intent did not abort exactly once");
+ }
+ Intent readback = requireIntent(findRow(intent.tokenHash()));
+ if (!"SOURCE_ABORTED".equals(readback.status())
+ || !"SOURCE_ABORTED".equals(fences.readSourceChange(readback.sourceChange()).status())) {
+ throw new IllegalStateException("Password-reset Draft source abort readback differs");
+ }
+ }
+
+ public void verifyWaiting(Intent intent) {
+ requireTransaction();
+ Intent readback = requireIntent(findRow(intent.tokenHash()));
+ if (!"WAITING".equals(readback.status())
+ || !"WAITING".equals(fences.readSourceChange(readback.sourceChange()).status())
+ || !Arrays.equals(readback.requestPayload(), intent.requestPayload())) {
+ throw new IllegalStateException("Password-reset waiting source intent readback differs");
+ }
+ }
+
+ private Record findRow(String tokenHash) {
+ return dsl.fetchOne(
+ "SELECT * FROM " + TABLE + " WHERE token_hash = ? FOR UPDATE", decodeHex(tokenHash));
+ }
+
+ private Intent requireIntent(Record row) {
+ if (row == null) {
+ throw new IllegalStateException("Password-reset Draft source intent is missing");
+ }
+ Intent intent = toIntent(row);
+ byte[] expectedRequest =
+ requestBytes(
+ intent.account(),
+ intent.tokenId(),
+ intent.tokenHash(),
+ intent.tokenExpiresAt(),
+ intent.requestDigest(),
+ intent.passwordVerifierDigest());
+ byte[] expectedMutation =
+ mutationBytes(
+ expectedRequest,
+ intent.expectedGeneration(),
+ intent.expectedSourceVersion(),
+ intent.expectedIssuanceFence(),
+ intent.expectedIssuanceFenceSourceVersion(),
+ intent.checkpointSequence(),
+ intent.sourceEvidence(),
+ Math.addExact(intent.expectedGeneration(), 1L),
+ Math.addExact(intent.expectedSourceVersion(), 1L),
+ Math.addExact(intent.expectedIssuanceFence(), 1L),
+ Math.addExact(intent.expectedIssuanceFenceSourceVersion(), 1L),
+ Math.addExact(intent.checkpointSequence(), 1L),
+ intent.requestId(),
+ intent.eventId());
+ if (intent.requestDigestVersion() != 1
+ || !MessageDigest.isEqual(expectedRequest, intent.requestPayload())
+ || !MessageDigest.isEqual(expectedMutation, intent.sourceChange().mutation())
+ || !Arrays.equals(intent.sourceChange().canonicalBytes(), intent.sourceChangeBinding())
+ || !Arrays.equals(
+ intent.sourceChange().sources().getFirst().canonicalBytes(), intent.sourceEvidence())
+ || !intent
+ .sourceChange()
+ .sources()
+ .getFirst()
+ .key()
+ .equals("ACCOUNT:" + intent.accountUuid())
+ || !sha256Hex(intent.passwordVerifier()).equals(intent.passwordVerifierDigest())
+ || !intent.requestId().equals(REQUEST_ID_PREFIX + intent.tokenHash())
+ || !intent.eventId().equals(EVENT_ID_PREFIX + intent.tokenHash())) {
+ throw new IllegalStateException("Stored password-reset Draft intent is inconsistent");
+ }
+ fences.readSourceChange(intent.sourceChange());
+ return intent;
+ }
+
+ private Intent toIntent(Record row) {
+ UUID accountUuid = Objects.requireNonNull(row.get("account_uuid", UUID.class));
+ Account account = new Account();
+ account.setId(row.get("account_id", Long.class));
+ account.setAccountUuid(accountUuid);
+ account.setAccountUuidProvenance(
+ net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance.fromStorageValue(
+ row.get("account_uuid_provenance", String.class)));
+ account.setAccountUuidSourceNumericId(row.get("account_uuid_source_numeric_id", Long.class));
+ String tokenHash = encodeHex(row.get("token_hash", byte[].class));
+ var event =
+ row.get("event_sequence", Long.class) == null
+ ? null
+ : new Event(
+ row.get("event_stream", String.class),
+ row.get("request_id", String.class),
+ row.get("event_sequence", Long.class),
+ row.get("event_id", String.class),
+ row.get("event_digest", String.class),
+ row.get("event_payload", byte[].class));
+ return new Intent(
+ account,
+ row.get("token_id", Long.class),
+ tokenHash,
+ row.get("request_id", String.class),
+ row.get("event_id", String.class),
+ row.get("request_digest_version", Integer.class),
+ encodeHex(row.get("request_digest", byte[].class)),
+ row.get("password_verifier", String.class),
+ encodeHex(row.get("password_verifier_digest", byte[].class)),
+ row.get("token_expires_at", LocalDateTime.class),
+ row.get("expected_generation", Long.class),
+ row.get("expected_source_version", Long.class),
+ row.get("expected_issuance_fence", Long.class),
+ row.get("expected_issuance_fence_source_version", Long.class),
+ row.get("checkpoint_stream", String.class),
+ row.get("checkpoint_sequence", Long.class),
+ row.get("capture_evidence", byte[].class),
+ row.get("request_payload", byte[].class),
+ row.get("source_evidence", byte[].class),
+ row.get("source_change_id", UUID.class),
+ row.get("source_change_request", byte[].class),
+ row.get("source_change_binding", byte[].class),
+ row.get("status", String.class),
+ row.get("abort_reason", String.class),
+ event,
+ SourceChange.fromStored(row.get("source_change_binding", byte[].class)));
+ }
+
+ private static SourceEvidence capture(
+ Account account,
+ ScopeState current,
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest) {
+ String stream = STREAM_PREFIX + account.getAccountUuid();
+ return new SourceEvidence(
+ SourceKind.ACCOUNT,
+ account.getAccountUuid().toString(),
+ Long.toString(current.generation()),
+ Long.toString(current.sourceVersion()),
+ stream,
+ Long.toString(latest.outboxSequence()),
+ captureEvidence(account, current, latest));
+ }
+
+ private static byte[] captureEvidence(
+ Account account,
+ ScopeState current,
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest) {
+ String stream = STREAM_PREFIX + account.getAccountUuid();
+ if (latest.outboxSequence() == 0L) {
+ if (latest.latestEvent().isPresent()
+ || current.generation() != 1L
+ || current.sourceVersion() != 1L) {
+ throw new IllegalStateException("Password-reset source sequence zero is not pristine");
+ }
+ return framed(
+ List.of(
+ "account-draft-source-baseline/v1",
+ account.getAccountUuid().toString(),
+ "1",
+ "1",
+ stream,
+ "0"));
+ }
+ Event latestEvent = latest.latestEvent().orElseThrow();
+ if (latestEvent.outboxSequence() != latest.outboxSequence()
+ || !stream.equals(latestEvent.outboxStreamKey())) {
+ throw new IllegalStateException("Password-reset source checkpoint readback differs");
+ }
+ return latestEvent.payload();
+ }
+
+ private static byte[] requestBytes(
+ Account account,
+ long tokenId,
+ String tokenHash,
+ LocalDateTime tokenExpiresAt,
+ String requestDigest,
+ String verifierDigest) {
+ return framed(
+ List.of(
+ REQUEST_SCHEMA,
+ REQUEST_ID_PREFIX + tokenHash,
+ Long.toString(account.getId()),
+ account.getAccountUuid().toString(),
+ Long.toString(tokenId),
+ tokenHashBytes(tokenHash),
+ Long.toString(epochNanos(tokenExpiresAt)),
+ "1",
+ decodeHex(requestDigest),
+ decodeHex(verifierDigest),
+ account.getAccountUuidProvenance().name(),
+ Long.toString(account.getAccountUuidSourceNumericId())));
+ }
+
+ private static byte[] mutationBytes(
+ byte[] request,
+ long generation,
+ long sourceVersion,
+ long issuanceFence,
+ long issuanceFenceSourceVersion,
+ long checkpointSequence,
+ byte[] sourceEvidence,
+ long nextGeneration,
+ long nextSourceVersion,
+ long nextFence,
+ long nextFenceSourceVersion,
+ long nextSequence,
+ String requestId,
+ String eventId) {
+ return framed(
+ List.of(
+ MUTATION_SCHEMA,
+ request,
+ Long.toString(generation),
+ Long.toString(sourceVersion),
+ Long.toString(issuanceFence),
+ Long.toString(issuanceFenceSourceVersion),
+ Long.toString(checkpointSequence),
+ sourceEvidence,
+ Long.toString(nextGeneration),
+ Long.toString(nextSourceVersion),
+ Long.toString(nextFence),
+ Long.toString(nextFenceSourceVersion),
+ Long.toString(nextSequence),
+ requestId,
+ eventId));
+ }
+
+ private static byte[] framed(List> fields) {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ for (Object field : fields) {
+ byte[] bytes =
+ field instanceof byte[] binary
+ ? binary
+ : field.toString().getBytes(StandardCharsets.UTF_8);
+ output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array());
+ output.writeBytes(bytes);
+ }
+ return output.toByteArray();
+ }
+
+ private static void requireSameRequest(Intent intent, byte[] request, Account account) {
+ if (intent.accountId() != account.getId()
+ || !intent.accountUuid().equals(account.getAccountUuid())
+ || !Arrays.equals(intent.requestPayload(), request)) {
+ throw new IllegalStateException(
+ "Password-reset token is already bound to a different Account or reset request");
+ }
+ }
+
+ private static void requireAccount(Account account) {
+ if (account == null
+ || account.getId() == null
+ || account.getId() <= 0L
+ || account.getAccountUuid() == null
+ || account.getAccountUuidProvenance() == null
+ || account.getAccountUuidSourceNumericId() == null
+ || !account.getId().equals(account.getAccountUuidSourceNumericId())) {
+ throw new IllegalArgumentException("Persisted Account identity is required");
+ }
+ }
+
+ private static void requireDigest(String digest, String field) {
+ if (digest == null || !digest.matches("[0-9a-f]{64}")) {
+ throw new IllegalArgumentException("Password-reset " + field + " must be lowercase SHA-256");
+ }
+ }
+
+ private static byte[] tokenHashBytes(String value) {
+ requireDigest(value, "token hash");
+ return decodeHex(value);
+ }
+
+ private static byte[] decodeHex(String value) {
+ requireDigest(value, "digest");
+ return HEX.parseHex(value);
+ }
+
+ private static String encodeHex(byte[] value) {
+ if (value == null || value.length != 32) {
+ throw new IllegalStateException("Password-reset source digest is missing or malformed");
+ }
+ return HEX.formatHex(value);
+ }
+
+ private static String sha256Hex(String value) {
+ try {
+ return HEX.formatHex(
+ MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));
+ } catch (java.security.NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException("SHA-256 is unavailable", impossible);
+ }
+ }
+
+ private static long epochNanos(LocalDateTime value) {
+ Objects.requireNonNull(value, "token deadline");
+ return Math.addExact(
+ Math.multiplyExact(value.toEpochSecond(ZoneOffset.UTC), 1_000_000_000L), value.getNano());
+ }
+
+ private static void requireTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException(
+ "Writable Account transaction required for password-reset source fencing");
+ }
+ }
+
+ /** In-memory recovery value; its password verifier is deliberately redacted from diagnostics. */
+ public static final class Intent {
+ private final Account account;
+ private final long tokenId;
+ private final String tokenHash;
+ private final String requestId;
+ private final String eventId;
+ private final int requestDigestVersion;
+ private final String requestDigest;
+ private final String passwordVerifier;
+ private final String passwordVerifierDigest;
+ private final LocalDateTime tokenExpiresAt;
+ private final long expectedGeneration;
+ private final long expectedSourceVersion;
+ private final long expectedIssuanceFence;
+ private final long expectedIssuanceFenceSourceVersion;
+ private final String checkpointStream;
+ private final long checkpointSequence;
+ private final byte[] captureEvidence;
+ private final byte[] requestPayload;
+ private final byte[] sourceEvidence;
+ private final UUID sourceChangeId;
+ private final byte[] sourceChangeRequest;
+ private final byte[] sourceChangeBinding;
+ private final String status;
+ private final String abortReason;
+ private final Event event;
+ private final SourceChange sourceChange;
+
+ private Intent(
+ Account account,
+ long tokenId,
+ String tokenHash,
+ String requestId,
+ String eventId,
+ int requestDigestVersion,
+ String requestDigest,
+ String passwordVerifier,
+ String passwordVerifierDigest,
+ LocalDateTime tokenExpiresAt,
+ long expectedGeneration,
+ long expectedSourceVersion,
+ long expectedIssuanceFence,
+ long expectedIssuanceFenceSourceVersion,
+ String checkpointStream,
+ long checkpointSequence,
+ byte[] captureEvidence,
+ byte[] requestPayload,
+ byte[] sourceEvidence,
+ UUID sourceChangeId,
+ byte[] sourceChangeRequest,
+ byte[] sourceChangeBinding,
+ String status,
+ String abortReason,
+ Event event,
+ SourceChange sourceChange) {
+ this.account = account;
+ this.tokenId = tokenId;
+ this.tokenHash = tokenHash;
+ this.requestId = requestId;
+ this.eventId = eventId;
+ this.requestDigestVersion = requestDigestVersion;
+ this.requestDigest = requestDigest;
+ this.passwordVerifier = passwordVerifier;
+ this.passwordVerifierDigest = passwordVerifierDigest;
+ this.tokenExpiresAt = tokenExpiresAt;
+ this.expectedGeneration = expectedGeneration;
+ this.expectedSourceVersion = expectedSourceVersion;
+ this.expectedIssuanceFence = expectedIssuanceFence;
+ this.expectedIssuanceFenceSourceVersion = expectedIssuanceFenceSourceVersion;
+ this.checkpointStream = checkpointStream;
+ this.checkpointSequence = checkpointSequence;
+ this.captureEvidence = captureEvidence.clone();
+ this.requestPayload = requestPayload.clone();
+ this.sourceEvidence = sourceEvidence.clone();
+ this.sourceChangeId = sourceChangeId;
+ this.sourceChangeRequest = sourceChangeRequest.clone();
+ this.sourceChangeBinding = sourceChangeBinding.clone();
+ this.status = status;
+ this.abortReason = abortReason;
+ this.event = event;
+ this.sourceChange = sourceChange;
+ }
+
+ public long accountId() {
+ return account.getId();
+ }
+
+ public UUID accountUuid() {
+ return account.getAccountUuid();
+ }
+
+ Account account() {
+ return account;
+ }
+
+ public long tokenId() {
+ return tokenId;
+ }
+
+ public String tokenHash() {
+ return tokenHash;
+ }
+
+ public String requestId() {
+ return requestId;
+ }
+
+ public String eventId() {
+ return eventId;
+ }
+
+ int requestDigestVersion() {
+ return requestDigestVersion;
+ }
+
+ public String requestDigest() {
+ return requestDigest;
+ }
+
+ public String passwordVerifier() {
+ return passwordVerifier;
+ }
+
+ public String passwordVerifierDigest() {
+ return passwordVerifierDigest;
+ }
+
+ public LocalDateTime tokenExpiresAt() {
+ return tokenExpiresAt;
+ }
+
+ public long expectedGeneration() {
+ return expectedGeneration;
+ }
+
+ public long expectedSourceVersion() {
+ return expectedSourceVersion;
+ }
+
+ public long expectedIssuanceFence() {
+ return expectedIssuanceFence;
+ }
+
+ public long expectedIssuanceFenceSourceVersion() {
+ return expectedIssuanceFenceSourceVersion;
+ }
+
+ public String checkpointStream() {
+ return checkpointStream;
+ }
+
+ public long checkpointSequence() {
+ return checkpointSequence;
+ }
+
+ byte[] captureEvidence() {
+ return captureEvidence.clone();
+ }
+
+ byte[] requestPayload() {
+ return requestPayload.clone();
+ }
+
+ byte[] sourceEvidence() {
+ return sourceEvidence.clone();
+ }
+
+ public UUID sourceChangeId() {
+ return sourceChangeId;
+ }
+
+ byte[] sourceChangeRequest() {
+ return sourceChangeRequest.clone();
+ }
+
+ byte[] sourceChangeBinding() {
+ return sourceChangeBinding.clone();
+ }
+
+ public String status() {
+ return status;
+ }
+
+ String abortReason() {
+ return abortReason;
+ }
+
+ public Event event() {
+ return event;
+ }
+
+ SourceChange sourceChange() {
+ return sourceChange;
+ }
+
+ @Override
+ public String toString() {
+ return "PasswordResetDraftIntent[accountId="
+ + accountId()
+ + ", tokenHash=, "
+ + "passwordVerifier=, status="
+ + status
+ + "]";
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java
new file mode 100644
index 0000000000..43ad8d45e4
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java
@@ -0,0 +1,20 @@
+package net.firedevops.firemud.accountservice.service;
+
+import java.util.function.Supplier;
+import net.firedevops.firemud.accountservice.dto.AccountTenantCreationBootstrapResult;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+
+/**
+ * Account-owned authorization/source participant required for a new creator bootstrap commit.
+ *
+ * The implementation must authenticate the initiating Account and exact source operation, verify
+ * the current Account authorization named by the creator evidence, and hold or participate in that
+ * source's commit fence until {@code mutationWhileCurrent} returns and the enclosing Account
+ * transaction commits. The immutable DTO alone is never authorization. No production implementation
+ * is registered by this storage slice, so new creator bootstrap attempts are default-denied.
+ */
+public interface AccountTenantCreationBootstrapAuthorizationSource {
+ AccountTenantCreationBootstrapResult withCurrentAuthorizationAndSourceParticipation(
+ FreshTenantCreatorEvidence evidence,
+ Supplier mutationWhileCurrent);
+}
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
new file mode 100644
index 0000000000..1dc443a273
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java
@@ -0,0 +1,792 @@
+package net.firedevops.firemud.accountservice.service;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope;
+import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity;
+import net.firedevops.firemud.accountservice.dto.AccountTenantCreationBootstrapResult;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.AccountTenantMembership;
+import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Claim;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot;
+import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Account-owned atomic membership bootstrap for an exact fresh tenant creator operation.
+ *
+ * This service is intentionally not exposed by REST or gRPC. A new commit requires a separately
+ * registered current Account authorization/source participant; no such production participant is
+ * registered by this slice, so new bootstrap attempts remain default-denied.
+ */
+@Service
+@SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification =
+ "Injected Account repositories and source participants are internal collaborators.")
+public class AccountTenantCreationBootstrapService {
+ public static final String AUDIT_EVENT_TYPE = "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED";
+ private static final String ROLE_SNAPSHOT_JSON = "[\"tenantAdmin\"]";
+ private static final JsonMapper JSON = JsonMapper.builder().build();
+
+ private final AccountRepository accountRepository;
+ private final FreshTenantIdentityAssociationRepository tenantAssociationRepository;
+ private final AccountCreatorMembershipSourceReader creatorSourceReader;
+ private final AccountMembershipPairAuthorityRepository pairAuthorityRepository;
+ private final AccountTenantMembershipRepository membershipRepository;
+ private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository;
+ private final AccountAuthorityOutboxRepository authorityOutboxRepository;
+ private final AccountAuditOutboxRepository auditOutboxRepository;
+ private final AccountTenantCreationBootstrapOperationRepository operationRepository;
+ private final ObjectProvider
+ authorizationSourceProvider;
+
+ @SuppressFBWarnings(
+ value = "CT_CONSTRUCTOR_THROW",
+ justification =
+ "Spring transaction proxy requires a non-final class; constructor only validates its internal collaborators and publishes no partial instance.")
+ public AccountTenantCreationBootstrapService(
+ AccountRepository accountRepository,
+ FreshTenantIdentityAssociationRepository tenantAssociationRepository,
+ AccountCreatorMembershipSourceReader creatorSourceReader,
+ AccountMembershipPairAuthorityRepository pairAuthorityRepository,
+ AccountTenantMembershipRepository membershipRepository,
+ AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository,
+ AccountAuthorityOutboxRepository authorityOutboxRepository,
+ AccountAuditOutboxRepository auditOutboxRepository,
+ AccountTenantCreationBootstrapOperationRepository operationRepository,
+ ObjectProvider
+ authorizationSourceProvider) {
+ this.accountRepository = Objects.requireNonNull(accountRepository);
+ this.tenantAssociationRepository = Objects.requireNonNull(tenantAssociationRepository);
+ this.creatorSourceReader = Objects.requireNonNull(creatorSourceReader);
+ this.pairAuthorityRepository = Objects.requireNonNull(pairAuthorityRepository);
+ this.membershipRepository = Objects.requireNonNull(membershipRepository);
+ this.roleSnapshotRepository = Objects.requireNonNull(roleSnapshotRepository);
+ this.authorityOutboxRepository = Objects.requireNonNull(authorityOutboxRepository);
+ this.auditOutboxRepository = Objects.requireNonNull(auditOutboxRepository);
+ this.operationRepository = Objects.requireNonNull(operationRepository);
+ this.authorizationSourceProvider = Objects.requireNonNull(authorizationSourceProvider);
+ }
+
+ /**
+ * Replays only an exact committed historical result, or runs a new commit under a current-source
+ * participant. The creator evidence value itself is data and does not authorize this method.
+ */
+ @Transactional
+ public AccountTenantCreationBootstrapResult bootstrap(FreshTenantCreatorEvidence evidence) {
+ requireWritableOwnerTransaction();
+ Objects.requireNonNull(evidence, "Authenticated creator evidence is required");
+ UUID creatorUuid = evidence.initiatingAccountId();
+ UUID tenantUuid = evidence.creationEvidence().canonicalTenantId();
+ Account creator =
+ accountRepository
+ .findByAccountUuidForUpdate(creatorUuid)
+ .orElseThrow(() -> new IllegalStateException("Creator Account row is absent"));
+ requireAccountIdentity(creator, creatorUuid);
+
+ UUID requestId = evidence.accountAuthorizationOperationId();
+ Optional original = operationRepository.findForUpdate(requestId);
+ if (original.isPresent()) {
+ return replayExactOriginal(evidence, original.orElseThrow());
+ }
+ Optional tenantOperation = operationRepository.findRequestIdByTenantForUpdate(tenantUuid);
+ if (tenantOperation.isPresent()) {
+ throw new AccountTenantCreationBootstrapOperationRepository.OperationConflictException(
+ "Fresh tenant already has a different immutable creator-bootstrap operation");
+ }
+
+ AccountTenantCreationBootstrapAuthorizationSource currentSource =
+ authorizationSourceProvider.getIfAvailable();
+ if (currentSource == null) {
+ throw new IllegalStateException(
+ "No current Account creator-authorization/source participant is registered");
+ }
+ AtomicBoolean callbackRan = new AtomicBoolean();
+ AtomicReference committed = new AtomicReference<>();
+ AccountTenantCreationBootstrapResult returned =
+ currentSource.withCurrentAuthorizationAndSourceParticipation(
+ evidence,
+ () -> {
+ if (!callbackRan.compareAndSet(false, true)) {
+ throw new IllegalStateException(
+ "Account creator authorization/source participant repeated its commit callback");
+ }
+ AccountTenantCreationBootstrapResult result = commitNew(evidence, creator);
+ committed.set(result);
+ return result;
+ });
+ if (!callbackRan.get() || returned == null || !returned.equals(committed.get())) {
+ throw new IllegalStateException(
+ "Account creator authorization/source participant did not preserve the owner result");
+ }
+ return returned;
+ }
+
+ /**
+ * Reads an already committed creator-control source under the existing Account/source locks. This
+ * immutable source capture authenticates no caller and grants no authoring or gameplay
+ * permission. Historical receipt recovery is verified separately from current source equality.
+ */
+ @Transactional(propagation = org.springframework.transaction.annotation.Propagation.MANDATORY)
+ public AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources
+ readExistingCreatorControlCaptureSources(UUID accountUuid, UUID tenantUuid) {
+ requireWritableOwnerTransaction();
+ return creatorSourceReader.readExistingCreatorControlCaptureSources(
+ accountUuid,
+ tenantUuid,
+ () -> {
+ UUID requestId =
+ operationRepository
+ .findRequestIdByTenantForUpdate(tenantUuid)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Committed creator-bootstrap operation is absent"));
+ StoredOperation operation =
+ operationRepository
+ .findForUpdate(requestId)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Committed creator-bootstrap receipt is absent"));
+ FreshTenantCreationEvidence creation =
+ tenantAssociationRepository
+ .read(tenantUuid)
+ .orElseThrow(
+ () -> new IllegalStateException("Creator fresh tenant source is absent"));
+ if (!accountUuid.equals(operation.initiatingAccountUuid())) {
+ throw new IllegalStateException("Creator-bootstrap receipt belongs to another Account");
+ }
+ FreshTenantCreatorEvidence evidence =
+ new FreshTenantCreatorEvidence(
+ 1,
+ creation,
+ accountUuid,
+ operation.accountAuthorizationOperationId(),
+ operation.accountAuthorizationDigest(),
+ operation.creatorEvidenceDigest());
+ replayExactOriginal(evidence, operation);
+ operationRepository.assertNoContradictoryMembershipHistory(accountUuid, tenantUuid);
+ return operation;
+ });
+ }
+
+ private AccountTenantCreationBootstrapResult commitNew(
+ FreshTenantCreatorEvidence evidence, Account creator) {
+ requireWritableOwnerTransaction();
+ UUID creatorUuid = evidence.initiatingAccountId();
+ UUID tenantUuid = evidence.creationEvidence().canonicalTenantId();
+ FreshTenantCreationEvidence associated =
+ tenantAssociationRepository
+ .read(tenantUuid)
+ .orElseThrow(
+ () -> new IllegalStateException("Fresh Game Design tenant source is absent"));
+ if (!associated.equals(evidence.creationEvidence())) {
+ throw new IllegalStateException(
+ "Fresh Game Design tenant source differs from creator qualification evidence");
+ }
+
+ AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot baseline =
+ creatorSourceReader.readFreshNeverJoinedMembershipSnapshot(creatorUuid, tenantUuid);
+ if (!creatorUuid.toString().equals(baseline.accountId())
+ || !tenantUuid.toString().equals(baseline.tenantId())
+ || baseline.membershipExists()
+ || !"MISSING".equals(baseline.membershipLifecycleState())
+ || baseline.gameplayAdmissionAllowed()
+ || !List.of(
+ new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry(
+ baseline.outboxStreamKey(), "0"))
+ .equals(
+ baseline.outboxCheckpoints().stream()
+ .filter(
+ checkpoint ->
+ checkpoint.outboxStreamKey().equals(baseline.outboxStreamKey()))
+ .toList())) {
+ throw new IllegalStateException(
+ "Creator bootstrap baseline is not exact sequence-zero absence");
+ }
+
+ operationRepository.assertNoContradictoryMembershipHistory(creatorUuid, tenantUuid);
+ VerifiedTenantProvenance provenance = freshProvenance(associated);
+ PairAuthority priorPair =
+ pairAuthorityRepository
+ .readForUpdate(creatorUuid, tenantUuid)
+ .orElseThrow(
+ () -> new IllegalStateException("Positive creator membership baseline is absent"));
+ long baselineVersion =
+ positiveLong(baseline.membershipVersion().get(tenantUuid.toString()), "membership version");
+ long baselineGeneration =
+ positiveLong(baseline.membershipAuthorityGeneration(), "membership authority generation");
+ if (!priorPair.accountUuid().equals(creatorUuid)
+ || !priorPair.tenantUuid().equals(tenantUuid)
+ || !priorPair.provenance().equals(provenance)
+ || priorPair.membershipExists()
+ || priorPair.membershipVersion() != baselineVersion
+ || priorPair.membershipAuthorityGeneration() != baselineGeneration
+ || priorPair.eventSequence() != 0L
+ || priorPair.eventId() != null
+ || priorPair.eventDigest() != null
+ || priorPair.lastTransitionInvalidated()) {
+ throw new IllegalStateException("Creator pair differs from its same-fence positive baseline");
+ }
+
+ byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence);
+ byte[] sourcePayload = AccountTenantCreationBootstrapDigest.sourceSnapshotPayload(baseline);
+ String sourceDigest = AccountTenantCreationBootstrapDigest.sha256(sourcePayload);
+ byte[] requestPayload =
+ AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload);
+ String requestDigest = AccountTenantCreationBootstrapDigest.sha256(requestPayload);
+ Claim claim =
+ operationRepository.claim(
+ evidence,
+ creatorPayload,
+ sourcePayload,
+ sourceDigest,
+ requestPayload,
+ requestDigest,
+ baselineVersion,
+ baselineGeneration);
+ if (!claim.claimed()) {
+ return replayExactOriginal(evidence, claim.operation());
+ }
+
+ long newVersion = increment(baselineVersion, "membership version");
+ AccountTenantMembership persisted =
+ membershipRepository.createFreshCreatorMembership(creatorUuid, tenantUuid);
+ RoleSnapshot roles =
+ roleSnapshotRepository.replaceCanonical(
+ persisted, creatorUuid, tenantUuid, provenance, newVersion, List.of("tenantAdmin"));
+ if (!roles.roles().equals(List.of("tenantAdmin"))) {
+ throw new IllegalStateException("Creator membership role readback is not tenantAdmin-only");
+ }
+
+ String requestId = evidence.accountAuthorizationOperationId().toString();
+ String streamKey =
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX
+ + "membership/"
+ + creatorUuid
+ + "/"
+ + tenantUuid;
+ if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) {
+ throw new IllegalStateException(
+ "Creator membership stream acquired history before bootstrap");
+ }
+ String eventId =
+ UUID.nameUUIDFromBytes(
+ (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + requestId)
+ .getBytes(StandardCharsets.UTF_8))
+ .toString();
+ MembershipEvent[] candidate = new MembershipEvent[1];
+ Event event =
+ authorityOutboxRepository.append(
+ streamKey,
+ requestId,
+ sequence -> {
+ if (sequence != 1L) {
+ throw new IllegalStateException(
+ "First creator membership event must use sequence one");
+ }
+ MembershipEvent sealed =
+ MembershipAuthorityEventV1Codec.seal(
+ eventPreimage(
+ baseline,
+ creatorUuid,
+ tenantUuid,
+ newVersion,
+ baselineGeneration,
+ streamKey,
+ requestId,
+ eventId));
+ candidate[0] = sealed;
+ return new EventEvidence(
+ sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8());
+ });
+ MembershipEvent expectedEvent = candidate[0];
+ Event eventReadback =
+ authorityOutboxRepository
+ .findEvent(streamKey, requestId)
+ .orElseThrow(
+ () -> new IllegalStateException("Creator membership event readback is absent"));
+ Checkpoint checkpoint =
+ authorityOutboxRepository
+ .readCheckpoint(streamKey)
+ .orElseThrow(
+ () -> new IllegalStateException("Creator membership checkpoint is absent"));
+ MembershipEvent verifiedEvent =
+ MembershipAuthorityEventV1Codec.verify(
+ new String(eventReadback.payload(), StandardCharsets.UTF_8));
+ if (expectedEvent == null
+ || !event.equals(eventReadback)
+ || !checkpoint.outboxStreamKey().equals(streamKey)
+ || checkpoint.outboxSequence() != 1L
+ || !checkpoint.sourceEventId().equals(event.eventId())
+ || !checkpoint.sourceEventDigest().equals(event.eventDigest())
+ || !verifiedEvent.canonicalJson().equals(expectedEvent.canonicalJson())
+ || !verifiedEvent.roles().equals(List.of("tenantAdmin"))
+ || verifiedEvent.gameplayAdmissionAllowed()
+ || verifiedEvent.callerBoundAuthorityInvalidated()
+ || !Long.toString(newVersion)
+ .equals(verifiedEvent.membershipVersion().get(tenantUuid.toString()))) {
+ throw new IllegalStateException("Creator membership event or checkpoint readback differs");
+ }
+
+ PairAuthority advanced =
+ pairAuthorityRepository.commitTransition(
+ priorPair, new PairTransition(true, 1L, event.eventId(), event.eventDigest(), false));
+ if (!advanced.membershipExists()
+ || advanced.membershipVersion() != newVersion
+ || advanced.membershipAuthorityGeneration() != baselineGeneration
+ || advanced.eventSequence() != 1L
+ || !event.eventId().equals(advanced.eventId())
+ || !event.eventDigest().equals(advanced.eventDigest())
+ || advanced.lastTransitionInvalidated()) {
+ throw new IllegalStateException("Creator membership pair transition readback differs");
+ }
+
+ byte[] rolesPayload = ROLE_SNAPSHOT_JSON.getBytes(StandardCharsets.UTF_8);
+ UUID auditEventId =
+ UUID.nameUUIDFromBytes(
+ ("account-tenant-creation-bootstrap-audit/v1:" + requestId)
+ .getBytes(StandardCharsets.UTF_8));
+ byte[] auditPayload =
+ auditPayload(
+ evidence,
+ requestDigest,
+ sourceDigest,
+ newVersion,
+ baselineGeneration,
+ event,
+ checkpoint);
+ String auditText = new String(auditPayload, StandardCharsets.UTF_8);
+ AccountAuditEnvelope audit =
+ auditOutboxRepository.appendCanonicalTenant(
+ auditEventId, tenantUuid.toString(), AUDIT_EVENT_TYPE, auditText);
+ byte[] resultPayload =
+ AccountTenantCreationBootstrapDigest.resultPayload(
+ requestId,
+ requestDigest,
+ sourceDigest,
+ tenantUuid,
+ verifiedEvent.membershipVersion(),
+ Long.toString(baselineGeneration),
+ streamKey,
+ requestId,
+ checkpoint.outboxSequence(),
+ event.eventId(),
+ event.eventDigest(),
+ event.payload(),
+ audit.auditEventId(),
+ audit.eventType(),
+ audit.occurredAt().toString(),
+ audit.payloadDigest(),
+ audit.payload().getBytes(StandardCharsets.UTF_8),
+ creatorPayload,
+ sourcePayload);
+ String resultDigest = AccountTenantCreationBootstrapDigest.sha256(resultPayload);
+ StoredOperation completed =
+ operationRepository.complete(
+ evidence.accountAuthorizationOperationId(),
+ new Completion(
+ persisted.getId(),
+ newVersion,
+ baselineGeneration,
+ "ACTIVE",
+ false,
+ rolesPayload,
+ streamKey,
+ requestId,
+ checkpoint.outboxSequence(),
+ event.eventId(),
+ event.eventDigest(),
+ false,
+ event.payload(),
+ audit.auditEventId(),
+ audit.eventType(),
+ audit.occurredAt(),
+ audit.payloadDigest(),
+ audit.payload().getBytes(StandardCharsets.UTF_8),
+ resultPayload,
+ resultDigest));
+
+ verifyCommittedReadback(completed, persisted, roles, advanced, event, audit);
+ return completed.result();
+ }
+
+ private AccountTenantCreationBootstrapResult replayExactOriginal(
+ FreshTenantCreatorEvidence evidence, StoredOperation operation) {
+ byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence);
+ if (!operation.requestId().equals(evidence.accountAuthorizationOperationId())
+ || !operation.initiatingAccountUuid().equals(evidence.initiatingAccountId())
+ || !operation.tenantUuid().equals(evidence.creationEvidence().canonicalTenantId())
+ || !Arrays.equals(operation.creatorEvidencePayload(), creatorPayload)
+ || !operation.creatorEvidenceDigest().equals(evidence.evidenceDigest())
+ || !operation.creationOperationId().equals(evidence.creationEvidence().operationId())
+ || !operation.creationRequestId().equals(evidence.creationEvidence().creationRequestId())
+ || !operation
+ .accountAuthorizationOperationId()
+ .equals(evidence.accountAuthorizationOperationId())
+ || !operation.accountAuthorizationDigest().equals(evidence.accountAuthorizationDigest())) {
+ throw new AccountTenantCreationBootstrapOperationRepository.OperationConflictException(
+ "Creator-bootstrap operation ID was reused with changed creator or authorization source");
+ }
+ requireCommittedOperation(operation);
+ byte[] sourcePayload = operation.sourceSnapshotPayload();
+ byte[] requestPayload =
+ AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload);
+ if (!AccountTenantCreationBootstrapDigest.sha256(sourcePayload)
+ .equals(operation.sourceSnapshotDigest())
+ || !Arrays.equals(requestPayload, operation.requestPayload())
+ || !AccountTenantCreationBootstrapDigest.sha256(requestPayload)
+ .equals(operation.requestDigest())
+ || !AccountTenantCreationBootstrapDigest.sha256(operation.resultPayload())
+ .equals(operation.resultDigest())) {
+ throw new IllegalStateException(
+ "Creator-bootstrap immutable source or result digest differs");
+ }
+
+ MembershipEvent event =
+ MembershipAuthorityEventV1Codec.verify(
+ new String(operation.eventPayload(), StandardCharsets.UTF_8));
+ String expectedStream =
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX
+ + "membership/"
+ + evidence.initiatingAccountId()
+ + "/"
+ + evidence.creationEvidence().canonicalTenantId();
+ if (!expectedStream.equals(operation.eventStreamKey())
+ || !operation.requestId().toString().equals(operation.eventRequestId())
+ || operation.eventSequence() != 1L
+ || !event.outboxStreamKey().equals(operation.eventStreamKey())
+ || !event.requestId().equals(operation.eventRequestId())
+ || !event.eventId().equals(operation.eventId())
+ || !event.eventDigest().equals(operation.eventDigest())
+ || !"ACTIVE".equals(event.membershipLifecycleState())
+ || event.gameplayAdmissionAllowed()
+ || event.callerBoundAuthorityInvalidated()
+ || !event.roles().equals(List.of("tenantAdmin"))
+ || !Map.of(operation.tenantUuid().toString(), Long.toString(operation.membershipVersion()))
+ .equals(event.membershipVersion())) {
+ throw new IllegalStateException("Creator-bootstrap historical event receipt is inconsistent");
+ }
+ Event originalEvent =
+ authorityOutboxRepository
+ .findEvent(operation.eventStreamKey(), operation.eventRequestId())
+ .orElseThrow(() -> new IllegalStateException("Original creator event is absent"));
+ if (originalEvent.outboxSequence() != operation.eventSequence()
+ || !originalEvent.eventId().equals(operation.eventId())
+ || !originalEvent.eventDigest().equals(operation.eventDigest())
+ || !Arrays.equals(originalEvent.payload(), operation.eventPayload())) {
+ throw new IllegalStateException("Original creator event readback differs from its receipt");
+ }
+
+ AccountAuditEnvelope expectedAudit = auditEnvelope(operation);
+ AccountAuditEnvelope actualAudit =
+ auditOutboxRepository
+ .findExactCanonicalTenantEnvelopeForUpdate(expectedAudit)
+ .orElseThrow(
+ () -> new IllegalStateException("Original creator audit envelope is absent"));
+ if (!actualAudit.equals(expectedAudit)) {
+ throw new IllegalStateException("Original creator audit envelope differs from its receipt");
+ }
+ byte[] expectedResultPayload =
+ AccountTenantCreationBootstrapDigest.resultPayload(
+ operation.requestId().toString(),
+ operation.requestDigest(),
+ operation.sourceSnapshotDigest(),
+ operation.tenantUuid(),
+ event.membershipVersion(),
+ Long.toString(operation.membershipAuthorityGeneration()),
+ operation.eventStreamKey(),
+ operation.eventRequestId(),
+ operation.eventSequence(),
+ operation.eventId(),
+ operation.eventDigest(),
+ operation.eventPayload(),
+ operation.auditEventId(),
+ operation.auditEventType(),
+ operation.auditOccurredAt().toString(),
+ operation.auditPayloadDigest(),
+ operation.auditPayload(),
+ operation.creatorEvidencePayload(),
+ operation.sourceSnapshotPayload());
+ if (!Arrays.equals(expectedResultPayload, operation.resultPayload())) {
+ throw new IllegalStateException("Creator-bootstrap historical result bytes differ");
+ }
+ // This is immutable historical recovery. It intentionally does not read or rewrite current
+ // membership, roles, pair authority, or later JOIN state.
+ return operation.result();
+ }
+
+ private void verifyCommittedReadback(
+ StoredOperation completed,
+ AccountTenantMembership expectedMembership,
+ RoleSnapshot expectedRoles,
+ PairAuthority expectedPair,
+ Event expectedEvent,
+ AccountAuditEnvelope expectedAudit) {
+ AccountTenantMembership membership =
+ membershipRepository
+ .findCanonicalMembershipForUpdate(expectedPair.accountUuid(), expectedPair.tenantUuid())
+ .orElseThrow(() -> new IllegalStateException("Creator membership readback is absent"));
+ RoleSnapshot roles =
+ roleSnapshotRepository
+ .findForCanonicalUpdate(
+ expectedPair.accountUuid(),
+ expectedPair.tenantUuid(),
+ expectedPair.provenance(),
+ expectedMembership.getId(),
+ expectedMembership.getMembershipVersion())
+ .orElseThrow(
+ () -> new IllegalStateException("Creator role snapshot readback is absent"));
+ PairAuthority pair =
+ pairAuthorityRepository
+ .readForUpdate(expectedPair.accountUuid(), expectedPair.tenantUuid())
+ .orElseThrow(
+ () -> new IllegalStateException("Creator pair authority readback is absent"));
+ Event event =
+ authorityOutboxRepository
+ .findEvent(expectedEvent.outboxStreamKey(), expectedEvent.requestId())
+ .orElseThrow(() -> new IllegalStateException("Creator event readback is absent"));
+ MembershipEvent eventSnapshot =
+ MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8));
+ AccountTenantCreationBootstrapResult result = completed.result();
+ AccountAuditEnvelope audit =
+ auditOutboxRepository
+ .findExactCanonicalTenantEnvelopeForUpdate(expectedAudit)
+ .orElseThrow(() -> new IllegalStateException("Creator audit readback is absent"));
+ StoredOperation receipt =
+ operationRepository
+ .findForUpdate(completed.requestId())
+ .orElseThrow(() -> new IllegalStateException("Creator operation receipt is absent"));
+ if (!sameMembership(expectedMembership, membership)
+ || !expectedRoles.equals(roles)
+ || !expectedPair.equals(pair)
+ || !expectedEvent.equals(event)
+ || !expectedAudit.equals(audit)
+ || !result.membershipVersion().equals(eventSnapshot.membershipVersion())
+ || !Map.of(
+ expectedPair.tenantUuid().toString(),
+ Long.toString(expectedMembership.getMembershipVersion()))
+ .equals(result.membershipVersion())
+ || !"COMMITTED".equals(receipt.status())
+ || !completed.resultDigest().equals(receipt.resultDigest())
+ || !Arrays.equals(completed.resultPayload(), receipt.resultPayload())
+ || !Arrays.equals(completed.eventPayload(), receipt.eventPayload())
+ || !Arrays.equals(completed.auditPayload(), receipt.auditPayload())) {
+ throw new IllegalStateException(
+ "Creator membership, roles, pair, event, audit, or receipt readback differs");
+ }
+ }
+
+ private Map eventPreimage(
+ AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot baseline,
+ UUID creatorUuid,
+ UUID tenantUuid,
+ long membershipVersion,
+ long membershipGeneration,
+ String streamKey,
+ String requestId,
+ String eventId) {
+ Map event = new LinkedHashMap<>();
+ event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION);
+ event.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE);
+ event.put("eventId", eventId);
+ event.put("requestId", requestId);
+ event.put("outboxStreamKey", streamKey);
+ event.put("outboxSequence", "1");
+ event.put("sourceScope", "membership/" + creatorUuid + "/" + tenantUuid);
+ event.put("accountId", creatorUuid.toString());
+ event.put("tenantId", tenantUuid.toString());
+ event.put("membershipExists", true);
+ event.put("membershipLifecycleState", "ACTIVE");
+ event.put("membershipVersion", Map.of(tenantUuid.toString(), Long.toString(membershipVersion)));
+ event.put("membershipAuthorityGeneration", Long.toString(membershipGeneration));
+ event.put(
+ "authorityTuple",
+ AccountTenantCreationBootstrapDigest.authorityTupleMap(baseline.authorityTuple()));
+ event.put("issuanceFence", baseline.issuanceFence());
+ event.put("roles", List.of("tenantAdmin"));
+ event.put("gameplayAdmissionAllowed", false);
+ event.put("callerBoundAuthorityInvalidated", false);
+ return event;
+ }
+
+ private byte[] auditPayload(
+ FreshTenantCreatorEvidence evidence,
+ String requestDigest,
+ String sourceSnapshotDigest,
+ long membershipVersion,
+ long membershipGeneration,
+ Event event,
+ Checkpoint checkpoint) {
+ Map payload = new LinkedHashMap<>();
+ payload.put("schemaVersion", "account-tenant-creation-bootstrap-audit/v1");
+ payload.put("requestId", evidence.accountAuthorizationOperationId().toString());
+ payload.put("requestDigest", requestDigest);
+ payload.put("initiatingAccountUuid", evidence.initiatingAccountId().toString());
+ payload.put("tenantUuid", evidence.creationEvidence().canonicalTenantId().toString());
+ payload.put("creationRequestId", evidence.creationEvidence().creationRequestId().toString());
+ payload.put("creationOperationId", evidence.creationEvidence().operationId().toString());
+ payload.put("creationRequestDigest", evidence.creationEvidence().requestDigest());
+ payload.put("creationEvidenceDigest", evidence.creationEvidence().evidenceDigest());
+ payload.put(
+ "accountAuthorizationOperationId", evidence.accountAuthorizationOperationId().toString());
+ payload.put("accountAuthorizationDigest", evidence.accountAuthorizationDigest());
+ payload.put("creatorEvidenceDigest", evidence.evidenceDigest());
+ payload.put("sourceSnapshotDigest", sourceSnapshotDigest);
+ payload.put(
+ "membershipVersion",
+ Map.of(
+ evidence.creationEvidence().canonicalTenantId().toString(),
+ Long.toString(membershipVersion)));
+ payload.put("membershipAuthorityGeneration", Long.toString(membershipGeneration));
+ payload.put("outboxStreamKey", checkpoint.outboxStreamKey());
+ payload.put("outboxSequence", Long.toString(checkpoint.outboxSequence()));
+ payload.put("eventId", event.eventId());
+ payload.put("eventDigest", event.eventDigest());
+ payload.put("callerBoundAuthorityInvalidated", false);
+ try {
+ return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(payload));
+ } catch (IOException | RuntimeException failure) {
+ throw new IllegalStateException("Creator-bootstrap audit serialization failed", failure);
+ }
+ }
+
+ private AccountAuditEnvelope auditEnvelope(StoredOperation operation) {
+ return new AccountAuditEnvelope(
+ operation.auditEventId(),
+ "tenant",
+ AccountAuditTenantIdentity.canonicalTenantV2(operation.tenantUuid().toString()),
+ "account-service",
+ operation.auditEventType(),
+ operation.auditOccurredAt(),
+ 1,
+ 1,
+ operation.auditPayloadDigest(),
+ new String(operation.auditPayload(), StandardCharsets.UTF_8));
+ }
+
+ private static VerifiedTenantProvenance freshProvenance(FreshTenantCreationEvidence source) {
+ return new VerifiedTenantProvenance(
+ null,
+ TenantProvenanceKind.FRESH_GAME_DESIGN,
+ source.operationId(),
+ source.evidenceDigest());
+ }
+
+ private static void requireCommittedOperation(StoredOperation operation) {
+ if (!"COMMITTED".equals(operation.status())
+ || operation.membershipId() == null
+ || operation.membershipVersion() == null
+ || operation.membershipAuthorityGeneration() == null
+ || !"ACTIVE".equals(operation.membershipLifecycleState())
+ || !Boolean.FALSE.equals(operation.gameplayAdmissionAllowed())
+ || !Boolean.FALSE.equals(operation.callerBoundAuthorityInvalidated())
+ || operation.membershipRolesPayload() == null
+ || operation.eventPayload() == null
+ || operation.auditPayload() == null
+ || operation.resultPayload() == null
+ || operation.resultDigest() == null
+ || operation.committedAt() == null) {
+ throw new IllegalStateException("Incomplete creator-bootstrap operation cannot be replayed");
+ }
+ }
+
+ private static boolean sameMembership(
+ AccountTenantMembership expected, AccountTenantMembership actual) {
+ return Objects.equals(expected.getId(), actual.getId())
+ && Objects.equals(
+ expected.getAccount().getAccountUuid(), actual.getAccount().getAccountUuid())
+ && Objects.equals(expected.getTenantUuid(), actual.getTenantUuid())
+ && Objects.equals(expected.getTenantId(), actual.getTenantId())
+ && Objects.equals(expected.getTenantProvenanceKind(), actual.getTenantProvenanceKind())
+ && Objects.equals(
+ expected.getTenantSourceOperationId(), actual.getTenantSourceOperationId())
+ && Objects.equals(expected.getTenantProvenanceDigest(), actual.getTenantProvenanceDigest())
+ && Objects.equals(expected.getLifecycleState(), actual.getLifecycleState())
+ && expected.isGameplayAdmissionAllowed() == actual.isGameplayAdmissionAllowed()
+ && expected.getMembershipVersion() == actual.getMembershipVersion()
+ && expected.getMembershipAuthorityGeneration() == actual.getMembershipAuthorityGeneration()
+ && Objects.equals(expected.getAuthorityProvenance(), actual.getAuthorityProvenance());
+ }
+
+ private static void requireAccountIdentity(Account account, UUID expectedUuid) {
+ if (account.getId() == null
+ || account.getId() <= 0L
+ || !expectedUuid.equals(account.getAccountUuid())
+ || account.getAccountUuidProvenance() == null
+ || account.getAccountUuidSourceNumericId() == null
+ || !account.getId().equals(account.getAccountUuidSourceNumericId())) {
+ throw new IllegalStateException(
+ "Creator Account UUID provenance is incomplete or mismatched");
+ }
+ }
+
+ private static long positiveLong(String value, String label) {
+ if (value == null || !value.matches("[1-9][0-9]*")) {
+ throw new IllegalStateException("Creator-bootstrap " + label + " is not a positive decimal");
+ }
+ try {
+ long parsed = Long.parseLong(value);
+ if (parsed <= 0L) {
+ throw new IllegalStateException("Creator-bootstrap " + label + " is not positive");
+ }
+ return parsed;
+ } catch (NumberFormatException overflow) {
+ throw new IllegalStateException(
+ "Creator-bootstrap " + label + " exceeds Account BIGINT", overflow);
+ }
+ }
+
+ private static long increment(long value, String label) {
+ try {
+ return Math.addExact(value, 1L);
+ } catch (ArithmeticException overflow) {
+ throw new IllegalStateException("Account " + label + " is exhausted", overflow);
+ }
+ }
+
+ private static void requireWritableOwnerTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException("Creator bootstrap requires a writable Account transaction");
+ }
+ }
+}
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..72868ce788
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java
@@ -0,0 +1,272 @@
+package net.firedevops.firemud.accountservice.service;
+
+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.repository.AccountAuthorityGenerationRepository.ScopeKind;
+import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence;
+import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec;
+import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent;
+import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+import tools.jackson.databind.node.ObjectNode;
+
+/** 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/" + GameSessionAccountDelegationProfile.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 JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .build();
+
+ 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 verified = AccountAuthoritySourceEventV1Codec.verify(sourceEvent.orElseThrow());
+ if (!(verified instanceof IssuerEvent event)) {
+ throw new IllegalArgumentException("Issuer projection source event is not an issuer event");
+ }
+ if (!sourceEvent.orElseThrow().equals(event.canonicalJson())
+ || !event.eventId().equals(event.requestId())
+ || !issuerId.equals(event.issuerId())
+ || !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");
+ }
+ }
+ }
+
+ /** Adapts only the owner-proved original source; unsupported historical codecs deny. */
+ public static IssuerGenerationProjection fromSource(
+ net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository
+ .CanonicalIssuerSourceSnapshot
+ snapshot) {
+ Objects.requireNonNull(snapshot);
+ CurrentSourceEvidence source = snapshot.source();
+ if (source.checkpoint().sequence() == 0L) return fromSource(source);
+ if (source.scope().kind() != ScopeKind.ISSUER
+ || !"ISSUER_SCOPE_INSERT".equals(source.initializationProvenance())
+ || source.initializationTransactionId() <= 0L
+ || source.issuanceFence() != null) {
+ throw new IllegalArgumentException("Issuer source enrollment is unavailable");
+ }
+ var stored = snapshot.latestEvent().orElseThrow();
+ var verified =
+ AccountAuthoritySourceEventV1Codec.verify(
+ new String(stored.payload(), java.nio.charset.StandardCharsets.UTF_8));
+ if (!(verified instanceof IssuerEvent event)) {
+ throw new IllegalArgumentException(
+ "Issuer source checkpoint does not contain an issuer event");
+ }
+ if (!java.util.Arrays.equals(stored.payload(), event.canonicalJsonUtf8())
+ || !stored.outboxStreamKey().equals(source.checkpoint().outboxStreamKey())
+ || stored.outboxSequence() != source.checkpoint().sequence()
+ || !event.outboxStreamKey().equals(source.checkpoint().outboxStreamKey())
+ || !event.outboxSequence().equals(Long.toString(source.checkpoint().sequence()))
+ || !event.issuerId().equals(source.scope().issuerId())
+ || !event.issuerAuthGeneration().equals(Long.toString(source.generation()))
+ || !event.sourceVersion().equals(Long.toString(source.sourceVersion()))
+ || !source.checkpoint().sourceEventId().equals(Optional.of(stored.eventId()))
+ || !source.checkpoint().sourceEventDigest().equals(Optional.of(stored.eventDigest()))
+ || !stored.eventId().equals(event.eventId())
+ || !stored.eventDigest().equals(event.eventDigest())
+ || !stored.requestId().equals(event.requestId())
+ || !stored.eventId().equals(stored.requestId())
+ || !event.eventId().equals(event.requestId())) {
+ throw new IllegalArgumentException(
+ "Issuer projection event differs from the owned checkpoint");
+ }
+ return new IssuerGenerationProjection(
+ source.scope().issuerId(), Long.toString(source.generation()),
+ Long.toString(source.sourceVersion()), source.checkpoint().outboxStreamKey(),
+ Long.toString(source.checkpoint().sequence()), source.checkpoint().sourceEventId(),
+ source.checkpoint().sourceEventDigest(), Optional.of(event.canonicalJson()));
+ }
+
+ /** Original enrollment only; advanced values require their unchanged canonical event bytes. */
+ public static IssuerGenerationProjection fromSource(CurrentSourceEvidence source) {
+ Objects.requireNonNull(source);
+ if (source.scope().kind() != ScopeKind.ISSUER
+ || !"ISSUER_SCOPE_INSERT".equals(source.initializationProvenance())
+ || source.initializationTransactionId() <= 0L
+ || source.issuanceFence() != null
+ || source.checkpoint().sequence() != 0L
+ || source.checkpoint().sourceEventId().isPresent()
+ || source.checkpoint().sourceEventDigest().isPresent()) {
+ throw new IllegalArgumentException(
+ "Current issuer source cannot prove the canonical issuer event contract");
+ }
+ return new IssuerGenerationProjection(
+ source.scope().issuerId(),
+ Long.toString(source.generation()),
+ Long.toString(source.sourceVersion()),
+ source.checkpoint().outboxStreamKey(),
+ Long.toString(source.checkpoint().sequence()),
+ Optional.empty(),
+ Optional.empty(),
+ Optional.empty());
+ }
+
+ public static IssuerGenerationProjection parse(String json) {
+ Objects.requireNonNull(json);
+ final JsonNode root;
+ try {
+ root = JSON.readTree(json);
+ } catch (tools.jackson.core.JacksonException 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.propertyNames().forEach(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 (tools.jackson.core.JacksonException 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 (!GameSessionAccountDelegationProfile.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/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java
index 3f7d619493..50b96c8b26 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
@@ -6,6 +6,7 @@
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.micrometer.core.annotation.Timed;
+import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -14,8 +15,10 @@
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.HashMap;
+import java.util.HexFormat;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import net.firedevops.firemud.account.AuthenticationErrorCodes;
@@ -66,12 +69,24 @@
import net.firedevops.firemud.accountservice.mapper.AccountMapper;
import net.firedevops.firemud.accountservice.mapper.ProfileMapper;
import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository;
import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository;
import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository;
import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository;
import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository.JoinOperation;
+import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt;
import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository;
import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository;
import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository;
import net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository;
import net.firedevops.firemud.accountservice.repository.ExternalAccountRepository;
@@ -79,6 +94,9 @@
import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository;
import net.firedevops.firemud.accountservice.repository.ProfileRepository;
import net.firedevops.firemud.accountservice.repository.SubscriptionRepository;
+import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback;
+import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository;
+import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository.Intent;
import net.firedevops.firemud.accountservice.service.AccountService;
import net.firedevops.firemud.accountservice.service.EmailService;
import net.firedevops.firemud.accountservice.service.NotificationService;
@@ -87,6 +105,8 @@
import net.firedevops.firemud.accountservice.service.exception.AuthenticationException;
import net.firedevops.firemud.common.EmailCanonicalization;
import net.firedevops.firemud.common.LoggingUtil;
+import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent;
import net.firedevops.firemud.common.security.JwtAuthProperties;
import net.firedevops.firemud.common.security.JwtClaims;
import net.firedevops.firemud.common.security.JwtUtil;
@@ -118,12 +138,22 @@ public class AccountServiceImpl implements AccountService {
private static final String JOIN_REQUIRED_CHARACTERS_MESSAGE =
"Join the selected world before discovering characters";
private static final String GAMEPLAY_DELEGATION_AUDIENCE = "account-service";
+ private static final String PASSWORD_RESET_OPERATION_KIND = "PASSWORD_RESET";
+ private static final String PASSWORD_RESET_REQUEST_DOMAIN = "account-password-reset-request/v1";
+ private static final String PASSWORD_RESET_REQUEST_ID_PREFIX =
+ "account-password-reset-request-v1:";
+ private static final String PASSWORD_RESET_EVENT_ID_PREFIX = "account-password-reset-event-v1:";
private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5;
private static final UUID NIL_ACCOUNT_UUID = new UUID(0L, 0L);
private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom();
private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build();
private final AccountRepository accountRepository;
+ private final AccountAuthorityGenerationRepository accountAuthorityGenerationRepository;
+ private final AccountAuthorityOutboxRepository accountAuthorityOutboxRepository;
+ private final AccountPasswordResetOperationRepository passwordResetOperationRepository;
+ private final AccountAuthoritySourceEventReadback accountAuthoritySourceEventReadback;
+ private final AccountPasswordResetDraftSourceChangeRepository passwordResetDraftSourceChanges;
private final AccountAuditOutboxRepository accountAuditOutboxRepository;
private final AccountConnectScopeRepository accountConnectScopeRepository;
private final AccountJoinOperationRepository accountJoinOperationRepository;
@@ -148,12 +178,19 @@ 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 passwordResetOwnerTransaction;
@SuppressFBWarnings(
value = "EI_EXPOSE_REP2",
justification = "Dependencies are injected and kept internal")
public AccountServiceImpl(
AccountRepository accountRepository,
+ AccountAuthorityGenerationRepository accountAuthorityGenerationRepository,
+ AccountAuthorityOutboxRepository accountAuthorityOutboxRepository,
+ AccountPasswordResetOperationRepository passwordResetOperationRepository,
+ AccountLogoutAllOperationRepository logoutAllOperationRepository,
+ AccountSecurityStateOperationRepository securityStateOperationRepository,
+ AccountPasswordResetDraftSourceChangeRepository passwordResetDraftSourceChanges,
AccountAuditOutboxRepository accountAuditOutboxRepository,
AccountConnectScopeRepository accountConnectScopeRepository,
AccountJoinOperationRepository accountJoinOperationRepository,
@@ -179,6 +216,16 @@ public AccountServiceImpl(
net.firedevops.firemud.accountservice.service.session.SessionService sessionService,
PlatformTransactionManager transactionManager) {
this.accountRepository = accountRepository;
+ this.accountAuthorityGenerationRepository = accountAuthorityGenerationRepository;
+ this.accountAuthorityOutboxRepository = accountAuthorityOutboxRepository;
+ this.passwordResetOperationRepository = passwordResetOperationRepository;
+ this.accountAuthoritySourceEventReadback =
+ new AccountAuthoritySourceEventReadback(
+ accountAuthorityOutboxRepository,
+ passwordResetOperationRepository,
+ logoutAllOperationRepository,
+ securityStateOperationRepository);
+ this.passwordResetDraftSourceChanges = passwordResetDraftSourceChanges;
this.accountAuditOutboxRepository = accountAuditOutboxRepository;
this.accountConnectScopeRepository = accountConnectScopeRepository;
this.accountJoinOperationRepository = accountJoinOperationRepository;
@@ -205,6 +252,12 @@ public AccountServiceImpl(
this.joinTransactionTemplate = new TransactionTemplate(transactionManager);
this.joinTransactionTemplate.setPropagationBehavior(
TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+ this.passwordResetOwnerTransaction = new TransactionTemplate(transactionManager);
+ this.passwordResetOwnerTransaction.setPropagationBehavior(
+ TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+ this.passwordResetOwnerTransaction.setIsolationLevel(
+ TransactionDefinition.ISOLATION_READ_COMMITTED);
+ this.passwordResetOwnerTransaction.setReadOnly(false);
}
@Override
@@ -1980,6 +2033,22 @@ private boolean allowsPassword(Account account) {
return AccountLoginAuthModes.allows(account.getLoginAuthModes(), AccountLoginAuthMode.PASSWORD);
}
+ private void requireAuthenticationPersistedIdentity(Account account) {
+ AccountIdentityProvenance provenance =
+ account == null ? null : account.getAccountUuidProvenance();
+ if (account == null
+ || account.getId() == null
+ || account.getId() <= 0L
+ || account.getAccountUuid() == null
+ || NIL_ACCOUNT_UUID.equals(account.getAccountUuid())
+ || account.getAccountUuidSourceNumericId() == null
+ || !account.getId().equals(account.getAccountUuidSourceNumericId())
+ || !AccountIdentityProvenance.isAccepted(provenance)) {
+ throw new IllegalStateException(
+ "Exact persisted Account identity is required for password-reset authority");
+ }
+ }
+
private record PrimaryAuthentication(
Account account, Optional emailLoginChallenge) {}
@@ -2265,20 +2334,634 @@ public void requestPasswordReset(PasswordResetRequest request) {
}
@Override
- @Transactional
@Timed(value = "account.complete_password_reset")
public void completePasswordReset(CompletePasswordResetRequest request) {
- net.firedevops.firemud.accountservice.entity.PasswordResetToken token =
- passwordResetTokenRepository
- .findByToken(request.token())
+ if (request == null
+ || request.token() == null
+ || request.token().isBlank()
+ || request.newPassword() == null) {
+ throw new IllegalArgumentException("Password-reset token and new password are required");
+ }
+ String tokenHash = sha256Hex(request.token());
+ PasswordResetAttempt attempt =
+ passwordResetOwnerTransaction.execute(
+ status -> completePasswordResetInOwnerTransaction(request, tokenHash));
+ if (attempt == null) {
+ throw new IllegalStateException("Password-reset owner transaction returned no result");
+ }
+ if (attempt.pending()) {
+ throw new AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException();
+ }
+ if (attempt.aborted()) {
+ throw new IllegalArgumentException(attempt.abortReason());
+ }
+ PasswordResetReceipt committed =
+ Objects.requireNonNull(attempt.receipt(), "Committed password-reset receipt is required");
+ PasswordResetReceipt postCommitReadback =
+ passwordResetOwnerTransaction.execute(
+ status ->
+ passwordResetOperationRepository
+ .findByTokenHash(tokenHash)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Password-reset receipt disappeared after commit")));
+ if (!committed.equals(postCommitReadback)) {
+ throw new IllegalStateException("Password-reset committed receipt readback differs");
+ }
+ }
+
+ private PasswordResetAttempt completePasswordResetInOwnerTransaction(
+ CompletePasswordResetRequest request, String tokenHash) {
+ Optional resolvedReceipt =
+ passwordResetOperationRepository.findByTokenHash(tokenHash);
+ Optional resolvedIntentAccountId =
+ passwordResetDraftSourceChanges.findAccountIdByTokenHash(tokenHash);
+ Optional resolvedToken =
+ resolvedReceipt.isPresent() || resolvedIntentAccountId.isPresent()
+ ? Optional.empty()
+ : passwordResetTokenRepository.findByToken(request.token());
+ Long accountId =
+ resolvedReceipt
+ .map(PasswordResetReceipt::accountId)
+ .orElseGet(
+ () ->
+ resolvedIntentAccountId.orElseGet(
+ () ->
+ resolvedToken
+ .map(
+ token ->
+ token.getAccount() == null
+ ? null
+ : token.getAccount().getId())
+ .orElse(null)));
+ if (accountId == null || accountId <= 0L) {
+ throw new IllegalArgumentException("Invalid token");
+ }
+
+ Account account =
+ accountRepository
+ .findByIdForUpdate(accountId)
.orElseThrow(() -> new IllegalArgumentException("Invalid token"));
- if (token.getExpiresAt().isBefore(java.time.LocalDateTime.now())) {
+ requireAuthenticationPersistedIdentity(account);
+
+ Optional lockedReceipt =
+ passwordResetOperationRepository.findByTokenHash(tokenHash);
+ if (lockedReceipt.isPresent()) {
+ PasswordResetReceipt receipt = lockedReceipt.orElseThrow();
+ requireReceiptAccountBinding(receipt, account);
+ completePasswordResetRetry(account, receipt, request, tokenHash);
+ return PasswordResetAttempt.committed(receipt);
+ }
+ if (resolvedReceipt.isPresent()) {
+ throw new IllegalStateException(
+ "Password-reset receipt changed while its Account was locked");
+ }
+
+ Optional pending = passwordResetDraftSourceChanges.findByTokenHash(tokenHash);
+ if (resolvedIntentAccountId.isPresent() && pending.isEmpty()) {
+ throw new IllegalStateException(
+ "Password-reset Draft source intent disappeared while its Account was locked");
+ }
+ Intent originalIntent = pending.orElse(null);
+ if (originalIntent != null
+ && (originalIntent.accountId() != account.getId()
+ || !originalIntent.accountUuid().equals(account.getAccountUuid()))) {
+ throw new IllegalStateException("Password-reset Draft intent Account binding changed");
+ }
+
+ net.firedevops.firemud.accountservice.entity.PasswordResetToken token =
+ passwordResetTokenRepository.findByToken(request.token()).orElse(null);
+ String newPasswordVerifier;
+ String passwordVerifierDigest;
+ String requestDigest;
+ LocalDateTime tokenExpiresAt;
+ if (originalIntent != null) {
+ if (!verifyPassword(request.newPassword(), originalIntent.passwordVerifier())) {
+ throw new AccountPasswordResetOperationRepository.OperationConflictException(
+ "Password-reset token is already bound to a different pending password request");
+ }
+ newPasswordVerifier = originalIntent.passwordVerifier();
+ passwordVerifierDigest = originalIntent.passwordVerifierDigest();
+ requestDigest = originalIntent.requestDigest();
+ tokenExpiresAt = originalIntent.tokenExpiresAt();
+ } else {
+ if (token == null) {
+ throw new IllegalArgumentException("Invalid token");
+ }
+ requireTokenAccountBinding(token, account);
+ if (token.getExpiresAt() == null || !token.getExpiresAt().isAfter(LocalDateTime.now())) {
+ throw new IllegalArgumentException("Token expired");
+ }
+ newPasswordVerifier = hashPassword(request.newPassword());
+ passwordVerifierDigest = sha256Hex(newPasswordVerifier);
+ tokenExpiresAt = token.getExpiresAt();
+ requestDigest =
+ passwordResetRequestDigest(
+ account.getAccountUuid(), tokenHash, tokenExpiresAt, passwordVerifierDigest);
+ }
+
+ AuthorityScope accountScope = AuthorityScope.account(account.getAccountUuid());
+ ScopeState currentAuthority = readPasswordResetAccountAuthority(accountScope);
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot latestSource =
+ accountAuthoritySourceEventReadback.requireCurrentLatest(account, currentAuthority);
+
+ if (originalIntent == null) {
+ if (token == null) {
+ throw new IllegalArgumentException("Invalid token");
+ }
+ requireTokenAccountBinding(token, account);
+ if (token.getId() == null || !Objects.equals(token.getExpiresAt(), tokenExpiresAt)) {
+ throw new IllegalArgumentException("Invalid token");
+ }
+ if (!tokenExpiresAt.isAfter(LocalDateTime.now())) {
+ throw new IllegalArgumentException("Token expired");
+ }
+ } else if (token != null
+ && (!Objects.equals(token.getId(), originalIntent.tokenId())
+ || !Objects.equals(token.getExpiresAt(), tokenExpiresAt)
+ || token.getAccount() == null
+ || !Objects.equals(token.getAccount().getId(), account.getId()))) {
+ token = null;
+ }
+
+ Intent intent =
+ passwordResetDraftSourceChanges.participate(
+ account,
+ originalIntent == null
+ ? Objects.requireNonNull(token).getId()
+ : originalIntent.tokenId(),
+ tokenHash,
+ tokenExpiresAt,
+ requestDigest,
+ newPasswordVerifier,
+ currentAuthority,
+ latestSource);
+
+ boolean settled = passwordResetDraftSourceChanges.sourceMutationPermitted(intent);
+ if (!settled) {
+ passwordResetDraftSourceChanges.verifyWaiting(intent);
+ return PasswordResetAttempt.waiting();
+ }
+
+ if (!passwordResetDraftSourceChanges.matchesCapture(
+ intent, account, currentAuthority, latestSource)) {
+ passwordResetDraftSourceChanges.markSourceAborted(
+ intent,
+ net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository
+ .SourceChangeAbortReason.DEFINITIVE_ABORT);
+ return PasswordResetAttempt.aborted("Invalid token");
+ }
+ if (token == null
+ || !Objects.equals(token.getId(), intent.tokenId())
+ || !Objects.equals(token.getExpiresAt(), tokenExpiresAt)
+ || !Objects.equals(token.getAccount().getId(), account.getId())) {
+ passwordResetDraftSourceChanges.markSourceAborted(
+ intent,
+ net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository
+ .SourceChangeAbortReason.DEFINITIVE_ABORT);
+ return PasswordResetAttempt.aborted("Invalid token");
+ }
+ LocalDateTime claimTime = LocalDateTime.now();
+ if (!tokenExpiresAt.isAfter(claimTime)) {
+ passwordResetDraftSourceChanges.markSourceAborted(
+ intent,
+ net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository
+ .SourceChangeAbortReason.EXPIRED);
+ return PasswordResetAttempt.aborted("Token expired");
+ }
+ if (!passwordResetTokenRepository.consumeIfUnexpired(token, claimTime)) {
+ passwordResetDraftSourceChanges.markSourceAborted(
+ intent,
+ net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository
+ .SourceChangeAbortReason.DEFINITIVE_ABORT);
+ return PasswordResetAttempt.aborted("Invalid token");
+ }
+
+ Account passwordUpdated =
+ accountRepository.updatePasswordHashForLockedAccount(account, newPasswordVerifier);
+ requireAccountReadback(account, passwordUpdated, newPasswordVerifier);
+ ScopeState advancedAuthority =
+ accountAuthorityGenerationRepository.advance(
+ currentAuthority, currentAuthority.issuanceFence());
+ requireAdvancedPasswordResetAuthority(accountScope, currentAuthority, advancedAuthority);
+
+ Event appended =
+ accountAuthorityOutboxRepository.append(
+ passwordResetStreamKey(account.getAccountUuid()),
+ intent.requestId(),
+ sequence ->
+ passwordResetEventEvidence(
+ account.getAccountUuid(),
+ intent.requestId(),
+ intent.eventId(),
+ sequence,
+ advancedAuthority.generation(),
+ advancedAuthority.sourceVersion()));
+ PasswordResetAuthorityEvent committedEvent =
+ requirePasswordResetEvent(
+ appended,
+ account.getAccountUuid(),
+ intent.requestId(),
+ intent.eventId(),
+ advancedAuthority.generation(),
+ advancedAuthority.sourceVersion());
+ Checkpoint committedCheckpoint =
+ accountAuthorityOutboxRepository
+ .readCheckpoint(passwordResetStreamKey(account.getAccountUuid()))
+ .orElseThrow(
+ () -> new IllegalStateException("Password-reset outbox checkpoint is missing"));
+ requireCheckpointMatches(committedCheckpoint, appended);
+
+ PasswordResetReceipt receipt =
+ PasswordResetReceipt.committed(
+ account.getId(),
+ account.getAccountUuid(),
+ tokenHash,
+ intent.requestId(),
+ requestDigest,
+ tokenExpiresAt,
+ passwordVerifierDigest,
+ appended.outboxStreamKey(),
+ appended.outboxSequence(),
+ committedEvent.eventId(),
+ committedEvent.eventDigest(),
+ advancedAuthority,
+ advancedAuthority.issuanceFence());
+ passwordResetOperationRepository.insert(receipt);
+ passwordResetDraftSourceChanges.markSourceCommitted(intent, appended);
+
+ Account finalAccount =
+ accountRepository
+ .findByIdForUpdate(account.getId())
+ .orElseThrow(
+ () -> new IllegalStateException("Password-reset Account readback is missing"));
+ requireAccountReadback(account, finalAccount, newPasswordVerifier);
+ ScopeState finalAuthority = readPasswordResetAccountAuthority(accountScope);
+ if (!advancedAuthority.equals(finalAuthority)) {
+ throw new IllegalStateException("Password-reset authority readback did not match its commit");
+ }
+ AccountAuthoritySourceEventReadback.LatestSourceSnapshot finalSource =
+ accountAuthoritySourceEventReadback.requireCurrentLatest(finalAccount, finalAuthority);
+ if (finalSource.outboxSequence() != appended.outboxSequence()
+ || !finalSource.latestEvent().orElseThrow().equals(appended)) {
+ throw new IllegalStateException(
+ "Password-reset closed source readback differs from its commit");
+ }
+ Event eventReadback =
+ accountAuthorityOutboxRepository
+ .findEvent(appended.outboxStreamKey(), appended.outboxSequence())
+ .orElseThrow(
+ () -> new IllegalStateException("Password-reset event readback is missing"));
+ if (!appended.equals(eventReadback)) {
+ throw new IllegalStateException("Password-reset event readback did not match its commit");
+ }
+ requirePasswordResetEvent(
+ eventReadback,
+ account.getAccountUuid(),
+ intent.requestId(),
+ intent.eventId(),
+ advancedAuthority.generation(),
+ advancedAuthority.sourceVersion());
+ Checkpoint finalCheckpoint =
+ accountAuthorityOutboxRepository
+ .readCheckpoint(appended.outboxStreamKey())
+ .orElseThrow(
+ () -> new IllegalStateException("Password-reset checkpoint readback is missing"));
+ requireCheckpointMatches(finalCheckpoint, eventReadback);
+ PasswordResetReceipt receiptReadback =
+ passwordResetOperationRepository
+ .findByTokenHash(tokenHash)
+ .orElseThrow(
+ () -> new IllegalStateException("Password-reset receipt readback is missing"));
+ if (!receipt.equals(receiptReadback)) {
+ throw new IllegalStateException("Password-reset receipt readback did not match its commit");
+ }
+ if (passwordResetTokenRepository.findByToken(request.token()).isPresent()) {
+ throw new IllegalStateException("Consumed password-reset token remained readable");
+ }
+ return PasswordResetAttempt.committed(receipt);
+ }
+
+ private void completePasswordResetRetry(
+ Account account,
+ PasswordResetReceipt receipt,
+ CompletePasswordResetRequest request,
+ String tokenHash) {
+ if (!receipt.tokenExpiresAt().isAfter(LocalDateTime.now())) {
throw new IllegalArgumentException("Token expired");
}
- net.firedevops.firemud.accountservice.entity.Account account = token.getAccount();
- account.setPasswordHash(hashPassword(request.newPassword()));
- accountRepository.save(account);
- passwordResetTokenRepository.delete(token);
+ requireReceiptAccountBinding(receipt, account);
+ String currentVerifier = account.getPasswordHash();
+ if (currentVerifier == null || currentVerifier.isBlank()) {
+ throw new IllegalStateException("Password-reset result was superseded");
+ }
+ String currentVerifierDigest = sha256Hex(currentVerifier);
+ if (!constantTimeTextEquals(currentVerifierDigest, receipt.passwordVerifierDigest())) {
+ throw new IllegalStateException("Password-reset result was superseded");
+ }
+ if (!verifyPassword(request.newPassword(), currentVerifier)) {
+ throw new AccountPasswordResetOperationRepository.OperationConflictException(
+ "Password-reset token was already committed with a different password");
+ }
+ requireReceiptRequestDigest(receipt);
+ if (!constantTimeTextEquals(receipt.tokenHash(), tokenHash)) {
+ throw new IllegalStateException("Password-reset receipt token identity changed");
+ }
+
+ AuthorityScope accountScope = AuthorityScope.account(account.getAccountUuid());
+ ScopeState currentAuthority = readPasswordResetAccountAuthority(accountScope);
+ accountAuthoritySourceEventReadback.requireCurrentLatest(account, currentAuthority);
+ requireReceiptAuthorityIsCurrentOrEarlier(receipt, currentAuthority);
+ Event event =
+ accountAuthorityOutboxRepository
+ .findEvent(receipt.outboxStreamKey(), receipt.outboxSequence())
+ .orElseThrow(
+ () -> new IllegalStateException("Password-reset event readback is missing"));
+ requireReceiptEventBinding(receipt, event);
+ PasswordResetReceipt receiptReadback =
+ passwordResetOperationRepository
+ .findByTokenHash(tokenHash)
+ .orElseThrow(
+ () -> new IllegalStateException("Password-reset receipt readback is missing"));
+ if (!receipt.equals(receiptReadback)) {
+ throw new IllegalStateException("Password-reset receipt readback did not match its commit");
+ }
+ if (!receipt.tokenExpiresAt().isAfter(LocalDateTime.now())) {
+ throw new IllegalArgumentException("Token expired");
+ }
+ }
+
+ private ScopeState readPasswordResetAccountAuthority(AuthorityScope accountScope) {
+ ScopeState state;
+ try {
+ state = accountAuthorityGenerationRepository.read(accountScope);
+ } catch (IllegalStateException missingAuthority) {
+ String message = missingAuthority.getMessage();
+ if ("Account authority generation is missing".equals(message)
+ || "Account authority issuance fence is missing".equals(message)) {
+ throw new AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException();
+ }
+ throw missingAuthority;
+ }
+ if (!accountScope.equals(state.scope())) {
+ throw new IllegalStateException("Account password-reset authority scope changed");
+ }
+ requirePositiveAccountFence(state.issuanceFence(), accountScope.accountId());
+ return state;
+ }
+
+ private void requirePositiveAccountFence(
+ AccountAuthorityGenerationRepository.IssuanceFence fence, UUID accountUuid) {
+ if (fence == null
+ || !accountUuid.equals(fence.accountId())
+ || fence.value() <= 0L
+ || fence.sourceVersion() <= 0L) {
+ throw new IllegalStateException(
+ "Account password-reset issuance fence is missing or invalid");
+ }
+ }
+
+ private void requireAdvancedPasswordResetAuthority(
+ AuthorityScope expectedScope, ScopeState previous, ScopeState advanced) {
+ if (advanced == null
+ || !expectedScope.equals(advanced.scope())
+ || advanced.generation() != Math.addExact(previous.generation(), 1L)
+ || advanced.sourceVersion() != Math.addExact(previous.sourceVersion(), 1L)) {
+ throw new IllegalStateException(
+ "Account password-reset authority did not advance exactly once");
+ }
+ requirePositiveAccountFence(advanced.issuanceFence(), expectedScope.accountId());
+ if (advanced.issuanceFence().value() != Math.addExact(previous.issuanceFence().value(), 1L)
+ || advanced.issuanceFence().sourceVersion()
+ != Math.addExact(previous.issuanceFence().sourceVersion(), 1L)) {
+ throw new IllegalStateException(
+ "Account password-reset issuance fence did not advance exactly once");
+ }
+ }
+
+ private void requireReceiptAccountBinding(PasswordResetReceipt receipt, Account account) {
+ if (receipt.accountId() != account.getId()
+ || !account.getAccountUuid().equals(receipt.accountUuid())
+ || !passwordResetStreamKey(account.getAccountUuid()).equals(receipt.outboxStreamKey())) {
+ throw new IllegalStateException(
+ "Password-reset receipt does not match its Account source row");
+ }
+ requireReceiptRequestDigest(receipt);
+ }
+
+ private void requireReceiptRequestDigest(PasswordResetReceipt receipt) {
+ String expected =
+ passwordResetRequestDigest(
+ receipt.accountUuid(),
+ receipt.tokenHash(),
+ receipt.tokenExpiresAt(),
+ receipt.passwordVerifierDigest());
+ if (receipt.requestDigestVersion() != 1
+ || !PASSWORD_RESET_OPERATION_KIND.equals(receipt.operationKind())
+ || !passwordResetRequestId(receipt.tokenHash()).equals(receipt.requestId())
+ || !constantTimeTextEquals(expected, receipt.requestDigest())) {
+ throw new IllegalStateException("Password-reset receipt request evidence is inconsistent");
+ }
+ }
+
+ private void requireReceiptEventBinding(PasswordResetReceipt receipt, Event event) {
+ PasswordResetAuthorityEvent verified = verifyPasswordResetEvent(event, receipt.accountUuid());
+ if (!receipt.outboxStreamKey().equals(event.outboxStreamKey())
+ || receipt.outboxSequence() != event.outboxSequence()
+ || !receipt.requestId().equals(event.requestId())
+ || !receipt.eventId().equals(event.eventId())
+ || !receipt.eventDigest().equals(event.eventDigest())
+ || !passwordResetEventId(receipt.tokenHash()).equals(event.eventId())
+ || !Long.toString(receipt.accountAuthorityGeneration())
+ .equals(verified.accountAuthorityGeneration())
+ || !Long.toString(receipt.accountSourceVersion()).equals(verified.sourceVersion())) {
+ throw new IllegalStateException("Password-reset receipt does not match its source event");
+ }
+ }
+
+ private void requireReceiptAuthorityIsCurrentOrEarlier(
+ PasswordResetReceipt receipt, ScopeState state) {
+ AccountAuthorityGenerationRepository.IssuanceFence currentFence = state.issuanceFence();
+ requirePositiveAccountFence(currentFence, receipt.accountUuid());
+ if (receipt.accountAuthorityGeneration() > state.generation()
+ || receipt.accountSourceVersion() > state.sourceVersion()
+ || receipt.issuanceFence() > currentFence.value()
+ || receipt.issuanceFenceSourceVersion() > currentFence.sourceVersion()) {
+ throw new IllegalStateException(
+ "Password-reset receipt is ahead of current Account authority");
+ }
+ }
+
+ private void requireAccountReadback(Account expected, Account readback, String passwordVerifier) {
+ requireAuthenticationPersistedIdentity(readback);
+ if (!Objects.equals(expected.getId(), readback.getId())
+ || !Objects.equals(expected.getAccountUuid(), readback.getAccountUuid())
+ || expected.getAccountUuidProvenance() != readback.getAccountUuidProvenance()
+ || !Objects.equals(
+ expected.getAccountUuidSourceNumericId(), readback.getAccountUuidSourceNumericId())
+ || !Objects.equals(passwordVerifier, readback.getPasswordHash())) {
+ throw new IllegalStateException("Password-reset Account readback did not match its commit");
+ }
+ }
+
+ private void requireTokenAccountBinding(
+ net.firedevops.firemud.accountservice.entity.PasswordResetToken token, Account account) {
+ if (token.getId() == null
+ || token.getToken() == null
+ || token.getExpiresAt() == null
+ || token.getAccount() == null
+ || !Objects.equals(token.getAccount().getId(), account.getId())) {
+ throw new IllegalStateException("Password-reset token source does not match its Account row");
+ }
+ }
+
+ private EventEvidence passwordResetEventEvidence(
+ UUID accountUuid,
+ String requestId,
+ String eventId,
+ long sequence,
+ long accountAuthorityGeneration,
+ long sourceVersion) {
+ PasswordResetAuthorityEvent event =
+ PasswordResetAuthorityEventV1Codec.seal(
+ Map.ofEntries(
+ Map.entry("schemaVersion", PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION),
+ Map.entry("eventType", PasswordResetAuthorityEventV1Codec.EVENT_TYPE),
+ Map.entry("eventId", eventId),
+ Map.entry("requestId", requestId),
+ Map.entry("accountId", accountUuid.toString()),
+ Map.entry("sourceScope", "account/" + accountUuid),
+ Map.entry("outboxStreamKey", passwordResetStreamKey(accountUuid)),
+ Map.entry("outboxSequence", Long.toString(sequence)),
+ Map.entry("accountAuthorityGeneration", Long.toString(accountAuthorityGeneration)),
+ Map.entry("sourceVersion", Long.toString(sourceVersion)),
+ Map.entry(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration", Long.toString(accountAuthorityGeneration),
+ "outboxStreamKey", passwordResetStreamKey(accountUuid),
+ "outboxSequence", Long.toString(sequence)))));
+ return new EventEvidence(event.eventId(), event.eventDigest(), event.canonicalJsonUtf8());
+ }
+
+ private PasswordResetAuthorityEvent requirePasswordResetEvent(
+ Event event,
+ UUID accountUuid,
+ String requestId,
+ String eventId,
+ long accountAuthorityGeneration,
+ long sourceVersion) {
+ PasswordResetAuthorityEvent verified = verifyPasswordResetEvent(event, accountUuid);
+ if (!passwordResetStreamKey(accountUuid).equals(event.outboxStreamKey())
+ || !requestId.equals(event.requestId())
+ || !eventId.equals(event.eventId())
+ || !Long.toString(accountAuthorityGeneration).equals(verified.accountAuthorityGeneration())
+ || !Long.toString(sourceVersion).equals(verified.sourceVersion())) {
+ throw new IllegalStateException(
+ "Password-reset source event does not match its committed state");
+ }
+ return verified;
+ }
+
+ private PasswordResetAuthorityEvent verifyPasswordResetEvent(Event event, UUID accountUuid) {
+ if (event == null) {
+ throw new IllegalStateException("Password-reset source event is missing");
+ }
+ PasswordResetAuthorityEvent verified =
+ PasswordResetAuthorityEventV1Codec.verify(
+ new String(event.payload(), StandardCharsets.UTF_8));
+ if (!MessageDigest.isEqual(event.payload(), verified.canonicalJsonUtf8())
+ || !event.outboxStreamKey().equals(verified.outboxStreamKey())
+ || !event.requestId().equals(verified.requestId())
+ || !event.eventId().equals(verified.eventId())
+ || !event.eventDigest().equals(verified.eventDigest())
+ || !accountUuid.toString().equals(verified.accountId())
+ || !Long.toString(event.outboxSequence()).equals(verified.outboxSequence())) {
+ throw new IllegalStateException("Password-reset source event readback is inconsistent");
+ }
+ return verified;
+ }
+
+ private void requireCheckpointMatches(Checkpoint checkpoint, Event event) {
+ if (!checkpoint.outboxStreamKey().equals(event.outboxStreamKey())
+ || checkpoint.outboxSequence() != event.outboxSequence()
+ || !checkpoint.sourceEventId().equals(event.eventId())
+ || !checkpoint.sourceEventDigest().equals(event.eventDigest())) {
+ throw new IllegalStateException("Password-reset outbox checkpoint does not match its event");
+ }
+ }
+
+ private String passwordResetRequestDigest(
+ UUID accountUuid, String tokenHash, LocalDateTime tokenExpiresAt, String verifierDigest) {
+ if (accountUuid == null || tokenExpiresAt == null) {
+ throw new IllegalArgumentException("Password-reset request identity is incomplete");
+ }
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ updateLengthPrefixed(digest, PASSWORD_RESET_REQUEST_DOMAIN);
+ updateLengthPrefixed(digest, PASSWORD_RESET_OPERATION_KIND);
+ updateLengthPrefixed(digest, accountUuid.toString());
+ updateLengthPrefixed(digest, tokenHash);
+ updateLengthPrefixed(digest, tokenExpiresAt.toString());
+ updateLengthPrefixed(digest, verifierDigest);
+ return HexFormat.of().formatHex(digest.digest());
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is unavailable", exception);
+ }
+ }
+
+ private void updateLengthPrefixed(MessageDigest digest, String value) {
+ if (value == null) {
+ throw new IllegalArgumentException("Password-reset request field is required");
+ }
+ byte[] encoded = value.getBytes(StandardCharsets.UTF_8);
+ digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array());
+ digest.update(encoded);
+ }
+
+ private boolean constantTimeTextEquals(String left, String right) {
+ return left != null
+ && right != null
+ && MessageDigest.isEqual(
+ left.getBytes(StandardCharsets.US_ASCII), right.getBytes(StandardCharsets.US_ASCII));
+ }
+
+ private String sha256Hex(String value) {
+ try {
+ return HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is unavailable", exception);
+ }
+ }
+
+ private String passwordResetRequestId(String tokenHash) {
+ return PASSWORD_RESET_REQUEST_ID_PREFIX + tokenHash;
+ }
+
+ private String passwordResetEventId(String tokenHash) {
+ return PASSWORD_RESET_EVENT_ID_PREFIX + tokenHash;
+ }
+
+ private String passwordResetStreamKey(UUID accountUuid) {
+ return "account:auth-authority:v1:account/" + accountUuid;
+ }
+
+ private record PasswordResetAttempt(
+ boolean pending, boolean aborted, String abortReason, PasswordResetReceipt receipt) {
+ static PasswordResetAttempt waiting() {
+ return new PasswordResetAttempt(true, false, null, null);
+ }
+
+ static PasswordResetAttempt aborted(String reason) {
+ return new PasswordResetAttempt(false, true, reason, null);
+ }
+
+ static PasswordResetAttempt committed(PasswordResetReceipt receipt) {
+ return new PasswordResetAttempt(false, false, null, receipt);
+ }
}
@Override
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java
new file mode 100644
index 0000000000..ec432eac62
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java
@@ -0,0 +1,180 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot;
+import net.firedevops.firemud.accountservice.service.AccountGenerationProjection;
+import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection;
+
+/**
+ * Converts exact owner-read issuer and Account source heads to their canonical projections.
+ *
+ * The returned bytes are informational source projections. They do not authorize a token or
+ * establish freshness, publication, or admission state.
+ */
+public final class AccountGameplayDelegationAuthorityProjection {
+ public static final String ISSUER_KEY_PREFIX = "session:auth:generation:issuer:";
+ public static final String ACCOUNT_KEY_PREFIX = "session:auth:generation:account:";
+ public static final int MAX_PROJECTION_BYTES = 8 * 1024;
+
+ private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}");
+
+ private AccountGameplayDelegationAuthorityProjection() {}
+
+ /** Encodes exact source DTOs for the two projection keys; these bytes are not authority proof. */
+ public static byte[][] canonicalProjectionPair(IssuerAccountSourceSnapshot source) {
+ Objects.requireNonNull(source, "Account authority source snapshot is required");
+ var canonicalIssuer = source.canonicalIssuerProjection();
+ if (canonicalIssuer == null
+ || !source.issuer().scope().issuerId().equals(canonicalIssuer.issuerId())
+ || !Long.toString(source.issuer().generation())
+ .equals(canonicalIssuer.issuerAuthGeneration())
+ || !Long.toString(source.issuer().sourceVersion()).equals(canonicalIssuer.sourceVersion())
+ || !source.issuer().checkpoint().outboxStreamKey().equals(canonicalIssuer.outboxStreamKey())
+ || !Long.toString(source.issuer().checkpoint().sequence())
+ .equals(canonicalIssuer.lastAppliedSourceOutboxSequence())
+ || !source
+ .issuer()
+ .checkpoint()
+ .sourceEventId()
+ .equals(canonicalIssuer.lastAppliedSourceEventId())
+ || !source
+ .issuer()
+ .checkpoint()
+ .sourceEventDigest()
+ .equals(canonicalIssuer.lastAppliedSourceEventDigest())) {
+ throw new ProjectionUnavailableException();
+ }
+ ProjectionValue issuer =
+ ProjectionValue.decode(
+ canonicalIssuer.toJson().getBytes(StandardCharsets.UTF_8),
+ "issuer",
+ canonicalIssuer.issuerId());
+ AccountGenerationProjection canonicalAccount = source.canonicalAccountProjection();
+ if (canonicalAccount == null
+ || !source.account().scope().accountId().toString().equals(canonicalAccount.accountId())
+ || !Long.toString(source.account().generation())
+ .equals(canonicalAccount.accountAuthorityGeneration())
+ || !Long.toString(source.account().sourceVersion()).equals(canonicalAccount.sourceVersion())
+ || !source
+ .account()
+ .checkpoint()
+ .outboxStreamKey()
+ .equals(canonicalAccount.outboxStreamKey())
+ || !Long.toString(source.account().checkpoint().sequence())
+ .equals(canonicalAccount.outboxSequence())
+ || !source.issuanceFence().equals(source.account().issuanceFence())) {
+ throw new ProjectionUnavailableException();
+ }
+ ProjectionValue account =
+ ProjectionValue.decode(
+ canonicalAccount.toJson().getBytes(StandardCharsets.UTF_8),
+ "account",
+ canonicalAccount.accountId());
+ return new byte[][] {issuer.canonicalBytes(), account.canonicalBytes()};
+ }
+
+ /** Strict canonical non-authorizing value stored at one canonical authority key. */
+ public static final class ProjectionValue {
+ private static final String ISSUER = "issuer";
+ private static final String ACCOUNT = "account";
+
+ private final String scope;
+ private final String scopeId;
+ private final BigInteger generation;
+ private final String digest;
+ private final byte[] canonicalBytes;
+
+ private ProjectionValue(
+ String scope, String scopeId, BigInteger generation, String digest, byte[] canonicalBytes) {
+ this.scope = scope;
+ this.scopeId = scopeId;
+ this.generation = generation;
+ this.digest = digest;
+ this.canonicalBytes = canonicalBytes.clone();
+ }
+
+ /** Strictly parses canonical owner projection bytes and verifies their preimage digest. */
+ public static ProjectionValue decode(
+ byte[] bytes, String expectedScope, String expectedScopeId) {
+ if (bytes == null || bytes.length == 0 || bytes.length > MAX_PROJECTION_BYTES) {
+ throw new ProjectionUnavailableException();
+ }
+ try {
+ String text =
+ StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
+ .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes))
+ .toString();
+ if (ACCOUNT.equals(expectedScope)) {
+ AccountGenerationProjection account = AccountGenerationProjection.parse(text);
+ if (!expectedScopeId.equals(account.accountId())) {
+ throw new ProjectionUnavailableException();
+ }
+ return new ProjectionValue(
+ ACCOUNT, account.accountId(), account.generationValue(), sha256(bytes), bytes);
+ }
+ if (!ISSUER.equals(expectedScope)) throw new ProjectionUnavailableException();
+ IssuerGenerationProjection issuer = IssuerGenerationProjection.parse(text);
+ if (!expectedScopeId.equals(issuer.issuerId())) throw new ProjectionUnavailableException();
+ return new ProjectionValue(
+ ISSUER, issuer.issuerId(), issuer.generationValue(), sha256(bytes), bytes);
+ } catch (ProjectionUnavailableException ex) {
+ throw ex;
+ } catch (Exception ex) {
+ throw new ProjectionUnavailableException();
+ }
+ }
+
+ public String scope() {
+ return scope;
+ }
+
+ public String scopeId() {
+ return scopeId;
+ }
+
+ public long generation() {
+ return generation.longValueExact();
+ }
+
+ public BigInteger generationValue() {
+ return generation;
+ }
+
+ public String digest() {
+ return digest;
+ }
+
+ public byte[] canonicalBytes() {
+ return canonicalBytes.clone();
+ }
+
+ @Override
+ public String toString() {
+ return "AccountAuthorityProjection[redacted]";
+ }
+ }
+
+ public static final class ProjectionUnavailableException extends IllegalStateException {
+ public ProjectionUnavailableException() {
+ super("Account authority projection is unavailable or inconsistent");
+ }
+ }
+
+ private static String sha256(byte[] bytes) {
+ try {
+ return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
+ } catch (NoSuchAlgorithmException ex) {
+ throw new ProjectionUnavailableException();
+ }
+ }
+}
diff --git a/services/account-service/src/main/resources/db/migration/V74__account_global_role_source.sql b/services/account-service/src/main/resources/db/migration/V74__account_global_role_source.sql
new file mode 100644
index 0000000000..78047e0790
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V74__account_global_role_source.sql
@@ -0,0 +1,158 @@
+ALTER TABLE accounts
+ ADD CONSTRAINT accounts_global_role_source_identity_uq
+ UNIQUE (account_uuid, account_uuid_source_numeric_id, account_uuid_provenance);
+
+CREATE TABLE account_global_role_sources (
+ account_uuid UUID PRIMARY KEY,
+ account_uuid_source_numeric_id BIGINT NOT NULL,
+ account_uuid_provenance VARCHAR(40) NOT NULL,
+ global_roles TEXT[] NOT NULL,
+ global_role_source_version BIGINT NOT NULL,
+ CONSTRAINT account_global_role_sources_account_identity_fk
+ FOREIGN KEY (
+ account_uuid,
+ account_uuid_source_numeric_id,
+ account_uuid_provenance
+ )
+ REFERENCES accounts (
+ account_uuid,
+ account_uuid_source_numeric_id,
+ account_uuid_provenance
+ )
+ ON DELETE RESTRICT,
+ CONSTRAINT account_global_role_sources_account_numeric_id_check
+ CHECK (account_uuid_source_numeric_id > 0),
+ CONSTRAINT account_global_role_sources_account_uuid_check
+ CHECK (account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID),
+ CONSTRAINT account_global_role_sources_fresh_provenance_check
+ CHECK (account_uuid_provenance IN (
+ 'ACCOUNT_REPOSITORY_INSERT',
+ 'ACCOUNT_DATABASE_INSERT'
+ )),
+ CONSTRAINT account_global_role_sources_empty_roles_check
+ CHECK (global_roles = ARRAY[]::TEXT[]),
+ CONSTRAINT account_global_role_sources_positive_version_check
+ CHECK (global_role_source_version > 0)
+);
+
+-- This prerequisite admits only the explicit-empty state. Role mutations need a
+-- separately versioned, fenced producer before this immutable source can advance.
+-- [jooq ignore start]
+CREATE FUNCTION account_global_role_source_immutable_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RAISE EXCEPTION 'Fresh Account global-role source is immutable until a versioned writer exists'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_immutable';
+ RETURN OLD;
+END;
+$$;
+
+CREATE TRIGGER account_global_role_source_immutable
+ BEFORE UPDATE OR DELETE ON account_global_role_sources
+ FOR EACH ROW EXECUTE FUNCTION account_global_role_source_immutable_guard();
+
+CREATE FUNCTION account_global_role_source_truncate_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RAISE EXCEPTION 'Fresh Account global-role source cannot be truncated'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_truncate_denied';
+ RETURN NULL;
+END;
+$$;
+
+CREATE TRIGGER account_global_role_source_truncate_guard
+ BEFORE TRUNCATE ON account_global_role_sources
+ FOR EACH STATEMENT EXECUTE FUNCTION account_global_role_source_truncate_guard();
+
+CREATE FUNCTION account_global_role_source_birth_insert_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ account_identity_exists BOOLEAN;
+BEGIN
+ IF pg_trigger_depth() <> 2 THEN
+ RAISE EXCEPTION 'Account global-role source may only be inserted by its fresh Account birth path'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_birth_only';
+ END IF;
+
+ -- The source table and its Account owner may be written through a
+ -- schema-qualified relation while the connection search_path names another
+ -- schema. Resolve the paired Account row in the trigger table's own schema.
+ EXECUTE format(
+ 'SELECT EXISTS (
+ SELECT 1
+ FROM %I.accounts account_row
+ WHERE account_row.id = $1
+ AND account_row.account_uuid = $2
+ AND account_row.account_uuid_source_numeric_id = $3
+ AND account_row.account_uuid_provenance = $4
+ AND account_row.account_uuid_provenance IN (
+ ''ACCOUNT_REPOSITORY_INSERT'',
+ ''ACCOUNT_DATABASE_INSERT''
+ )
+ AND account_row.role IS NULL
+ )',
+ TG_TABLE_SCHEMA
+ ) INTO account_identity_exists
+ USING NEW.account_uuid_source_numeric_id,
+ NEW.account_uuid,
+ NEW.account_uuid_source_numeric_id,
+ NEW.account_uuid_provenance;
+
+ IF NOT account_identity_exists THEN
+ RAISE EXCEPTION 'Account global-role source may only be inserted by its fresh Account birth path'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_birth_only';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE TRIGGER account_global_role_source_birth_insert_guard
+ BEFORE INSERT ON account_global_role_sources
+ FOR EACH ROW EXECUTE FUNCTION account_global_role_source_birth_insert_guard();
+
+CREATE FUNCTION account_global_role_source_birth()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ IF NEW.account_uuid_provenance IN (
+ 'ACCOUNT_REPOSITORY_INSERT',
+ 'ACCOUNT_DATABASE_INSERT'
+ ) AND NEW.role IS NULL THEN
+ IF NEW.account_uuid IS NULL
+ OR NEW.account_uuid = '00000000-0000-0000-0000-000000000000'::UUID
+ OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM NEW.id THEN
+ RAISE EXCEPTION 'Fresh Account has no exact canonical UUID source identity'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_global_role_source_birth_identity';
+ END IF;
+
+ -- Bind the fresh source row to the schema that owns this Account row,
+ -- even when the caller inserted through a qualified table name.
+ EXECUTE format(
+ 'INSERT INTO %I.account_global_role_sources (
+ account_uuid,
+ account_uuid_source_numeric_id,
+ account_uuid_provenance,
+ global_roles,
+ global_role_source_version
+ ) VALUES ($1, $2, $3, ARRAY[]::TEXT[], 1)',
+ TG_TABLE_SCHEMA
+ ) USING NEW.account_uuid,
+ NEW.account_uuid_source_numeric_id,
+ NEW.account_uuid_provenance;
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE TRIGGER accounts_global_role_source_birth
+ AFTER INSERT ON accounts
+ FOR EACH ROW EXECUTE FUNCTION account_global_role_source_birth();
+-- [jooq ignore stop]
diff --git a/services/account-service/src/main/resources/db/migration/V75__draft_commit_authorization_fences.sql b/services/account-service/src/main/resources/db/migration/V75__draft_commit_authorization_fences.sql
new file mode 100644
index 0000000000..6cfd73f856
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V75__draft_commit_authorization_fences.sql
@@ -0,0 +1,188 @@
+-- Internal storage only. No source writer or authenticated authorization producer is enabled.
+CREATE TABLE account_draft_authorization_source_locks (
+ source_key VARCHAR(512) PRIMARY KEY CHECK (length(source_key) > 0 AND octet_length(source_key) <= 512)
+);
+
+CREATE TABLE account_draft_authorization_fences (
+ operation_id UUID PRIMARY KEY,
+ request_id UUID NOT NULL UNIQUE,
+ commit_id UUID NOT NULL UNIQUE,
+ fence_id UUID NOT NULL UNIQUE,
+ 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))
+);
+
+CREATE TABLE account_draft_authorization_sources (
+ operation_id UUID NOT NULL REFERENCES account_draft_authorization_fences(operation_id),
+ source_key VARCHAR(512) 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_draft_authorization_sources_by_scope
+ ON account_draft_authorization_sources(source_key, operation_id);
+
+CREATE TABLE account_draft_authorization_owner_readbacks (
+ operation_id UUID NOT NULL REFERENCES account_draft_authorization_fences(operation_id),
+ owner VARCHAR(16) NOT NULL CHECK (owner IN ('GAME_DESIGN', 'WORLD')),
+ outcome VARCHAR(24) NOT NULL CHECK (outcome IN ('COMMITTED', 'DEFINITIVELY_ABORTED')),
+ readback BYTEA NOT NULL CHECK (octet_length(readback) > 0),
+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (operation_id, owner)
+);
+
+CREATE TABLE account_draft_authorization_source_changes (
+ change_id UUID PRIMARY KEY,
+ binding BYTEA NOT NULL CHECK (octet_length(binding) > 0),
+ status VARCHAR(16) NOT NULL
+ CHECK (status IN ('WAITING', 'SOURCE_COMMITTED', 'SOURCE_ABORTED')),
+ requested_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ committed_at TIMESTAMPTZ,
+ aborted_at TIMESTAMPTZ,
+ abort_reason VARCHAR(32) CHECK (abort_reason IN ('EXPIRED', 'DEFINITIVE_ABORT')),
+ CHECK (
+ (status = 'WAITING'
+ AND committed_at IS NULL
+ AND aborted_at IS NULL
+ AND abort_reason IS NULL)
+ OR (status = 'SOURCE_COMMITTED'
+ AND committed_at IS NOT NULL
+ AND aborted_at IS NULL
+ AND abort_reason IS NULL)
+ OR (status = 'SOURCE_ABORTED'
+ AND committed_at IS NULL
+ AND aborted_at IS NOT NULL
+ AND abort_reason IS NOT NULL)
+ )
+);
+
+CREATE TABLE account_draft_authorization_changed_scopes (
+ change_id UUID NOT NULL REFERENCES account_draft_authorization_source_changes(change_id),
+ source_key VARCHAR(512) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key),
+ PRIMARY KEY (change_id, source_key)
+);
+CREATE INDEX account_draft_authorization_changes_by_scope
+ ON account_draft_authorization_changed_scopes(source_key, change_id);
+
+-- [jooq ignore start]
+CREATE FUNCTION account_draft_authorization_immutable_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ RAISE EXCEPTION 'Draft authorization evidence is immutable'
+ USING ERRCODE = '23514';
+END;
+$$;
+
+CREATE FUNCTION account_draft_authorization_order_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ RAISE EXCEPTION 'Draft authorization fence cannot be deleted';
+ END IF;
+ IF OLD.ordering <> 'RESERVED' OR NEW.ordering NOT IN ('COMMIT_ORDER', 'REVOKE_ORDER')
+ OR NEW.operation_id IS DISTINCT FROM OLD.operation_id
+ OR NEW.request_id IS DISTINCT FROM OLD.request_id
+ OR NEW.commit_id IS DISTINCT FROM OLD.commit_id
+ OR NEW.fence_id IS DISTINCT FROM OLD.fence_id
+ OR NEW.binding IS DISTINCT FROM OLD.binding
+ OR NEW.reserved_at IS DISTINCT FROM OLD.reserved_at
+ OR NEW.ordered_at IS NULL THEN
+ RAISE EXCEPTION 'Draft commit/revoke ordering is immutable';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE FUNCTION account_draft_authorization_source_change_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ RAISE EXCEPTION 'Draft source change cannot be deleted';
+ END IF;
+ IF OLD.status <> 'WAITING' OR NEW.status NOT IN ('SOURCE_COMMITTED', 'SOURCE_ABORTED')
+ OR NEW.change_id IS DISTINCT FROM OLD.change_id
+ OR NEW.binding IS DISTINCT FROM OLD.binding
+ OR NEW.requested_at IS DISTINCT FROM OLD.requested_at
+ OR (NEW.status = 'SOURCE_COMMITTED'
+ AND (NEW.committed_at IS NULL OR NEW.aborted_at IS NOT NULL OR NEW.abort_reason IS NOT NULL))
+ OR (NEW.status = 'SOURCE_ABORTED'
+ AND (NEW.committed_at IS NOT NULL OR NEW.aborted_at IS NULL
+ OR NEW.abort_reason IS NULL
+ OR NEW.abort_reason NOT IN ('EXPIRED', 'DEFINITIVE_ABORT'))) THEN
+ RAISE EXCEPTION 'Draft source change result is immutable';
+ END IF;
+ IF EXISTS (
+ SELECT 1 FROM account_draft_authorization_changed_scopes changed
+ JOIN account_draft_authorization_sources source USING (source_key)
+ JOIN account_draft_authorization_fences fence USING (operation_id)
+ WHERE changed.change_id = OLD.change_id
+ AND NOT ((fence.ordering = 'REVOKE_ORDER' AND (
+ SELECT count(*) FROM account_draft_authorization_owner_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_draft_authorization_owner_readbacks readback
+ WHERE readback.operation_id = fence.operation_id
+ ) = 2))
+ ) THEN
+ RAISE EXCEPTION 'Both definitive owner outcomes are required before source commit';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE FUNCTION account_draft_authorization_insert_phase_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE
+ phase TEXT;
+BEGIN
+ IF TG_TABLE_NAME = 'account_draft_authorization_changed_scopes' THEN
+ SELECT status INTO phase FROM account_draft_authorization_source_changes
+ WHERE change_id = NEW.change_id FOR UPDATE;
+ IF phase IS DISTINCT FROM 'WAITING' THEN
+ RAISE EXCEPTION 'Completed source change cannot acquire new scopes';
+ END IF;
+ ELSE
+ SELECT ordering INTO phase FROM account_draft_authorization_fences
+ WHERE operation_id = NEW.operation_id FOR UPDATE;
+ IF TG_TABLE_NAME = 'account_draft_authorization_sources' AND phase IS DISTINCT FROM 'RESERVED' THEN
+ RAISE EXCEPTION 'Ordered Draft operation cannot acquire new sources';
+ ELSIF TG_TABLE_NAME = 'account_draft_authorization_owner_readbacks'
+ AND (phase IS NULL OR phase = 'RESERVED') THEN
+ RAISE EXCEPTION 'Reservation alone cannot produce owner terminal evidence';
+ END IF;
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE TRIGGER account_draft_authorization_fence_guard
+ BEFORE UPDATE OR DELETE ON account_draft_authorization_fences
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_order_guard();
+CREATE TRIGGER account_draft_authorization_change_guard
+ BEFORE UPDATE OR DELETE ON account_draft_authorization_source_changes
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_source_change_guard();
+CREATE TRIGGER account_draft_authorization_sources_immutable
+ BEFORE UPDATE OR DELETE ON account_draft_authorization_sources
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard();
+CREATE TRIGGER account_draft_authorization_readbacks_immutable
+ BEFORE UPDATE OR DELETE ON account_draft_authorization_owner_readbacks
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard();
+CREATE TRIGGER account_draft_authorization_scopes_immutable
+ BEFORE UPDATE OR DELETE ON account_draft_authorization_changed_scopes
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard();
+CREATE TRIGGER account_draft_authorization_source_locks_immutable
+ BEFORE UPDATE OR DELETE ON account_draft_authorization_source_locks
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard();
+CREATE TRIGGER account_draft_authorization_source_insert_phase
+ BEFORE INSERT ON account_draft_authorization_sources
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard();
+CREATE TRIGGER account_draft_authorization_readback_insert_phase
+ BEFORE INSERT ON account_draft_authorization_owner_readbacks
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard();
+CREATE TRIGGER account_draft_authorization_scope_insert_phase
+ BEFORE INSERT ON account_draft_authorization_changed_scopes
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard();
+-- [jooq ignore stop]
diff --git a/services/account-service/src/main/resources/db/migration/V76__account_draft_required_owner_fence.sql b/services/account-service/src/main/resources/db/migration/V76__account_draft_required_owner_fence.sql
new file mode 100644
index 0000000000..e9c94764f2
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V76__account_draft_required_owner_fence.sql
@@ -0,0 +1,371 @@
+-- Forward-only Account Draft required-owner/readback closure. Preserve every original binding and readback byte.
+-- Shared byte-frame helpers are used by this Account owner only; no publication tables or authority are installed.
+-- Source keys are shared with current Account issuer evidence. Widen without rewriting stored values.
+-- PostgreSQL and the H2 schema simulator assign different names to V76's inline constraints.
+-- jOOQ omits only these name-dependent swaps from H2 simulation; Flyway executes all swaps below.
+-- [jooq ignore start]
+ALTER TABLE account_draft_authorization_sources
+ DROP CONSTRAINT account_draft_authorization_sources_source_key_fkey;
+ALTER TABLE account_draft_authorization_changed_scopes
+ DROP CONSTRAINT account_draft_authorization_changed_scopes_source_key_fkey;
+-- [jooq ignore stop]
+-- [jooq ignore start]
+ALTER TABLE account_draft_authorization_source_locks
+ DROP CONSTRAINT account_draft_authorization_source_locks_source_key_check;
+-- [jooq ignore stop]
+
+ALTER TABLE account_draft_authorization_source_locks
+ ALTER COLUMN source_key TYPE VARCHAR(2048);
+ALTER TABLE account_draft_authorization_sources
+ ALTER COLUMN source_key TYPE VARCHAR(2048);
+ALTER TABLE account_draft_authorization_changed_scopes
+ ALTER COLUMN source_key TYPE VARCHAR(2048);
+
+-- [jooq ignore start]
+ALTER TABLE account_draft_authorization_source_locks
+ ADD CONSTRAINT account_draft_authorization_source_locks_source_key_check
+ CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048);
+-- [jooq ignore stop]
+-- [jooq ignore start]
+ALTER TABLE account_draft_authorization_sources
+ ADD CONSTRAINT account_draft_authorization_sources_source_key_fkey
+ FOREIGN KEY (source_key) REFERENCES account_draft_authorization_source_locks(source_key);
+ALTER TABLE account_draft_authorization_changed_scopes
+ ADD CONSTRAINT account_draft_authorization_changed_scopes_source_key_fkey
+ FOREIGN KEY (source_key) REFERENCES account_draft_authorization_source_locks(source_key);
+-- [jooq ignore stop]
+
+-- [jooq ignore start]
+ALTER TABLE account_draft_authorization_owner_readbacks
+ DROP CONSTRAINT account_draft_authorization_owner_readbacks_owner_check;
+ALTER TABLE account_draft_authorization_owner_readbacks
+ ADD CONSTRAINT account_draft_authorization_owner_readbacks_owner_check
+ CHECK (owner IN ('GAME_DESIGN', 'WORLD', 'ENTITY', 'GAME_LOGIC', 'AUTOMATION'));
+-- [jooq ignore stop]
+
+-- [jooq ignore start]
+CREATE FUNCTION account_publication_authorization_source_sort_key(value TEXT)
+RETURNS INTEGER[] LANGUAGE plpgsql IMMUTABLE STRICT AS $$
+DECLARE
+ units INTEGER[] := ARRAY[]::INTEGER[];
+ codepoint INTEGER;
+ character_index INTEGER;
+BEGIN
+ FOR character_index IN 1..char_length(value) LOOP
+ codepoint := ascii(substring(value FROM character_index FOR 1));
+ IF codepoint > 65535 THEN
+ units := array_append(units, 55296 + ((codepoint - 65536) / 1024));
+ units := array_append(units, 56320 + ((codepoint - 65536) % 1024));
+ ELSE
+ units := array_append(units, codepoint);
+ END IF;
+ END LOOP;
+ RETURN units;
+END;
+$$;
+
+CREATE FUNCTION account_publication_authorization_read_frame(
+ encoded BYTEA,
+ position_value INTEGER,
+ OUT frame_value BYTEA,
+ OUT next_position INTEGER)
+RETURNS RECORD LANGUAGE plpgsql IMMUTABLE STRICT AS $$
+DECLARE
+ frame_length BIGINT;
+ encoded_length INTEGER := octet_length(encoded);
+BEGIN
+ IF position_value < 1 OR position_value > encoded_length - 3
+ OR get_byte(encoded, position_value - 1) >= 128 THEN
+ RAISE EXCEPTION 'Publication terminal byte frame is truncated or oversized'
+ USING ERRCODE = '23514';
+ END IF;
+ frame_length := get_byte(encoded, position_value - 1)::BIGINT * 16777216
+ + get_byte(encoded, position_value)::BIGINT * 65536
+ + get_byte(encoded, position_value + 1)::BIGINT * 256
+ + get_byte(encoded, position_value + 2)::BIGINT;
+ IF frame_length > encoded_length - position_value - 3 THEN
+ RAISE EXCEPTION 'Publication terminal byte frame is incomplete'
+ USING ERRCODE = '23514';
+ END IF;
+ frame_value := substring(encoded FROM position_value + 4 FOR frame_length::INTEGER);
+ next_position := position_value + 4 + frame_length::INTEGER;
+ RETURN;
+END;
+$$;
+
+-- Forward-only structural validation. Retained bindings and owner evidence are never rewritten.
+CREATE FUNCTION account_draft_authorization_required_owners(encoded BYTEA)
+RETURNS TEXT[] LANGUAGE plpgsql IMMUTABLE STRICT AS $$
+DECLARE
+ frames BYTEA[] := ARRAY[]::BYTEA[];
+ position_value INTEGER := 1;
+ parsed BYTEA;
+ schema_value TEXT;
+ source_count INTEGER;
+ owner_start INTEGER;
+ owners TEXT[] := ARRAY[]::TEXT[];
+ derived TEXT[];
+ complete JSONB;
+ declared TEXT[];
+ revision_owners TEXT[];
+ affected_owners TEXT[];
+ allowed TEXT[] := ARRAY['WORLD_MANAGEMENT', 'ENTITY_MANAGEMENT', 'GAME_LOGIC',
+ 'AUTOMATION_SCRIPTING', 'GAME_DESIGN_CONTROL_PLANE'];
+ i INTEGER;
+BEGIN
+ WHILE position_value <= octet_length(encoded) LOOP
+ SELECT frame_value, next_position INTO parsed, position_value
+ FROM account_publication_authorization_read_frame(encoded, position_value);
+ IF octet_length(parsed) = 0 THEN
+ RAISE EXCEPTION 'Draft authorization contains an empty frame' USING ERRCODE = '23514';
+ END IF;
+ frames := array_append(frames, parsed);
+ END LOOP;
+ schema_value := convert_from(frames[1], 'UTF8');
+ IF schema_value NOT IN ('account-draft-authorization-fence/v1', 'account-draft-authorization-fence/v2')
+ OR cardinality(frames) < 18
+ OR convert_from(frames[10], 'UTF8') <> 'DRAFT'
+ OR convert_from(frames[11], 'UTF8') !~ '^(0|[1-9][0-9]*)$'
+ OR convert_from(frames[15], 'UTF8') !~ '^[1-9][0-9]*$' THEN
+ RAISE EXCEPTION 'Invalid original Draft authorization framing' USING ERRCODE = '23514';
+ END IF;
+ source_count := convert_from(frames[15], 'UTF8')::INTEGER;
+ owner_start := 16 + source_count;
+ IF owner_start > cardinality(frames) THEN
+ RAISE EXCEPTION 'Incomplete original Draft source capture' USING ERRCODE = '23514';
+ END IF;
+ IF schema_value = 'account-draft-authorization-fence/v1' THEN
+ IF cardinality(frames) <> owner_start + 1
+ OR convert_from(frames[owner_start], 'UTF8') <> 'GAME_DESIGN'
+ OR convert_from(frames[owner_start + 1], 'UTF8') <> 'WORLD' THEN
+ RAISE EXCEPTION 'V1 original owner set is immutable' USING ERRCODE = '23514';
+ END IF;
+ RETURN ARRAY['GAME_DESIGN', 'WORLD'];
+ END IF;
+ IF convert_from(frames[owner_start], 'UTF8') !~ '^[1-5]$'
+ OR cardinality(frames) <> owner_start + convert_from(frames[owner_start], 'UTF8')::INTEGER THEN
+ RAISE EXCEPTION 'Incomplete or trailing V2 owner vector' USING ERRCODE = '23514';
+ END IF;
+ FOR i IN owner_start + 1 .. cardinality(frames) LOOP
+ owners := array_append(owners, convert_from(frames[i], 'UTF8'));
+ END LOOP;
+ complete := convert_from(frames[12], 'UTF8')::JSONB;
+ IF frames[12] IS DISTINCT FROM frames[13]
+ OR convert_from(frames[14], 'UTF8') IS DISTINCT FROM 'sha256:' || encode(sha256(frames[12]), 'hex')
+ OR complete->>'schemaVersion' IS DISTINCT FROM '1'
+ OR complete->>'requestId' IS DISTINCT FROM convert_from(frames[3], 'UTF8')
+ OR complete->>'commitId' IS DISTINCT FROM convert_from(frames[4], 'UTF8')
+ OR complete->>'canonicalTenantId' IS DISTINCT FROM convert_from(frames[7], 'UTF8')
+ OR complete->>'canonicalVersionId' IS DISTINCT FROM convert_from(frames[8], 'UTF8')
+ OR complete->>'baseCommitId' IS DISTINCT FROM convert_from(frames[9], 'UTF8')
+ OR jsonb_typeof(complete->'requiredOwners') IS DISTINCT FROM 'array'
+ OR jsonb_typeof(complete->'revisions') IS DISTINCT FROM 'array'
+ OR jsonb_typeof(complete->'affectedUnits') IS DISTINCT FROM 'array' THEN
+ RAISE EXCEPTION 'V2 requires the complete original Game Design binding' USING ERRCODE = '23514';
+ END IF;
+ SELECT array_agg(value ORDER BY ordinal) INTO declared
+ FROM jsonb_array_elements_text(complete->'requiredOwners') WITH ORDINALITY entry(value, ordinal);
+ SELECT array_agg(DISTINCT value->>'owner' ORDER BY value->>'owner') INTO revision_owners
+ FROM jsonb_array_elements(complete->'revisions');
+ SELECT array_agg(DISTINCT value->>'owner' ORDER BY value->>'owner') INTO affected_owners
+ FROM jsonb_array_elements(complete->'affectedUnits');
+ IF declared IS NULL OR revision_owners IS NULL OR affected_owners IS NULL
+ OR NOT declared <@ allowed OR NOT revision_owners <@ allowed OR NOT affected_owners <@ allowed
+ OR array_position(revision_owners, NULL) IS NOT NULL
+ OR array_position(affected_owners, NULL) IS NOT NULL
+ OR declared IS DISTINCT FROM (SELECT array_agg(label ORDER BY ordinal)
+ FROM unnest(allowed) WITH ORDINALITY entry(label, ordinal) WHERE label = ANY(revision_owners))
+ OR revision_owners IS DISTINCT FROM affected_owners THEN
+ RAISE EXCEPTION 'Required owners differ from complete revision and affected-owner coverage'
+ USING ERRCODE = '23514';
+ END IF;
+ SELECT array_agg(label ORDER BY ordinal) INTO derived
+ FROM unnest(ARRAY['GAME_DESIGN', 'WORLD', 'ENTITY', 'GAME_LOGIC', 'AUTOMATION'])
+ WITH ORDINALITY entry(label, ordinal)
+ WHERE label = 'GAME_DESIGN' OR label = ANY(SELECT CASE value
+ WHEN 'WORLD_MANAGEMENT' THEN 'WORLD' WHEN 'ENTITY_MANAGEMENT' THEN 'ENTITY'
+ WHEN 'GAME_LOGIC' THEN 'GAME_LOGIC' WHEN 'AUTOMATION_SCRIPTING' THEN 'AUTOMATION'
+ WHEN 'GAME_DESIGN_CONTROL_PLANE' THEN 'GAME_DESIGN' END FROM unnest(declared) value);
+ IF owners IS DISTINCT FROM derived THEN
+ RAISE EXCEPTION 'V2 owner vector differs from complete original binding' USING ERRCODE = '23514';
+ END IF;
+ RETURN owners;
+END;
+$$;
+
+CREATE FUNCTION account_draft_authorization_valid_readback(
+ encoded BYTEA, original BYTEA, operation UUID, commit_value UUID, fence_value UUID,
+ owner_value TEXT, outcome_value TEXT)
+RETURNS BOOLEAN LANGUAGE plpgsql IMMUTABLE STRICT AS $$
+DECLARE
+ position_value INTEGER := 1;
+ parsed BYTEA;
+ values_array BYTEA[] := ARRAY[]::BYTEA[];
+ original_position INTEGER := 1;
+ original_frames BYTEA[] := ARRAY[]::BYTEA[];
+BEGIN
+ WHILE position_value <= octet_length(encoded) LOOP
+ SELECT frame_value, next_position INTO parsed, position_value
+ FROM account_publication_authorization_read_frame(encoded, position_value);
+ values_array := array_append(values_array, parsed);
+ END LOOP;
+ -- The original decoder validates its complete owner vector and trailing-free framing.
+ IF NOT owner_value = ANY(account_draft_authorization_required_owners(original)) THEN
+ RETURN FALSE;
+ END IF;
+ FOR i IN 1..14 LOOP
+ SELECT frame_value, next_position INTO parsed, original_position
+ FROM account_publication_authorization_read_frame(original, original_position);
+ original_frames := array_append(original_frames, parsed);
+ END LOOP;
+ RETURN cardinality(values_array) = 9 AND octet_length(values_array[9]) > 0
+ AND convert_from(values_array[1], 'UTF8') = replace(convert_from(original_frames[1], 'UTF8'),
+ 'account-draft-authorization-fence/', 'account-draft-owner-readback/')
+ AND convert_from(values_array[2], 'UTF8') = owner_value
+ AND convert_from(values_array[3], 'UTF8') = outcome_value
+ AND values_array[4] = original_frames[2]
+ AND convert_from(values_array[4], 'UTF8') = operation::TEXT
+ AND values_array[5] = original_frames[4]
+ AND convert_from(values_array[5], 'UTF8') = commit_value::TEXT
+ AND values_array[6] = original_frames[5]
+ AND convert_from(values_array[6], 'UTF8') = fence_value::TEXT
+ AND values_array[7] = original_frames[14] AND values_array[8] = original;
+EXCEPTION WHEN OTHERS THEN
+ RETURN FALSE;
+END;
+$$;
+
+CREATE FUNCTION account_draft_authorization_complete_sources(operation UUID, original BYTEA)
+RETURNS BOOLEAN LANGUAGE plpgsql STABLE STRICT AS $$
+DECLARE
+ position_value INTEGER := 1;
+ parsed BYTEA;
+ source_count INTEGER;
+ source_bytes BYTEA;
+ source_position INTEGER;
+ source_kind TEXT;
+ source_scope TEXT;
+ source_key_value TEXT;
+ seen TEXT[] := ARRAY[]::TEXT[];
+BEGIN
+ FOR i IN 1..15 LOOP
+ SELECT frame_value, next_position INTO parsed, position_value
+ FROM account_publication_authorization_read_frame(original, position_value);
+ END LOOP;
+ source_count := convert_from(parsed, 'UTF8')::INTEGER;
+ IF source_count < 1 OR source_count <> (SELECT count(*)
+ FROM account_draft_authorization_sources WHERE operation_id = operation) THEN
+ RETURN FALSE;
+ END IF;
+ FOR i IN 1..source_count LOOP
+ SELECT frame_value, next_position INTO source_bytes, position_value
+ FROM account_publication_authorization_read_frame(original, position_value);
+ SELECT frame_value, next_position INTO parsed, source_position
+ FROM account_publication_authorization_read_frame(source_bytes, 1);
+ IF convert_from(parsed, 'UTF8') <> 'account-draft-source-evidence/v1' THEN RETURN FALSE; END IF;
+ SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_kind, source_position
+ FROM account_publication_authorization_read_frame(source_bytes, source_position);
+ SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_scope, source_position
+ FROM account_publication_authorization_read_frame(source_bytes, source_position);
+ source_key_value := source_kind || ':' || source_scope;
+ IF source_key_value = ANY(seen) OR NOT EXISTS (
+ SELECT 1 FROM account_draft_authorization_sources
+ WHERE operation_id = operation AND source_key = source_key_value
+ AND source_evidence = source_bytes) THEN
+ RETURN FALSE;
+ END IF;
+ seen := array_append(seen, source_key_value);
+ END LOOP;
+ RETURN TRUE;
+EXCEPTION WHEN OTHERS THEN
+ RETURN FALSE;
+END;
+$$;
+
+CREATE FUNCTION account_draft_authorization_owner_readback_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE
+ fence account_draft_authorization_fences%ROWTYPE;
+ key_value TEXT;
+BEGIN
+ FOR key_value IN SELECT source_key FROM account_draft_authorization_sources
+ WHERE operation_id = NEW.operation_id
+ ORDER BY account_publication_authorization_source_sort_key(source_key) LOOP
+ PERFORM 1 FROM account_draft_authorization_source_locks WHERE source_key = key_value FOR UPDATE;
+ END LOOP;
+ SELECT * INTO fence FROM account_draft_authorization_fences WHERE operation_id = NEW.operation_id FOR UPDATE;
+ IF fence.ordering IS NULL OR fence.ordering = 'RESERVED'
+ OR NOT account_draft_authorization_complete_sources(fence.operation_id, fence.binding)
+ OR NOT account_draft_authorization_valid_readback(NEW.readback, fence.binding,
+ fence.operation_id, fence.commit_id, fence.fence_id, NEW.owner, NEW.outcome) THEN
+ RAISE EXCEPTION 'Owner result must exactly bind one original required owner'
+ USING ERRCODE = '23514';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+-- Replace only the Draft readback insert-phase trigger; other independent guards remain intact.
+DROP TRIGGER account_draft_authorization_readback_insert_phase ON account_draft_authorization_owner_readbacks;
+CREATE TRIGGER account_draft_authorization_readback_insert_phase
+ BEFORE INSERT ON account_draft_authorization_owner_readbacks
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_owner_readback_guard();
+
+CREATE FUNCTION account_draft_authorization_is_settled(operation UUID)
+RETURNS BOOLEAN LANGUAGE plpgsql STABLE STRICT AS $$
+DECLARE
+ fence account_draft_authorization_fences%ROWTYPE;
+ owners TEXT[];
+ actual TEXT[];
+ outcomes INTEGER;
+BEGIN
+ SELECT * INTO fence FROM account_draft_authorization_fences WHERE operation_id = operation;
+ IF NOT FOUND OR fence.ordering = 'RESERVED' THEN RETURN FALSE; END IF;
+ IF NOT account_draft_authorization_complete_sources(fence.operation_id, fence.binding) THEN RETURN FALSE; END IF;
+ owners := account_draft_authorization_required_owners(fence.binding);
+ SELECT array_agg(owner ORDER BY array_position(owners, owner)), count(DISTINCT outcome)
+ INTO actual, outcomes FROM account_draft_authorization_owner_readbacks WHERE operation_id = operation;
+ RETURN actual IS NOT DISTINCT FROM owners AND outcomes = 1
+ AND NOT EXISTS (SELECT 1 FROM account_draft_authorization_owner_readbacks r
+ WHERE r.operation_id = operation AND (
+ NOT account_draft_authorization_valid_readback(r.readback, fence.binding,
+ fence.operation_id, fence.commit_id, fence.fence_id, r.owner, r.outcome)
+ OR (fence.ordering = 'REVOKE_ORDER' AND r.outcome <> 'DEFINITIVELY_ABORTED')));
+EXCEPTION WHEN OTHERS THEN
+ RETURN FALSE;
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION account_draft_authorization_source_change_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE
+ key_value TEXT;
+ operation UUID;
+BEGIN
+ IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Draft source change cannot be deleted'; END IF;
+ IF OLD.status <> 'WAITING' OR NEW.status NOT IN ('SOURCE_COMMITTED', 'SOURCE_ABORTED')
+ OR NEW.change_id IS DISTINCT FROM OLD.change_id OR NEW.binding IS DISTINCT FROM OLD.binding
+ OR NEW.requested_at IS DISTINCT FROM OLD.requested_at
+ OR (NEW.status = 'SOURCE_COMMITTED' AND (NEW.committed_at IS NULL OR NEW.aborted_at IS NOT NULL OR NEW.abort_reason IS NOT NULL))
+ OR (NEW.status = 'SOURCE_ABORTED' AND (NEW.committed_at IS NOT NULL OR NEW.aborted_at IS NULL
+ OR NEW.abort_reason IS NULL OR NEW.abort_reason NOT IN ('EXPIRED', 'DEFINITIVE_ABORT'))) THEN
+ RAISE EXCEPTION 'Draft source change result is immutable' USING ERRCODE = '23514';
+ END IF;
+ FOR key_value IN SELECT source_key FROM account_draft_authorization_changed_scopes
+ WHERE change_id = OLD.change_id ORDER BY account_publication_authorization_source_sort_key(source_key) LOOP
+ PERFORM 1 FROM account_draft_authorization_source_locks WHERE source_key = key_value FOR UPDATE;
+ END LOOP;
+ FOR operation IN SELECT DISTINCT source.operation_id
+ FROM account_draft_authorization_changed_scopes changed
+ JOIN account_draft_authorization_sources source USING (source_key)
+ WHERE changed.change_id = OLD.change_id ORDER BY source.operation_id LOOP
+ PERFORM 1 FROM account_draft_authorization_fences WHERE operation_id = operation FOR UPDATE;
+ IF NOT account_draft_authorization_is_settled(operation) THEN
+ RAISE EXCEPTION 'Every original required owner must have one uniform exact terminal outcome'
+ USING ERRCODE = '23514';
+ END IF;
+ END LOOP;
+ RETURN NEW;
+END;
+$$;
+-- [jooq ignore stop]
diff --git a/services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql b/services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql
new file mode 100644
index 0000000000..33b0cb2992
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql
@@ -0,0 +1,91 @@
+-- Immutable source receipts make a consumed Account-issued reset token an exact retry identity.
+CREATE TABLE account_password_reset_operation_receipts (
+ token_hash BYTEA NOT NULL,
+ account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT,
+ account_uuid UUID NOT NULL,
+ operation_kind VARCHAR(32) NOT NULL DEFAULT 'PASSWORD_RESET',
+ request_id VARCHAR(128) NOT NULL UNIQUE,
+ request_digest_version INTEGER NOT NULL,
+ request_digest BYTEA NOT NULL,
+ token_expires_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
+ password_verifier_digest BYTEA NOT NULL,
+ outbox_stream_key VARCHAR(2048) NOT NULL,
+ outbox_sequence BIGINT NOT NULL,
+ event_id VARCHAR(128) NOT NULL,
+ event_digest VARCHAR(71) NOT NULL,
+ account_authority_generation BIGINT NOT NULL,
+ account_source_version BIGINT NOT NULL,
+ issuance_fence BIGINT NOT NULL,
+ issuance_fence_source_version BIGINT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ CONSTRAINT account_password_reset_operation_token_hash_check
+ CHECK (octet_length(token_hash) = 32),
+ CONSTRAINT account_password_reset_operation_identity_check
+ CHECK (account_id > 0
+ AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND operation_kind = 'PASSWORD_RESET'
+ AND length(btrim(request_id)) BETWEEN 1 AND 128
+ AND request_id = 'account-password-reset-request-v1:' || encode(token_hash, 'hex')
+ AND request_digest_version = 1
+ AND octet_length(request_digest) = 32
+ AND octet_length(password_verifier_digest) = 32),
+ CONSTRAINT account_password_reset_operation_checkpoint_check
+ CHECK (outbox_stream_key = 'account:auth-authority:v1:account/' || account_uuid::TEXT
+ AND outbox_sequence > 0
+ AND length(btrim(event_id)) BETWEEN 1 AND 128
+ AND event_id = 'account-password-reset-event-v1:' || encode(token_hash, 'hex')
+ AND event_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND account_authority_generation > 0
+ AND account_source_version > 0
+ AND issuance_fence > 0
+ AND issuance_fence_source_version > 0),
+ CONSTRAINT account_password_reset_operation_event_uq
+ UNIQUE (outbox_stream_key, event_id),
+ CONSTRAINT account_password_reset_operation_outbox_fk
+ FOREIGN KEY (outbox_stream_key, outbox_sequence)
+ REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence)
+ ON DELETE RESTRICT
+);
+
+-- Bind the private numeric association and canonical Account UUID at the immutable insert point.
+-- [jooq ignore start]
+ALTER TABLE account_password_reset_operation_receipts
+ ADD CONSTRAINT account_password_reset_operation_receipts_pk PRIMARY KEY (token_hash);
+
+CREATE FUNCTION account_password_reset_operation_account_binding_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ persisted_uuid UUID;
+BEGIN
+ SELECT account_uuid INTO persisted_uuid
+ FROM accounts
+ WHERE id = NEW.account_id;
+ IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN
+ RAISE EXCEPTION 'Password-reset receipt Account identity does not match its source row'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_password_reset_operation_account_binding';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE TRIGGER account_password_reset_operation_account_binding
+ BEFORE INSERT ON account_password_reset_operation_receipts
+ FOR EACH ROW EXECUTE FUNCTION account_password_reset_operation_account_binding_guard();
+
+CREATE FUNCTION account_password_reset_operation_immutable_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RAISE EXCEPTION 'Password-reset operation receipts are immutable'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_password_reset_operation_immutable';
+ RETURN OLD;
+END;
+$$;
+
+CREATE TRIGGER account_password_reset_operation_immutable
+ BEFORE UPDATE OR DELETE ON account_password_reset_operation_receipts
+ FOR EACH ROW EXECUTE FUNCTION account_password_reset_operation_immutable_guard();
+-- [jooq ignore end]
diff --git a/services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql b/services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql
new file mode 100644
index 0000000000..09ae1789ae
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql
@@ -0,0 +1,90 @@
+-- Immutable lifecycle receipts bind one logout-all request and presented token to its source event.
+CREATE TABLE account_logout_all_operation_receipts (
+ request_id UUID NOT NULL,
+ account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT,
+ account_uuid UUID NOT NULL,
+ operation_kind VARCHAR(32) NOT NULL DEFAULT 'ACCOUNT_LOGOUT_ALL',
+ request_digest_version INTEGER NOT NULL,
+ request_digest BYTEA NOT NULL,
+ presented_token_hash BYTEA NOT NULL,
+ token_profile VARCHAR(32) NOT NULL,
+ outbox_stream_key VARCHAR(2048) NOT NULL,
+ outbox_sequence BIGINT NOT NULL,
+ event_id VARCHAR(128) NOT NULL,
+ event_digest VARCHAR(71) NOT NULL,
+ account_authority_generation BIGINT NOT NULL,
+ account_source_version BIGINT NOT NULL,
+ issuance_fence BIGINT NOT NULL,
+ issuance_fence_source_version BIGINT NOT NULL,
+ lifecycle_result VARCHAR(32) NOT NULL DEFAULT 'LOGOUT_ALL_COMMITTED',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ CONSTRAINT account_logout_all_operation_identity_check
+ CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND operation_kind = 'ACCOUNT_LOGOUT_ALL'
+ AND request_digest_version = 1
+ AND octet_length(request_digest) = 32
+ AND octet_length(presented_token_hash) = 32
+ AND token_profile IN ('control-ui', 'player-bootstrap')
+ AND lifecycle_result = 'LOGOUT_ALL_COMMITTED'),
+ CONSTRAINT account_logout_all_operation_checkpoint_check
+ CHECK (outbox_stream_key = 'account:auth-authority:v1:account/' || account_uuid::TEXT
+ AND outbox_sequence > 0
+ AND event_id = 'account-logout-all-event-v1:' || request_id::TEXT
+ AND event_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND account_authority_generation > 0
+ AND account_source_version > 0
+ AND issuance_fence > 0
+ AND issuance_fence_source_version > 0),
+ CONSTRAINT account_logout_all_operation_event_uq
+ UNIQUE (outbox_stream_key, event_id),
+ CONSTRAINT account_logout_all_operation_outbox_fk
+ FOREIGN KEY (outbox_stream_key, outbox_sequence)
+ REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence)
+ ON DELETE RESTRICT
+);
+
+-- [jooq ignore start]
+ALTER TABLE account_logout_all_operation_receipts
+ ADD CONSTRAINT account_logout_all_operation_receipts_pk PRIMARY KEY (request_id);
+
+CREATE UNIQUE INDEX account_logout_all_operation_presented_token_uq
+ ON account_logout_all_operation_receipts (presented_token_hash);
+
+CREATE FUNCTION account_logout_all_operation_account_binding_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ persisted_uuid UUID;
+BEGIN
+ SELECT account_uuid INTO persisted_uuid
+ FROM accounts
+ WHERE id = NEW.account_id;
+ IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN
+ RAISE EXCEPTION 'Logout-all receipt Account identity does not match its source row'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_logout_all_operation_account_binding';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE TRIGGER account_logout_all_operation_account_binding
+ BEFORE INSERT ON account_logout_all_operation_receipts
+ FOR EACH ROW EXECUTE FUNCTION account_logout_all_operation_account_binding_guard();
+
+CREATE FUNCTION account_logout_all_operation_immutable_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RAISE EXCEPTION 'Logout-all operation receipts are immutable'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_logout_all_operation_immutable';
+ RETURN OLD;
+END;
+$$;
+
+CREATE TRIGGER account_logout_all_operation_immutable
+ BEFORE UPDATE OR DELETE ON account_logout_all_operation_receipts
+ FOR EACH ROW EXECUTE FUNCTION account_logout_all_operation_immutable_guard();
+-- [jooq ignore end]
diff --git a/services/account-service/src/main/resources/db/migration/V79__account_security_state_operations.sql b/services/account-service/src/main/resources/db/migration/V79__account_security_state_operations.sql
new file mode 100644
index 0000000000..78309fc3fd
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V79__account_security_state_operations.sql
@@ -0,0 +1,401 @@
+-- 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;
+ baseline_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
+ SELECT * INTO baseline_row FROM account_authority_source_records
+ WHERE outbox_stream_key = key FOR SHARE;
+ SELECT * INTO stream_row FROM account_authority_outbox_streams
+ WHERE outbox_stream_key = key FOR SHARE;
+ -- V40 retains an explicit zero stream; counters alone never prove fresh provenance.
+ IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1
+ OR NEW.expected_fence <> 1 OR NEW.expected_fence_source_version <> 1
+ OR octet_length(NEW.checkpoint_payload) <> 0
+ OR baseline_row IS NULL OR stream_row IS NULL
+ OR stream_row.last_sequence IS DISTINCT FROM 0
+ OR baseline_row.scope_kind IS DISTINCT FROM 'ACCOUNT'
+ OR baseline_row.issuer_id IS NOT NULL
+ OR baseline_row.account_uuid IS DISTINCT FROM NEW.account_uuid
+ OR baseline_row.baseline_generation IS DISTINCT FROM 1
+ OR baseline_row.baseline_source_version IS DISTINCT FROM 1
+ OR baseline_row.baseline_issuance_fence IS DISTINCT FROM 1
+ OR baseline_row.current_generation IS DISTINCT FROM 1
+ OR baseline_row.current_source_version IS DISTINCT FROM 1
+ OR baseline_row.current_issuance_fence IS DISTINCT FROM 1
+ OR baseline_row.current_issuance_fence_source_version IS DISTINCT FROM 1
+ OR baseline_row.last_outbox_sequence IS DISTINCT FROM 0
+ OR baseline_row.last_event_id IS NOT NULL OR baseline_row.last_event_digest IS NOT NULL
+ OR baseline_row.cutoff_generation IS NOT NULL OR baseline_row.cutoff_stream_key IS NOT NULL
+ OR baseline_row.cutoff_sequence IS NOT NULL
+ OR baseline_row.initialization_provenance IS DISTINCT FROM 'ACCOUNT_REPOSITORY_INSERT'
+ OR baseline_row.account_uuid_provenance IS DISTINCT FROM NEW.account_provenance
+ OR baseline_row.account_source_numeric_id IS DISTINCT FROM NEW.account_id
+ OR baseline_row.initialization_transaction_id <= 0
+ OR baseline_row.initialization_transaction_id IS DISTINCT FROM authority_row.created_transaction_id
+ OR baseline_row.initialization_transaction_id IS DISTINCT FROM account_row.account_repository_insert_transaction_id
+ OR baseline_row.account_repository_insert_transaction_id IS DISTINCT FROM account_row.account_repository_insert_transaction_id
+ OR EXISTS (SELECT 1 FROM account_authority_outbox_events 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/V80__account_security_event_source_guard.sql b/services/account-service/src/main/resources/db/migration/V80__account_security_event_source_guard.sql
new file mode 100644
index 0000000000..59aadb67c7
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V80__account_security_event_source_guard.sql
@@ -0,0 +1,398 @@
+-- Extend the V40 source-head guard for the immutable V78 security-state event without changing
+-- historical migrations or treating the legacy scalar Account role as canonical role authority.
+-- [jooq ignore start]
+CREATE OR REPLACE FUNCTION account_authority_source_record_update_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ event_row RECORD;
+ event_payload JSONB;
+ account_row RECORD;
+ expected_modes JSONB;
+ authority_row RECORD;
+ fence_row RECORD;
+ role_source_row RECORD;
+ operation_row RECORD;
+ account_state JSONB;
+ security_request_id UUID;
+BEGIN
+ IF NEW.outbox_stream_key IS DISTINCT FROM OLD.outbox_stream_key
+ OR NEW.scope_kind IS DISTINCT FROM OLD.scope_kind
+ OR NEW.issuer_id IS DISTINCT FROM OLD.issuer_id
+ OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid
+ OR NEW.initialization_transaction_id IS DISTINCT FROM OLD.initialization_transaction_id
+ OR NEW.baseline_generation IS DISTINCT FROM OLD.baseline_generation
+ OR NEW.baseline_source_version IS DISTINCT FROM OLD.baseline_source_version
+ OR NEW.baseline_issuance_fence IS DISTINCT FROM OLD.baseline_issuance_fence
+ OR NEW.initialization_provenance IS DISTINCT FROM OLD.initialization_provenance
+ OR NEW.account_source_numeric_id IS DISTINCT FROM OLD.account_source_numeric_id
+ OR NEW.account_uuid_provenance IS DISTINCT FROM OLD.account_uuid_provenance
+ OR NEW.account_repository_insert_transaction_id
+ IS DISTINCT FROM OLD.account_repository_insert_transaction_id
+ OR NEW.last_outbox_sequence <> OLD.last_outbox_sequence + 1
+ OR NEW.current_generation <> OLD.current_generation + 1
+ OR NEW.current_source_version <> OLD.current_source_version + 1
+ OR (NEW.scope_kind = 'ACCOUNT' AND (
+ NEW.current_issuance_fence <> OLD.current_issuance_fence + 1
+ OR NEW.current_issuance_fence_source_version <> OLD.current_issuance_fence_source_version + 1
+ OR NEW.cutoff_generation IS DISTINCT FROM NEW.current_generation
+ OR NEW.cutoff_stream_key IS DISTINCT FROM NEW.outbox_stream_key
+ OR NEW.cutoff_sequence IS DISTINCT FROM NEW.last_outbox_sequence))
+ OR NEW.last_event_id IS NULL OR NEW.last_event_digest IS NULL THEN
+ RAISE EXCEPTION 'Account authority source record must advance one exact immutable event'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_record_monotonic';
+ END IF;
+
+ SELECT event_id, event_digest, payload INTO event_row
+ FROM account_authority_outbox_events
+ WHERE outbox_stream_key = NEW.outbox_stream_key
+ AND outbox_sequence = NEW.last_outbox_sequence;
+ IF event_row.event_id IS DISTINCT FROM NEW.last_event_id
+ OR event_row.event_digest IS DISTINCT FROM NEW.last_event_digest THEN
+ RAISE EXCEPTION 'Account authority source head does not match its exact outbox event'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_link';
+ END IF;
+ event_payload := convert_from(event_row.payload, 'UTF8')::JSONB;
+ IF event_payload->>'outboxStreamKey' IS DISTINCT FROM NEW.outbox_stream_key
+ OR event_payload->>'outboxSequence' IS DISTINCT FROM NEW.last_outbox_sequence::TEXT
+ OR event_payload->>'eventId' IS DISTINCT FROM NEW.last_event_id
+ OR event_payload->>'eventDigest' IS DISTINCT FROM NEW.last_event_digest THEN
+ RAISE EXCEPTION 'Account authority source event does not match its exact outbox head'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_link';
+ END IF;
+
+ IF NEW.scope_kind = 'ISSUER' THEN
+ IF event_payload->>'eventType' IS DISTINCT FROM 'ISSUER_AUTHORITY_CHANGED'
+ OR event_payload->>'issuerId' IS DISTINCT FROM NEW.issuer_id
+ OR event_payload->>'issuerAuthGeneration' IS DISTINCT FROM NEW.current_generation::TEXT
+ OR event_payload->>'sourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT THEN
+ RAISE EXCEPTION 'Issuer source event does not match exact advanced owner rows'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values';
+ END IF;
+ ELSIF NEW.scope_kind = 'ACCOUNT' THEN
+ SELECT id, account_uuid_provenance, account_uuid_source_numeric_id, email_verified,
+ login_auth_modes, role, lifecycle_state
+ INTO account_row FROM accounts WHERE account_uuid = NEW.account_uuid;
+ SELECT COALESCE(jsonb_agg(to_jsonb(login_mode) ORDER BY login_mode), '[]'::JSONB)
+ INTO expected_modes
+ FROM unnest(string_to_array(account_row.login_auth_modes, ',')) AS modes(login_mode);
+ IF account_row.id IS NULL
+ OR account_row.id IS DISTINCT FROM NEW.account_source_numeric_id
+ OR account_row.account_uuid_source_numeric_id IS DISTINCT FROM NEW.account_source_numeric_id
+ OR account_row.account_uuid_provenance IS DISTINCT FROM NEW.account_uuid_provenance THEN
+ RAISE EXCEPTION 'Account source event has no exact Account identity/provenance'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_account_state';
+ END IF;
+
+ IF event_payload->>'eventType' = 'ACCOUNT_AUTHORITY_CHANGED' THEN
+ -- Preserve the pre-V78 Account source event contract exactly.
+ IF event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT
+ OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.current_generation::TEXT
+ OR event_payload->>'sourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT
+ OR event_payload->>'issuanceFence' IS DISTINCT FROM NEW.current_issuance_fence::TEXT
+ OR event_payload->>'issuanceFenceSourceVersion' IS DISTINCT FROM NEW.current_issuance_fence_source_version::TEXT
+ OR event_payload#>>'{accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM NEW.cutoff_generation::TEXT
+ OR event_payload#>>'{accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM NEW.cutoff_stream_key
+ OR event_payload#>>'{accountSecurityCutoff,outboxSequence}' IS DISTINCT FROM NEW.cutoff_sequence::TEXT
+ OR event_payload#>>'{accountState,emailVerified}' IS DISTINCT FROM account_row.email_verified::TEXT
+ OR event_payload#>'{accountState,loginAuthModes}' IS DISTINCT FROM expected_modes
+ OR event_payload#>>'{accountState,globalRole}' IS DISTINCT FROM account_row.role
+ OR event_payload#>>'{accountState,lifecycleState}' IS DISTINCT FROM upper(account_row.lifecycle_state) THEN
+ RAISE EXCEPTION 'Account source event does not match exact current Account state'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_account_state';
+ END IF;
+ ELSIF event_payload->>'eventType' = 'ACCOUNT_SECURITY_STATE_CHANGED' THEN
+ -- V78 deliberately omits issuance-fence fields from its canonical event. Bind that
+ -- state to the actual Account authority/fence and global-role source owners instead.
+ SELECT generation, source_version INTO authority_row
+ FROM account_authority_generations
+ WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid
+ AND issuer_id IS NULL AND tenant_uuid IS NULL;
+ SELECT issuance_fence, source_version INTO fence_row
+ FROM account_authority_issuance_fences
+ WHERE account_uuid = NEW.account_uuid;
+ SELECT account_uuid_source_numeric_id, account_uuid_provenance,
+ global_roles, global_role_source_version
+ INTO role_source_row FROM account_global_role_sources
+ WHERE account_uuid = NEW.account_uuid;
+
+ account_state := event_payload->'accountState';
+ IF event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-account-security-state-event/v1'
+ OR event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT
+ OR event_payload->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT
+ OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.current_generation::TEXT
+ OR event_payload->>'sourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT
+ OR event_payload#>>'{accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM NEW.cutoff_generation::TEXT
+ OR event_payload#>>'{accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM NEW.cutoff_stream_key
+ OR event_payload#>>'{accountSecurityCutoff,outboxSequence}' IS DISTINCT FROM NEW.cutoff_sequence::TEXT
+ OR authority_row.generation IS DISTINCT FROM NEW.current_generation
+ OR authority_row.source_version IS DISTINCT FROM NEW.current_source_version
+ OR fence_row.issuance_fence IS DISTINCT FROM NEW.current_issuance_fence
+ OR fence_row.source_version IS DISTINCT FROM NEW.current_issuance_fence_source_version
+ OR role_source_row.account_uuid_source_numeric_id IS DISTINCT FROM NEW.account_source_numeric_id
+ OR role_source_row.account_uuid_provenance IS DISTINCT FROM NEW.account_uuid_provenance
+ OR role_source_row.global_role_source_version IS NULL
+ OR jsonb_typeof(account_state) IS DISTINCT FROM 'object'
+ OR (account_state - ARRAY['emailVerified','globalRoles','lifecycleState','loginAuthModes']) <> '{}'::JSONB
+ OR NOT (account_state ?& ARRAY['emailVerified','globalRoles','lifecycleState','loginAuthModes'])
+ OR account_state->'emailVerified' IS DISTINCT FROM to_jsonb(account_row.email_verified)
+ OR account_state->'loginAuthModes' IS DISTINCT FROM expected_modes
+ OR account_state->'globalRoles' IS DISTINCT FROM to_jsonb(role_source_row.global_roles)
+ OR account_state->>'lifecycleState' IS DISTINCT FROM upper(account_row.lifecycle_state)
+ OR role_source_row.global_roles IS DISTINCT FROM
+ (SELECT COALESCE(array_agg(DISTINCT role_name ORDER BY role_name), ARRAY[]::TEXT[])
+ FROM unnest(role_source_row.global_roles) AS roles(role_name)) THEN
+ RAISE EXCEPTION 'Security-state source event does not match exact Account authority/fence/role owners'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values';
+ END IF;
+
+ IF event_payload->>'requestId' IS NULL
+ OR event_payload->>'requestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN
+ RAISE EXCEPTION 'Security-state source event request identity is malformed'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values';
+ END IF;
+ security_request_id := (event_payload->>'requestId')::UUID;
+ SELECT * INTO operation_row FROM account_security_state_operations
+ WHERE request_id = security_request_id;
+ IF operation_row.request_id IS NULL
+ OR operation_row.status IS DISTINCT FROM 'COMMITTED'
+ OR operation_row.account_uuid IS DISTINCT FROM NEW.account_uuid
+ OR operation_row.account_id IS DISTINCT FROM account_row.id
+ OR operation_row.account_provenance IS DISTINCT FROM NEW.account_uuid_provenance
+ OR operation_row.event_sequence IS DISTINCT FROM NEW.last_outbox_sequence
+ OR operation_row.event_id IS DISTINCT FROM NEW.last_event_id
+ OR operation_row.event_digest IS DISTINCT FROM NEW.last_event_digest
+ OR operation_row.event_payload IS DISTINCT FROM event_row.payload
+ OR operation_row.result_generation IS DISTINCT FROM NEW.current_generation
+ OR operation_row.result_source_version IS DISTINCT FROM NEW.current_source_version
+ OR operation_row.result_fence IS DISTINCT FROM NEW.current_issuance_fence
+ OR operation_row.result_fence_source_version IS DISTINCT FROM NEW.current_issuance_fence_source_version
+ OR operation_row.result_global_role_source_version IS DISTINCT FROM role_source_row.global_role_source_version
+ OR convert_from(operation_row.after_state, 'UTF8')::JSONB IS DISTINCT FROM account_state
+ OR event_payload->>'eventId' IS DISTINCT FROM 'account-security-state-event-v1:' || security_request_id::TEXT THEN
+ RAISE EXCEPTION 'Security-state source event has no exact committed owner receipt'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values';
+ END IF;
+ ELSE
+ RAISE EXCEPTION 'Unsupported Account source event type'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values';
+ END IF;
+ END IF;
+ NEW.updated_at = CURRENT_TIMESTAMP;
+ RETURN NEW;
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION account_authority_account_security_update_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ source_row RECORD;
+ event_row RECORD;
+ event_payload JSONB;
+ expected_modes JSONB;
+ expected_old_modes JSONB;
+ authority_row RECORD;
+ fence_row RECORD;
+ role_source_row RECORD;
+ operation_row RECORD;
+ before_state JSONB;
+ after_state JSONB;
+ expected_before_state JSONB;
+ expected_after_state JSONB;
+ changed_kinds TEXT[] := ARRAY[]::TEXT[];
+ security_request_id UUID;
+BEGIN
+ IF OLD.password_hash IS NOT DISTINCT FROM NEW.password_hash
+ AND OLD.email_verified IS NOT DISTINCT FROM NEW.email_verified
+ AND OLD.login_auth_modes IS NOT DISTINCT FROM NEW.login_auth_modes
+ AND OLD.role IS NOT DISTINCT FROM NEW.role
+ AND OLD.lifecycle_state IS NOT DISTINCT FROM NEW.lifecycle_state THEN
+ RETURN NULL;
+ END IF;
+
+ SELECT source_record.* INTO source_row
+ FROM account_authority_source_records source_record
+ WHERE source_record.scope_kind = 'ACCOUNT'
+ AND source_record.account_uuid = NEW.account_uuid;
+ IF source_row.outbox_stream_key IS NULL OR source_row.last_outbox_sequence < 1
+ OR source_row.last_event_id IS NULL OR source_row.last_event_digest IS NULL THEN
+ RAISE EXCEPTION 'Account security mutation requires an appended Account authority source event'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_required';
+ END IF;
+
+ SELECT payload INTO event_row
+ FROM account_authority_outbox_events
+ WHERE outbox_stream_key = source_row.outbox_stream_key
+ AND outbox_sequence = source_row.last_outbox_sequence
+ AND event_id = source_row.last_event_id
+ AND event_digest = source_row.last_event_digest;
+ event_payload := convert_from(event_row.payload, 'UTF8')::JSONB;
+ SELECT COALESCE(jsonb_agg(to_jsonb(login_mode) ORDER BY login_mode), '[]'::JSONB)
+ INTO expected_modes
+ FROM unnest(string_to_array(NEW.login_auth_modes, ',')) AS modes(login_mode);
+
+ IF event_payload->>'eventType' = 'ACCOUNT_SECURITY_STATE_CHANGED' THEN
+ SELECT generation, source_version INTO authority_row
+ FROM account_authority_generations
+ WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid
+ AND issuer_id IS NULL AND tenant_uuid IS NULL;
+ SELECT issuance_fence, source_version INTO fence_row
+ FROM account_authority_issuance_fences
+ WHERE account_uuid = NEW.account_uuid;
+ SELECT account_uuid_source_numeric_id, account_uuid_provenance,
+ global_roles, global_role_source_version
+ INTO role_source_row FROM account_global_role_sources
+ WHERE account_uuid = NEW.account_uuid;
+ SELECT COALESCE(jsonb_agg(to_jsonb(login_mode) ORDER BY login_mode), '[]'::JSONB)
+ INTO expected_old_modes
+ FROM unnest(string_to_array(OLD.login_auth_modes, ',')) AS modes(login_mode);
+ IF OLD.password_hash IS DISTINCT FROM NEW.password_hash
+ OR OLD.role IS DISTINCT FROM NEW.role THEN
+ RAISE EXCEPTION 'V78 security-state events cannot authorize password or scalar-role changes'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch';
+ END IF;
+ IF event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-account-security-state-event/v1'
+ OR event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT
+ OR event_payload->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT
+ OR event_payload->>'outboxStreamKey' IS DISTINCT FROM source_row.outbox_stream_key
+ OR event_payload->>'outboxSequence' IS DISTINCT FROM source_row.last_outbox_sequence::TEXT
+ OR event_payload->>'eventId' IS DISTINCT FROM source_row.last_event_id
+ OR event_payload->>'eventDigest' IS DISTINCT FROM source_row.last_event_digest
+ OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM source_row.current_generation::TEXT
+ OR event_payload->>'sourceVersion' IS DISTINCT FROM source_row.current_source_version::TEXT
+ OR event_payload#>>'{accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM source_row.cutoff_generation::TEXT
+ OR event_payload#>>'{accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM source_row.cutoff_stream_key
+ OR event_payload#>>'{accountSecurityCutoff,outboxSequence}' IS DISTINCT FROM source_row.cutoff_sequence::TEXT
+ OR authority_row.generation IS DISTINCT FROM source_row.current_generation
+ OR authority_row.source_version IS DISTINCT FROM source_row.current_source_version
+ OR fence_row.issuance_fence IS DISTINCT FROM source_row.current_issuance_fence
+ OR fence_row.source_version IS DISTINCT FROM source_row.current_issuance_fence_source_version
+ OR role_source_row.account_uuid_source_numeric_id IS DISTINCT FROM NEW.account_uuid_source_numeric_id
+ OR role_source_row.account_uuid_provenance IS DISTINCT FROM NEW.account_uuid_provenance
+ OR role_source_row.global_role_source_version IS NULL
+ OR role_source_row.global_roles IS DISTINCT FROM
+ (SELECT COALESCE(array_agg(DISTINCT role_name ORDER BY role_name), ARRAY[]::TEXT[])
+ FROM unnest(role_source_row.global_roles) AS roles(role_name)) THEN
+ RAISE EXCEPTION 'V78 security-state event does not match current Account source owners'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch';
+ END IF;
+
+ IF event_payload->>'requestId' IS NULL
+ OR event_payload->>'requestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN
+ RAISE EXCEPTION 'V78 security-state event request identity is malformed'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch';
+ END IF;
+ security_request_id := (event_payload->>'requestId')::UUID;
+ SELECT * INTO operation_row FROM account_security_state_operations
+ WHERE request_id = security_request_id;
+ IF operation_row.request_id IS NULL
+ OR operation_row.status IS DISTINCT FROM 'COMMITTED'
+ OR operation_row.account_uuid IS DISTINCT FROM NEW.account_uuid
+ OR operation_row.account_id IS DISTINCT FROM NEW.id
+ OR operation_row.account_provenance IS DISTINCT FROM NEW.account_uuid_provenance
+ OR operation_row.event_sequence IS DISTINCT FROM source_row.last_outbox_sequence
+ OR operation_row.event_id IS DISTINCT FROM source_row.last_event_id
+ OR operation_row.event_digest IS DISTINCT FROM source_row.last_event_digest
+ OR operation_row.event_payload IS DISTINCT FROM event_row.payload
+ OR operation_row.expected_generation + 1 IS DISTINCT FROM source_row.current_generation
+ OR operation_row.expected_source_version + 1 IS DISTINCT FROM source_row.current_source_version
+ OR operation_row.expected_fence + 1 IS DISTINCT FROM source_row.current_issuance_fence
+ OR operation_row.expected_fence_source_version + 1 IS DISTINCT FROM source_row.current_issuance_fence_source_version
+ OR operation_row.checkpoint_sequence + 1 IS DISTINCT FROM source_row.last_outbox_sequence
+ OR operation_row.result_generation IS DISTINCT FROM source_row.current_generation
+ OR operation_row.result_source_version IS DISTINCT FROM source_row.current_source_version
+ OR operation_row.result_fence IS DISTINCT FROM source_row.current_issuance_fence
+ OR operation_row.result_fence_source_version IS DISTINCT FROM source_row.current_issuance_fence_source_version
+ OR operation_row.result_global_role_source_version IS DISTINCT FROM role_source_row.global_role_source_version
+ OR event_payload->>'eventId' IS DISTINCT FROM 'account-security-state-event-v1:' || security_request_id::TEXT THEN
+ RAISE EXCEPTION 'V78 security-state event has no exact committed Account operation receipt'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch';
+ END IF;
+
+ before_state := convert_from(operation_row.before_state, 'UTF8')::JSONB;
+ after_state := convert_from(operation_row.after_state, 'UTF8')::JSONB;
+ expected_before_state := jsonb_build_object(
+ 'emailVerified', OLD.email_verified,
+ 'globalRoles', to_jsonb(role_source_row.global_roles),
+ 'lifecycleState', upper(OLD.lifecycle_state),
+ 'loginAuthModes', expected_old_modes);
+ expected_after_state := jsonb_build_object(
+ 'emailVerified', NEW.email_verified,
+ 'globalRoles', to_jsonb(role_source_row.global_roles),
+ 'lifecycleState', upper(NEW.lifecycle_state),
+ 'loginAuthModes', expected_modes);
+ IF before_state IS DISTINCT FROM expected_before_state
+ OR after_state IS DISTINCT FROM expected_after_state
+ OR event_payload->'accountState' IS DISTINCT FROM after_state THEN
+ RAISE EXCEPTION 'V78 security-state receipt does not bind the exact original and current Account states'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch';
+ END IF;
+
+ IF before_state->'emailVerified' IS DISTINCT FROM after_state->'emailVerified' THEN
+ changed_kinds := array_append(changed_kinds, 'EMAIL_LOGIN_ELIGIBILITY_CHANGED');
+ END IF;
+ IF before_state->'globalRoles' IS DISTINCT FROM after_state->'globalRoles' THEN
+ changed_kinds := array_append(changed_kinds, 'GLOBAL_ROLE_CHANGED');
+ END IF;
+ IF before_state->'lifecycleState' IS DISTINCT FROM after_state->'lifecycleState' THEN
+ changed_kinds := array_append(changed_kinds, 'LIFECYCLE_STATE_CHANGED');
+ END IF;
+ IF before_state->'loginAuthModes' IS DISTINCT FROM after_state->'loginAuthModes' THEN
+ changed_kinds := array_append(changed_kinds, 'LOGIN_AUTH_MODES_CHANGED');
+ END IF;
+ IF cardinality(changed_kinds) = 0
+ OR changed_kinds IS DISTINCT FROM operation_row.mutation_kinds
+ OR changed_kinds IS DISTINCT FROM ARRAY(
+ SELECT jsonb_array_elements_text(event_payload->'mutationKinds')) THEN
+ RAISE EXCEPTION 'V78 security-state receipt mutation families differ from the original states'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch';
+ END IF;
+ RETURN NULL;
+ END IF;
+
+ -- Keep the legacy Account-auth event checks and mutation-family interpretation unchanged.
+ SELECT source_record.* INTO source_row
+ FROM account_authority_source_records source_record
+ WHERE source_record.scope_kind = 'ACCOUNT'
+ AND source_record.account_uuid = NEW.account_uuid;
+ IF event_payload IS NULL
+ OR event_payload->>'eventType' IS DISTINCT FROM 'ACCOUNT_AUTHORITY_CHANGED'
+ OR event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT
+ OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM source_row.current_generation::TEXT
+ OR event_payload->>'sourceVersion' IS DISTINCT FROM source_row.current_source_version::TEXT
+ OR event_payload->>'issuanceFence' IS DISTINCT FROM source_row.current_issuance_fence::TEXT
+ OR event_payload->>'issuanceFenceSourceVersion' IS DISTINCT FROM source_row.current_issuance_fence_source_version::TEXT
+ OR event_payload#>>'{accountState,emailVerified}' IS DISTINCT FROM NEW.email_verified::TEXT
+ OR event_payload#>'{accountState,loginAuthModes}' IS DISTINCT FROM expected_modes
+ OR event_payload#>>'{accountState,globalRole}' IS DISTINCT FROM NEW.role
+ OR event_payload#>>'{accountState,lifecycleState}' IS DISTINCT FROM upper(NEW.lifecycle_state)
+ OR (OLD.password_hash IS DISTINCT FROM NEW.password_hash
+ AND NOT (event_payload->'mutationKinds' ? 'PASSWORD_RESET'))
+ OR (OLD.password_hash IS NOT DISTINCT FROM NEW.password_hash
+ AND (event_payload->'mutationKinds' ? 'PASSWORD_RESET'))
+ OR (OLD.email_verified IS DISTINCT FROM NEW.email_verified
+ AND NOT (event_payload->'mutationKinds' ? 'EMAIL_LOGIN_ELIGIBILITY_CHANGED'))
+ OR (OLD.email_verified IS NOT DISTINCT FROM NEW.email_verified
+ AND (event_payload->'mutationKinds' ? 'EMAIL_LOGIN_ELIGIBILITY_CHANGED'))
+ OR (OLD.login_auth_modes IS DISTINCT FROM NEW.login_auth_modes
+ AND NOT (event_payload->'mutationKinds' ? 'LOGIN_AUTH_MODES_CHANGED'))
+ OR (OLD.login_auth_modes IS NOT DISTINCT FROM NEW.login_auth_modes
+ AND (event_payload->'mutationKinds' ? 'LOGIN_AUTH_MODES_CHANGED'))
+ OR (OLD.role IS DISTINCT FROM NEW.role
+ AND NOT (event_payload->'mutationKinds' ? 'GLOBAL_ROLE_CHANGED'))
+ OR (OLD.role IS NOT DISTINCT FROM NEW.role
+ AND (event_payload->'mutationKinds' ? 'GLOBAL_ROLE_CHANGED'))
+ OR (OLD.lifecycle_state IS DISTINCT FROM NEW.lifecycle_state
+ AND NOT (event_payload->'mutationKinds' ? 'LIFECYCLE_STATE_CHANGED'))
+ OR (OLD.lifecycle_state IS NOT DISTINCT FROM NEW.lifecycle_state
+ AND (event_payload->'mutationKinds' ? 'LIFECYCLE_STATE_CHANGED')) THEN
+ RAISE EXCEPTION 'Account security mutation differs from its exact current source event'
+ USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch';
+ END IF;
+ RETURN NULL;
+END;
+$$;
+-- [jooq ignore stop]
diff --git a/services/account-service/src/main/resources/db/migration/V81__account_platform_restriction_birth_sources.sql b/services/account-service/src/main/resources/db/migration/V81__account_platform_restriction_birth_sources.sql
new file mode 100644
index 0000000000..eb6d9daf0d
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V81__account_platform_restriction_birth_sources.sql
@@ -0,0 +1,261 @@
+-- Explicit birth-only CATEGORY evidence for genuinely new repository-created Accounts.
+-- Historical birth generation/fence values are independent of current Account authority.
+-- No retained enrollment, moderation mutation API, current-lock proof, or activation is added.
+CREATE TABLE account_platform_restriction_births (
+ account_uuid UUID NOT NULL REFERENCES accounts(account_uuid),
+ category VARCHAR(32) NOT NULL,
+ revision BIGINT NOT NULL,
+ enforcement_epoch BIGINT NOT NULL,
+ source_kind VARCHAR(16) NOT NULL,
+ restriction_state VARCHAR(16) NOT NULL,
+ operation_id UUID NOT NULL UNIQUE,
+ result_id UUID NOT NULL UNIQUE,
+ event_id UUID NOT NULL UNIQUE,
+ payload_digest VARCHAR(64) NOT NULL,
+ account_source_numeric_id BIGINT NOT NULL REFERENCES accounts(id),
+ account_insert_transaction_id BIGINT NOT NULL,
+ account_generation BIGINT NOT NULL,
+ account_source_version BIGINT NOT NULL,
+ issuance_fence BIGINT NOT NULL,
+ fence_source_version BIGINT NOT NULL,
+ CONSTRAINT account_restriction_birth_pk PRIMARY KEY (account_uuid, category),
+ CONSTRAINT account_restriction_birth_category CHECK (
+ category IN ('account_security_lock', 'platform_access_ban')),
+ CONSTRAINT account_restriction_birth_baseline CHECK (
+ revision = 1 AND enforcement_epoch = 1
+ AND source_kind = 'CATEGORY' AND restriction_state = 'NONRESTRICTED'
+ AND account_source_numeric_id > 0 AND account_insert_transaction_id > 0
+ AND account_generation = 1 AND account_source_version = 1
+ AND issuance_fence = 1 AND fence_source_version = 1),
+ CONSTRAINT account_restriction_birth_digest_shape CHECK (
+ payload_digest ~ '^[0-9a-f]{64}$'),
+ CONSTRAINT account_restriction_birth_uuid_shape CHECK (
+ account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
+ AND operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
+ AND result_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
+ AND event_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'),
+ CONSTRAINT account_restriction_birth_distinct_ids CHECK (
+ operation_id <> result_id AND operation_id <> event_id AND result_id <> event_id),
+ CONSTRAINT account_restriction_birth_projection_identity UNIQUE (
+ account_uuid, category, revision, enforcement_epoch, result_id),
+ CONSTRAINT account_restriction_birth_event_identity UNIQUE (
+ account_uuid, category, revision, enforcement_epoch, operation_id,
+ result_id, event_id, payload_digest, source_kind, restriction_state)
+);
+
+CREATE TABLE account_platform_restriction_projections (
+ account_uuid UUID NOT NULL,
+ category VARCHAR(32) NOT NULL,
+ revision BIGINT NOT NULL CHECK (revision > 0),
+ enforcement_epoch BIGINT NOT NULL CHECK (enforcement_epoch > 0),
+ result_id UUID NOT NULL,
+ CONSTRAINT account_restriction_projection_pk PRIMARY KEY (account_uuid, category),
+ CONSTRAINT account_restriction_projection_exact_result FOREIGN KEY (
+ account_uuid, category, revision, enforcement_epoch, result_id)
+ REFERENCES account_platform_restriction_births (
+ account_uuid, category, revision, enforcement_epoch, result_id)
+);
+
+CREATE TABLE account_platform_restriction_birth_outbox (
+ account_uuid UUID NOT NULL,
+ category VARCHAR(32) NOT NULL,
+ revision BIGINT NOT NULL,
+ enforcement_epoch BIGINT NOT NULL,
+ operation_id UUID NOT NULL,
+ result_id UUID NOT NULL,
+ event_id UUID NOT NULL UNIQUE,
+ payload_digest VARCHAR(64) NOT NULL,
+ outbox_stream_key VARCHAR(160) NOT NULL UNIQUE,
+ outbox_sequence BIGINT NOT NULL,
+ source_kind VARCHAR(16) NOT NULL,
+ restriction_state VARCHAR(16) NOT NULL,
+ CONSTRAINT account_restriction_birth_outbox_pk PRIMARY KEY (account_uuid, category),
+ CONSTRAINT account_restriction_birth_outbox_stream CHECK (
+ outbox_sequence = 1
+ AND outbox_stream_key =
+ 'account:restriction-birth:v1:' || account_uuid::text || '/' || category),
+ CONSTRAINT account_restriction_birth_outbox_exact_result FOREIGN KEY (
+ account_uuid, category, revision, enforcement_epoch, operation_id,
+ result_id, event_id, payload_digest, source_kind, restriction_state)
+ REFERENCES account_platform_restriction_births (
+ account_uuid, category, revision, enforcement_epoch, operation_id,
+ result_id, event_id, payload_digest, source_kind, restriction_state)
+);
+
+-- Closed UTF-8 preimage matches AccountPlatformRestrictionBirthSource.birthDigest exactly.
+-- PostgreSQL proof must verify these checks; jOOQ's schema simulation does not execute them.
+-- [jooq ignore start]
+CREATE FUNCTION account_restriction_birth_digest(
+ birth account_platform_restriction_births)
+RETURNS TEXT LANGUAGE SQL IMMUTABLE STRICT AS $$
+ SELECT encode(sha256(convert_to(
+ concat_ws(E'\n',
+ 'account-restriction-birth/v1',
+ birth.account_uuid::text,
+ birth.account_source_numeric_id::text,
+ 'ACCOUNT_REPOSITORY_INSERT',
+ birth.account_insert_transaction_id::text,
+ birth.category,
+ birth.source_kind,
+ birth.restriction_state,
+ birth.revision::text,
+ birth.enforcement_epoch::text,
+ birth.account_generation::text,
+ birth.account_source_version::text,
+ birth.issuance_fence::text,
+ birth.fence_source_version::text,
+ birth.operation_id::text,
+ birth.result_id::text,
+ birth.event_id::text,
+ 'account:restriction-birth:v1:' || birth.account_uuid::text || '/' || birth.category,
+ '1') || E'\n', 'UTF8')), 'hex')
+$$;
+
+ALTER TABLE account_platform_restriction_births
+ ADD CONSTRAINT account_restriction_birth_exact_digest
+ CHECK (payload_digest = account_restriction_birth_digest(
+ ROW(account_uuid, category, revision, enforcement_epoch, source_kind,
+ restriction_state, operation_id, result_id, event_id, payload_digest,
+ account_source_numeric_id, account_insert_transaction_id,
+ account_generation, account_source_version, issuance_fence,
+ fence_source_version)::account_platform_restriction_births));
+
+CREATE FUNCTION account_restriction_birth_storage_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE
+ account_row RECORD;
+BEGIN
+ IF TG_OP IN ('DELETE', 'TRUNCATE') THEN
+ RAISE EXCEPTION 'Restriction source evidence cannot be removed'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_restriction_birth_no_remove';
+ END IF;
+
+ IF TG_OP = 'UPDATE'
+ AND TG_TABLE_NAME <> 'account_platform_restriction_projections' THEN
+ RAISE EXCEPTION 'Restriction birth result and outbox are immutable'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_restriction_birth_immutable';
+ END IF;
+
+ SELECT * INTO account_row FROM accounts
+ WHERE account_uuid = NEW.account_uuid FOR UPDATE;
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Restriction source requires exact Account'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_restriction_birth_account_required';
+ END IF;
+
+ IF TG_OP = 'UPDATE' THEN
+ IF NEW.account_uuid IS DISTINCT FROM OLD.account_uuid
+ OR NEW.category IS DISTINCT FROM OLD.category
+ OR NEW.revision <> OLD.revision + 1
+ OR NEW.enforcement_epoch <> OLD.enforcement_epoch + 1
+ OR NEW.result_id IS NOT DISTINCT FROM OLD.result_id THEN
+ RAISE EXCEPTION 'Restriction projection requires next exact revision'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_restriction_projection_monotonic';
+ END IF;
+ -- The exact-result FK remains birth-only, so no later revision is supported here.
+ ELSIF TG_TABLE_NAME = 'account_platform_restriction_births' THEN
+ IF account_row.account_uuid_provenance IS DISTINCT FROM 'ACCOUNT_REPOSITORY_INSERT'
+ OR account_row.lifecycle_state IS DISTINCT FROM 'active'
+ OR account_row.id IS DISTINCT FROM NEW.account_source_numeric_id
+ OR account_row.account_uuid_source_numeric_id
+ IS DISTINCT FROM NEW.account_source_numeric_id
+ OR account_row.account_repository_insert_transaction_id
+ IS DISTINCT FROM txid_current()
+ OR NEW.account_insert_transaction_id IS DISTINCT FROM txid_current()
+ OR NOT EXISTS (
+ SELECT 1 FROM account_authority_generations
+ WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid
+ AND generation = 1 AND source_version = 1
+ AND created_transaction_id = txid_current())
+ OR NOT EXISTS (
+ SELECT 1 FROM account_authority_issuance_fences
+ WHERE account_uuid = NEW.account_uuid
+ AND issuance_fence = 1 AND source_version = 1)
+ OR NOT EXISTS (
+ SELECT 1 FROM account_authority_source_records
+ WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid
+ AND initialization_provenance = 'ACCOUNT_REPOSITORY_INSERT'
+ AND initialization_transaction_id = txid_current()
+ AND account_repository_insert_transaction_id = txid_current()
+ AND account_source_numeric_id = NEW.account_source_numeric_id
+ AND current_generation = 1 AND current_source_version = 1
+ AND current_issuance_fence = 1
+ AND current_issuance_fence_source_version = 1
+ AND last_outbox_sequence = 0
+ AND last_event_id IS NULL AND last_event_digest IS NULL) THEN
+ RAISE EXCEPTION 'Restriction birth requires genuine fresh Account source'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_restriction_birth_fresh_provenance';
+ END IF;
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE TRIGGER account_restriction_birth_storage
+ BEFORE INSERT OR UPDATE OR DELETE ON account_platform_restriction_births
+ FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_storage_guard();
+CREATE TRIGGER account_restriction_projection_storage
+ BEFORE INSERT OR UPDATE OR DELETE ON account_platform_restriction_projections
+ FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_storage_guard();
+CREATE TRIGGER account_restriction_birth_outbox_storage
+ BEFORE INSERT OR UPDATE OR DELETE ON account_platform_restriction_birth_outbox
+ FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_storage_guard();
+CREATE TRIGGER account_restriction_birth_no_truncate
+ BEFORE TRUNCATE ON account_platform_restriction_births
+ FOR EACH STATEMENT EXECUTE FUNCTION account_restriction_birth_storage_guard();
+CREATE TRIGGER account_restriction_projection_no_truncate
+ BEFORE TRUNCATE ON account_platform_restriction_projections
+ FOR EACH STATEMENT EXECUTE FUNCTION account_restriction_birth_storage_guard();
+CREATE TRIGGER account_restriction_birth_outbox_no_truncate
+ BEFORE TRUNCATE ON account_platform_restriction_birth_outbox
+ FOR EACH STATEMENT EXECUTE FUNCTION account_restriction_birth_storage_guard();
+
+CREATE FUNCTION account_restriction_birth_complete_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ -- Existing/unmapped rows are not enrolled. This branch uses only the accounts row type.
+ IF TG_TABLE_NAME = 'accounts' THEN
+ IF NEW.account_uuid_provenance IS DISTINCT FROM 'ACCOUNT_REPOSITORY_INSERT'
+ OR NEW.id IS DISTINCT FROM NEW.account_uuid_source_numeric_id
+ OR NEW.account_repository_insert_transaction_id IS DISTINCT FROM txid_current() THEN
+ RETURN NEW;
+ END IF;
+ END IF;
+
+ IF (SELECT count(*)
+ FROM account_platform_restriction_births b
+ JOIN account_platform_restriction_projections p
+ USING (account_uuid, category, revision, enforcement_epoch, result_id)
+ JOIN account_platform_restriction_birth_outbox o
+ USING (account_uuid, category, revision, enforcement_epoch,
+ operation_id, result_id, event_id, payload_digest,
+ source_kind, restriction_state)
+ WHERE b.account_uuid = NEW.account_uuid) <> 2 THEN
+ RAISE EXCEPTION 'Fresh Account restriction birth must be complete'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_restriction_birth_complete';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE CONSTRAINT TRIGGER account_restriction_account_birth_complete
+ AFTER INSERT ON accounts DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard();
+CREATE CONSTRAINT TRIGGER account_restriction_birth_complete
+ AFTER INSERT ON account_platform_restriction_births DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard();
+CREATE CONSTRAINT TRIGGER account_restriction_projection_complete
+ AFTER INSERT OR UPDATE ON account_platform_restriction_projections
+ DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard();
+CREATE CONSTRAINT TRIGGER account_restriction_birth_outbox_complete
+ AFTER INSERT ON account_platform_restriction_birth_outbox
+ DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard();
+-- [jooq ignore stop]
diff --git a/services/account-service/src/main/resources/db/migration/V82__creator_membership_provenance.sql b/services/account-service/src/main/resources/db/migration/V82__creator_membership_provenance.sql
new file mode 100644
index 0000000000..bb724346c7
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V82__creator_membership_provenance.sql
@@ -0,0 +1,11 @@
+ALTER TABLE account_tenant_membership
+ DROP CONSTRAINT account_membership_provenance_check;
+
+ALTER TABLE account_tenant_membership
+ ADD CONSTRAINT account_membership_provenance_check
+ CHECK (authority_provenance IN (
+ 'EXPLICIT_JOIN',
+ 'LEGACY_UNVERIFIED',
+ 'SEEDED_DEMO',
+ 'TENANT_CREATION'
+ ));
diff --git a/services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql b/services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql
new file mode 100644
index 0000000000..662c0252a7
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql
@@ -0,0 +1,189 @@
+-- One immutable owner receipt for the first control-only Account membership created
+-- from an exact, authenticated Game Design tenant-creation source. This storage does
+-- not provide authentication or expose a mutation route.
+CREATE TABLE account_tenant_creation_bootstrap_operations (
+ request_id UUID PRIMARY KEY,
+ schema_version SMALLINT NOT NULL CHECK (schema_version = 1),
+ initiating_account_uuid UUID NOT NULL REFERENCES accounts (account_uuid),
+ tenant_uuid UUID NOT NULL,
+ creation_request_id UUID NOT NULL,
+ creation_operation_id UUID NOT NULL,
+ account_authorization_operation_id UUID NOT NULL,
+ account_authorization_digest VARCHAR(71) NOT NULL
+ CHECK (account_authorization_digest ~ '^sha256:[0-9a-f]{64}$'),
+ creator_evidence_digest VARCHAR(71) NOT NULL
+ CHECK (creator_evidence_digest ~ '^sha256:[0-9a-f]{64}$'),
+ creator_evidence_payload BYTEA NOT NULL,
+ source_snapshot_payload BYTEA NOT NULL,
+ source_snapshot_digest VARCHAR(71) NOT NULL
+ CHECK (source_snapshot_digest ~ '^sha256:[0-9a-f]{64}$'),
+ request_payload BYTEA NOT NULL,
+ request_digest VARCHAR(71) NOT NULL
+ CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'),
+ baseline_membership_version BIGINT NOT NULL CHECK (baseline_membership_version > 0),
+ baseline_membership_authority_generation BIGINT NOT NULL
+ CHECK (baseline_membership_authority_generation > 0),
+ baseline_event_sequence BIGINT NOT NULL CHECK (baseline_event_sequence = 0),
+ membership_id BIGINT,
+ membership_version BIGINT,
+ membership_authority_generation BIGINT,
+ membership_lifecycle_state VARCHAR(16),
+ gameplay_admission_allowed BOOLEAN,
+ membership_roles_payload BYTEA,
+ event_stream_key VARCHAR(256),
+ event_request_id VARCHAR(128),
+ event_sequence BIGINT,
+ event_id VARCHAR(512),
+ event_digest VARCHAR(71),
+ caller_bound_authority_invalidated BOOLEAN,
+ event_payload BYTEA,
+ audit_event_id UUID,
+ audit_event_type VARCHAR(80),
+ audit_occurred_at TIMESTAMPTZ,
+ audit_payload_digest VARCHAR(71),
+ audit_payload BYTEA,
+ result_payload BYTEA,
+ result_digest VARCHAR(71),
+ status VARCHAR(16) NOT NULL CHECK (status IN ('IN_PROGRESS', 'COMMITTED')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ committed_at TIMESTAMPTZ,
+ CONSTRAINT account_tenant_creation_bootstrap_authorization_identity_check
+ CHECK (request_id = account_authorization_operation_id),
+ CONSTRAINT account_tenant_creation_bootstrap_creator_tenant_uq
+ UNIQUE (tenant_uuid),
+ CONSTRAINT account_tenant_creation_bootstrap_creation_operation_uq
+ UNIQUE (creation_operation_id),
+ CONSTRAINT account_tenant_creation_bootstrap_membership_state_check
+ CHECK (membership_lifecycle_state IS NULL OR membership_lifecycle_state = 'ACTIVE'),
+ CONSTRAINT account_tenant_creation_bootstrap_admission_check
+ CHECK (gameplay_admission_allowed IS NULL OR gameplay_admission_allowed = FALSE),
+ CONSTRAINT account_tenant_creation_bootstrap_generation_check
+ CHECK (membership_authority_generation IS NULL OR
+ membership_authority_generation = baseline_membership_authority_generation),
+ CONSTRAINT account_tenant_creation_bootstrap_event_check
+ CHECK (event_sequence IS NULL OR event_sequence = 1),
+ CONSTRAINT account_tenant_creation_bootstrap_event_scope_check
+ CHECK (event_stream_key IS NULL OR event_stream_key =
+ 'account:auth-authority:v1:membership/' || initiating_account_uuid::TEXT || '/' || tenant_uuid::TEXT),
+ CONSTRAINT account_tenant_creation_bootstrap_event_request_check
+ CHECK (event_request_id IS NULL OR event_request_id = request_id::TEXT),
+ CONSTRAINT account_tenant_creation_bootstrap_invalidation_check
+ CHECK (caller_bound_authority_invalidated IS NULL OR caller_bound_authority_invalidated = FALSE),
+ CONSTRAINT account_tenant_creation_bootstrap_completion_shape CHECK (
+ (status = 'IN_PROGRESS'
+ AND membership_id IS NULL AND membership_version IS NULL
+ AND membership_authority_generation IS NULL AND membership_lifecycle_state IS NULL
+ AND gameplay_admission_allowed IS NULL AND membership_roles_payload IS NULL
+ AND event_stream_key IS NULL AND event_request_id IS NULL AND event_sequence IS NULL
+ AND event_id IS NULL AND event_digest IS NULL
+ AND caller_bound_authority_invalidated IS NULL AND event_payload IS NULL
+ AND audit_event_id IS NULL AND audit_event_type IS NULL AND audit_occurred_at IS NULL
+ AND audit_payload_digest IS NULL AND audit_payload IS NULL
+ AND result_payload IS NULL AND result_digest IS NULL AND committed_at IS NULL)
+ OR (status = 'COMMITTED'
+ AND membership_id IS NOT NULL AND membership_id > 0
+ AND membership_version = baseline_membership_version + 1
+ AND membership_authority_generation = baseline_membership_authority_generation
+ AND membership_lifecycle_state = 'ACTIVE'
+ AND gameplay_admission_allowed = FALSE
+ AND membership_roles_payload = convert_to('["tenantAdmin"]', 'UTF8')
+ AND event_stream_key IS NOT NULL AND event_request_id IS NOT NULL
+ AND event_sequence = 1 AND event_id IS NOT NULL AND length(btrim(event_id)) > 0
+ AND event_digest IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND caller_bound_authority_invalidated = FALSE AND event_payload IS NOT NULL
+ AND audit_event_id IS NOT NULL AND audit_event_type = 'ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED'
+ AND audit_occurred_at IS NOT NULL
+ AND audit_payload_digest IS NOT NULL AND audit_payload_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND audit_payload IS NOT NULL
+ AND result_payload IS NOT NULL AND result_digest IS NOT NULL
+ AND result_digest ~ '^sha256:[0-9a-f]{64}$' AND committed_at IS NOT NULL))
+);
+
+CREATE INDEX account_tenant_creation_bootstrap_creator_idx
+ ON account_tenant_creation_bootstrap_operations
+ (initiating_account_uuid, tenant_uuid, request_id);
+
+-- [jooq ignore start]
+CREATE FUNCTION account_tenant_creation_bootstrap_update_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ IF NEW.request_id IS DISTINCT FROM OLD.request_id
+ OR NEW.schema_version IS DISTINCT FROM OLD.schema_version
+ OR NEW.initiating_account_uuid IS DISTINCT FROM OLD.initiating_account_uuid
+ OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid
+ OR NEW.creation_request_id IS DISTINCT FROM OLD.creation_request_id
+ OR NEW.creation_operation_id IS DISTINCT FROM OLD.creation_operation_id
+ OR NEW.account_authorization_operation_id IS DISTINCT FROM OLD.account_authorization_operation_id
+ OR NEW.account_authorization_digest IS DISTINCT FROM OLD.account_authorization_digest
+ OR NEW.creator_evidence_digest IS DISTINCT FROM OLD.creator_evidence_digest
+ OR NEW.creator_evidence_payload IS DISTINCT FROM OLD.creator_evidence_payload
+ OR NEW.source_snapshot_payload IS DISTINCT FROM OLD.source_snapshot_payload
+ OR NEW.source_snapshot_digest IS DISTINCT FROM OLD.source_snapshot_digest
+ OR NEW.request_payload IS DISTINCT FROM OLD.request_payload
+ OR NEW.request_digest IS DISTINCT FROM OLD.request_digest
+ OR NEW.baseline_membership_version IS DISTINCT FROM OLD.baseline_membership_version
+ OR NEW.baseline_membership_authority_generation IS DISTINCT FROM OLD.baseline_membership_authority_generation
+ OR NEW.baseline_event_sequence IS DISTINCT FROM OLD.baseline_event_sequence
+ OR NEW.created_at IS DISTINCT FROM OLD.created_at
+ OR OLD.status <> 'IN_PROGRESS'
+ OR NEW.status <> 'COMMITTED' THEN
+ RAISE EXCEPTION 'Account creator-bootstrap request is immutable'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_tenant_creation_bootstrap_identity_immutable';
+ END IF;
+ NEW.committed_at = CURRENT_TIMESTAMP;
+ RETURN NEW;
+END;
+$$;
+
+CREATE FUNCTION account_tenant_creation_bootstrap_insert_guard()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ IF NEW.status <> 'IN_PROGRESS'
+ OR NEW.membership_id IS NOT NULL OR NEW.membership_version IS NOT NULL
+ OR NEW.membership_authority_generation IS NOT NULL
+ OR NEW.membership_lifecycle_state IS NOT NULL OR NEW.gameplay_admission_allowed IS NOT NULL
+ OR NEW.membership_roles_payload IS NOT NULL
+ OR NEW.event_stream_key IS NOT NULL OR NEW.event_request_id IS NOT NULL
+ OR NEW.event_sequence IS NOT NULL OR NEW.event_id IS NOT NULL OR NEW.event_digest IS NOT NULL
+ OR NEW.caller_bound_authority_invalidated IS NOT NULL OR NEW.event_payload IS NOT NULL
+ OR NEW.audit_event_id IS NOT NULL OR NEW.audit_event_type IS NOT NULL
+ OR NEW.audit_occurred_at IS NOT NULL OR NEW.audit_payload_digest IS NOT NULL
+ OR NEW.audit_payload IS NOT NULL OR NEW.result_payload IS NOT NULL
+ OR NEW.result_digest IS NOT NULL OR NEW.committed_at IS NOT NULL THEN
+ RAISE EXCEPTION 'Account creator-bootstrap operation must begin without a result'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_tenant_creation_bootstrap_initial_state';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE FUNCTION account_tenant_creation_bootstrap_no_delete()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+BEGIN
+ RAISE EXCEPTION 'Account creator-bootstrap history cannot be deleted'
+ USING ERRCODE = '23514',
+ CONSTRAINT = 'account_tenant_creation_bootstrap_no_delete';
+ RETURN OLD;
+END;
+$$;
+
+CREATE TRIGGER account_tenant_creation_bootstrap_insert
+ BEFORE INSERT ON account_tenant_creation_bootstrap_operations
+ FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_bootstrap_insert_guard();
+
+CREATE TRIGGER account_tenant_creation_bootstrap_update
+ BEFORE UPDATE ON account_tenant_creation_bootstrap_operations
+ FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_bootstrap_update_guard();
+
+CREATE TRIGGER account_tenant_creation_bootstrap_delete
+ BEFORE DELETE ON account_tenant_creation_bootstrap_operations
+ FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_bootstrap_no_delete();
+-- [jooq ignore stop]
diff --git a/services/account-service/src/main/resources/db/migration/V84__individual_creator_party_sources.sql b/services/account-service/src/main/resources/db/migration/V84__individual_creator_party_sources.sql
new file mode 100644
index 0000000000..d717b24762
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V84__individual_creator_party_sources.sql
@@ -0,0 +1,153 @@
+-- Owner-local preparation only: no party provisioning, authenticated caller producer,
+-- hosted terms, source revocation writer or runtime activation is supplied here.
+CREATE TABLE account_individual_creator_party_sources (
+ creator_party_id UUID PRIMARY KEY CHECK (creator_party_id <> '00000000-0000-0000-0000-000000000000'),
+ account_uuid UUID NOT NULL REFERENCES accounts (account_uuid),
+ verification_status VARCHAR(16) NOT NULL
+ CHECK (verification_status IN ('UNVERIFIED', 'VERIFIED', 'UNSUPPORTED')),
+ identity_version BIGINT NOT NULL CHECK (identity_version > 0),
+ policy_reference VARCHAR(512),
+ policy_version BIGINT,
+ verification_evidence_reference VARCHAR(512),
+ verification_evidence_version BIGINT,
+ source_version BIGINT NOT NULL CHECK (source_version = 1),
+ source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) > 0),
+ source_digest VARCHAR(71) NOT NULL CHECK (source_digest ~ '^sha256:[0-9a-f]{64}$'),
+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ CHECK (policy_reference IS NULL OR length(btrim(policy_reference)) > 0),
+ CHECK (verification_evidence_reference IS NULL OR length(btrim(verification_evidence_reference)) > 0),
+ CHECK ((policy_reference IS NULL) = (policy_version IS NULL)),
+ CHECK ((verification_evidence_reference IS NULL) = (verification_evidence_version IS NULL)),
+ CHECK (policy_version IS NULL OR policy_version > 0),
+ CHECK (verification_evidence_version IS NULL OR verification_evidence_version > 0),
+ CHECK (verification_status <> 'VERIFIED' OR
+ (policy_reference IS NOT NULL AND verification_evidence_reference IS NOT NULL)),
+ UNIQUE (creator_party_id, account_uuid)
+);
+
+-- All history counts as prior state. Retained/tombstoned evidence cannot be reset to fresh.
+-- This migration intentionally enrolls no existing tenant or party.
+CREATE TABLE account_tenant_creator_party_history (
+ history_id UUID PRIMARY KEY CHECK (history_id <> '00000000-0000-0000-0000-000000000000'),
+ tenant_uuid UUID NOT NULL,
+ origin VARCHAR(24) NOT NULL CHECK (origin IN ('FRESH_INITIAL', 'RETAINED', 'TOMBSTONE')),
+ creator_party_id UUID REFERENCES account_individual_creator_party_sources (creator_party_id),
+ source_version BIGINT NOT NULL CHECK (source_version > 0),
+ evidence_payload BYTEA NOT NULL CHECK (octet_length(evidence_payload) > 0),
+ evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$'),
+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE (tenant_uuid, source_version),
+ CHECK (origin <> 'FRESH_INITIAL' OR (creator_party_id IS NOT NULL AND source_version = 1))
+);
+
+CREATE TABLE account_fresh_creator_party_association_operations (
+ request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'),
+ tenant_uuid UUID NOT NULL UNIQUE REFERENCES account_canonical_tenant_identity_claims (canonical_tenant_id),
+ initiating_account_uuid UUID NOT NULL REFERENCES accounts (account_uuid),
+ creator_party_id UUID NOT NULL,
+ creation_operation_id UUID NOT NULL UNIQUE,
+ creator_evidence_payload BYTEA NOT NULL CHECK (octet_length(creator_evidence_payload) > 0),
+ party_source_payload BYTEA NOT NULL CHECK (octet_length(party_source_payload) > 0),
+ request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0),
+ request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'),
+ history_id UUID NOT NULL UNIQUE REFERENCES account_tenant_creator_party_history (history_id),
+ result_payload BYTEA NOT NULL CHECK (octet_length(result_payload) > 0),
+ result_digest VARCHAR(71) NOT NULL CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'),
+ committed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (creator_party_id, initiating_account_uuid)
+ REFERENCES account_individual_creator_party_sources (creator_party_id, account_uuid)
+);
+
+-- [jooq ignore start]
+CREATE FUNCTION account_creator_party_immutable_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ RAISE EXCEPTION 'Account creator-party source/history/receipt is immutable';
+END;
+$$;
+CREATE TRIGGER account_individual_creator_party_immutable
+ BEFORE UPDATE OR DELETE ON account_individual_creator_party_sources
+ FOR EACH ROW EXECUTE FUNCTION account_creator_party_immutable_guard();
+CREATE TRIGGER account_creator_party_history_immutable
+ BEFORE UPDATE OR DELETE ON account_tenant_creator_party_history
+ FOR EACH ROW EXECUTE FUNCTION account_creator_party_immutable_guard();
+CREATE TRIGGER account_creator_party_operation_immutable
+ BEFORE UPDATE OR DELETE ON account_fresh_creator_party_association_operations
+ FOR EACH ROW EXECUTE FUNCTION account_creator_party_immutable_guard();
+
+CREATE FUNCTION account_creator_party_history_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ -- All future history writers must use this same canonical tenant serialization.
+ -- An older repeatable snapshot cannot prove history absence after waiting for this lock.
+ IF current_setting('transaction_isolation') <> 'read committed' THEN
+ RAISE EXCEPTION 'Creator-party history requires READ COMMITTED owner transaction';
+ END IF;
+ PERFORM 1 FROM account_canonical_tenant_identity_claims
+ WHERE canonical_tenant_id = NEW.tenant_uuid FOR UPDATE;
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Creator-party history requires existing canonical tenant provenance';
+ END IF;
+ IF NEW.origin = 'FRESH_INITIAL' AND EXISTS (
+ SELECT 1 FROM account_tenant_creator_party_history WHERE tenant_uuid = NEW.tenant_uuid) THEN
+ RAISE EXCEPTION 'Fresh association cannot replace prior creator-party history';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER account_creator_party_history_insert
+ BEFORE INSERT ON account_tenant_creator_party_history
+ FOR EACH ROW EXECUTE FUNCTION account_creator_party_history_insert_guard();
+
+CREATE FUNCTION account_creator_party_initial_receipt_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE
+ history account_tenant_creator_party_history%ROWTYPE;
+ receipt account_fresh_creator_party_association_operations%ROWTYPE;
+BEGIN
+ IF TG_TABLE_NAME = 'account_tenant_creator_party_history' THEN
+ history := NEW;
+ IF history.origin <> 'FRESH_INITIAL' THEN RETURN NEW; END IF;
+ SELECT * INTO receipt FROM account_fresh_creator_party_association_operations
+ WHERE history_id = history.history_id;
+ ELSE
+ receipt := NEW;
+ SELECT * INTO history FROM account_tenant_creator_party_history
+ WHERE history_id = receipt.history_id;
+ END IF;
+ IF receipt.request_id IS NULL OR history.history_id IS NULL
+ OR history.origin <> 'FRESH_INITIAL'
+ OR history.tenant_uuid <> receipt.tenant_uuid
+ OR history.creator_party_id <> receipt.creator_party_id
+ OR history.evidence_payload <> receipt.result_payload
+ OR history.evidence_digest <> receipt.result_digest
+ OR (SELECT count(*) FROM account_tenant_creator_party_history
+ WHERE tenant_uuid = receipt.tenant_uuid) <> 1 THEN
+ RAISE EXCEPTION 'Fresh creator-party history requires exact immutable owner receipt';
+ END IF;
+ IF NOT EXISTS (
+ SELECT 1 FROM account_individual_creator_party_sources party
+ WHERE party.creator_party_id = receipt.creator_party_id
+ AND party.account_uuid = receipt.initiating_account_uuid
+ AND party.verification_status = 'VERIFIED'
+ AND party.source_payload = receipt.party_source_payload)
+ OR NOT EXISTS (
+ SELECT 1 FROM account_tenant_creation_bootstrap_operations bootstrap
+ JOIN account_fresh_tenant_identity_associations fresh
+ ON fresh.canonical_tenant_id = bootstrap.tenant_uuid
+ WHERE bootstrap.status = 'COMMITTED'
+ AND bootstrap.tenant_uuid = receipt.tenant_uuid
+ AND bootstrap.initiating_account_uuid = receipt.initiating_account_uuid
+ AND bootstrap.creation_operation_id = receipt.creation_operation_id
+ AND fresh.operation_id = receipt.creation_operation_id
+ AND fresh.creation_request_id = bootstrap.creation_request_id
+ AND bootstrap.creator_evidence_payload = receipt.creator_evidence_payload) THEN
+ RAISE EXCEPTION 'Fresh creator-party receipt requires exact persisted individual and creator sources';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE CONSTRAINT TRIGGER account_creator_party_initial_history_receipt
+ AFTER INSERT ON account_tenant_creator_party_history DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_creator_party_initial_receipt_guard();
+CREATE CONSTRAINT TRIGGER account_creator_party_initial_operation_receipt
+ AFTER INSERT ON account_fresh_creator_party_association_operations DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_creator_party_initial_receipt_guard();
+-- [jooq ignore stop]
diff --git a/services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql b/services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql
new file mode 100644
index 0000000000..bf01e873c1
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql
@@ -0,0 +1,383 @@
+-- Account-owned immutable hosted terms and individual affirmative acceptance workflow.
+-- This schema is deliberately unregistered: it creates no production route, bean or live legal
+-- publication. Existing Accounts and creator parties are not enrolled or backfilled.
+CREATE TABLE account_hosted_terms_scopes (
+ hosted_scope_id UUID PRIMARY KEY CHECK (hosted_scope_id <> '00000000-0000-0000-0000-000000000000'),
+ current_version_id UUID,
+ current_source_version BIGINT,
+ current_material_generation BIGINT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ CHECK ((current_version_id IS NULL) = (current_source_version IS NULL)),
+ CHECK ((current_version_id IS NULL) = (current_material_generation IS NULL)),
+ CHECK (current_source_version IS NULL OR current_source_version > 0),
+ CHECK (current_material_generation IS NULL OR current_material_generation > 0)
+);
+
+CREATE TABLE account_hosted_terms_catalog_versions (
+ version_id UUID PRIMARY KEY CHECK (version_id <> '00000000-0000-0000-0000-000000000000'),
+ hosted_scope_id UUID NOT NULL REFERENCES account_hosted_terms_scopes (hosted_scope_id),
+ predecessor_version_id UUID,
+ operator_legal_identity VARCHAR(2048) NOT NULL CHECK (length(btrim(operator_legal_identity)) > 0),
+ operator_identity_version BIGINT NOT NULL CHECK (operator_identity_version > 0),
+ document_bytes BYTEA NOT NULL CHECK (octet_length(document_bytes) > 0),
+ document_digest VARCHAR(71) NOT NULL CHECK (document_digest ~ '^sha256:[0-9a-f]{64}$'),
+ source_version BIGINT NOT NULL CHECK (source_version > 0),
+ material_generation BIGINT NOT NULL CHECK (material_generation > 0),
+ materiality VARCHAR(16) NOT NULL CHECK (materiality IN ('INITIAL', 'MATERIAL', 'NONMATERIAL')),
+ materiality_evidence_reference VARCHAR(512),
+ materiality_evidence_version BIGINT,
+ publication_evidence_reference VARCHAR(512) NOT NULL CHECK (length(btrim(publication_evidence_reference)) > 0),
+ publication_evidence_version BIGINT NOT NULL CHECK (publication_evidence_version > 0),
+ notice_evidence_reference VARCHAR(512) NOT NULL CHECK (length(btrim(notice_evidence_reference)) > 0),
+ notice_evidence_version BIGINT NOT NULL CHECK (notice_evidence_version > 0),
+ effective_at TIMESTAMPTZ NOT NULL,
+ version_payload BYTEA NOT NULL CHECK (octet_length(version_payload) > 0),
+ version_digest VARCHAR(71) NOT NULL CHECK (version_digest ~ '^sha256:[0-9a-f]{64}$'),
+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE (hosted_scope_id, source_version),
+ UNIQUE (hosted_scope_id, version_id),
+ FOREIGN KEY (hosted_scope_id, predecessor_version_id)
+ REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, version_id),
+ CHECK ((predecessor_version_id IS NULL AND materiality = 'INITIAL'
+ AND source_version = 1 AND material_generation = 1
+ AND materiality_evidence_reference IS NULL AND materiality_evidence_version IS NULL)
+ OR (predecessor_version_id IS NOT NULL AND materiality IN ('MATERIAL', 'NONMATERIAL')
+ AND materiality_evidence_reference IS NOT NULL
+ AND length(btrim(materiality_evidence_reference)) > 0
+ AND materiality_evidence_version > 0)),
+ CHECK ((materiality_evidence_reference IS NULL) = (materiality_evidence_version IS NULL)),
+ CHECK (document_digest = 'sha256:' || encode(sha256(document_bytes), 'hex')),
+ CHECK (version_digest = 'sha256:' || encode(sha256(version_payload), 'hex'))
+);
+
+ALTER TABLE account_hosted_terms_scopes
+ ADD CONSTRAINT account_hosted_terms_current_version_fk
+ FOREIGN KEY (hosted_scope_id, current_version_id)
+ REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, version_id);
+
+CREATE TABLE account_hosted_terms_publication_operations (
+ request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'),
+ hosted_scope_id UUID NOT NULL REFERENCES account_hosted_terms_scopes (hosted_scope_id),
+ request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0),
+ request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'),
+ status VARCHAR(32) NOT NULL CHECK (status IN ('RECEIVED', 'SCHEDULED', 'PENDING_OWNER_SETTLEMENT', 'COMMITTED')),
+ candidate_version_id UUID,
+ source_change_binding BYTEA,
+ result_payload BYTEA,
+ result_digest VARCHAR(71),
+ requested_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ committed_at TIMESTAMPTZ,
+ UNIQUE (request_id, hosted_scope_id),
+ UNIQUE (candidate_version_id),
+ FOREIGN KEY (hosted_scope_id, candidate_version_id)
+ REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, version_id),
+ CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')),
+ CHECK ((candidate_version_id IS NULL) = (status = 'RECEIVED')),
+ CHECK (status <> 'PENDING_OWNER_SETTLEMENT' OR source_change_binding IS NOT NULL),
+ CHECK ((status = 'COMMITTED') = (result_payload IS NOT NULL)),
+ CHECK ((result_payload IS NULL) = (result_digest IS NULL)),
+ CHECK ((result_digest IS NULL) = (committed_at IS NULL)),
+ CHECK (result_digest IS NULL OR result_digest = 'sha256:' || encode(sha256(result_payload), 'hex'))
+);
+
+-- One pending/scheduled candidate per hosted scope preserves an unambiguous next independent
+-- source version. A due candidate remains durable even while owner settlement is unresolved.
+CREATE UNIQUE INDEX account_hosted_terms_one_unsettled_publication
+ ON account_hosted_terms_publication_operations (hosted_scope_id)
+ WHERE status IN ('SCHEDULED', 'PENDING_OWNER_SETTLEMENT');
+
+CREATE TABLE account_individual_hosted_terms_acceptances (
+ evidence_id UUID PRIMARY KEY CHECK (evidence_id <> '00000000-0000-0000-0000-000000000000'),
+ action_request_id UUID NOT NULL UNIQUE CHECK (action_request_id <> '00000000-0000-0000-0000-000000000000'),
+ creator_party_id UUID NOT NULL,
+ account_uuid UUID NOT NULL REFERENCES accounts (account_uuid),
+ hosted_scope_id UUID NOT NULL,
+ terms_version_id UUID NOT NULL,
+ document_digest VARCHAR(71) NOT NULL CHECK (document_digest ~ '^sha256:[0-9a-f]{64}$'),
+ operator_legal_identity VARCHAR(2048) NOT NULL CHECK (length(btrim(operator_legal_identity)) > 0),
+ operator_identity_version BIGINT NOT NULL CHECK (operator_identity_version > 0),
+ source_version BIGINT NOT NULL CHECK (source_version > 0),
+ material_generation BIGINT NOT NULL CHECK (material_generation > 0),
+ individual_party_source BYTEA NOT NULL CHECK (octet_length(individual_party_source) > 0),
+ individual_party_source_digest VARCHAR(71) NOT NULL CHECK (individual_party_source_digest ~ '^sha256:[0-9a-f]{64}$'),
+ affirmative_action_evidence BYTEA NOT NULL CHECK (octet_length(affirmative_action_evidence) > 0),
+ affirmative_action_digest VARCHAR(71) NOT NULL CHECK (affirmative_action_digest ~ '^sha256:[0-9a-f]{64}$'),
+ accepted_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (creator_party_id, account_uuid)
+ REFERENCES account_individual_creator_party_sources (creator_party_id, account_uuid),
+ FOREIGN KEY (hosted_scope_id, terms_version_id)
+ REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, version_id),
+ CHECK (individual_party_source_digest = 'sha256:' || encode(sha256(individual_party_source), 'hex')),
+ CHECK (affirmative_action_digest = 'sha256:' || encode(sha256(affirmative_action_evidence), 'hex'))
+);
+
+CREATE INDEX account_individual_hosted_terms_current_acceptance
+ ON account_individual_hosted_terms_acceptances
+ (creator_party_id, hosted_scope_id, accepted_at DESC, evidence_id);
+
+-- [jooq ignore start]
+CREATE FUNCTION account_hosted_terms_immutable_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ RAISE EXCEPTION 'Account hosted terms catalog and acceptance evidence is immutable';
+END;
+$$;
+CREATE TRIGGER account_hosted_terms_catalog_immutable
+ BEFORE UPDATE OR DELETE ON account_hosted_terms_catalog_versions
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_immutable_guard();
+CREATE TRIGGER account_hosted_terms_acceptance_immutable
+ BEFORE UPDATE OR DELETE ON account_individual_hosted_terms_acceptances
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_immutable_guard();
+
+CREATE FUNCTION account_hosted_terms_version_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE prior account_hosted_terms_catalog_versions%ROWTYPE;
+DECLARE scope account_hosted_terms_scopes%ROWTYPE;
+BEGIN
+ IF TG_OP <> 'INSERT' THEN
+ RAISE EXCEPTION 'Hosted terms versions are append-only';
+ END IF;
+ SELECT * INTO scope FROM account_hosted_terms_scopes
+ WHERE hosted_scope_id = NEW.hosted_scope_id FOR UPDATE;
+ IF scope.hosted_scope_id IS NULL THEN
+ RAISE EXCEPTION 'Hosted terms version requires canonical scope lock';
+ END IF;
+ IF NEW.predecessor_version_id IS NULL THEN
+ IF EXISTS (SELECT 1 FROM account_hosted_terms_catalog_versions
+ WHERE hosted_scope_id = NEW.hosted_scope_id)
+ OR scope.current_version_id IS NOT NULL THEN
+ RAISE EXCEPTION 'Initial hosted terms cannot replace prior source state';
+ END IF;
+ RETURN NEW;
+ END IF;
+ IF scope.current_version_id IS DISTINCT FROM NEW.predecessor_version_id
+ OR EXISTS (SELECT 1 FROM account_hosted_terms_catalog_versions
+ WHERE hosted_scope_id = NEW.hosted_scope_id
+ AND predecessor_version_id = NEW.predecessor_version_id) THEN
+ RAISE EXCEPTION 'Hosted terms candidate must extend the sole current predecessor';
+ END IF;
+ SELECT * INTO prior FROM account_hosted_terms_catalog_versions
+ WHERE hosted_scope_id = NEW.hosted_scope_id
+ AND version_id = NEW.predecessor_version_id;
+ IF prior.version_id IS NULL OR NEW.source_version <> prior.source_version + 1 THEN
+ RAISE EXCEPTION 'Hosted terms source version must advance from exact predecessor';
+ END IF;
+ IF NEW.operator_legal_identity <> prior.operator_legal_identity
+ OR NEW.operator_identity_version <> prior.operator_identity_version THEN
+ IF NEW.materiality <> 'MATERIAL'
+ OR NEW.material_generation <> prior.material_generation + 1 THEN
+ RAISE EXCEPTION 'Operator identity change requires material acceptance-generation advance';
+ END IF;
+ ELSIF NEW.materiality = 'MATERIAL' THEN
+ IF NEW.material_generation <> prior.material_generation + 1 THEN
+ RAISE EXCEPTION 'Material terms must advance acceptance generation exactly once';
+ END IF;
+ ELSIF NEW.materiality = 'NONMATERIAL' THEN
+ IF NEW.material_generation <> prior.material_generation THEN
+ RAISE EXCEPTION 'Nonmaterial terms must preserve acceptance generation';
+ END IF;
+ ELSE
+ RAISE EXCEPTION 'Only audited materiality classifications may follow a predecessor';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER account_hosted_terms_version_insert
+ BEFORE INSERT ON account_hosted_terms_catalog_versions
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_version_insert_guard();
+
+CREATE FUNCTION account_hosted_terms_scope_head_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE next_version account_hosted_terms_catalog_versions%ROWTYPE;
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ RAISE EXCEPTION 'Hosted terms source scope cannot be deleted';
+ END IF;
+ IF TG_OP = 'INSERT' THEN
+ IF NEW.current_version_id IS NOT NULL
+ OR NEW.current_source_version IS NOT NULL
+ OR NEW.current_material_generation IS NOT NULL THEN
+ RAISE EXCEPTION 'New hosted terms scope cannot fabricate a prior current source';
+ END IF;
+ RETURN NEW;
+ END IF;
+ IF NEW.hosted_scope_id <> OLD.hosted_scope_id
+ OR NEW.current_version_id IS NULL
+ OR NEW.current_source_version IS NULL
+ OR NEW.current_material_generation IS NULL THEN
+ RAISE EXCEPTION 'Hosted terms head update must retain canonical scope and positive source';
+ END IF;
+ SELECT * INTO next_version FROM account_hosted_terms_catalog_versions
+ WHERE hosted_scope_id = NEW.hosted_scope_id AND version_id = NEW.current_version_id;
+ IF next_version.version_id IS NULL
+ OR next_version.source_version <> NEW.current_source_version
+ OR next_version.material_generation <> NEW.current_material_generation
+ OR next_version.effective_at > clock_timestamp() THEN
+ RAISE EXCEPTION 'Only an exact due catalog version may become operative';
+ END IF;
+ IF NOT EXISTS (SELECT 1 FROM account_hosted_terms_publication_operations publication
+ WHERE publication.hosted_scope_id = NEW.hosted_scope_id
+ AND publication.candidate_version_id = NEW.current_version_id
+ AND publication.status IN ('SCHEDULED', 'PENDING_OWNER_SETTLEMENT')) THEN
+ RAISE EXCEPTION 'Operative terms must match a durable Account publication intent';
+ END IF;
+ IF OLD.current_version_id IS NULL THEN
+ IF next_version.predecessor_version_id IS NOT NULL
+ OR next_version.source_version <> 1 OR next_version.material_generation <> 1 THEN
+ RAISE EXCEPTION 'Initial operative source cannot invent predecessor state';
+ END IF;
+ ELSE
+ IF next_version.predecessor_version_id <> OLD.current_version_id
+ OR next_version.source_version <> OLD.current_source_version + 1 THEN
+ RAISE EXCEPTION 'Operative terms must advance from the exact prior head';
+ END IF;
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER account_hosted_terms_scope_head
+ BEFORE INSERT OR UPDATE OR DELETE ON account_hosted_terms_scopes
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_scope_head_guard();
+
+CREATE FUNCTION account_hosted_terms_scope_head_complete_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ IF TG_OP = 'UPDATE' AND NEW.current_version_id IS DISTINCT FROM OLD.current_version_id
+ AND NOT EXISTS (SELECT 1 FROM account_hosted_terms_publication_operations publication
+ WHERE publication.hosted_scope_id = NEW.hosted_scope_id
+ AND publication.candidate_version_id = NEW.current_version_id
+ AND publication.status = 'COMMITTED') THEN
+ RAISE EXCEPTION 'Operative catalog head requires committed publication readback';
+ END IF;
+ RETURN NULL;
+END;
+$$;
+CREATE CONSTRAINT TRIGGER account_hosted_terms_scope_head_complete
+ AFTER UPDATE ON account_hosted_terms_scopes DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_scope_head_complete_guard();
+
+CREATE FUNCTION account_hosted_terms_publication_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ RAISE EXCEPTION 'Hosted terms publication request history cannot be deleted';
+ END IF;
+ IF TG_OP = 'INSERT' THEN
+ IF NEW.status <> 'RECEIVED' OR NEW.candidate_version_id IS NOT NULL
+ OR NEW.source_change_binding IS NOT NULL OR NEW.result_payload IS NOT NULL THEN
+ RAISE EXCEPTION 'Publication operation must begin as exact received intent';
+ END IF;
+ RETURN NEW;
+ END IF;
+ IF NEW.request_id <> OLD.request_id OR NEW.hosted_scope_id <> OLD.hosted_scope_id
+ OR NEW.request_payload <> OLD.request_payload OR NEW.request_digest <> OLD.request_digest
+ OR (OLD.candidate_version_id IS NOT NULL
+ AND NEW.candidate_version_id IS DISTINCT FROM OLD.candidate_version_id)
+ OR (OLD.source_change_binding IS NOT NULL
+ AND NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding)
+ OR OLD.status = 'COMMITTED' THEN
+ RAISE EXCEPTION 'Publication request identity and candidate are immutable';
+ END IF;
+ IF NOT ((OLD.status = 'RECEIVED' AND NEW.status IN ('SCHEDULED', 'PENDING_OWNER_SETTLEMENT', 'COMMITTED'))
+ OR (OLD.status = 'SCHEDULED' AND NEW.status IN ('PENDING_OWNER_SETTLEMENT', 'COMMITTED'))
+ OR (OLD.status = 'PENDING_OWNER_SETTLEMENT' AND NEW.status = 'COMMITTED')) THEN
+ RAISE EXCEPTION 'Invalid hosted terms publication transition';
+ END IF;
+ IF NEW.status = 'COMMITTED' THEN
+ IF NEW.candidate_version_id IS NULL OR NEW.result_payload IS NULL
+ OR NEW.result_digest IS NULL OR NEW.committed_at IS NULL
+ OR NOT EXISTS (SELECT 1 FROM account_hosted_terms_scopes scope
+ WHERE scope.hosted_scope_id = NEW.hosted_scope_id
+ AND scope.current_version_id = NEW.candidate_version_id)
+ OR NOT EXISTS (SELECT 1 FROM account_hosted_terms_catalog_versions version
+ WHERE version.hosted_scope_id = NEW.hosted_scope_id
+ AND version.version_id = NEW.candidate_version_id
+ AND version.version_payload = NEW.result_payload) THEN
+ RAISE EXCEPTION 'Committed publication requires exact operative catalog readback';
+ END IF;
+ ELSIF NEW.result_payload IS NOT NULL OR NEW.result_digest IS NOT NULL OR NEW.committed_at IS NOT NULL THEN
+ RAISE EXCEPTION 'Unsettled publication cannot have a committed result';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER account_hosted_terms_publication_immutable
+ BEFORE INSERT OR UPDATE OR DELETE ON account_hosted_terms_publication_operations
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_publication_guard();
+
+CREATE FUNCTION account_hosted_terms_publication_fence_complete_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE predecessor UUID;
+BEGIN
+ IF NEW.status = 'COMMITTED' THEN
+ SELECT predecessor_version_id INTO predecessor
+ FROM account_hosted_terms_catalog_versions
+ WHERE hosted_scope_id = NEW.hosted_scope_id
+ AND version_id = NEW.candidate_version_id;
+ IF predecessor IS NOT NULL AND (NEW.source_change_binding IS NULL OR NOT EXISTS (
+ SELECT 1 FROM account_draft_authorization_source_changes change
+ JOIN account_draft_authorization_changed_scopes changed USING (change_id)
+ WHERE change.change_id = NEW.request_id
+ AND change.binding = NEW.source_change_binding
+ AND change.status = 'SOURCE_COMMITTED'
+ AND changed.source_key = 'HOSTED_TERMS:' || NEW.hosted_scope_id::TEXT)) THEN
+ RAISE EXCEPTION 'Updated hosted terms require fully settled exact Draft source change';
+ END IF;
+ END IF;
+ RETURN NULL;
+END;
+$$;
+CREATE CONSTRAINT TRIGGER account_hosted_terms_publication_fence_complete
+ AFTER INSERT OR UPDATE ON account_hosted_terms_publication_operations
+ DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_publication_fence_complete_guard();
+
+CREATE FUNCTION account_hosted_terms_acceptance_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE source account_individual_creator_party_sources%ROWTYPE;
+DECLARE terms account_hosted_terms_catalog_versions%ROWTYPE;
+DECLARE scope account_hosted_terms_scopes%ROWTYPE;
+DECLARE action JSONB;
+BEGIN
+ IF TG_OP <> 'INSERT' THEN
+ RAISE EXCEPTION 'Hosted terms acceptances are append-only';
+ END IF;
+ SELECT * INTO source FROM account_individual_creator_party_sources
+ WHERE creator_party_id = NEW.creator_party_id AND account_uuid = NEW.account_uuid FOR UPDATE;
+ SELECT * INTO terms FROM account_hosted_terms_catalog_versions
+ WHERE hosted_scope_id = NEW.hosted_scope_id AND version_id = NEW.terms_version_id;
+ SELECT * INTO scope FROM account_hosted_terms_scopes
+ WHERE hosted_scope_id = NEW.hosted_scope_id FOR UPDATE;
+ action := convert_from(NEW.affirmative_action_evidence, 'UTF8')::JSONB;
+ IF source.creator_party_id IS NULL OR source.verification_status <> 'VERIFIED'
+ OR source.source_payload <> NEW.individual_party_source
+ OR terms.version_id IS NULL
+ OR terms.document_digest <> NEW.document_digest
+ OR terms.operator_legal_identity <> NEW.operator_legal_identity
+ OR terms.operator_identity_version <> NEW.operator_identity_version
+ OR terms.source_version <> NEW.source_version
+ OR terms.material_generation <> NEW.material_generation
+ OR NEW.accepted_at IS DISTINCT FROM CURRENT_TIMESTAMP
+ OR action->>'schema' IS DISTINCT FROM 'account-hosted-terms-affirmative-action/v1'
+ OR action->>'actionRequestId' IS DISTINCT FROM NEW.action_request_id::TEXT
+ OR action->>'affirmative' IS DISTINCT FROM 'true'
+ OR action->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT
+ OR action->>'creatorPartyId' IS DISTINCT FROM NEW.creator_party_id::TEXT
+ OR action->>'hostedScopeId' IS DISTINCT FROM NEW.hosted_scope_id::TEXT
+ OR action->>'shownVersionId' IS DISTINCT FROM NEW.terms_version_id::TEXT
+ OR action->>'shownDocumentDigest' IS DISTINCT FROM NEW.document_digest
+ OR action->>'shownOperatorLegalIdentity' IS DISTINCT FROM NEW.operator_legal_identity
+ OR action->>'shownOperatorIdentityVersion' IS DISTINCT FROM NEW.operator_identity_version::TEXT
+ OR (scope.current_version_id IS DISTINCT FROM NEW.terms_version_id
+ AND NOT EXISTS (SELECT 1 FROM account_hosted_terms_publication_operations publication
+ WHERE publication.hosted_scope_id = NEW.hosted_scope_id
+ AND publication.candidate_version_id = NEW.terms_version_id
+ AND publication.status IN ('SCHEDULED', 'PENDING_OWNER_SETTLEMENT'))) THEN
+ RAISE EXCEPTION 'Acceptance must bind exact locally verified party and shown catalog evidence';
+ END IF;
+ -- Acceptance may be recorded in advance for one disclosed scheduled version. It remains
+ -- append-only and is not current until that exact version is on the operative ancestry.
+ IF scope.current_version_id IS NULL AND terms.predecessor_version_id IS NOT NULL THEN
+ RAISE EXCEPTION 'Hosted terms acceptance requires an existing operative source';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER account_hosted_terms_acceptance_insert
+ BEFORE INSERT OR UPDATE OR DELETE ON account_individual_hosted_terms_acceptances
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_acceptance_insert_guard();
+-- [jooq ignore stop]
diff --git a/services/account-service/src/main/resources/db/migration/V86__account_hosted_terms_environment_binding.sql b/services/account-service/src/main/resources/db/migration/V86__account_hosted_terms_environment_binding.sql
new file mode 100644
index 0000000000..35c21bb8a9
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V86__account_hosted_terms_environment_binding.sql
@@ -0,0 +1,288 @@
+-- Account-owned immutable selection of the official hosted-terms source for one existing
+-- environment boundary. The environment identity itself comes from the authenticated owner; this
+-- migration creates no environment registry, backfill, route, bean, or production publisher.
+CREATE TABLE account_hosted_terms_environment_binding_heads (
+ environment_boundary VARCHAR(512) PRIMARY KEY
+ CHECK (length(btrim(environment_boundary)) > 0),
+ current_binding_id UUID,
+ current_source_version BIGINT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ CHECK ((current_binding_id IS NULL) = (current_source_version IS NULL)),
+ CHECK (current_source_version IS NULL OR current_source_version > 0)
+);
+
+CREATE TABLE account_hosted_terms_environment_bindings (
+ binding_id UUID PRIMARY KEY CHECK (binding_id <> '00000000-0000-0000-0000-000000000000'),
+ publication_request_id UUID NOT NULL UNIQUE
+ CHECK (publication_request_id <> '00000000-0000-0000-0000-000000000000'),
+ environment_boundary VARCHAR(512) NOT NULL
+ REFERENCES account_hosted_terms_environment_binding_heads (environment_boundary),
+ hosted_scope_id UUID NOT NULL REFERENCES account_hosted_terms_scopes (hosted_scope_id),
+ operator_legal_identity VARCHAR(2048) NOT NULL
+ CHECK (length(btrim(operator_legal_identity)) > 0),
+ operator_identity_version BIGINT NOT NULL CHECK (operator_identity_version > 0),
+ catalog_version_id UUID NOT NULL,
+ catalog_source_version BIGINT NOT NULL CHECK (catalog_source_version > 0),
+ authenticated_publisher_identity VARCHAR(512) NOT NULL
+ CHECK (length(btrim(authenticated_publisher_identity)) > 0),
+ publication_event_identity VARCHAR(512) NOT NULL
+ CHECK (length(btrim(publication_event_identity)) > 0),
+ publication_evidence_digest VARCHAR(71) NOT NULL
+ CHECK (publication_evidence_digest ~ '^sha256:[0-9a-f]{64}$'),
+ predecessor_binding_id UUID,
+ predecessor_source_version BIGINT,
+ source_version BIGINT NOT NULL CHECK (source_version > 0),
+ binding_payload BYTEA NOT NULL CHECK (octet_length(binding_payload) > 0),
+ binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'),
+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE (environment_boundary, binding_id),
+ UNIQUE (environment_boundary, source_version),
+ FOREIGN KEY (environment_boundary, predecessor_binding_id)
+ REFERENCES account_hosted_terms_environment_bindings (environment_boundary, binding_id),
+ FOREIGN KEY (hosted_scope_id, catalog_version_id)
+ REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, version_id),
+ FOREIGN KEY (hosted_scope_id, catalog_source_version)
+ REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, source_version),
+ CHECK ((predecessor_binding_id IS NULL) = (predecessor_source_version IS NULL)),
+ CHECK ((predecessor_binding_id IS NULL AND source_version = 1
+ AND predecessor_source_version IS NULL)
+ OR (predecessor_binding_id IS NOT NULL AND predecessor_source_version > 0
+ AND source_version = predecessor_source_version + 1)),
+ CHECK (binding_digest = 'sha256:' || encode(sha256(binding_payload), 'hex'))
+);
+
+ALTER TABLE account_hosted_terms_environment_binding_heads
+ ADD CONSTRAINT account_hosted_terms_environment_binding_current_fk
+ FOREIGN KEY (environment_boundary, current_binding_id)
+ REFERENCES account_hosted_terms_environment_bindings (environment_boundary, binding_id)
+ DEFERRABLE INITIALLY DEFERRED;
+
+CREATE TABLE account_hosted_terms_environment_binding_publications (
+ request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'),
+ environment_boundary VARCHAR(512) NOT NULL
+ REFERENCES account_hosted_terms_environment_binding_heads (environment_boundary),
+ request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0),
+ request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'),
+ status VARCHAR(32) NOT NULL
+ CHECK (status IN ('RECEIVED', 'PENDING_OWNER_SETTLEMENT', 'COMMITTED')),
+ candidate_binding_id UUID,
+ source_change_binding BYTEA,
+ result_payload BYTEA,
+ result_digest VARCHAR(71),
+ requested_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ committed_at TIMESTAMPTZ,
+ UNIQUE (request_id, environment_boundary),
+ UNIQUE (candidate_binding_id),
+ FOREIGN KEY (environment_boundary, candidate_binding_id)
+ REFERENCES account_hosted_terms_environment_bindings (environment_boundary, binding_id),
+ CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')),
+ CHECK ((candidate_binding_id IS NULL) = (status = 'RECEIVED')),
+ CHECK (status <> 'PENDING_OWNER_SETTLEMENT' OR source_change_binding IS NOT NULL),
+ CHECK ((status = 'COMMITTED') = (result_payload IS NOT NULL)),
+ CHECK ((result_payload IS NULL) = (result_digest IS NULL)),
+ CHECK ((result_digest IS NULL) = (committed_at IS NULL)),
+ CHECK (result_digest IS NULL OR result_digest = 'sha256:' || encode(sha256(result_payload), 'hex'))
+);
+
+ALTER TABLE account_hosted_terms_environment_bindings
+ ADD CONSTRAINT account_hosted_terms_environment_binding_publication_fk
+ FOREIGN KEY (publication_request_id, environment_boundary)
+ REFERENCES account_hosted_terms_environment_binding_publications
+ (request_id, environment_boundary)
+ DEFERRABLE INITIALLY DEFERRED;
+
+CREATE UNIQUE INDEX account_hosted_terms_environment_one_unsettled_binding
+ ON account_hosted_terms_environment_binding_publications (environment_boundary)
+ WHERE status = 'PENDING_OWNER_SETTLEMENT';
+
+-- [jooq ignore start]
+CREATE FUNCTION account_hosted_terms_environment_binding_immutable_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ RAISE EXCEPTION 'Environment binding receipt history is immutable';
+END;
+$$;
+CREATE TRIGGER account_hosted_terms_environment_binding_immutable
+ BEFORE UPDATE OR DELETE ON account_hosted_terms_environment_bindings
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_immutable_guard();
+
+CREATE FUNCTION account_hosted_terms_environment_binding_insert_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE head account_hosted_terms_environment_binding_heads%ROWTYPE;
+DECLARE terms account_hosted_terms_catalog_versions%ROWTYPE;
+DECLARE scope account_hosted_terms_scopes%ROWTYPE;
+DECLARE publication account_hosted_terms_environment_binding_publications%ROWTYPE;
+BEGIN
+ IF TG_OP <> 'INSERT' THEN
+ RAISE EXCEPTION 'Environment binding receipts are append-only';
+ END IF;
+ SELECT * INTO head FROM account_hosted_terms_environment_binding_heads
+ WHERE environment_boundary = NEW.environment_boundary FOR UPDATE;
+ IF head.environment_boundary IS NULL THEN
+ RAISE EXCEPTION 'Environment binding receipt requires canonical environment head lock';
+ END IF;
+ SELECT * INTO publication FROM account_hosted_terms_environment_binding_publications
+ WHERE request_id = NEW.publication_request_id FOR UPDATE;
+ IF publication.request_id IS NULL OR publication.environment_boundary <> NEW.environment_boundary
+ OR publication.status <> 'RECEIVED'
+ OR publication.request_digest <> NEW.publication_evidence_digest THEN
+ RAISE EXCEPTION 'Binding receipt requires exact trusted publication intent';
+ END IF;
+ IF head.current_binding_id IS NULL THEN
+ IF NEW.predecessor_binding_id IS NOT NULL OR NEW.predecessor_source_version IS NOT NULL
+ OR NEW.source_version <> 1
+ OR EXISTS (SELECT 1 FROM account_hosted_terms_environment_bindings
+ WHERE environment_boundary = NEW.environment_boundary) THEN
+ RAISE EXCEPTION 'Initial environment binding cannot fabricate predecessor state';
+ END IF;
+ ELSE
+ IF head.current_binding_id IS DISTINCT FROM NEW.predecessor_binding_id
+ OR head.current_source_version IS DISTINCT FROM NEW.predecessor_source_version
+ OR NEW.source_version <> head.current_source_version + 1
+ OR EXISTS (SELECT 1 FROM account_hosted_terms_environment_bindings
+ WHERE environment_boundary = NEW.environment_boundary
+ AND predecessor_binding_id = head.current_binding_id) THEN
+ RAISE EXCEPTION 'Environment binding must extend the exact current predecessor';
+ END IF;
+ END IF;
+ SELECT * INTO scope FROM account_hosted_terms_scopes
+ WHERE hosted_scope_id = NEW.hosted_scope_id FOR UPDATE;
+ SELECT * INTO terms FROM account_hosted_terms_catalog_versions
+ WHERE hosted_scope_id = NEW.hosted_scope_id AND version_id = NEW.catalog_version_id;
+ IF scope.current_version_id IS DISTINCT FROM NEW.catalog_version_id
+ OR scope.current_source_version IS DISTINCT FROM NEW.catalog_source_version
+ OR terms.version_id IS NULL OR terms.source_version <> NEW.catalog_source_version
+ OR terms.operator_legal_identity <> NEW.operator_legal_identity
+ OR terms.operator_identity_version <> NEW.operator_identity_version
+ OR terms.effective_at > clock_timestamp() THEN
+ RAISE EXCEPTION 'Binding must name exact current due catalog and legal operator';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER account_hosted_terms_environment_binding_insert
+ BEFORE INSERT ON account_hosted_terms_environment_bindings
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_insert_guard();
+
+CREATE FUNCTION account_hosted_terms_environment_binding_head_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE next_binding account_hosted_terms_environment_bindings%ROWTYPE;
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ RAISE EXCEPTION 'Environment binding head cannot be deleted';
+ END IF;
+ IF TG_OP = 'INSERT' THEN
+ IF NEW.current_binding_id IS NOT NULL OR NEW.current_source_version IS NOT NULL THEN
+ RAISE EXCEPTION 'New environment binding head cannot fabricate prior source';
+ END IF;
+ RETURN NEW;
+ END IF;
+ IF NEW.environment_boundary <> OLD.environment_boundary OR NEW.current_binding_id IS NULL
+ OR NEW.current_source_version IS NULL THEN
+ RAISE EXCEPTION 'Environment binding head update must retain boundary and positive source';
+ END IF;
+ SELECT * INTO next_binding FROM account_hosted_terms_environment_bindings
+ WHERE environment_boundary = NEW.environment_boundary
+ AND binding_id = NEW.current_binding_id;
+ IF next_binding.binding_id IS NULL OR next_binding.source_version <> NEW.current_source_version
+ OR NOT EXISTS (SELECT 1 FROM account_hosted_terms_environment_binding_publications publication
+ WHERE publication.request_id = next_binding.publication_request_id
+ AND publication.environment_boundary = NEW.environment_boundary
+ AND publication.candidate_binding_id = NEW.current_binding_id
+ AND publication.status = 'COMMITTED') THEN
+ RAISE EXCEPTION 'Environment binding head must match exact publication candidate';
+ END IF;
+ IF OLD.current_binding_id IS NULL THEN
+ IF next_binding.predecessor_binding_id IS NOT NULL OR next_binding.source_version <> 1 THEN
+ RAISE EXCEPTION 'Initial environment binding head cannot invent a predecessor';
+ END IF;
+ ELSIF next_binding.predecessor_binding_id <> OLD.current_binding_id
+ OR next_binding.source_version <> OLD.current_source_version + 1 THEN
+ RAISE EXCEPTION 'Environment binding head must advance from its exact predecessor';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER account_hosted_terms_environment_binding_head
+ BEFORE INSERT OR UPDATE OR DELETE ON account_hosted_terms_environment_binding_heads
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_head_guard();
+
+CREATE FUNCTION account_hosted_terms_environment_binding_publication_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE candidate account_hosted_terms_environment_bindings%ROWTYPE;
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ RAISE EXCEPTION 'Environment binding publication history cannot be deleted';
+ END IF;
+ IF TG_OP = 'INSERT' THEN
+ IF NEW.status <> 'RECEIVED' OR NEW.candidate_binding_id IS NOT NULL
+ OR NEW.source_change_binding IS NOT NULL OR NEW.result_payload IS NOT NULL THEN
+ RAISE EXCEPTION 'Binding publication must begin as exact received intent';
+ END IF;
+ RETURN NEW;
+ END IF;
+ IF NEW.request_id <> OLD.request_id OR NEW.environment_boundary <> OLD.environment_boundary
+ OR NEW.request_payload <> OLD.request_payload OR NEW.request_digest <> OLD.request_digest
+ OR NEW.requested_at <> OLD.requested_at THEN
+ RAISE EXCEPTION 'Binding publication request intent is immutable';
+ END IF;
+ IF OLD.status = 'COMMITTED' THEN
+ RAISE EXCEPTION 'Committed binding publication result is immutable';
+ END IF;
+ IF NOT ((OLD.status = 'RECEIVED' AND NEW.status IN ('PENDING_OWNER_SETTLEMENT', 'COMMITTED'))
+ OR (OLD.status = 'PENDING_OWNER_SETTLEMENT' AND NEW.status = 'COMMITTED')) THEN
+ RAISE EXCEPTION 'Invalid binding publication transition';
+ END IF;
+ IF NEW.candidate_binding_id IS NULL THEN
+ RAISE EXCEPTION 'Binding publication transition requires exact candidate';
+ END IF;
+ IF OLD.status = 'PENDING_OWNER_SETTLEMENT'
+ AND (NEW.candidate_binding_id IS DISTINCT FROM OLD.candidate_binding_id
+ OR NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding) THEN
+ RAISE EXCEPTION 'Pending binding publication cannot replace its immutable candidate';
+ END IF;
+ IF NEW.status = 'PENDING_OWNER_SETTLEMENT' AND NEW.source_change_binding IS NULL THEN
+ RAISE EXCEPTION 'Pending binding publication requires durable source-change intent';
+ END IF;
+ IF NEW.status IN ('PENDING_OWNER_SETTLEMENT', 'COMMITTED') THEN
+ SELECT * INTO candidate FROM account_hosted_terms_environment_bindings
+ WHERE environment_boundary = NEW.environment_boundary
+ AND binding_id = NEW.candidate_binding_id;
+ IF candidate.binding_id IS NULL OR candidate.publication_request_id <> NEW.request_id
+ OR ((candidate.predecessor_binding_id IS NOT NULL)
+ <> (NEW.source_change_binding IS NOT NULL)) THEN
+ RAISE EXCEPTION 'Binding operation must retain its exact predecessor source change';
+ END IF;
+ END IF;
+ IF NEW.status = 'COMMITTED' THEN
+ IF NEW.result_payload <> candidate.binding_payload
+ OR NEW.result_digest <> candidate.binding_digest
+ OR NEW.committed_at IS NULL THEN
+ RAISE EXCEPTION 'Committed binding result must read back exact candidate and fence intent';
+ END IF;
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER account_hosted_terms_environment_binding_publication
+ BEFORE INSERT OR UPDATE OR DELETE ON account_hosted_terms_environment_binding_publications
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_publication_guard();
+
+CREATE FUNCTION account_hosted_terms_environment_binding_complete_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ IF TG_OP = 'UPDATE' AND NEW.current_binding_id IS DISTINCT FROM OLD.current_binding_id
+ AND NOT EXISTS (SELECT 1 FROM account_hosted_terms_environment_binding_publications publication
+ WHERE publication.environment_boundary = NEW.environment_boundary
+ AND publication.candidate_binding_id = NEW.current_binding_id
+ AND publication.status = 'COMMITTED') THEN
+ RAISE EXCEPTION 'Environment binding head requires committed exact publication result';
+ END IF;
+ RETURN NULL;
+END;
+$$;
+CREATE CONSTRAINT TRIGGER account_hosted_terms_environment_binding_complete
+ AFTER UPDATE ON account_hosted_terms_environment_binding_heads
+ DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_complete_guard();
+-- [jooq ignore stop]
diff --git a/services/account-service/src/main/resources/db/migration/V87__account_control_ui_owner_source_guards.sql b/services/account-service/src/main/resources/db/migration/V87__account_control_ui_owner_source_guards.sql
new file mode 100644
index 0000000000..5321fd5b97
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V87__account_control_ui_owner_source_guards.sql
@@ -0,0 +1,156 @@
+-- Forward-only source serialization guards for the existing Account Control UI schema.
+-- These guards derive exact owner source keys and do not create or backfill authority.
+-- [jooq ignore start]
+-- Derive exact source keys from owner rows, not from caller assertions or broad tenant matching.
+-- These keys identify serialization only and do not provision authority/baselines.
+CREATE FUNCTION account_control_ui_source_keys(table_name TEXT, row_value JSONB)
+RETURNS TEXT[] LANGUAGE plpgsql STABLE STRICT AS $$
+DECLARE
+ account_value TEXT := row_value->>'account_uuid';
+ tenant_value TEXT := row_value->>'tenant_uuid';
+ scope_kind TEXT;
+ member RECORD;
+BEGIN
+ CASE table_name
+ WHEN 'accounts' THEN
+ RETURN ARRAY['ACCOUNT:' || account_value, 'GLOBAL_ROLES:' || account_value];
+ WHEN 'account_authority_generations' THEN
+ scope_kind := row_value->>'scope_kind';
+ IF scope_kind = 'ISSUER' THEN RETURN ARRAY['ISSUER:' || (row_value->>'issuer_id')]; END IF;
+ IF scope_kind = 'TENANT' THEN RETURN ARRAY['TENANT:' || tenant_value]; END IF;
+ IF scope_kind = 'MEMBERSHIP' THEN RETURN ARRAY['MEMBERSHIP:' || account_value || '/' || tenant_value]; END IF;
+ RETURN ARRAY['ACCOUNT:' || account_value, 'GLOBAL_ROLES:' || account_value];
+ WHEN 'account_authority_issuance_fences' THEN
+ RETURN ARRAY['ACCOUNT:' || account_value, 'GLOBAL_ROLES:' || account_value];
+ WHEN 'account_membership_pair_authority' THEN
+ RETURN ARRAY['MEMBERSHIP:' || account_value || '/' || tenant_value];
+ WHEN 'account_tenant_membership' THEN
+ SELECT account_uuid::TEXT INTO account_value FROM accounts WHERE id = (row_value->>'account_id')::BIGINT;
+ IF tenant_value IS NULL THEN RETURN ARRAY[]::TEXT[]; END IF;
+ RETURN ARRAY['MEMBERSHIP:' || account_value || '/' || tenant_value];
+ WHEN 'account_tenant_membership_role_snapshots', 'account_tenant_membership_role_snapshot_roles' THEN
+ SELECT a.account_uuid::TEXT AS account_uuid, m.tenant_uuid::TEXT AS tenant_uuid INTO member
+ FROM account_tenant_membership m JOIN accounts a ON a.id = m.account_id
+ WHERE m.id = (row_value->>'membership_id')::BIGINT;
+ IF member.tenant_uuid IS NULL THEN RETURN ARRAY[]::TEXT[]; END IF;
+ RETURN ARRAY['MEMBERSHIP:' || member.account_uuid || '/' || member.tenant_uuid];
+ WHEN 'account_individual_creator_party_sources' THEN
+ RETURN ARRAY['CREATOR_PARTY:' || (row_value->>'creator_party_id')];
+ WHEN 'account_tenant_creator_party_history' THEN
+ RETURN ARRAY['TENANT:' || tenant_value];
+ WHEN 'account_hosted_terms_scopes' THEN
+ RETURN ARRAY['HOSTED_TERMS:' || (row_value->>'hosted_scope_id')];
+ WHEN 'account_individual_hosted_terms_acceptances' THEN
+ -- Acceptance currentness is party-specific; another party in this catalog is unrelated.
+ RETURN ARRAY['CREATOR_PARTY:' || (row_value->>'creator_party_id')];
+ WHEN 'account_hosted_terms_environment_binding_heads' THEN
+ RETURN ARRAY['HOSTED_TERMS:environment-boundary/' || (row_value->>'environment_boundary')];
+ ELSE
+ RAISE EXCEPTION 'Unsupported creator source guard owner' USING ERRCODE = '23514';
+ END CASE;
+END;
+$$;
+
+CREATE FUNCTION account_control_ui_hold_required_sources(source_keys TEXT[])
+RETURNS VOID LANGUAGE plpgsql AS $$
+DECLARE
+ source_key_value TEXT;
+ operation_value UUID;
+BEGIN
+ FOR source_key_value IN SELECT value FROM
+ (SELECT DISTINCT value FROM unnest(source_keys) value WHERE value IS NOT NULL) exact_keys
+ ORDER BY account_publication_authorization_source_sort_key(value) LOOP
+ INSERT INTO account_draft_authorization_source_locks(source_key)
+ VALUES (source_key_value) ON CONFLICT DO NOTHING;
+ PERFORM source_key FROM account_draft_authorization_source_locks
+ WHERE source_key = source_key_value FOR UPDATE NOWAIT;
+ END LOOP;
+ FOR operation_value IN SELECT DISTINCT s.operation_id
+ FROM account_draft_authorization_sources s WHERE s.source_key = ANY(source_keys)
+ ORDER BY s.operation_id LOOP
+ PERFORM operation_id FROM account_draft_authorization_fences
+ WHERE operation_id = operation_value FOR UPDATE NOWAIT;
+ IF NOT account_draft_authorization_is_settled(operation_value) THEN
+ RAISE EXCEPTION 'Required creator source is held until every original owner settles'
+ USING ERRCODE = '55P03';
+ END IF;
+ END LOOP;
+END;
+$$;
+
+CREATE FUNCTION account_control_ui_required_source_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE
+ old_value JSONB;
+ new_value JSONB;
+ protected_columns TEXT[];
+ source_keys TEXT[] := ARRAY[]::TEXT[];
+BEGIN
+ IF TG_OP = 'TRUNCATE' THEN
+ EXECUTE format('SELECT array_agg(k) FROM %I t CROSS JOIN LATERAL '
+ || 'unnest(account_control_ui_source_keys(%L, to_jsonb(t))) k', TG_TABLE_NAME, TG_TABLE_NAME)
+ INTO source_keys;
+ PERFORM account_control_ui_hold_required_sources(COALESCE(source_keys, ARRAY[]::TEXT[]));
+ RETURN NULL;
+ END IF;
+ IF TG_OP <> 'INSERT' THEN old_value := to_jsonb(OLD); END IF;
+ IF TG_OP <> 'DELETE' THEN new_value := to_jsonb(NEW); END IF;
+ IF TG_TABLE_NAME = 'accounts' AND TG_OP = 'UPDATE' THEN
+ protected_columns := ARRAY['account_uuid','account_uuid_provenance','account_uuid_source_numeric_id',
+ 'password_hash','email_verified','login_auth_modes','role','lifecycle_state'];
+ IF NOT EXISTS (SELECT 1 FROM unnest(protected_columns) c
+ WHERE old_value->c IS DISTINCT FROM new_value->c) THEN RETURN NEW; END IF;
+ ELSIF TG_OP = 'UPDATE' AND (old_value - ARRAY['created_at','updated_at','recorded_at'])
+ IS NOT DISTINCT FROM (new_value - ARRAY['created_at','updated_at','recorded_at']) THEN
+ RETURN NEW;
+ END IF;
+ IF old_value IS NOT NULL THEN
+ source_keys := source_keys || account_control_ui_source_keys(TG_TABLE_NAME, old_value);
+ END IF;
+ IF new_value IS NOT NULL THEN
+ source_keys := source_keys || account_control_ui_source_keys(TG_TABLE_NAME, new_value);
+ END IF;
+ PERFORM account_control_ui_hold_required_sources(source_keys);
+ IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
+END;
+$$;
+
+-- Backfill serialization rows from actual owner scopes only; no evidence or grant is backfilled.
+DO $$
+DECLARE
+ table_value TEXT;
+ row_value JSONB;
+ source_key_value TEXT;
+BEGIN
+ FOREACH table_value IN ARRAY ARRAY['accounts','account_authority_generations',
+ 'account_authority_issuance_fences','account_membership_pair_authority',
+ 'account_tenant_membership','account_tenant_membership_role_snapshots',
+ 'account_tenant_membership_role_snapshot_roles','account_individual_creator_party_sources',
+ 'account_tenant_creator_party_history','account_hosted_terms_scopes',
+ 'account_individual_hosted_terms_acceptances','account_hosted_terms_environment_binding_heads'] LOOP
+ FOR row_value IN EXECUTE format('SELECT to_jsonb(t) FROM %I t', table_value) LOOP
+ FOREACH source_key_value IN ARRAY account_control_ui_source_keys(table_value, row_value) LOOP
+ IF source_key_value IS NOT NULL THEN
+ INSERT INTO account_draft_authorization_source_locks(source_key)
+ VALUES(source_key_value) ON CONFLICT DO NOTHING;
+ END IF;
+ END LOOP;
+ END LOOP;
+ EXECUTE format('CREATE TRIGGER account_control_ui_required_source_guard '
+ || 'BEFORE INSERT OR UPDATE OR DELETE ON %I FOR EACH ROW '
+ || 'EXECUTE FUNCTION account_control_ui_required_source_guard()', table_value);
+ EXECUTE format('CREATE TRIGGER account_control_ui_required_source_truncate_guard '
+ || 'BEFORE TRUNCATE ON %I FOR EACH STATEMENT '
+ || 'EXECUTE FUNCTION account_control_ui_required_source_guard()', table_value);
+ END LOOP;
+ FOREACH table_value IN ARRAY ARRAY['account_draft_authorization_source_locks',
+ 'account_draft_authorization_fences','account_draft_authorization_sources',
+ 'account_draft_authorization_owner_readbacks','account_draft_authorization_source_changes',
+ 'account_draft_authorization_changed_scopes'] LOOP
+ EXECUTE format('CREATE TRIGGER account_control_ui_draft_no_truncate '
+ || 'BEFORE TRUNCATE ON %I FOR EACH STATEMENT '
+ || 'EXECUTE FUNCTION account_draft_authorization_immutable_guard()', table_value);
+ END LOOP;
+END;
+$$;
+-- [jooq ignore stop]
diff --git a/services/account-service/src/main/resources/db/migration/V88__account_logout_all_pending_draft_source_changes.sql b/services/account-service/src/main/resources/db/migration/V88__account_logout_all_pending_draft_source_changes.sql
new file mode 100644
index 0000000000..e2c34a085d
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V88__account_logout_all_pending_draft_source_changes.sql
@@ -0,0 +1,295 @@
+-- Logout-all has a richer immutable caller binding than the issuer/tenant V59 journal.
+CREATE TABLE account_logout_all_draft_source_changes (
+ 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 REFERENCES accounts(account_uuid) ON DELETE RESTRICT,
+ request_digest_version INTEGER NOT NULL CHECK (request_digest_version = 1),
+ request_digest BYTEA NOT NULL CHECK (octet_length(request_digest) = 32),
+ token_profile VARCHAR(32) NOT NULL CHECK (token_profile IN ('control-ui', 'player-bootstrap')),
+ presented_token_hash BYTEA NOT NULL CHECK (octet_length(presented_token_hash) = 32),
+ expected_generation BIGINT NOT NULL CHECK (expected_generation > 0),
+ expected_source_version BIGINT NOT NULL CHECK (expected_source_version > 0),
+ expected_issuance_fence BIGINT NOT NULL CHECK (expected_issuance_fence > 0),
+ expected_issuance_fence_source_version BIGINT NOT NULL
+ CHECK (expected_issuance_fence_source_version > 0),
+ checkpoint_stream VARCHAR(2048) NOT NULL,
+ checkpoint_sequence BIGINT NOT NULL CHECK (checkpoint_sequence >= 0),
+ capture_evidence BYTEA NOT NULL CHECK (octet_length(capture_evidence) > 0),
+ request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0),
+ source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0),
+ source_change_id UUID NOT NULL UNIQUE
+ REFERENCES account_draft_authorization_source_changes(change_id)
+ CHECK (source_change_id <> '00000000-0000-0000-0000-000000000000'),
+ source_change_request BYTEA NOT NULL CHECK (octet_length(source_change_request) > 0),
+ source_change_binding BYTEA NOT NULL CHECK (octet_length(source_change_binding) > 0),
+ status VARCHAR(16) NOT NULL CHECK (status IN ('WAITING', 'SOURCE_COMMITTED')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ committed_at TIMESTAMPTZ,
+ event_stream VARCHAR(2048),
+ event_sequence BIGINT CHECK (event_sequence > 0),
+ event_id VARCHAR(128),
+ event_digest VARCHAR(71),
+ event_payload BYTEA,
+ CONSTRAINT account_logout_all_draft_scope_check
+ CHECK (checkpoint_stream = 'account:auth-authority:v1:account/' || account_uuid::TEXT),
+ CONSTRAINT account_logout_all_draft_status_check
+ CHECK ((status = 'WAITING' AND committed_at IS NULL AND event_stream IS NULL
+ AND event_sequence IS NULL AND event_id IS NULL AND event_digest IS NULL
+ AND event_payload IS NULL)
+ OR (status = 'SOURCE_COMMITTED' AND committed_at IS NOT NULL
+ AND event_stream IS NOT NULL AND event_sequence IS NOT NULL
+ AND event_id IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND event_payload IS NOT NULL AND octet_length(event_payload) > 0))
+);
+
+-- [jooq ignore start]
+-- jOOQ's H2 DDL interpreter maps BYTEA to BLOB, which cannot be indexed there.
+-- PostgreSQL still enforces the exact token identity once across pending requests.
+CREATE UNIQUE INDEX account_logout_all_draft_source_token_hash_unique
+ ON account_logout_all_draft_source_changes (presented_token_hash);
+
+CREATE FUNCTION account_logout_all_draft_frame(value BYTEA)
+RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$
+ SELECT int4send(octet_length(value)) || value;
+$$;
+
+CREATE FUNCTION account_logout_all_draft_journal_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE
+ expected_request BYTEA;
+ expected_mutation BYTEA;
+ expected_evidence BYTEA;
+ expected_baseline BYTEA;
+ expected_change BYTEA;
+ expected_key TEXT;
+ persisted_uuid UUID;
+ current_generation BIGINT;
+ current_source_version BIGINT;
+ current_fence BIGINT;
+ current_fence_source_version BIGINT;
+ current_sequence BIGINT;
+BEGIN
+ IF TG_OP = 'UPDATE' THEN
+ IF OLD.status <> 'WAITING' OR NEW.status <> 'SOURCE_COMMITTED'
+ OR NEW.request_id IS DISTINCT FROM OLD.request_id
+ OR NEW.account_id IS DISTINCT FROM OLD.account_id
+ OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid
+ OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version
+ OR NEW.request_digest IS DISTINCT FROM OLD.request_digest
+ OR NEW.token_profile IS DISTINCT FROM OLD.token_profile
+ OR NEW.presented_token_hash IS DISTINCT FROM OLD.presented_token_hash
+ OR NEW.expected_generation IS DISTINCT FROM OLD.expected_generation
+ OR NEW.expected_source_version IS DISTINCT FROM OLD.expected_source_version
+ OR NEW.expected_issuance_fence IS DISTINCT FROM OLD.expected_issuance_fence
+ OR NEW.expected_issuance_fence_source_version IS DISTINCT FROM OLD.expected_issuance_fence_source_version
+ OR NEW.checkpoint_stream IS DISTINCT FROM OLD.checkpoint_stream
+ OR NEW.checkpoint_sequence IS DISTINCT FROM OLD.checkpoint_sequence
+ OR NEW.capture_evidence IS DISTINCT FROM OLD.capture_evidence
+ OR NEW.request_payload IS DISTINCT FROM OLD.request_payload
+ OR NEW.source_evidence IS DISTINCT FROM OLD.source_evidence
+ OR NEW.source_change_id IS DISTINCT FROM OLD.source_change_id
+ OR NEW.source_change_request IS DISTINCT FROM OLD.source_change_request
+ OR NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding
+ OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN
+ RAISE EXCEPTION 'Logout-all Draft source intent and original capture are immutable'
+ USING ERRCODE = '23514';
+ END IF;
+ NEW.committed_at = CURRENT_TIMESTAMP;
+ ELSE
+ IF NEW.status <> 'WAITING' THEN
+ RAISE EXCEPTION 'Logout-all Draft source intent must begin WAITING'
+ USING ERRCODE = '23514';
+ END IF;
+ SELECT account_uuid INTO persisted_uuid FROM accounts WHERE id = NEW.account_id;
+ IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN
+ RAISE EXCEPTION 'Logout-all Draft intent Account association does not match'
+ USING ERRCODE = '23514';
+ END IF;
+
+ expected_request := account_logout_all_draft_frame(convert_to('account-logout-all-draft-source-request/v1', 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.request_id::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.account_id::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.request_digest_version::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(NEW.request_digest)
+ || account_logout_all_draft_frame(convert_to(NEW.token_profile, 'UTF8'))
+ || account_logout_all_draft_frame(NEW.presented_token_hash);
+ expected_evidence := account_logout_all_draft_frame(convert_to('account-draft-source-evidence/v1', 'UTF8'))
+ || account_logout_all_draft_frame(convert_to('ACCOUNT', 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to('PRESENT', 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.expected_generation::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.expected_source_version::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to('PRESENT', 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.checkpoint_stream, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.checkpoint_sequence::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(NEW.capture_evidence);
+ expected_mutation := account_logout_all_draft_frame(convert_to('account-logout-all-draft-source-mutation/v1', 'UTF8'))
+ || account_logout_all_draft_frame(NEW.request_payload)
+ || account_logout_all_draft_frame(convert_to(NEW.expected_generation::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.expected_source_version::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.expected_issuance_fence::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.expected_issuance_fence_source_version::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.checkpoint_sequence::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(NEW.source_evidence);
+ expected_change := account_logout_all_draft_frame(convert_to('account-draft-source-change/v1', 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.source_change_id::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to('1', 'UTF8'))
+ || account_logout_all_draft_frame(NEW.source_evidence)
+ || account_logout_all_draft_frame(NEW.source_change_request);
+ expected_key := 'ACCOUNT:' || NEW.account_uuid::TEXT;
+ IF NEW.request_payload IS DISTINCT FROM expected_request
+ OR NEW.source_evidence IS DISTINCT FROM expected_evidence
+ OR NEW.source_change_request IS DISTINCT FROM expected_mutation
+ OR NEW.source_change_binding IS DISTINCT FROM expected_change
+ OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_source_changes
+ WHERE change_id = NEW.source_change_id AND status = 'WAITING'
+ AND binding = expected_change)
+ OR (SELECT count(*) FROM account_draft_authorization_changed_scopes
+ WHERE change_id = NEW.source_change_id) <> 1
+ OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_changed_scopes
+ WHERE change_id = NEW.source_change_id AND source_key = expected_key) THEN
+ RAISE EXCEPTION 'Logout-all request must bind its exact V57 Account source intent'
+ USING ERRCODE = '23514';
+ END IF;
+
+ SELECT generation, source_version INTO current_generation, current_source_version
+ FROM account_authority_generations
+ WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid;
+ SELECT issuance_fence, source_version INTO current_fence, current_fence_source_version
+ FROM account_authority_issuance_fences WHERE account_uuid = NEW.account_uuid;
+ IF current_generation IS DISTINCT FROM NEW.expected_generation
+ OR current_source_version IS DISTINCT FROM NEW.expected_source_version
+ OR current_fence IS DISTINCT FROM NEW.expected_issuance_fence
+ OR current_fence_source_version IS DISTINCT FROM NEW.expected_issuance_fence_source_version THEN
+ RAISE EXCEPTION 'Logout-all Draft capture differs from current Account source counters'
+ USING ERRCODE = '23514';
+ END IF;
+ SELECT last_sequence INTO current_sequence FROM account_authority_outbox_streams
+ WHERE outbox_stream_key = NEW.checkpoint_stream;
+ IF NEW.checkpoint_sequence = 0 THEN
+ expected_baseline := account_logout_all_draft_frame(convert_to('account-draft-source-baseline/v1', 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to('1', 'UTF8'))
+ || account_logout_all_draft_frame(convert_to('1', 'UTF8'))
+ || account_logout_all_draft_frame(convert_to(NEW.checkpoint_stream, 'UTF8'))
+ || account_logout_all_draft_frame(convert_to('0', 'UTF8'));
+ IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1
+ OR NEW.capture_evidence IS DISTINCT FROM expected_baseline
+ OR (current_sequence IS NOT NULL AND current_sequence <> 0)
+ OR EXISTS (SELECT 1 FROM account_authority_outbox_events
+ WHERE outbox_stream_key = NEW.checkpoint_stream) THEN
+ RAISE EXCEPTION 'Logout-all zero checkpoint lacks exact pristine source evidence'
+ USING ERRCODE = '23514';
+ END IF;
+ ELSIF current_sequence IS DISTINCT FROM NEW.checkpoint_sequence
+ OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events
+ WHERE outbox_stream_key = NEW.checkpoint_stream
+ AND outbox_sequence = NEW.checkpoint_sequence
+ AND payload = NEW.capture_evidence) THEN
+ RAISE EXCEPTION 'Logout-all capture does not bind the exact current Account event'
+ USING ERRCODE = '23514';
+ END IF;
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE FUNCTION account_logout_all_draft_link_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE
+ journal account_logout_all_draft_source_changes%ROWTYPE;
+ source_status TEXT;
+ source_binding BYTEA;
+ selected_change UUID;
+ persisted_generation BIGINT;
+ persisted_source_version BIGINT;
+ persisted_fence BIGINT;
+ persisted_fence_source_version BIGINT;
+BEGIN
+ IF TG_TABLE_NAME = 'account_logout_all_draft_source_changes' THEN
+ selected_change := NEW.source_change_id;
+ ELSE
+ selected_change := NEW.change_id;
+ END IF;
+ SELECT * INTO journal FROM account_logout_all_draft_source_changes
+ WHERE source_change_id = selected_change;
+ IF NOT FOUND THEN
+ RETURN NULL;
+ END IF;
+ SELECT status, binding INTO source_status, source_binding
+ FROM account_draft_authorization_source_changes WHERE change_id = selected_change;
+ IF source_status IS DISTINCT FROM journal.status
+ OR source_binding IS DISTINCT FROM journal.source_change_binding THEN
+ RAISE EXCEPTION 'Logout-all journal and V57 Account source transition must commit together'
+ USING ERRCODE = '23514';
+ END IF;
+ IF journal.status = 'WAITING' AND EXISTS (SELECT 1 FROM account_authority_outbox_events
+ WHERE outbox_stream_key = journal.checkpoint_stream
+ AND request_id = journal.request_id::TEXT) THEN
+ RAISE EXCEPTION 'A WAITING logout-all request cannot publish its source event'
+ USING ERRCODE = '23514';
+ END IF;
+ IF journal.status = 'SOURCE_COMMITTED' AND (
+ journal.event_stream IS DISTINCT FROM journal.checkpoint_stream
+ OR journal.event_id IS DISTINCT FROM 'account-logout-all-event-v1:' || journal.request_id::TEXT
+ OR journal.event_sequence IS DISTINCT FROM journal.checkpoint_sequence + 1
+ OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events
+ WHERE outbox_stream_key = journal.event_stream AND outbox_sequence = journal.event_sequence
+ AND request_id = journal.request_id::TEXT AND event_id = journal.event_id
+ AND event_digest = journal.event_digest AND payload = journal.event_payload)
+ OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_streams
+ WHERE outbox_stream_key = journal.event_stream AND last_sequence = journal.event_sequence)
+ OR NOT EXISTS (SELECT 1 FROM account_logout_all_operation_receipts
+ WHERE request_id = journal.request_id AND account_id = journal.account_id
+ AND account_uuid = journal.account_uuid
+ AND request_digest_version = journal.request_digest_version
+ AND request_digest = journal.request_digest AND token_profile = journal.token_profile
+ AND presented_token_hash = journal.presented_token_hash
+ AND outbox_stream_key = journal.event_stream
+ AND outbox_sequence = journal.event_sequence
+ AND event_id = journal.event_id AND event_digest = journal.event_digest
+ AND account_authority_generation = journal.expected_generation + 1
+ AND account_source_version = journal.expected_source_version + 1
+ AND issuance_fence = journal.expected_issuance_fence + 1
+ AND issuance_fence_source_version = journal.expected_issuance_fence_source_version + 1)) THEN
+ RAISE EXCEPTION 'Committed logout-all intent lacks its exact receipt, event, or checkpoint'
+ USING ERRCODE = '23514';
+ END IF;
+ IF journal.status = 'SOURCE_COMMITTED' THEN
+ SELECT generation, source_version INTO persisted_generation, persisted_source_version
+ FROM account_authority_generations
+ WHERE scope_kind = 'ACCOUNT' AND account_uuid = journal.account_uuid;
+ SELECT issuance_fence, source_version INTO persisted_fence, persisted_fence_source_version
+ FROM account_authority_issuance_fences WHERE account_uuid = journal.account_uuid;
+ IF persisted_generation IS DISTINCT FROM journal.expected_generation + 1
+ OR persisted_source_version IS DISTINCT FROM journal.expected_source_version + 1
+ OR persisted_fence IS DISTINCT FROM journal.expected_issuance_fence + 1
+ OR persisted_fence_source_version
+ IS DISTINCT FROM journal.expected_issuance_fence_source_version + 1 THEN
+ RAISE EXCEPTION 'Logout-all Account authority counters did not advance once from capture'
+ USING ERRCODE = '23514';
+ END IF;
+ END IF;
+ RETURN NULL;
+END;
+$$;
+
+CREATE TRIGGER account_logout_all_draft_source_request_guard
+ BEFORE INSERT OR UPDATE ON account_logout_all_draft_source_changes
+ FOR EACH ROW EXECUTE FUNCTION account_logout_all_draft_journal_guard();
+CREATE TRIGGER account_logout_all_draft_source_delete_guard
+ BEFORE DELETE ON account_logout_all_draft_source_changes
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard();
+CREATE TRIGGER account_logout_all_draft_source_truncate_guard
+ BEFORE TRUNCATE ON account_logout_all_draft_source_changes
+ FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard();
+CREATE CONSTRAINT TRIGGER account_logout_all_draft_source_complete_guard
+ AFTER INSERT OR UPDATE ON account_logout_all_draft_source_changes
+ DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_logout_all_draft_link_guard();
+CREATE CONSTRAINT TRIGGER account_logout_all_draft_source_v57_link_guard
+ AFTER INSERT OR UPDATE ON account_draft_authorization_source_changes
+ DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_logout_all_draft_link_guard();
+-- [jooq ignore stop]
diff --git a/services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql b/services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql
new file mode 100644
index 0000000000..fa5e2218c3
--- /dev/null
+++ b/services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql
@@ -0,0 +1,378 @@
+-- V89 persists exact password-reset source intent while V76 owner outcomes settle.
+CREATE TABLE account_password_reset_draft_source_changes (
+ token_hash BYTEA NOT NULL CHECK (octet_length(token_hash) = 32),
+ account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT,
+ account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT,
+ account_uuid_provenance VARCHAR(40) NOT NULL,
+ account_uuid_source_numeric_id BIGINT NOT NULL CHECK (account_uuid_source_numeric_id > 0),
+ token_id BIGINT NOT NULL CHECK (token_id > 0),
+ request_id VARCHAR(128) NOT NULL UNIQUE,
+ event_id VARCHAR(128) NOT NULL UNIQUE,
+ request_digest_version INTEGER NOT NULL CHECK (request_digest_version = 1),
+ request_digest BYTEA NOT NULL CHECK (octet_length(request_digest) = 32),
+ password_verifier VARCHAR(255) NOT NULL CHECK (length(btrim(password_verifier)) > 0),
+ password_verifier_digest BYTEA NOT NULL CHECK (octet_length(password_verifier_digest) = 32),
+ token_expires_at TIMESTAMP WITHOUT TIME ZONE NOT NULL,
+ token_expires_epoch_nanos BIGINT NOT NULL CHECK (token_expires_epoch_nanos > 0),
+ expected_generation BIGINT NOT NULL CHECK (expected_generation > 0),
+ expected_source_version BIGINT NOT NULL CHECK (expected_source_version > 0),
+ expected_issuance_fence BIGINT NOT NULL CHECK (expected_issuance_fence > 0),
+ expected_issuance_fence_source_version BIGINT NOT NULL
+ CHECK (expected_issuance_fence_source_version > 0),
+ checkpoint_stream VARCHAR(2048) NOT NULL,
+ checkpoint_sequence BIGINT NOT NULL CHECK (checkpoint_sequence >= 0),
+ capture_evidence BYTEA NOT NULL CHECK (octet_length(capture_evidence) > 0),
+ request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0),
+ source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0),
+ source_change_id UUID NOT NULL UNIQUE
+ REFERENCES account_draft_authorization_source_changes(change_id)
+ CHECK (source_change_id <> '00000000-0000-0000-0000-000000000000'::UUID),
+ source_change_request BYTEA NOT NULL CHECK (octet_length(source_change_request) > 0),
+ source_change_binding BYTEA NOT NULL CHECK (octet_length(source_change_binding) > 0),
+ status VARCHAR(16) NOT NULL CHECK (status IN ('WAITING', 'SOURCE_COMMITTED', 'SOURCE_ABORTED')),
+ abort_reason VARCHAR(32) CHECK (abort_reason IN ('EXPIRED', 'DEFINITIVE_ABORT')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ committed_at TIMESTAMPTZ,
+ aborted_at TIMESTAMPTZ,
+ event_stream VARCHAR(2048),
+ event_sequence BIGINT CHECK (event_sequence > 0),
+ event_digest VARCHAR(71),
+ event_payload BYTEA,
+ CONSTRAINT account_password_reset_draft_identity_check
+ CHECK (account_id > 0 AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID
+ AND account_uuid_source_numeric_id = account_id
+ AND request_id = 'account-password-reset-request-v1:' || encode(token_hash, 'hex')
+ AND event_id = 'account-password-reset-event-v1:' || encode(token_hash, 'hex')),
+ CONSTRAINT account_password_reset_draft_scope_check
+ CHECK (checkpoint_stream = 'account:auth-authority:v1:account/' || account_uuid::TEXT),
+ CONSTRAINT account_password_reset_draft_status_check
+ CHECK ((status = 'WAITING' AND abort_reason IS NULL AND committed_at IS NULL
+ AND aborted_at IS NULL AND event_stream IS NULL AND event_sequence IS NULL
+ AND event_digest IS NULL AND event_payload IS NULL)
+ OR (status = 'SOURCE_COMMITTED' AND abort_reason IS NULL AND committed_at IS NOT NULL
+ AND aborted_at IS NULL AND event_stream IS NOT NULL AND event_sequence IS NOT NULL
+ AND event_digest ~ '^sha256:[0-9a-f]{64}$'
+ AND event_payload IS NOT NULL AND octet_length(event_payload) > 0)
+ OR (status = 'SOURCE_ABORTED' AND abort_reason IS NOT NULL AND committed_at IS NULL
+ AND aborted_at IS NOT NULL AND event_stream IS NULL AND event_sequence IS NULL
+ AND event_digest IS NULL AND event_payload IS NULL))
+);
+
+-- [jooq ignore start]
+-- PostgreSQL supports the BYTEA key; jOOQ's H2 DDL interpreter cannot index its BLOB mapping.
+ALTER TABLE account_password_reset_draft_source_changes
+ ADD CONSTRAINT account_password_reset_draft_source_changes_pk PRIMARY KEY (token_hash);
+
+CREATE FUNCTION account_password_reset_draft_frame(value BYTEA)
+RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$
+ SELECT int4send(octet_length(value)) || value;
+$$;
+
+CREATE FUNCTION account_password_reset_draft_journal_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE
+ expected_request BYTEA;
+ expected_mutation BYTEA;
+ expected_evidence BYTEA;
+ expected_baseline BYTEA;
+ expected_change BYTEA;
+ expected_key TEXT;
+ persisted_uuid UUID;
+ persisted_provenance TEXT;
+ persisted_source_id BIGINT;
+ token_account BIGINT;
+ token_deadline TIMESTAMP WITHOUT TIME ZONE;
+ current_generation BIGINT;
+ current_source_version BIGINT;
+ current_fence BIGINT;
+ current_fence_source_version BIGINT;
+ current_sequence BIGINT;
+BEGIN
+ IF TG_OP = 'UPDATE' THEN
+ IF OLD.status <> 'WAITING' OR NEW.status NOT IN ('SOURCE_COMMITTED', 'SOURCE_ABORTED')
+ OR NEW.token_hash IS DISTINCT FROM OLD.token_hash
+ OR NEW.account_id IS DISTINCT FROM OLD.account_id
+ OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid
+ OR NEW.account_uuid_provenance IS DISTINCT FROM OLD.account_uuid_provenance
+ OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM OLD.account_uuid_source_numeric_id
+ OR NEW.token_id IS DISTINCT FROM OLD.token_id
+ OR NEW.request_id IS DISTINCT FROM OLD.request_id
+ OR NEW.event_id IS DISTINCT FROM OLD.event_id
+ OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version
+ OR NEW.request_digest IS DISTINCT FROM OLD.request_digest
+ OR NEW.password_verifier IS DISTINCT FROM OLD.password_verifier
+ OR NEW.password_verifier_digest IS DISTINCT FROM OLD.password_verifier_digest
+ OR NEW.token_expires_at IS DISTINCT FROM OLD.token_expires_at
+ OR NEW.token_expires_epoch_nanos IS DISTINCT FROM OLD.token_expires_epoch_nanos
+ OR NEW.expected_generation IS DISTINCT FROM OLD.expected_generation
+ OR NEW.expected_source_version IS DISTINCT FROM OLD.expected_source_version
+ OR NEW.expected_issuance_fence IS DISTINCT FROM OLD.expected_issuance_fence
+ OR NEW.expected_issuance_fence_source_version IS DISTINCT FROM OLD.expected_issuance_fence_source_version
+ OR NEW.checkpoint_stream IS DISTINCT FROM OLD.checkpoint_stream
+ OR NEW.checkpoint_sequence IS DISTINCT FROM OLD.checkpoint_sequence
+ OR NEW.capture_evidence IS DISTINCT FROM OLD.capture_evidence
+ OR NEW.request_payload IS DISTINCT FROM OLD.request_payload
+ OR NEW.source_evidence IS DISTINCT FROM OLD.source_evidence
+ OR NEW.source_change_id IS DISTINCT FROM OLD.source_change_id
+ OR NEW.source_change_request IS DISTINCT FROM OLD.source_change_request
+ OR NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding
+ OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN
+ RAISE EXCEPTION 'Password-reset Draft source intent and original capture are immutable'
+ USING ERRCODE = '23514';
+ END IF;
+ IF NEW.status = 'SOURCE_COMMITTED' THEN
+ IF NEW.abort_reason IS NOT NULL OR NEW.aborted_at IS NOT NULL
+ OR NEW.event_stream IS NULL OR NEW.event_sequence IS NULL
+ OR NEW.event_id IS DISTINCT FROM OLD.event_id
+ OR NEW.event_digest IS NULL OR NEW.event_payload IS NULL THEN
+ RAISE EXCEPTION 'Committed password-reset source result is incomplete'
+ USING ERRCODE = '23514';
+ END IF;
+ NEW.committed_at = CURRENT_TIMESTAMP;
+ ELSE
+ IF NEW.abort_reason NOT IN ('EXPIRED', 'DEFINITIVE_ABORT')
+ OR NEW.event_stream IS NOT NULL OR NEW.event_sequence IS NOT NULL
+ OR NEW.event_digest IS NOT NULL OR NEW.event_payload IS NOT NULL THEN
+ RAISE EXCEPTION 'Aborted password-reset source result must contain no mutation'
+ USING ERRCODE = '23514';
+ END IF;
+ NEW.aborted_at = CURRENT_TIMESTAMP;
+ END IF;
+ RETURN NEW;
+ END IF;
+
+ IF NEW.status <> 'WAITING' OR NEW.abort_reason IS NOT NULL
+ OR NEW.committed_at IS NOT NULL OR NEW.aborted_at IS NOT NULL
+ OR NEW.event_stream IS NOT NULL OR NEW.event_sequence IS NOT NULL
+ OR NEW.event_digest IS NOT NULL OR NEW.event_payload IS NOT NULL THEN
+ RAISE EXCEPTION 'Password-reset Draft source intent must begin WAITING'
+ USING ERRCODE = '23514';
+ END IF;
+
+ SELECT account_uuid, account_uuid_provenance, account_uuid_source_numeric_id
+ INTO persisted_uuid, persisted_provenance, persisted_source_id
+ FROM accounts WHERE id = NEW.account_id;
+ IF persisted_uuid IS DISTINCT FROM NEW.account_uuid
+ OR persisted_provenance IS DISTINCT FROM NEW.account_uuid_provenance
+ OR persisted_source_id IS DISTINCT FROM NEW.account_uuid_source_numeric_id
+ OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM NEW.account_id THEN
+ RAISE EXCEPTION 'Password-reset Draft intent Account identity differs from persisted source'
+ USING ERRCODE = '23514';
+ END IF;
+ SELECT account_id, expires_at INTO token_account, token_deadline
+ FROM password_reset_token WHERE id = NEW.token_id;
+ IF token_account IS DISTINCT FROM NEW.account_id OR token_deadline IS DISTINCT FROM NEW.token_expires_at
+ OR NEW.token_expires_epoch_nanos IS DISTINCT FROM
+ ((extract(epoch FROM (NEW.token_expires_at AT TIME ZONE 'UTC')) * 1000000000)::numeric)::bigint THEN
+ RAISE EXCEPTION 'Password-reset Draft intent does not bind its exact token row and deadline'
+ USING ERRCODE = '23514';
+ END IF;
+
+ expected_request := account_password_reset_draft_frame(convert_to('account-password-reset-draft-source-request/v1', 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.request_id, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.account_id::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.token_id::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(NEW.token_hash)
+ || account_password_reset_draft_frame(convert_to(NEW.token_expires_epoch_nanos::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to('1', 'UTF8'))
+ || account_password_reset_draft_frame(NEW.request_digest)
+ || account_password_reset_draft_frame(NEW.password_verifier_digest)
+ || account_password_reset_draft_frame(convert_to(NEW.account_uuid_provenance, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.account_uuid_source_numeric_id::TEXT, 'UTF8'));
+ expected_evidence := account_password_reset_draft_frame(convert_to('account-draft-source-evidence/v1', 'UTF8'))
+ || account_password_reset_draft_frame(convert_to('ACCOUNT', 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to('PRESENT', 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.expected_generation::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.expected_source_version::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to('PRESENT', 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.checkpoint_stream, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.checkpoint_sequence::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(NEW.capture_evidence);
+ expected_mutation := account_password_reset_draft_frame(convert_to('account-password-reset-draft-source-mutation/v1', 'UTF8'))
+ || account_password_reset_draft_frame(NEW.request_payload)
+ || account_password_reset_draft_frame(convert_to(NEW.expected_generation::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.expected_source_version::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.expected_issuance_fence::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.expected_issuance_fence_source_version::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.checkpoint_sequence::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(NEW.source_evidence)
+ || account_password_reset_draft_frame(convert_to((NEW.expected_generation + 1)::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to((NEW.expected_source_version + 1)::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to((NEW.expected_issuance_fence + 1)::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to((NEW.expected_issuance_fence_source_version + 1)::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to((NEW.checkpoint_sequence + 1)::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.request_id, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.event_id, 'UTF8'));
+ expected_change := account_password_reset_draft_frame(convert_to('account-draft-source-change/v1', 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.source_change_id::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to('1', 'UTF8'))
+ || account_password_reset_draft_frame(NEW.source_evidence)
+ || account_password_reset_draft_frame(NEW.source_change_request);
+ expected_key := 'ACCOUNT:' || NEW.account_uuid::TEXT;
+ IF NEW.request_id IS DISTINCT FROM 'account-password-reset-request-v1:' || encode(NEW.token_hash, 'hex')
+ OR NEW.event_id IS DISTINCT FROM 'account-password-reset-event-v1:' || encode(NEW.token_hash, 'hex')
+ OR NEW.checkpoint_stream IS DISTINCT FROM 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT
+ OR NEW.request_payload IS DISTINCT FROM expected_request
+ OR NEW.source_evidence IS DISTINCT FROM expected_evidence
+ OR NEW.source_change_request IS DISTINCT FROM expected_mutation
+ OR NEW.source_change_binding IS DISTINCT FROM expected_change
+ OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_source_changes
+ WHERE change_id = NEW.source_change_id AND status = 'WAITING' AND binding = expected_change)
+ OR (SELECT count(*) FROM account_draft_authorization_changed_scopes
+ WHERE change_id = NEW.source_change_id) <> 1
+ OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_changed_scopes
+ WHERE change_id = NEW.source_change_id AND source_key = expected_key) THEN
+ RAISE EXCEPTION 'Password-reset request must bind its exact V76 Account source intent'
+ USING ERRCODE = '23514';
+ END IF;
+
+ SELECT generation, source_version INTO current_generation, current_source_version
+ FROM account_authority_generations
+ WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid;
+ SELECT issuance_fence, source_version INTO current_fence, current_fence_source_version
+ FROM account_authority_issuance_fences WHERE account_uuid = NEW.account_uuid;
+ IF current_generation IS DISTINCT FROM NEW.expected_generation
+ OR current_source_version IS DISTINCT FROM NEW.expected_source_version
+ OR current_fence IS DISTINCT FROM NEW.expected_issuance_fence
+ OR current_fence_source_version IS DISTINCT FROM NEW.expected_issuance_fence_source_version THEN
+ RAISE EXCEPTION 'Password-reset Draft capture differs from current Account source counters'
+ USING ERRCODE = '23514';
+ END IF;
+ SELECT last_sequence INTO current_sequence FROM account_authority_outbox_streams
+ WHERE outbox_stream_key = NEW.checkpoint_stream;
+ IF NEW.checkpoint_sequence = 0 THEN
+ expected_baseline := account_password_reset_draft_frame(convert_to('account-draft-source-baseline/v1', 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to('1', 'UTF8'))
+ || account_password_reset_draft_frame(convert_to('1', 'UTF8'))
+ || account_password_reset_draft_frame(convert_to(NEW.checkpoint_stream, 'UTF8'))
+ || account_password_reset_draft_frame(convert_to('0', 'UTF8'));
+ IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1
+ OR NEW.capture_evidence IS DISTINCT FROM expected_baseline
+ OR (current_sequence IS NOT NULL AND current_sequence <> 0)
+ OR EXISTS (SELECT 1 FROM account_authority_outbox_events
+ WHERE outbox_stream_key = NEW.checkpoint_stream) THEN
+ RAISE EXCEPTION 'Password-reset zero checkpoint lacks exact pristine source evidence'
+ USING ERRCODE = '23514';
+ END IF;
+ ELSIF current_sequence IS DISTINCT FROM NEW.checkpoint_sequence
+ OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events
+ WHERE outbox_stream_key = NEW.checkpoint_stream
+ AND outbox_sequence = NEW.checkpoint_sequence
+ AND payload = NEW.capture_evidence) THEN
+ RAISE EXCEPTION 'Password-reset capture does not bind the exact current Account event'
+ USING ERRCODE = '23514';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE FUNCTION account_password_reset_draft_link_guard()
+RETURNS TRIGGER LANGUAGE plpgsql AS $$
+DECLARE
+ journal account_password_reset_draft_source_changes%ROWTYPE;
+ source_status TEXT;
+ source_binding BYTEA;
+ selected_change UUID;
+ persisted_generation BIGINT;
+ persisted_source_version BIGINT;
+ persisted_fence BIGINT;
+ persisted_fence_source_version BIGINT;
+BEGIN
+ IF TG_TABLE_NAME = 'account_password_reset_draft_source_changes' THEN
+ selected_change := NEW.source_change_id;
+ ELSE
+ selected_change := NEW.change_id;
+ END IF;
+ SELECT * INTO journal FROM account_password_reset_draft_source_changes
+ WHERE source_change_id = selected_change;
+ IF NOT FOUND THEN
+ RETURN NULL;
+ END IF;
+ SELECT status, binding INTO source_status, source_binding
+ FROM account_draft_authorization_source_changes WHERE change_id = selected_change;
+ IF source_status IS DISTINCT FROM journal.status OR source_binding IS DISTINCT FROM journal.source_change_binding THEN
+ RAISE EXCEPTION 'Password-reset journal and V76 source transition must commit together'
+ USING ERRCODE = '23514';
+ END IF;
+ IF journal.status = 'WAITING' AND (
+ EXISTS (SELECT 1 FROM account_password_reset_operation_receipts WHERE token_hash = journal.token_hash)
+ OR EXISTS (SELECT 1 FROM account_authority_outbox_events
+ WHERE outbox_stream_key = journal.checkpoint_stream AND request_id = journal.request_id)) THEN
+ RAISE EXCEPTION 'WAITING password-reset intent cannot publish or complete its receipt'
+ USING ERRCODE = '23514';
+ END IF;
+ IF journal.status = 'SOURCE_ABORTED' AND (
+ EXISTS (SELECT 1 FROM account_password_reset_operation_receipts WHERE token_hash = journal.token_hash)
+ OR EXISTS (SELECT 1 FROM account_authority_outbox_events
+ WHERE outbox_stream_key = journal.checkpoint_stream AND request_id = journal.request_id)) THEN
+ RAISE EXCEPTION 'Aborted password-reset intent cannot contain a source mutation'
+ USING ERRCODE = '23514';
+ END IF;
+ IF journal.status = 'SOURCE_COMMITTED' AND (
+ journal.event_stream IS DISTINCT FROM journal.checkpoint_stream
+ OR journal.event_id IS DISTINCT FROM 'account-password-reset-event-v1:' || encode(journal.token_hash, 'hex')
+ OR journal.event_sequence IS DISTINCT FROM journal.checkpoint_sequence + 1
+ OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events
+ WHERE outbox_stream_key = journal.event_stream AND outbox_sequence = journal.event_sequence
+ AND request_id = journal.request_id AND event_id = journal.event_id
+ AND event_digest = journal.event_digest AND payload = journal.event_payload)
+ OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_streams
+ WHERE outbox_stream_key = journal.event_stream AND last_sequence = journal.event_sequence)
+ OR NOT EXISTS (SELECT 1 FROM account_password_reset_operation_receipts
+ WHERE token_hash = journal.token_hash AND account_id = journal.account_id
+ AND account_uuid = journal.account_uuid AND request_id = journal.request_id
+ AND request_digest_version = journal.request_digest_version
+ AND request_digest = journal.request_digest
+ AND token_expires_at = journal.token_expires_at
+ AND password_verifier_digest = journal.password_verifier_digest
+ AND outbox_stream_key = journal.event_stream AND outbox_sequence = journal.event_sequence
+ AND event_id = journal.event_id AND event_digest = journal.event_digest
+ AND account_authority_generation = journal.expected_generation + 1
+ AND account_source_version = journal.expected_source_version + 1
+ AND issuance_fence = journal.expected_issuance_fence + 1
+ AND issuance_fence_source_version = journal.expected_issuance_fence_source_version + 1)
+ OR EXISTS (SELECT 1 FROM password_reset_token WHERE id = journal.token_id)
+ OR NOT EXISTS (SELECT 1 FROM accounts WHERE id = journal.account_id
+ AND account_uuid = journal.account_uuid AND password_hash = journal.password_verifier)) THEN
+ RAISE EXCEPTION 'Committed password-reset intent lacks exact receipt, event, token, or Account readback'
+ USING ERRCODE = '23514';
+ END IF;
+ IF journal.status = 'SOURCE_COMMITTED' THEN
+ SELECT generation, source_version INTO persisted_generation, persisted_source_version
+ FROM account_authority_generations
+ WHERE scope_kind = 'ACCOUNT' AND account_uuid = journal.account_uuid;
+ SELECT issuance_fence, source_version INTO persisted_fence, persisted_fence_source_version
+ FROM account_authority_issuance_fences WHERE account_uuid = journal.account_uuid;
+ IF persisted_generation IS DISTINCT FROM journal.expected_generation + 1
+ OR persisted_source_version IS DISTINCT FROM journal.expected_source_version + 1
+ OR persisted_fence IS DISTINCT FROM journal.expected_issuance_fence + 1
+ OR persisted_fence_source_version IS DISTINCT FROM journal.expected_issuance_fence_source_version + 1 THEN
+ RAISE EXCEPTION 'Password-reset Account authority counters did not advance once from capture'
+ USING ERRCODE = '23514';
+ END IF;
+ END IF;
+ RETURN NULL;
+END;
+$$;
+
+CREATE TRIGGER account_password_reset_draft_journal_guard
+ BEFORE INSERT OR UPDATE ON account_password_reset_draft_source_changes
+ FOR EACH ROW EXECUTE FUNCTION account_password_reset_draft_journal_guard();
+CREATE TRIGGER account_password_reset_draft_delete_guard
+ BEFORE DELETE ON account_password_reset_draft_source_changes
+ FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard();
+CREATE TRIGGER account_password_reset_draft_truncate_guard
+ BEFORE TRUNCATE ON account_password_reset_draft_source_changes
+ FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard();
+CREATE CONSTRAINT TRIGGER account_password_reset_draft_complete_guard
+ AFTER INSERT OR UPDATE ON account_password_reset_draft_source_changes
+ DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_password_reset_draft_link_guard();
+CREATE CONSTRAINT TRIGGER account_password_reset_draft_v76_link_guard
+ AFTER INSERT OR UPDATE ON account_draft_authorization_source_changes
+ DEFERRABLE INITIALLY DEFERRED
+ FOR EACH ROW EXECUTE FUNCTION account_password_reset_draft_link_guard();
+-- [jooq ignore stop]
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
new file mode 100644
index 0000000000..c7122f94ea
--- /dev/null
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java
@@ -0,0 +1,730 @@
+package integration.net.firedevops.firemud.accountservice;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.LocalDateTime;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Supplier;
+import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository;
+import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.PasswordResetToken;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.OperationConflictException;
+import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository;
+import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository;
+import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository;
+import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl;
+import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+import net.firedevops.firemud.common.authoring.DraftCommitBinding;
+import org.flywaydb.core.Flyway;
+import org.jooq.DSLContext;
+import org.jooq.SQLDialect;
+import org.jooq.exception.DataAccessException;
+import org.jooq.impl.DSL;
+import org.junit.jupiter.api.Test;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.support.TransactionTemplate;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+@Testcontainers(disabledWithoutDocker = true)
+class PasswordResetAuthorityProducerPostgresIntegrationTest {
+ private static final String SCHEMA_PREFIX = "password_reset_source_proof";
+ private static final String STREAM_PREFIX = "account:auth-authority:v1:account/";
+ private static final String REQUEST_PREFIX = "account-password-reset-request-v1:";
+ private static final String EVENT_PREFIX = "account-password-reset-event-v1:";
+
+ @Container
+ static PostgreSQLContainer> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
+
+ @Test
+ void commitsPasswordTokenAuthorityFenceClosedEventAndImmutableReceiptTogether() {
+ Fixture fixture = newFixture();
+ Seed seed = seedAccountAndToken(fixture, "initial-password");
+
+ reset(fixture, seed.rawToken(), "new-password-one");
+
+ Account account = account(fixture, seed.accountId());
+ ScopeState authority = readAuthority(fixture, seed.accountUuid());
+ String streamKey = streamKey(seed.accountUuid());
+ PasswordResetReceipt receipt =
+ transaction(
+ fixture.transaction(),
+ () -> fixture.operations().findByTokenHash(tokenHash(seed.rawToken())).orElseThrow());
+ var checkpoint =
+ transaction(
+ fixture.transaction(), () -> fixture.outbox().readCheckpoint(streamKey).orElseThrow());
+ var event =
+ transaction(
+ fixture.transaction(),
+ () -> fixture.outbox().findEvent(streamKey, receipt.outboxSequence()).orElseThrow());
+ var decoded =
+ PasswordResetAuthorityEventV1Codec.verify(
+ new String(event.payload(), StandardCharsets.UTF_8));
+ String payload = new String(event.payload(), StandardCharsets.UTF_8);
+
+ assertThat(account.getPasswordHash()).isNotEqualTo(seed.originalVerifier());
+ assertThat(account.getPasswordHash()).startsWith("$argon2");
+ assertThat(authority.generation()).isEqualTo(2L);
+ assertThat(authority.sourceVersion()).isEqualTo(2L);
+ assertThat(authority.issuanceFence().value()).isEqualTo(2L);
+ assertThat(authority.issuanceFence().sourceVersion()).isEqualTo(2L);
+ assertThat(tokenExists(fixture, seed.rawToken())).isFalse();
+ assertThat(receipt.accountId()).isEqualTo(seed.accountId());
+ assertThat(receipt.accountUuid()).isEqualTo(seed.accountUuid());
+ assertThat(receipt.tokenHash()).isEqualTo(tokenHash(seed.rawToken()));
+ assertThat(receipt.tokenExpiresAt()).isEqualTo(seed.deadline());
+ assertThat(receipt.passwordVerifierDigest()).isEqualTo(sha256Hex(account.getPasswordHash()));
+ assertThat(receipt.eventId()).isEqualTo(EVENT_PREFIX + tokenHash(seed.rawToken()));
+ assertThat(receipt.requestId()).isEqualTo(REQUEST_PREFIX + tokenHash(seed.rawToken()));
+ assertThat(checkpoint.outboxSequence()).isEqualTo(receipt.outboxSequence());
+ assertThat(checkpoint.sourceEventId()).isEqualTo(receipt.eventId());
+ assertThat(checkpoint.sourceEventDigest()).isEqualTo(receipt.eventDigest());
+ assertThat(decoded.accountId()).isEqualTo(seed.accountUuid().toString());
+ assertThat(decoded.accountAuthorityGeneration()).isEqualTo("2");
+ assertThat(decoded.sourceVersion()).isEqualTo("2");
+ assertThat(payload)
+ .doesNotContain(
+ seed.rawToken(),
+ "new-password-one",
+ account.getPasswordHash(),
+ seed.originalVerifier());
+ assertThat(countReceipts(fixture, seed.accountId())).isEqualTo(1L);
+ assertThat(countEvents(fixture, streamKey)).isEqualTo(1L);
+ byte[] tokenHashBytes = HexFormat.of().parseHex(tokenHash(seed.rawToken()));
+ assertThatThrownBy(
+ () ->
+ fixture
+ .setupDsl()
+ .execute(
+ "UPDATE account_password_reset_operation_receipts "
+ + "SET request_digest = request_digest WHERE token_hash = ?",
+ tokenHashBytes))
+ .isInstanceOf(DataAccessException.class);
+ assertThatThrownBy(
+ () ->
+ fixture
+ .setupDsl()
+ .execute(
+ "DELETE FROM account_password_reset_operation_receipts WHERE token_hash = ?",
+ tokenHashBytes))
+ .isInstanceOf(DataAccessException.class);
+ assertThat(countReceipts(fixture, seed.accountId())).isEqualTo(1L);
+ }
+
+ @Test
+ void exactRetryRecoversLostResponseWithoutAnySecondMutation() {
+ Fixture fixture = newFixture();
+ Seed seed = seedAccountAndToken(fixture, "initial-password");
+
+ reset(fixture, seed.rawToken(), "recovered-password");
+ StoredState committed = snapshot(fixture, seed);
+ reset(fixture, seed.rawToken(), "recovered-password");
+
+ assertThat(snapshot(fixture, seed)).isEqualTo(committed);
+ }
+
+ @Test
+ void concurrentExactRetriesCommitOneSourceMutation() throws Exception {
+ Fixture fixture = newFixture();
+ Seed seed = seedAccountAndToken(fixture, "initial-password");
+ CountDownLatch ready = new CountDownLatch(2);
+ CountDownLatch start = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ var first = executor.submit(() -> concurrentReset(fixture, seed, ready, start));
+ var second = executor.submit(() -> concurrentReset(fixture, seed, ready, start));
+ assertThat(ready.await(20, TimeUnit.SECONDS)).isTrue();
+ start.countDown();
+ first.get(45, TimeUnit.SECONDS);
+ second.get(45, TimeUnit.SECONDS);
+ } finally {
+ start.countDown();
+ executor.shutdownNow();
+ }
+
+ StoredState state = snapshot(fixture, seed);
+ assertThat(state.generation()).isEqualTo(2L);
+ assertThat(state.sourceVersion()).isEqualTo(2L);
+ assertThat(state.issuanceFence()).isEqualTo(2L);
+ assertThat(state.tokenCount()).isZero();
+ assertThat(state.receiptCount()).isEqualTo(1L);
+ assertThat(state.eventCount()).isEqualTo(1L);
+ }
+
+ @Test
+ void waitingResetRetainsExactIntentAndSettlesOnlyAfterOriginalOwnersDeny() {
+ Fixture fixture = newFixture();
+ Seed seed = seedAccountAndToken(fixture, "initial-password");
+ DraftAuthorizationFenceBinding binding = draftBinding(seed);
+ transaction(
+ fixture.transaction(),
+ () -> {
+ fixture.fences().reserve(binding);
+ return null;
+ });
+
+ assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "waiting-password"))
+ .isInstanceOf(
+ net.firedevops.firemud.accountservice.repository
+ .AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class);
+
+ assertThat(snapshot(fixture, seed))
+ .isEqualTo(new StoredState(seed.originalVerifier(), 1L, 1L, 1L, 1L, 0L, 0L));
+ var intentBeforeSettlement =
+ Objects.requireNonNull(
+ fixture
+ .setupDsl()
+ .fetchOne(
+ "SELECT status, request_payload, source_evidence, source_change_binding "
+ + "FROM account_password_reset_draft_source_changes WHERE token_hash = ?",
+ HexFormat.of().parseHex(tokenHash(seed.rawToken()))),
+ "Waiting password-reset source intent must be persisted");
+ assertThat(intentBeforeSettlement.get("status", String.class)).isEqualTo("WAITING");
+ byte[] requestBytes = intentBeforeSettlement.get("request_payload", byte[].class);
+ byte[] capturedSource = intentBeforeSettlement.get("source_evidence", byte[].class);
+ byte[] changeBinding = intentBeforeSettlement.get("source_change_binding", byte[].class);
+ assertThat(requestBytes).isNotEmpty();
+ assertThat(capturedSource).isNotEmpty();
+ assertThat(changeBinding).isNotEmpty();
+ var persistedTokenBinding =
+ Objects.requireNonNull(
+ fixture
+ .setupDsl()
+ .fetchOne(
+ "SELECT token_id, token_expires_at FROM "
+ + "account_password_reset_draft_source_changes WHERE token_hash = ?",
+ HexFormat.of().parseHex(tokenHash(seed.rawToken()))),
+ "Waiting password-reset token binding must be persisted");
+ assertThat(persistedTokenBinding.get("token_id", Long.class)).isPositive();
+ assertThat(persistedTokenBinding.get("token_expires_at", LocalDateTime.class))
+ .isEqualTo(seed.deadline());
+ assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "different-waiting-password"))
+ .isInstanceOf(OperationConflictException.class);
+ assertThat(snapshot(fixture, seed))
+ .isEqualTo(new StoredState(seed.originalVerifier(), 1L, 1L, 1L, 1L, 0L, 0L));
+ var sameIntentAfterConflict =
+ Objects.requireNonNull(
+ fixture
+ .setupDsl()
+ .fetchOne(
+ "SELECT status, request_payload FROM "
+ + "account_password_reset_draft_source_changes WHERE token_hash = ?",
+ HexFormat.of().parseHex(tokenHash(seed.rawToken()))),
+ "Original waiting reset intent must remain after a conflicting retry");
+ assertThat(sameIntentAfterConflict.get("request_payload", byte[].class))
+ .isEqualTo(requestBytes);
+
+ transaction(
+ fixture.transaction(),
+ () -> {
+ fixture.fences().recordOwnerReadback(binding, ownerDenial(binding, Owner.GAME_DESIGN));
+ fixture.fences().recordOwnerReadback(binding, ownerDenial(binding, Owner.WORLD));
+ return null;
+ });
+ reset(fixture, seed.rawToken(), "waiting-password");
+
+ assertThat(snapshot(fixture, seed).generation()).isEqualTo(2L);
+ assertThat(countEvents(fixture, streamKey(seed.accountUuid()))).isEqualTo(1L);
+ var committedResetIntent =
+ Objects.requireNonNull(
+ fixture
+ .setupDsl()
+ .fetchOne(
+ "SELECT status FROM account_password_reset_draft_source_changes "
+ + "WHERE token_hash = ?",
+ HexFormat.of().parseHex(tokenHash(seed.rawToken()))),
+ "Committed password-reset source intent must remain readable");
+ assertThat(committedResetIntent.get("status", String.class)).isEqualTo("SOURCE_COMMITTED");
+ var committedV76Change =
+ Objects.requireNonNull(
+ fixture
+ .setupDsl()
+ .fetchOne(
+ "SELECT status FROM account_draft_authorization_source_changes "
+ + "WHERE change_id = (SELECT source_change_id "
+ + "FROM account_password_reset_draft_source_changes WHERE token_hash = ?)",
+ HexFormat.of().parseHex(tokenHash(seed.rawToken()))),
+ "Committed V76 source change must remain readable");
+ assertThat(committedV76Change.get("status", String.class)).isEqualTo("SOURCE_COMMITTED");
+ }
+
+ @Test
+ void changedRetryConflictsAndConsecutiveResetsRequireExactPriorSourceProof() {
+ Fixture fixture = newFixture();
+ Seed seed = seedAccountAndToken(fixture, "initial-password");
+ reset(fixture, seed.rawToken(), "first-password");
+ StoredState committed = snapshot(fixture, seed);
+
+ assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "different-password"))
+ .isInstanceOf(OperationConflictException.class);
+ assertThat(snapshot(fixture, seed)).isEqualTo(committed);
+
+ String secondToken = "second-token-" + UUID.randomUUID();
+ LocalDateTime secondDeadline = LocalDateTime.now().plusHours(2);
+ transaction(
+ fixture.transaction(),
+ () -> {
+ Account owner = fixture.accounts().findById(seed.accountId()).orElseThrow();
+ PasswordResetToken token = new PasswordResetToken();
+ token.setAccount(owner);
+ token.setToken(secondToken);
+ token.setExpiresAt(secondDeadline);
+ fixture.tokens().save(token);
+ return null;
+ });
+ reset(fixture, secondToken, "second-password");
+
+ ScopeState authority = readAuthority(fixture, seed.accountUuid());
+ assertThat(authority.generation()).isEqualTo(3L);
+ assertThat(authority.sourceVersion()).isEqualTo(3L);
+ assertThat(authority.issuanceFence().value()).isEqualTo(3L);
+ assertThat(authority.issuanceFence().sourceVersion()).isEqualTo(3L);
+ assertThat(countEvents(fixture, streamKey(seed.accountUuid()))).isEqualTo(2L);
+ assertThat(countReceipts(fixture, seed.accountId())).isEqualTo(2L);
+ }
+
+ @Test
+ void appendAndReceiptReadbackFailuresRollBackEveryEarlierMutation() {
+ Fixture appendFailure = newFixture();
+ Seed appendSeed = seedAccountAndToken(appendFailure, "initial-password");
+ appendFailure
+ .setupDsl()
+ .execute(
+ "ALTER TABLE account_authority_outbox_events "
+ + "ADD CONSTRAINT reject_password_reset_producer_event "
+ + "CHECK (event_id NOT LIKE 'account-password-reset-event-v1:%')");
+
+ assertThatThrownBy(() -> reset(appendFailure, appendSeed.rawToken(), "append-failure-password"))
+ .isInstanceOf(RuntimeException.class);
+ assertUnchangedAfterRollback(appendFailure, appendSeed, 1L, 1L);
+
+ Fixture readbackFailure = newFixture();
+ Seed readbackSeed = seedAccountAndToken(readbackFailure, "initial-password");
+ AccountPasswordResetOperationRepository hideInsertedReceipt =
+ new AccountPasswordResetOperationRepository(readbackFailure.transactionDsl()) {
+ private final AtomicInteger lookups = new AtomicInteger();
+
+ @Override
+ public Optional findByTokenHash(String tokenHash) {
+ int lookup = lookups.incrementAndGet();
+ if (lookup >= 3) {
+ return Optional.empty();
+ }
+ return super.findByTokenHash(tokenHash);
+ }
+ };
+ AccountServiceImpl service = newService(readbackFailure, hideInsertedReceipt);
+
+ assertThatThrownBy(
+ () ->
+ transaction(
+ readbackFailure.transaction(),
+ () -> {
+ service.completePasswordReset(
+ new CompletePasswordResetRequest(
+ readbackSeed.rawToken(), "readback-failure-password"));
+ return null;
+ }))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("receipt readback is missing");
+ assertUnchangedAfterRollback(readbackFailure, readbackSeed, 1L, 1L);
+ }
+
+ @Test
+ void issuanceFenceOverflowRollsBackTokenPasswordAuthorityAndOutbox() {
+ Fixture fixture = newFixture();
+ Seed seed = seedAccountAndToken(fixture, "initial-password");
+ fixture
+ .setupDsl()
+ .execute(
+ "ALTER TABLE account_authority_issuance_fences DISABLE TRIGGER account_authority_issuance_fences_monotonic");
+ try {
+ fixture
+ .setupDsl()
+ .execute(
+ "UPDATE account_authority_issuance_fences "
+ + "SET issuance_fence = ?, source_version = ? WHERE account_uuid = ?",
+ Long.MAX_VALUE,
+ 11L,
+ seed.accountUuid());
+ } finally {
+ fixture
+ .setupDsl()
+ .execute(
+ "ALTER TABLE account_authority_issuance_fences ENABLE TRIGGER account_authority_issuance_fences_monotonic");
+ }
+
+ assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "overflow-password"))
+ .isInstanceOf(RuntimeException.class);
+ assertUnchangedAfterRollback(fixture, seed, Long.MAX_VALUE, 11L);
+ }
+
+ private boolean concurrentReset(
+ Fixture fixture, Seed seed, CountDownLatch ready, CountDownLatch start) {
+ ready.countDown();
+ await(start);
+ reset(fixture, seed.rawToken(), "concurrent-password");
+ return true;
+ }
+
+ private Fixture newFixture() {
+ String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?";
+ dataSource.setUrl(postgres.getJdbcUrl() + separator + "currentSchema=" + schema);
+ dataSource.setUsername(postgres.getUsername());
+ dataSource.setPassword(postgres.getPassword());
+ Flyway.configure()
+ .dataSource(dataSource)
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .locations("classpath:db/migration")
+ .load()
+ .migrate();
+
+ DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES);
+ DSLContext transactionDsl =
+ DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES);
+ PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
+ TransactionTemplate transaction = new TransactionTemplate(transactionManager);
+ AccountRepository accounts = new AccountRepository(transactionDsl);
+ AccountAuthorityGenerationRepository authority =
+ new AccountAuthorityGenerationRepository(transactionDsl);
+ AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(transactionDsl);
+ AccountPasswordResetOperationRepository operations =
+ new AccountPasswordResetOperationRepository(transactionDsl);
+ AccountLogoutAllOperationRepository logoutAllOperations =
+ new AccountLogoutAllOperationRepository(transactionDsl);
+ AccountSecurityStateOperationRepository securityStateOperations =
+ new AccountSecurityStateOperationRepository(transactionDsl);
+ AccountPasswordResetDraftSourceChangeRepository sourceChanges =
+ new AccountPasswordResetDraftSourceChangeRepository(transactionDsl);
+ DraftAuthorizationFenceRepository fences =
+ new DraftAuthorizationFenceRepository(transactionDsl);
+ PasswordResetTokenRepository tokens = new PasswordResetTokenRepository(transactionDsl);
+ return new Fixture(
+ setupDsl,
+ transactionDsl,
+ transactionManager,
+ transaction,
+ accounts,
+ authority,
+ outbox,
+ operations,
+ logoutAllOperations,
+ securityStateOperations,
+ sourceChanges,
+ fences,
+ tokens);
+ }
+
+ private Seed seedAccountAndToken(Fixture fixture, String initialVerifier) {
+ return transaction(
+ fixture.transaction(),
+ () -> {
+ Account account = new Account();
+ String unique = UUID.randomUUID().toString();
+ account.setUsername("reset-" + unique);
+ account.setEmail("reset-" + unique + "@example.test");
+ account.setPasswordHash(initialVerifier);
+ Account saved = fixture.accounts().save(account);
+
+ String tokenValue = "reset-token-" + unique;
+ LocalDateTime deadline = LocalDateTime.now().plusHours(2);
+ PasswordResetToken token = new PasswordResetToken();
+ token.setAccount(saved);
+ token.setToken(tokenValue);
+ token.setExpiresAt(deadline);
+ fixture.tokens().save(token);
+ LocalDateTime storedDeadline =
+ fixture.tokens().findByToken(tokenValue).orElseThrow().getExpiresAt();
+ return new Seed(
+ saved.getId(), saved.getAccountUuid(), tokenValue, storedDeadline, initialVerifier);
+ });
+ }
+
+ private AccountServiceImpl newService(
+ Fixture fixture, AccountPasswordResetOperationRepository operations) {
+ return new AccountServiceImpl(
+ fixture.accounts(),
+ fixture.authority(),
+ fixture.outbox(),
+ operations,
+ fixture.logoutAllOperations(),
+ fixture.securityStateOperations(),
+ fixture.sourceChanges(),
+ null, // audit outbox
+ null, // connect scopes
+ null, // join operations
+ null, // email login challenges
+ null, // realm grants
+ null, // tenant memberships
+ null, // account mapper is not on the password-reset path
+ null, // profiles
+ null, // profile mapper
+ null, // payment transactions
+ null, // subscriptions
+ null, // external account identities
+ fixture.tokens(),
+ null, // email verification tokens
+ null, // notifications
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ fixture.transactionManager());
+ }
+
+ private void reset(Fixture fixture, String rawToken, String password) {
+ AccountServiceImpl service = newService(fixture, fixture.operations());
+ transaction(
+ fixture.transaction(),
+ () -> {
+ service.completePasswordReset(new CompletePasswordResetRequest(rawToken, password));
+ return null;
+ });
+ }
+
+ private DraftAuthorizationFenceBinding draftBinding(Seed seed) {
+ var complete =
+ DraftCommitBinding.create(
+ new DraftCommitBinding.TargetProof(
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ 1,
+ "test-only-tenant",
+ 2,
+ "test-only-tenant",
+ "NEW_GAME_ROW"),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ "test-only/base",
+ List.of(
+ new DraftCommitBinding.RevisionPayload(
+ "0",
+ UUID.randomUUID(),
+ DraftCommitBinding.Owner.WORLD_MANAGEMENT,
+ "test-only-world-payload")),
+ List.of(
+ new DraftCommitBinding.AffectedUnit(
+ DraftCommitBinding.Owner.WORLD_MANAGEMENT,
+ "region",
+ "test-region",
+ "aggregate",
+ "test-region",
+ "0")));
+ SourceEvidence accountSource =
+ new SourceEvidence(
+ SourceKind.ACCOUNT,
+ seed.accountUuid().toString(),
+ "1",
+ "1",
+ streamKey(seed.accountUuid()),
+ "0",
+ "account-password-reset-source-proof".getBytes(StandardCharsets.UTF_8));
+ return new DraftAuthorizationFenceBinding(
+ UUID.randomUUID(),
+ complete.requestId(),
+ complete.commitId(),
+ UUID.randomUUID(),
+ seed.accountUuid(),
+ complete.target().canonicalTenantId(),
+ complete.target().canonicalVersionId(),
+ complete.baseCommitId(),
+ "0",
+ complete.canonicalBytes(),
+ complete.canonicalBytes(),
+ complete.digest(),
+ List.of(accountSource));
+ }
+
+ private OwnerReadback ownerDenial(DraftAuthorizationFenceBinding binding, Owner owner) {
+ return new OwnerReadback(
+ owner,
+ Outcome.DEFINITIVELY_ABORTED,
+ binding.operationId(),
+ binding.commitId(),
+ binding.fenceId(),
+ binding.inputDigest(),
+ binding.canonicalBytes(),
+ new byte[] {7});
+ }
+
+ private void assertUnchangedAfterRollback(
+ Fixture fixture, Seed seed, long expectedFence, long expectedFenceSourceVersion) {
+ Account account = account(fixture, seed.accountId());
+ ScopeState authority = readAuthority(fixture, seed.accountUuid());
+ assertThat(account.getPasswordHash()).isEqualTo(seed.originalVerifier());
+ assertThat(tokenExists(fixture, seed.rawToken())).isTrue();
+ assertThat(authority.generation()).isEqualTo(1L);
+ assertThat(authority.sourceVersion()).isEqualTo(1L);
+ assertThat(authority.issuanceFence().value()).isEqualTo(expectedFence);
+ assertThat(authority.issuanceFence().sourceVersion()).isEqualTo(expectedFenceSourceVersion);
+ assertThat(countReceipts(fixture, seed.accountId())).isZero();
+ assertThat(countEvents(fixture, streamKey(seed.accountUuid()))).isZero();
+ assertThat(
+ Objects.requireNonNull(
+ fixture
+ .setupDsl()
+ .fetchOne(
+ "SELECT last_sequence FROM account_authority_outbox_streams "
+ + "WHERE outbox_stream_key = ?",
+ streamKey(seed.accountUuid())),
+ "Fresh Account baseline checkpoint must remain after rollback")
+ .get("last_sequence", Long.class))
+ .isZero();
+ }
+
+ private StoredState snapshot(Fixture fixture, Seed seed) {
+ Account account = account(fixture, seed.accountId());
+ ScopeState authority = readAuthority(fixture, seed.accountUuid());
+ return new StoredState(
+ account.getPasswordHash(),
+ authority.generation(),
+ authority.sourceVersion(),
+ authority.issuanceFence().value(),
+ tokenExists(fixture, seed.rawToken()) ? 1L : 0L,
+ countReceipts(fixture, seed.accountId()),
+ countEvents(fixture, streamKey(seed.accountUuid())));
+ }
+
+ private Account account(Fixture fixture, long accountId) {
+ return transaction(
+ fixture.transaction(), () -> fixture.accounts().findById(accountId).orElseThrow());
+ }
+
+ private ScopeState readAuthority(Fixture fixture, UUID accountUuid) {
+ return transaction(
+ fixture.transaction(), () -> fixture.authority().read(AuthorityScope.account(accountUuid)));
+ }
+
+ private boolean tokenExists(Fixture fixture, String rawToken) {
+ return transaction(
+ fixture.transaction(), () -> fixture.tokens().findByToken(rawToken).isPresent());
+ }
+
+ private long countReceipts(Fixture fixture, long accountId) {
+ return Objects.requireNonNull(
+ fixture
+ .setupDsl()
+ .resultQuery(
+ "SELECT COUNT(*) FROM account_password_reset_operation_receipts WHERE account_id = ?",
+ accountId)
+ .fetchOne(0, Long.class),
+ "Password-reset receipt count readback is missing");
+ }
+
+ private long countEvents(Fixture fixture, String streamKey) {
+ return Objects.requireNonNull(
+ fixture
+ .setupDsl()
+ .resultQuery(
+ "SELECT COUNT(*) FROM account_authority_outbox_events WHERE outbox_stream_key = ?",
+ streamKey)
+ .fetchOne(0, Long.class),
+ "Password-reset event count readback is missing");
+ }
+
+ private String streamKey(UUID accountUuid) {
+ return STREAM_PREFIX + accountUuid;
+ }
+
+ private String tokenHash(String rawToken) {
+ return sha256Hex(rawToken);
+ }
+
+ private String sha256Hex(String value) {
+ try {
+ return HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is unavailable", exception);
+ }
+ }
+
+ private void await(CountDownLatch latch) {
+ try {
+ if (!latch.await(20, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("Concurrent password-reset barrier timed out");
+ }
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(
+ "Concurrent password-reset proof was interrupted", interrupted);
+ }
+ }
+
+ private T transaction(TransactionTemplate transaction, Supplier operation) {
+ return transaction.execute(status -> operation.get());
+ }
+
+ private record Fixture(
+ DSLContext setupDsl,
+ DSLContext transactionDsl,
+ PlatformTransactionManager transactionManager,
+ TransactionTemplate transaction,
+ AccountRepository accounts,
+ AccountAuthorityGenerationRepository authority,
+ AccountAuthorityOutboxRepository outbox,
+ AccountPasswordResetOperationRepository operations,
+ AccountLogoutAllOperationRepository logoutAllOperations,
+ AccountSecurityStateOperationRepository securityStateOperations,
+ AccountPasswordResetDraftSourceChangeRepository sourceChanges,
+ DraftAuthorizationFenceRepository fences,
+ PasswordResetTokenRepository tokens) {}
+
+ private record Seed(
+ long accountId,
+ UUID accountUuid,
+ String rawToken,
+ LocalDateTime deadline,
+ String originalVerifier) {}
+
+ private record StoredState(
+ String passwordVerifier,
+ long generation,
+ long sourceVersion,
+ long issuanceFence,
+ long tokenCount,
+ long receiptCount,
+ long eventCount) {}
+}
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java
index 45ad6ec7b0..460c8cb80e 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java
@@ -101,25 +101,35 @@ void preV40RetainedPasswordResetFailsTypedAndRollsBackWithoutInventingSource() {
var service =
new net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl(
accounts,
+ new AccountAuthorityGenerationRepository(dsl),
+ new AccountAuthorityOutboxRepository(dsl),
+ new net.firedevops.firemud.accountservice.repository
+ .AccountPasswordResetOperationRepository(dsl),
+ new net.firedevops.firemud.accountservice.repository
+ .AccountLogoutAllOperationRepository(dsl),
+ new net.firedevops.firemud.accountservice.repository
+ .AccountSecurityStateOperationRepository(dsl),
+ new net.firedevops.firemud.accountservice.service
+ .AccountPasswordResetDraftSourceChangeRepository(dsl),
+ null, // audit outbox
null,
null,
null,
null,
null,
- null, // audit/scope/JOIN/challenge/grant/membership
+ null, // account mapper, profiles, payments, subscriptions, external identities
null,
null,
null,
null,
null,
- null, // mapper/profile/payment/subscription/external
resetTokens,
+ null, // verification token repository
null,
null,
null,
null,
null,
- null, // verification/notification/mail/config
null,
null,
null,
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java
index f00f397145..d217a400f0 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java
@@ -608,6 +608,18 @@ void privateRealmGrantRevocationRetainsMonotonicCurrentnessForRevalidation() {
AccountServiceImpl accountService =
new AccountServiceImpl(
new AccountRepository(transactionAwareDsl),
+ new net.firedevops.firemud.accountservice.repository
+ .AccountAuthorityGenerationRepository(transactionAwareDsl),
+ new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository(
+ transactionAwareDsl),
+ new net.firedevops.firemud.accountservice.repository
+ .AccountPasswordResetOperationRepository(transactionAwareDsl),
+ new net.firedevops.firemud.accountservice.repository
+ .AccountLogoutAllOperationRepository(transactionAwareDsl),
+ new net.firedevops.firemud.accountservice.repository
+ .AccountSecurityStateOperationRepository(transactionAwareDsl),
+ new net.firedevops.firemud.accountservice.service
+ .AccountPasswordResetDraftSourceChangeRepository(transactionAwareDsl),
null,
null,
null,
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java
new file mode 100644
index 0000000000..075d0d4ca9
--- /dev/null
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java
@@ -0,0 +1,650 @@
+package integration.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 java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.HexFormat;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.AccountLifecycleState;
+import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository;
+import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository;
+import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader;
+import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource;
+import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+import net.firedevops.firemud.common.tenant.GameTenantCreationDigest;
+import org.flywaydb.core.Flyway;
+import org.jooq.DSLContext;
+import org.jooq.SQLDialect;
+import org.jooq.exception.DataAccessException;
+import org.jooq.impl.DSL;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.beans.factory.support.StaticListableBeanFactory;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/** Physical PostgreSQL proof for the first Account source/currentness forward stage. */
+class AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest {
+ private static final AccountPostgresIntegrationFixture POSTGRES =
+ new AccountPostgresIntegrationFixture();
+
+ @BeforeAll
+ static void startPostgres() {
+ POSTGRES.start();
+ }
+
+ @AfterAll
+ static void stopPostgres() {
+ POSTGRES.stop();
+ }
+
+ @Test
+ void freshInstallAppliesEveryForwardMigrationThroughV89() {
+ TestContext context = context(null);
+
+ assertThat(
+ context
+ .dsl()
+ .resultQuery(
+ "SELECT version FROM flyway_schema_history WHERE success "
+ + "ORDER BY installed_rank DESC LIMIT 1")
+ .fetchOne(0, String.class))
+ .isEqualTo("89");
+ assertThat(
+ context
+ .dsl()
+ .resultQuery(
+ "SELECT count(*) FROM flyway_schema_history "
+ + "WHERE version BETWEEN '74' AND '89' AND success")
+ .fetchOne(0, Long.class))
+ .isEqualTo(16L);
+
+ for (String relation :
+ new String[] {
+ "account_global_role_sources",
+ "account_draft_authorization_source_locks",
+ "account_draft_authorization_fences",
+ "account_draft_authorization_source_changes",
+ "account_password_reset_operation_receipts",
+ "account_logout_all_operation_receipts",
+ "account_security_state_operations",
+ "account_platform_restriction_births",
+ "account_tenant_creation_bootstrap_operations",
+ "account_individual_creator_party_sources",
+ "account_tenant_creator_party_history",
+ "account_hosted_terms_scopes",
+ "account_hosted_terms_catalog_versions",
+ "account_hosted_terms_environment_binding_heads",
+ "account_logout_all_draft_source_changes",
+ "account_password_reset_draft_source_changes"
+ }) {
+ assertThat(
+ context
+ .dsl()
+ .resultQuery("SELECT to_regclass(?)::TEXT", relation)
+ .fetchOne(0, String.class))
+ .as("forward relation %s", relation)
+ .isNotNull();
+ }
+ for (String function :
+ new String[] {
+ "account_draft_authorization_required_owners(bytea)",
+ "account_draft_authorization_is_settled(uuid)",
+ "account_creator_party_initial_receipt_guard()",
+ "account_hosted_terms_acceptance_insert_guard()",
+ "account_password_reset_draft_link_guard()"
+ }) {
+ assertThat(
+ context
+ .dsl()
+ .resultQuery("SELECT to_regprocedure(?)::TEXT", function)
+ .fetchOne(0, String.class))
+ .as("forward SQL guard %s", function)
+ .isNotNull();
+ }
+ }
+
+ @Test
+ void v73RetainedAccountStaysUnenrolledWhileFreshRepositoryAccountGetsExactBirthSources() {
+ TestContext context = context("73");
+ String retainedSuffix = UUID.randomUUID().toString();
+ Long retainedId =
+ Objects.requireNonNull(
+ context
+ .dsl()
+ .fetchOne(
+ "INSERT INTO accounts (username, email, password_hash, role) "
+ + "VALUES (?, ?, ?, 'player') RETURNING id",
+ "retained-" + retainedSuffix,
+ retainedSuffix + "@example.test",
+ "retained-password-" + retainedSuffix))
+ .get(0, Long.class);
+ UUID retainedUuid =
+ Objects.requireNonNull(
+ context
+ .dsl()
+ .resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", retainedId)
+ .fetchOne(0, UUID.class));
+
+ migrate(context, null);
+ Account fresh = account(null);
+ context
+ .transaction()
+ .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(fresh));
+
+ assertThat(count(context, "account_authority_source_records", "account_uuid", retainedUuid))
+ .isZero();
+ assertThat(count(context, "account_global_role_sources", "account_uuid", retainedUuid))
+ .isZero();
+ assertThat(count(context, "account_platform_restriction_births", "account_uuid", retainedUuid))
+ .isZero();
+
+ assertThat(
+ count(
+ context,
+ "account_authority_source_records",
+ "account_uuid",
+ fresh.getAccountUuid()))
+ .isEqualTo(1L);
+ assertThat(
+ context
+ .dsl()
+ .resultQuery(
+ "SELECT count(*) FROM account_global_role_sources "
+ + "WHERE account_uuid = ? AND global_role_source_version = 1 "
+ + "AND global_roles = ARRAY[]::TEXT[]",
+ fresh.getAccountUuid())
+ .fetchOne(0, Long.class))
+ .isEqualTo(1L);
+ assertThat(
+ context
+ .dsl()
+ .resultQuery(
+ "SELECT count(*) FROM account_platform_restriction_births "
+ + "WHERE account_uuid = ? AND revision = 1 AND enforcement_epoch = 1 "
+ + "AND source_kind = 'CATEGORY' AND restriction_state = 'NONRESTRICTED'",
+ fresh.getAccountUuid())
+ .fetchOne(0, Long.class))
+ .isEqualTo(2L);
+ assertThat(
+ context
+ .dsl()
+ .resultQuery(
+ "SELECT count(*) FROM account_platform_restriction_birth_outbox "
+ + "WHERE account_uuid = ? AND outbox_sequence = 1",
+ fresh.getAccountUuid())
+ .fetchOne(0, Long.class))
+ .isEqualTo(2L);
+ assertThat(
+ count(
+ context,
+ "account_platform_restriction_projections",
+ "account_uuid",
+ fresh.getAccountUuid()))
+ .isEqualTo(2L);
+
+ assertThatThrownBy(
+ () ->
+ context
+ .dsl()
+ .execute(
+ "UPDATE account_global_role_sources "
+ + "SET global_roles = ARRAY['moderator']::TEXT[] "
+ + "WHERE account_uuid = ?",
+ fresh.getAccountUuid()))
+ .isInstanceOf(DataAccessException.class);
+ assertThatThrownBy(
+ () ->
+ context
+ .dsl()
+ .execute(
+ "UPDATE account_platform_restriction_births "
+ + "SET payload_digest = repeat('0', 64) "
+ + "WHERE account_uuid = ? AND category = 'account_security_lock'",
+ fresh.getAccountUuid()))
+ .isInstanceOf(DataAccessException.class);
+ }
+
+ @Test
+ void malformedDraftOwnerEvidenceCannotSettleOrRewriteItsSourceChange() {
+ TestContext context = context(null);
+ UUID operationId = UUID.randomUUID();
+ UUID changeId = UUID.randomUUID();
+ String sourceKey = "TEST_SOURCE:" + UUID.randomUUID();
+ byte[] malformedBinding = "not-a-canonical-draft-fence".getBytes(StandardCharsets.UTF_8);
+
+ context
+ .dsl()
+ .execute(
+ "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)",
+ sourceKey);
+ context
+ .dsl()
+ .execute(
+ "INSERT INTO account_draft_authorization_fences "
+ + "(operation_id, request_id, commit_id, fence_id, binding, ordering) "
+ + "VALUES (?, ?, ?, ?, ?, 'RESERVED')",
+ operationId,
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ malformedBinding);
+ context
+ .dsl()
+ .execute(
+ "INSERT INTO account_draft_authorization_sources "
+ + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?)",
+ operationId,
+ sourceKey,
+ "malformed-source-evidence".getBytes(StandardCharsets.UTF_8));
+ context
+ .dsl()
+ .execute(
+ "UPDATE account_draft_authorization_fences SET ordering = 'COMMIT_ORDER', "
+ + "ordered_at = CURRENT_TIMESTAMP WHERE operation_id = ?",
+ operationId);
+ context
+ .dsl()
+ .execute(
+ "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) "
+ + "VALUES (?, ?, 'WAITING')",
+ changeId,
+ malformedBinding);
+ context
+ .dsl()
+ .execute(
+ "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) "
+ + "VALUES (?, ?)",
+ changeId,
+ sourceKey);
+
+ assertThatThrownBy(
+ () ->
+ context
+ .dsl()
+ .execute(
+ "INSERT INTO account_draft_authorization_owner_readbacks "
+ + "(operation_id, owner, outcome, readback) "
+ + "VALUES (?, 'GAME_DESIGN', 'COMMITTED', ?)",
+ operationId,
+ new byte[] {1}))
+ .isInstanceOf(DataAccessException.class);
+ assertThatThrownBy(
+ () ->
+ context
+ .dsl()
+ .execute(
+ "UPDATE account_draft_authorization_source_changes "
+ + "SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP "
+ + "WHERE change_id = ?",
+ changeId))
+ .isInstanceOf(DataAccessException.class);
+ assertThatThrownBy(
+ () ->
+ context
+ .dsl()
+ .execute(
+ "DELETE FROM account_draft_authorization_source_changes WHERE change_id = ?",
+ changeId))
+ .isInstanceOf(DataAccessException.class);
+ assertThat(
+ context
+ .dsl()
+ .resultQuery(
+ "SELECT status FROM account_draft_authorization_source_changes WHERE change_id = ?",
+ changeId)
+ .fetchOne(0, String.class))
+ .isEqualTo("WAITING");
+ assertThat(
+ context
+ .dsl()
+ .resultQuery(
+ "SELECT count(*) FROM account_draft_authorization_owner_readbacks "
+ + "WHERE operation_id = ?",
+ operationId)
+ .fetchOne(0, Long.class))
+ .isZero();
+ }
+
+ @Test
+ void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradictoryEvidence() {
+ TestContext context = context(null);
+ Account account = account("player");
+ context
+ .transaction()
+ .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(account));
+
+ UUID creatorPartyId = UUID.randomUUID();
+ byte[] creatorPayload = "test-only unverified creator source".getBytes(StandardCharsets.UTF_8);
+ context
+ .dsl()
+ .execute(
+ "INSERT INTO account_individual_creator_party_sources "
+ + "(creator_party_id, account_uuid, verification_status, identity_version, "
+ + "source_version, source_payload, source_digest) "
+ + "VALUES (?, ?, 'UNVERIFIED', 1, 1, ?, ?)",
+ creatorPartyId,
+ account.getAccountUuid(),
+ creatorPayload,
+ sha256(creatorPayload));
+
+ assertThatThrownBy(
+ () ->
+ context
+ .dsl()
+ .execute(
+ "UPDATE account_individual_creator_party_sources "
+ + "SET source_version = source_version WHERE creator_party_id = ?",
+ creatorPartyId))
+ .isInstanceOf(DataAccessException.class);
+ assertThatThrownBy(
+ () ->
+ context
+ .dsl()
+ .execute(
+ "DELETE FROM account_individual_creator_party_sources "
+ + "WHERE creator_party_id = ?",
+ creatorPartyId))
+ .isInstanceOf(DataAccessException.class);
+
+ UUID missingTenantSource = UUID.randomUUID();
+ byte[] creatorHistory = "no canonical tenant owner source".getBytes(StandardCharsets.UTF_8);
+ assertThatThrownBy(
+ () ->
+ context
+ .dsl()
+ .execute(
+ "INSERT INTO account_tenant_creator_party_history "
+ + "(history_id, tenant_uuid, origin, creator_party_id, source_version, "
+ + "evidence_payload, evidence_digest) "
+ + "VALUES (?, ?, 'FRESH_INITIAL', ?, 1, ?, ?)",
+ UUID.randomUUID(),
+ missingTenantSource,
+ creatorPartyId,
+ creatorHistory,
+ sha256(creatorHistory)))
+ .isInstanceOf(DataAccessException.class);
+ assertThat(
+ context
+ .dsl()
+ .resultQuery(
+ "SELECT count(*) FROM account_tenant_creator_party_history "
+ + "WHERE tenant_uuid = ?",
+ missingTenantSource)
+ .fetchOne(0, Long.class))
+ .isZero();
+
+ UUID hostedScopeId = UUID.randomUUID();
+ UUID termsVersionId = UUID.randomUUID();
+ byte[] nonoperativeDocument =
+ "synthetic test fixture; not legal terms or a publication".getBytes(StandardCharsets.UTF_8);
+ byte[] versionPayload =
+ "synthetic nonoperative catalog candidate".getBytes(StandardCharsets.UTF_8);
+ context
+ .dsl()
+ .execute(
+ "INSERT INTO account_hosted_terms_scopes (hosted_scope_id) VALUES (?)", hostedScopeId);
+ context
+ .dsl()
+ .execute(
+ "INSERT INTO account_hosted_terms_catalog_versions "
+ + "(version_id, hosted_scope_id, predecessor_version_id, operator_legal_identity, "
+ + "operator_identity_version, document_bytes, document_digest, source_version, "
+ + "material_generation, materiality, publication_evidence_reference, "
+ + "publication_evidence_version, notice_evidence_reference, notice_evidence_version, "
+ + "effective_at, version_payload, version_digest) "
+ + "VALUES (?, ?, NULL, 'TEST FIXTURE ONLY', 1, ?, ?, 1, 1, 'INITIAL', "
+ + "'no-publication-fixture', 1, 'no-notice-fixture', 1, ?, ?, ?)",
+ termsVersionId,
+ hostedScopeId,
+ nonoperativeDocument,
+ sha256(nonoperativeDocument),
+ OffsetDateTime.now(ZoneOffset.UTC).plusDays(1).toString(),
+ versionPayload,
+ sha256(versionPayload));
+
+ assertThatThrownBy(
+ () ->
+ context
+ .dsl()
+ .execute(
+ "UPDATE account_hosted_terms_catalog_versions "
+ + "SET operator_legal_identity = 'changed fixture' WHERE version_id = ?",
+ termsVersionId))
+ .isInstanceOf(DataAccessException.class);
+ assertThatThrownBy(
+ () ->
+ context
+ .dsl()
+ .execute(
+ "DELETE FROM account_hosted_terms_catalog_versions WHERE version_id = ?",
+ termsVersionId))
+ .isInstanceOf(DataAccessException.class);
+ assertThat(
+ context
+ .dsl()
+ .resultQuery(
+ "SELECT current_version_id FROM account_hosted_terms_scopes "
+ + "WHERE hosted_scope_id = ?",
+ hostedScopeId)
+ .fetchOne(0, UUID.class))
+ .isNull();
+ assertThat(
+ context
+ .dsl()
+ .resultQuery("SELECT count(*) FROM account_hosted_terms_publication_operations")
+ .fetchOne(0, Long.class))
+ .isZero();
+
+ byte[] affirmativeAction = "{}".getBytes(StandardCharsets.UTF_8);
+ assertThatThrownBy(
+ () ->
+ context
+ .dsl()
+ .execute(
+ "INSERT INTO account_individual_hosted_terms_acceptances "
+ + "(evidence_id, action_request_id, creator_party_id, account_uuid, "
+ + "hosted_scope_id, terms_version_id, document_digest, "
+ + "operator_legal_identity, operator_identity_version, source_version, "
+ + "material_generation, individual_party_source, "
+ + "individual_party_source_digest, "
+ + "affirmative_action_evidence, affirmative_action_digest, accepted_at) "
+ + "VALUES (?, ?, ?, ?, ?, ?, ?, 'TEST FIXTURE ONLY', 1, 1, 1, ?, ?, ?, ?, "
+ + "CURRENT_TIMESTAMP)",
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ creatorPartyId,
+ account.getAccountUuid(),
+ hostedScopeId,
+ termsVersionId,
+ sha256(nonoperativeDocument),
+ creatorPayload,
+ sha256(creatorPayload),
+ affirmativeAction,
+ sha256(affirmativeAction)))
+ .isInstanceOf(DataAccessException.class);
+ assertThat(
+ context
+ .dsl()
+ .resultQuery(
+ "SELECT count(*) FROM account_individual_hosted_terms_acceptances "
+ + "WHERE creator_party_id = ?",
+ creatorPartyId)
+ .fetchOne(0, Long.class))
+ .isZero();
+ }
+
+ @Test
+ void creatorBootstrapWithoutAuthorizationSourceDeniesBeforeAnyOwnerWrite() {
+ TestContext context = context(null);
+ Account creator = account("player");
+ context
+ .transaction()
+ .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(creator));
+
+ StaticListableBeanFactory beans = new StaticListableBeanFactory();
+ ObjectProvider noAuthorizationSource =
+ beans.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class);
+ AccountTenantCreationBootstrapService service =
+ new AccountTenantCreationBootstrapService(
+ new AccountRepository(context.dsl()),
+ mock(FreshTenantIdentityAssociationRepository.class),
+ mock(AccountCreatorMembershipSourceReader.class),
+ mock(AccountMembershipPairAuthorityRepository.class),
+ mock(AccountTenantMembershipRepository.class),
+ mock(AccountTenantMembershipRoleSnapshotRepository.class),
+ mock(AccountAuthorityOutboxRepository.class),
+ mock(AccountAuditOutboxRepository.class),
+ new AccountTenantCreationBootstrapOperationRepository(context.dsl()),
+ noAuthorizationSource);
+ FreshTenantCreatorEvidence evidence = creatorEvidence(creator.getAccountUuid());
+
+ assertThatThrownBy(
+ () -> context.transaction().executeWithoutResult(status -> service.bootstrap(evidence)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("No current Account creator-authorization/source participant");
+ assertThat(
+ context
+ .dsl()
+ .resultQuery("SELECT count(*) FROM account_tenant_creation_bootstrap_operations")
+ .fetchOne(0, Long.class))
+ .isZero();
+ assertThat(
+ context
+ .dsl()
+ .resultQuery("SELECT count(*) FROM account_tenant_membership")
+ .fetchOne(0, Long.class))
+ .isZero();
+ assertThat(
+ context
+ .dsl()
+ .resultQuery("SELECT count(*) FROM account_authority_outbox_events")
+ .fetchOne(0, Long.class))
+ .isZero();
+ }
+
+ private static FreshTenantCreatorEvidence creatorEvidence(UUID accountUuid) {
+ UUID creationRequestId = UUID.randomUUID();
+ UUID creationOperationId = UUID.randomUUID();
+ UUID tenantUuid = UUID.randomUUID();
+ String namespace = "test";
+ String tenantKey = "fixture-tenant";
+ String creationRequestDigest =
+ GameTenantCreationDigest.requestDigest(
+ namespace, creationRequestId, tenantKey, "test fixture", null);
+ String creationEvidenceDigest =
+ GameTenantCreationDigest.evidenceDigest(
+ namespace,
+ creationRequestId,
+ creationOperationId,
+ creationRequestDigest,
+ tenantUuid,
+ 1L,
+ tenantKey,
+ "NEW_GAME_ROW");
+ FreshTenantCreationEvidence creation =
+ new FreshTenantCreationEvidence(
+ 1,
+ namespace,
+ creationRequestId,
+ creationOperationId,
+ creationRequestDigest,
+ tenantUuid,
+ 1L,
+ tenantKey,
+ "NEW_GAME_ROW",
+ creationEvidenceDigest);
+ UUID authorizationOperationId = UUID.randomUUID();
+ String authorizationDigest =
+ GameTenantCreationDigest.requestDigest(
+ namespace, UUID.randomUUID(), "fixture-authorization", "test fixture", null);
+ String creatorDigest =
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, creation, accountUuid, authorizationOperationId, authorizationDigest);
+ return new FreshTenantCreatorEvidence(
+ 1, creation, accountUuid, authorizationOperationId, authorizationDigest, creatorDigest);
+ }
+
+ private static Account account(String role) {
+ String suffix = UUID.randomUUID().toString();
+ Account account = new Account();
+ account.setUsername("forward-source-" + suffix);
+ account.setEmail(suffix.replace("-", "") + "@example.test");
+ account.setPasswordHash("test-only-password-hash");
+ account.setRole(role);
+ account.setLifecycleState(AccountLifecycleState.ACTIVE);
+ return account;
+ }
+
+ private static long count(TestContext context, String table, String column, UUID value) {
+ return Objects.requireNonNull(
+ context
+ .dsl()
+ .resultQuery("SELECT count(*) FROM " + table + " WHERE " + column + " = ?", value)
+ .fetchOne(0, Long.class));
+ }
+
+ private static String sha256(byte[] value) {
+ try {
+ return "sha256:"
+ + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value));
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException("SHA-256 is unavailable", impossible);
+ }
+ }
+
+ private static TestContext context(String target) {
+ String schema = "account_forward_source_" + UUID.randomUUID().toString().replace("-", "");
+ DriverManagerDataSource dataSource = POSTGRES.dataSource(schema);
+ TestContext context =
+ new TestContext(
+ schema,
+ dataSource,
+ DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES),
+ new TransactionTemplate(new DataSourceTransactionManager(dataSource)));
+ migrate(context, target);
+ return context;
+ }
+
+ private static void migrate(TestContext context, String target) {
+ var configuration =
+ Flyway.configure()
+ .dataSource(context.dataSource())
+ .schemas(context.schema())
+ .defaultSchema(context.schema())
+ .locations("classpath:db/migration")
+ .placeholders(Map.of("serviceSchema", context.schema()));
+ if (target != null) {
+ configuration.target(target);
+ }
+ configuration.load().migrate();
+ }
+
+ private record TestContext(
+ String schema,
+ DriverManagerDataSource dataSource,
+ DSLContext dsl,
+ TransactionTemplate transaction) {}
+}
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceFoundationV73UpgradePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceFoundationV73UpgradePostgresIntegrationTest.java
new file mode 100644
index 0000000000..fd87ec9478
--- /dev/null
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceFoundationV73UpgradePostgresIntegrationTest.java
@@ -0,0 +1,116 @@
+package integration.net.firedevops.firemud.accountservice.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import org.flywaydb.core.Flyway;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+/**
+ * Physical PostgreSQL proof that the V73-to-source-foundation uplift does not enroll retained
+ * Accounts.
+ */
+class AccountSourceFoundationV73UpgradePostgresIntegrationTest {
+ private static final AccountPostgresIntegrationFixture postgres =
+ new AccountPostgresIntegrationFixture();
+
+ @BeforeAll
+ static void startPostgres() {
+ postgres.start();
+ }
+
+ @AfterAll
+ static void stopPostgres() {
+ postgres.stop();
+ }
+
+ @Test
+ void retainedPreV40AccountAtV73GetsSerializationLocksButNoInventedAuthoritySource() {
+ String schema = "account_source_v73_" + UUID.randomUUID().toString().replace("-", "");
+ var dataSource = postgres.dataSource(schema);
+ Flyway.configure()
+ .dataSource(dataSource)
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .locations("classpath:db/migration")
+ .target("39")
+ .load()
+ .migrate();
+
+ JdbcTemplate jdbc = new JdbcTemplate(dataSource);
+ String suffix = UUID.randomUUID().toString();
+ Long accountId =
+ Objects.requireNonNull(
+ jdbc.queryForObject(
+ "INSERT INTO accounts (username, email, password_hash, role) "
+ + "VALUES (?, ?, ?, 'player') RETURNING id",
+ Long.class,
+ "retained-source-" + suffix,
+ suffix + "@example.test",
+ "retained-password-" + suffix));
+ UUID accountUuid =
+ Objects.requireNonNull(
+ jdbc.queryForObject(
+ "SELECT account_uuid FROM accounts WHERE id = ?", UUID.class, accountId));
+
+ Flyway.configure()
+ .dataSource(dataSource)
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .locations("classpath:db/migration")
+ .target("73")
+ .load()
+ .migrate();
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT count(*) FROM account_authority_source_records "
+ + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?",
+ Long.class,
+ accountUuid))
+ .isZero();
+
+ Flyway.configure()
+ .dataSource(dataSource)
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .locations("classpath:db/migration")
+ .load()
+ .migrate();
+
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT count(*) FROM account_authority_source_records "
+ + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?",
+ Long.class,
+ accountUuid))
+ .isZero();
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT count(*) FROM account_global_role_sources WHERE account_uuid = ?",
+ Long.class,
+ accountUuid))
+ .isZero();
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT count(*) FROM account_platform_restriction_births WHERE account_uuid = ?",
+ Long.class,
+ accountUuid))
+ .isZero();
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT count(*) FROM account_draft_authorization_source_locks "
+ + "WHERE source_key IN (?, ?)",
+ Long.class,
+ "ACCOUNT:" + accountUuid,
+ "GLOBAL_ROLES:" + accountUuid))
+ .isEqualTo(2L);
+ }
+}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java
new file mode 100644
index 0000000000..5d5abc9c43
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java
@@ -0,0 +1,416 @@
+package unit.net.firedevops.firemud.accountservice.creatorparty;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding;
+import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository;
+import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.InitialAssociationReadback;
+import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource;
+import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation;
+import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
+import net.firedevops.firemud.common.tenant.GameTenantCreationDigest;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentMatchers;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Mock-backed owner-boundary predicates only; this is not PostgreSQL lock or trigger proof. */
+class IndividualCreatorPartyRepositoryTest {
+ @AfterEach
+ void clearTransactionMarkers() {
+ TransactionSynchronizationManager.clear();
+ }
+
+ @Test
+ void preparationLocksOnlyTenantAndDerivesExistingCandidateIdentities() {
+ Fixture fixture = new Fixture();
+ beginWritableTransaction();
+ var scope = fixture.repository.lockExistingInitialAssociationScope(fixture.tenantId);
+ assertThat(scope.accountId()).isEqualTo(fixture.accountId);
+ assertThat(scope.creatorPartyId()).isEqualTo(fixture.party.creatorPartyId());
+ assertThat(scope.associationRequestId()).isEqualTo(fixture.associationRequestId);
+ verifyNoInteractions(fixture.bootstraps, fixture.freshTenants);
+ verify(fixture.dsl, never())
+ .fetchOne(
+ org.mockito.ArgumentMatchers.contains("account_individual_creator_party_sources"),
+ any(Object[].class));
+ fixture.assertNoWrites();
+ }
+
+ @Test
+ void preparationRejectsMissingIdentityAndAbsentTransaction() {
+ Fixture fixture = new Fixture();
+ assertThatThrownBy(
+ () -> fixture.repository.lockExistingInitialAssociationScope(fixture.tenantId))
+ .isInstanceOf(IllegalStateException.class);
+ beginWritableTransaction();
+ fixture.associationByTenantFields.remove("initiating_account_uuid");
+ assertThatThrownBy(
+ () -> fixture.repository.lockExistingInitialAssociationScope(fixture.tenantId))
+ .isInstanceOf(RuntimeException.class);
+ verifyNoInteractions(fixture.bootstraps, fixture.freshTenants);
+ }
+
+ @Test
+ void derivesAndVerifiesTheExactFreshInitialAssociationFromTenantOwnerRows() {
+ Fixture fixture = new Fixture();
+
+ InitialAssociationReadback readback = fixture.read();
+
+ assertThat(readback.creatorEvidence()).isEqualTo(fixture.creatorEvidence);
+ assertThat(readback.receipt())
+ .isEqualTo(
+ new IndividualCreatorPartyRepository.AssociationReceipt(
+ fixture.associationRequestId,
+ fixture.tenantId,
+ fixture.party.creatorPartyId(),
+ fixture.historyId,
+ CreatorPartyEncoding.digest(fixture.resultPayload)));
+ assertThat(readback.partySource()).isEqualTo(fixture.party);
+ fixture.assertNoWrites();
+ }
+
+ @Test
+ void missingAssociationFailsWithoutCreatingAReceiptOrHistory() {
+ Fixture fixture = new Fixture();
+ fixture.associationByTenant = null;
+
+ fixture.rejects();
+ }
+
+ @Test
+ void incompleteBootstrapAndAssociationIdentitiesFailClosed() {
+ Fixture uncommittedBootstrap = new Fixture();
+ uncommittedBootstrap.bootstrap = uncommittedBootstrap.withStatus("IN_PROGRESS");
+ uncommittedBootstrap.whenBootstrapRead();
+ uncommittedBootstrap.rejects();
+
+ Fixture malformedAssociation = new Fixture();
+ malformedAssociation.associationByTenantFields.remove("creator_party_id");
+ malformedAssociation.rejects();
+ }
+
+ @Test
+ void foreignInitiatorOrPartyCannotBeReadAsTheFreshCreatorAssociation() {
+ Fixture foreignInitiator = new Fixture();
+ foreignInitiator.associationByRequestFields.put("initiating_account_uuid", UUID.randomUUID());
+ foreignInitiator.associationByTenantFields.put(
+ "initiating_account_uuid",
+ foreignInitiator.associationByRequestFields.get("initiating_account_uuid"));
+ foreignInitiator.rejects();
+
+ Fixture foreignParty = new Fixture();
+ foreignParty.partyFields.put("account_uuid", UUID.randomUUID());
+ foreignParty.rejects();
+ }
+
+ @Test
+ void changedPartyBytesOrReceiptHistoryFailClosed() {
+ Fixture changedParty = new Fixture();
+ changedParty.partyFields.put("source_payload", new byte[] {8, 8});
+ changedParty.rejects();
+
+ Fixture changedReceipt = new Fixture();
+ changedReceipt.associationByRequestFields.put("result_digest", "sha256:" + "f".repeat(64));
+ changedReceipt.rejects();
+ }
+
+ @Test
+ void retainedOrTombstonedHistoryCannotBeReinterpretedAsInitialAssociation() {
+ Fixture retained = new Fixture();
+ retained.historyFields.put("origin", "RETAINED");
+ retained.rejects();
+
+ Fixture tombstoned = new Fixture();
+ tombstoned.historyFields.put("origin", "TOMBSTONE");
+ tombstoned.rejects();
+
+ Fixture multipleHistory = new Fixture();
+ multipleHistory.historyCountFields.put("count", 2L);
+ multipleHistory.rejects();
+ }
+
+ private static final class Fixture {
+ private final DSLContext dsl = mock(DSLContext.class);
+ private final FreshTenantIdentityAssociationRepository freshTenants =
+ mock(FreshTenantIdentityAssociationRepository.class);
+ private final AccountTenantCreationBootstrapOperationRepository bootstraps =
+ mock(AccountTenantCreationBootstrapOperationRepository.class);
+ private final UUID accountId = UUID.randomUUID();
+ private final UUID tenantId = UUID.randomUUID();
+ private final UUID creatorBootstrapRequestId = UUID.randomUUID();
+ private final UUID associationRequestId = UUID.randomUUID();
+ private final UUID historyId = UUID.randomUUID();
+ private final UUID creationRequestId = UUID.randomUUID();
+ private final UUID creationOperationId = UUID.randomUUID();
+ private final UUID accountAuthorizationOperationId = creatorBootstrapRequestId;
+ private final String accountAuthorizationDigest = sha256('a');
+ private final FreshTenantCreationEvidence creation = creation();
+ private final FreshTenantCreatorEvidence creatorEvidence = creatorEvidence();
+ private final IndividualCreatorPartySource party = party();
+ private final byte[] requestPayload =
+ CreatorPartyEncoding.request(associationRequestId, creatorEvidence, party);
+ private final byte[] resultPayload = CreatorPartyEncoding.result(historyId, requestPayload);
+ private final Map associationByTenantFields = new HashMap<>();
+ private final Map associationByRequestFields = new HashMap<>();
+ private final Map partyFields = new HashMap<>();
+ private final Map historyFields = new HashMap<>();
+ private final Map historyCountFields = new HashMap<>();
+ private StoredOperation bootstrap;
+ private StoredOperation currentBootstrap;
+ private Record associationByTenant;
+ private final IndividualCreatorPartyRepository repository;
+
+ private Fixture() {
+ bootstrap = bootstrap("COMMITTED");
+ currentBootstrap = bootstrap;
+ associationByTenantFields.put("request_id", associationRequestId);
+ associationByTenantFields.put("tenant_uuid", tenantId);
+ associationByTenantFields.put("initiating_account_uuid", accountId);
+ associationByTenantFields.put("creator_party_id", party.creatorPartyId());
+ associationByTenantFields.put("creation_operation_id", creationOperationId);
+
+ associationByRequestFields.put("request_id", associationRequestId);
+ associationByRequestFields.put("tenant_uuid", tenantId);
+ associationByRequestFields.put("initiating_account_uuid", accountId);
+ associationByRequestFields.put("creator_party_id", party.creatorPartyId());
+ associationByRequestFields.put("creation_operation_id", creationOperationId);
+ associationByRequestFields.put(
+ "creator_evidence_payload", CreatorPartyEncoding.creation(creatorEvidence));
+ associationByRequestFields.put("party_source_payload", CreatorPartyEncoding.party(party));
+ associationByRequestFields.put("request_payload", requestPayload);
+ associationByRequestFields.put("request_digest", CreatorPartyEncoding.digest(requestPayload));
+ associationByRequestFields.put("history_id", historyId);
+ associationByRequestFields.put("result_payload", resultPayload);
+ associationByRequestFields.put("result_digest", CreatorPartyEncoding.digest(resultPayload));
+ associationByRequestFields.put(
+ "committed_at", OffsetDateTime.ofInstant(Instant.EPOCH, ZoneOffset.UTC));
+
+ partyFields.put("creator_party_id", party.creatorPartyId());
+ partyFields.put("account_uuid", accountId);
+ partyFields.put("verification_status", VerificationStatus.VERIFIED.name());
+ partyFields.put("identity_version", party.identityVersion());
+ partyFields.put("policy_reference", party.policyReference());
+ partyFields.put("policy_version", party.policyVersion());
+ partyFields.put("verification_evidence_reference", party.verificationEvidenceReference());
+ partyFields.put("verification_evidence_version", party.verificationEvidenceVersion());
+ partyFields.put("source_version", party.sourceVersion());
+ partyFields.put("source_payload", CreatorPartyEncoding.party(party));
+ partyFields.put(
+ "source_digest", CreatorPartyEncoding.digest(CreatorPartyEncoding.party(party)));
+
+ historyFields.put("history_id", historyId);
+ historyFields.put("origin", "FRESH_INITIAL");
+ historyFields.put("tenant_uuid", tenantId);
+ historyFields.put("creator_party_id", party.creatorPartyId());
+ historyFields.put("source_version", 1L);
+ historyFields.put("evidence_payload", resultPayload);
+ historyFields.put("evidence_digest", CreatorPartyEncoding.digest(resultPayload));
+ historyCountFields.put("count", 1L);
+
+ associationByTenant = row(associationByTenantFields);
+ when(freshTenants.read(tenantId)).thenReturn(Optional.of(creation));
+ when(bootstraps.findRequestIdByTenantForUpdate(tenantId))
+ .thenReturn(Optional.of(creatorBootstrapRequestId));
+ when(bootstraps.findForUpdate(creatorBootstrapRequestId))
+ .thenAnswer(ignored -> Optional.of(currentBootstrap));
+ when(dsl.fetchOne(anyString(), any(Object[].class))).thenAnswer(this::fetch);
+ when(dsl.fetchOne(anyString())).thenAnswer(this::fetch);
+ repository = new IndividualCreatorPartyRepository(dsl, freshTenants, bootstraps);
+ }
+
+ private InitialAssociationReadback read() {
+ beginWritableTransaction();
+ try {
+ return repository.readExistingInitialAssociation(tenantId);
+ } finally {
+ TransactionSynchronizationManager.clear();
+ }
+ }
+
+ private void rejects() {
+ beginWritableTransaction();
+ try {
+ assertThatThrownBy(() -> repository.readExistingInitialAssociation(tenantId))
+ .isInstanceOf(IllegalStateException.class);
+ assertNoWrites();
+ } finally {
+ TransactionSynchronizationManager.clear();
+ }
+ }
+
+ private void assertNoWrites() {
+ verify(dsl, never()).execute(anyString(), any(Object[].class));
+ }
+
+ private void whenBootstrapRead() {
+ currentBootstrap = bootstrap;
+ when(bootstraps.findForUpdate(creatorBootstrapRequestId))
+ .thenAnswer(ignored -> Optional.of(currentBootstrap));
+ }
+
+ private StoredOperation withStatus(String status) {
+ return bootstrap(status);
+ }
+
+ private Object fetch(org.mockito.invocation.InvocationOnMock invocation) {
+ String sql = invocation.getArgument(0);
+ if (sql.equals("SHOW transaction_isolation")) {
+ Record isolation = mock(Record.class);
+ when(isolation.get(0, String.class)).thenReturn("read committed");
+ return isolation;
+ }
+ if (sql.contains("account_canonical_tenant_identity_claims")) {
+ return row(Map.of("identity_kind", "FRESH_GAME_DESIGN"));
+ }
+ if (sql.contains("account_fresh_creator_party_association_operations")
+ && sql.contains("WHERE tenant_uuid = ?")) {
+ return associationByTenant;
+ }
+ if (sql.contains("account_individual_creator_party_sources")) {
+ return row(partyFields);
+ }
+ if (sql.contains("WHERE request_id = ?")) {
+ return row(associationByRequestFields);
+ }
+ if (sql.contains("SELECT count(*) AS count FROM account_tenant_creator_party_history")) {
+ return row(historyCountFields);
+ }
+ if (sql.contains("account_tenant_creator_party_history WHERE history_id = ?")) {
+ return row(historyFields);
+ }
+ throw new AssertionError("Unexpected repository SQL: " + sql);
+ }
+
+ private FreshTenantCreationEvidence creation() {
+ String requestDigest = sha256('c');
+ return new FreshTenantCreationEvidence(
+ 1,
+ "firemud-test",
+ creationRequestId,
+ creationOperationId,
+ requestDigest,
+ tenantId,
+ 1,
+ "test-game",
+ "NEW_GAME_ROW",
+ GameTenantCreationDigest.evidenceDigest(
+ "firemud-test",
+ creationRequestId,
+ creationOperationId,
+ requestDigest,
+ tenantId,
+ 1,
+ "test-game",
+ "NEW_GAME_ROW"));
+ }
+
+ private FreshTenantCreatorEvidence creatorEvidence() {
+ return new FreshTenantCreatorEvidence(
+ 1,
+ creation,
+ accountId,
+ accountAuthorizationOperationId,
+ accountAuthorizationDigest,
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1, creation, accountId, accountAuthorizationOperationId, accountAuthorizationDigest));
+ }
+
+ private IndividualCreatorPartySource party() {
+ return new IndividualCreatorPartySource(
+ UUID.randomUUID(),
+ accountId,
+ VerificationStatus.VERIFIED,
+ 1,
+ "test-policy",
+ 1L,
+ "test-individual-verification",
+ 1L,
+ 1);
+ }
+
+ private StoredOperation bootstrap(String status) {
+ return new StoredOperation(
+ creatorBootstrapRequestId,
+ accountId,
+ tenantId,
+ creationRequestId,
+ creationOperationId,
+ accountAuthorizationOperationId,
+ accountAuthorizationDigest,
+ creatorEvidence.evidenceDigest(),
+ CreatorPartyEncoding.creation(creatorEvidence),
+ new byte[] {1},
+ sha256('s'),
+ new byte[] {2},
+ sha256('r'),
+ 1L,
+ 1L,
+ 0L,
+ status,
+ 1L,
+ 2L,
+ 1L,
+ "ACTIVE",
+ false,
+ "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8),
+ "account:auth-authority:v1:membership/" + accountId + "/" + tenantId,
+ UUID.randomUUID().toString(),
+ 1L,
+ "test-event",
+ sha256('e'),
+ false,
+ new byte[] {3},
+ UUID.randomUUID(),
+ "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED",
+ Instant.EPOCH,
+ sha256('a'),
+ new byte[] {4},
+ new byte[] {5},
+ sha256('b'),
+ Instant.EPOCH);
+ }
+ }
+
+ private static Record row(Map fields) {
+ Record record = mock(Record.class);
+ when(record.get(anyString())).thenAnswer(invocation -> fields.get(invocation.getArgument(0)));
+ doAnswer(invocation -> fields.get(invocation.getArgument(0)))
+ .when(record)
+ .get(anyString(), ArgumentMatchers.>any());
+ return record;
+ }
+
+ private static void beginWritableTransaction() {
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
+ }
+
+ private static String sha256(char repeated) {
+ return "sha256:" + String.valueOf(repeated).repeat(64);
+ }
+}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java
new file mode 100644
index 0000000000..6483eb5542
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java
@@ -0,0 +1,130 @@
+package unit.net.firedevops.firemud.accountservice.hostedterms;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.nio.charset.StandardCharsets;
+import net.firedevops.firemud.accountservice.hostedterms.AccountDeploymentEnvironmentBoundaryProvider;
+import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService;
+import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding;
+import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding;
+import org.junit.jupiter.api.Test;
+
+class AccountDeploymentEnvironmentBoundaryProviderTest {
+ private static final String ENVIRONMENT = "production-eu";
+ private static final String OWNER = "deployment-owner/cluster-eu";
+ private static final String EVENT = "environment-observation/84";
+ private static final byte[] OWNER_EVIDENCE = "owner-evidence-v1".getBytes(StandardCharsets.UTF_8);
+ private static final String OWNER_EVIDENCE_DIGEST = HostedTermsEncoding.digest(OWNER_EVIDENCE);
+
+ @Test
+ void returnsOnlyTheExactFixedDeploymentBoundaryAndHasNoRequestSelector() throws Exception {
+ var provider = provider(evidence(OWNER_EVIDENCE));
+
+ var captured = provider.currentBoundary();
+
+ assertThat(captured.environmentBoundary()).isEqualTo(ENVIRONMENT);
+ assertThat(captured.authenticatedOwnerIdentity()).isEqualTo(OWNER);
+ assertThat(captured.observationEventIdentity()).isEqualTo(EVENT);
+ assertThat(captured.ownerEvidenceDigest()).isEqualTo(OWNER_EVIDENCE_DIGEST);
+ assertThat(captured.exactOwnerEvidence()).isEqualTo(OWNER_EVIDENCE);
+ assertThat(
+ AccountHostedTermsService.CurrentEnvironmentBoundaryAuthority.class
+ .getMethod("currentBoundary")
+ .getParameterCount())
+ .isZero();
+ }
+
+ @Test
+ void rejectsEveryExpectedFieldMismatch() {
+ var evidence = evidence(OWNER_EVIDENCE);
+ String otherDigest =
+ HostedTermsEncoding.digest("different-evidence".getBytes(StandardCharsets.UTF_8));
+
+ assertMismatch("another-environment", OWNER, EVENT, OWNER_EVIDENCE_DIGEST, evidence);
+ assertMismatch(ENVIRONMENT, "another-owner", EVENT, OWNER_EVIDENCE_DIGEST, evidence);
+ assertMismatch(ENVIRONMENT, OWNER, "another-event", OWNER_EVIDENCE_DIGEST, evidence);
+ assertMismatch(ENVIRONMENT, OWNER, EVENT, otherDigest, evidence);
+ }
+
+ @Test
+ void rejectsAbsentExpectedValuesAndEvidence() {
+ assertThatThrownBy(
+ () ->
+ new AccountDeploymentEnvironmentBoundaryProvider(
+ null, OWNER, EVENT, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE)))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ new AccountDeploymentEnvironmentBoundaryProvider(
+ ENVIRONMENT, null, EVENT, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE)))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ new AccountDeploymentEnvironmentBoundaryProvider(
+ ENVIRONMENT, OWNER, null, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE)))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ new AccountDeploymentEnvironmentBoundaryProvider(
+ ENVIRONMENT, OWNER, EVENT, null, evidence(OWNER_EVIDENCE)))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ new AccountDeploymentEnvironmentBoundaryProvider(
+ ENVIRONMENT, OWNER, EVENT, OWNER_EVIDENCE_DIGEST, null))
+ .isInstanceOf(NullPointerException.class);
+ }
+
+ @Test
+ void keepsAnIndependentImmutableCopyOfTheSuppliedEvidenceBytes() {
+ byte[] callerBytes = OWNER_EVIDENCE.clone();
+ var suppliedEvidence = evidence(callerBytes);
+ var provider = provider(suppliedEvidence);
+ callerBytes[0] ^= 0x7f;
+
+ byte[] returnedBytes = provider.currentBoundary().exactOwnerEvidence();
+ returnedBytes[0] ^= 0x7f;
+
+ assertThat(provider.currentBoundary().exactOwnerEvidence()).isEqualTo(OWNER_EVIDENCE);
+ }
+
+ @Test
+ void existingBoundaryRecordRejectsBytesWithAConflictingDigest() {
+ assertThatThrownBy(
+ () ->
+ new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary(
+ ENVIRONMENT,
+ OWNER,
+ EVENT,
+ "different-evidence".getBytes(StandardCharsets.UTF_8),
+ OWNER_EVIDENCE_DIGEST))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Environment-owner evidence digest conflicts");
+ }
+
+ private static AccountDeploymentEnvironmentBoundaryProvider provider(
+ HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary evidence) {
+ return new AccountDeploymentEnvironmentBoundaryProvider(
+ ENVIRONMENT, OWNER, EVENT, OWNER_EVIDENCE_DIGEST, evidence);
+ }
+
+ private static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary evidence(byte[] bytes) {
+ return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary(
+ ENVIRONMENT, OWNER, EVENT, bytes, HostedTermsEncoding.digest(bytes));
+ }
+
+ private static void assertMismatch(
+ String environment,
+ String owner,
+ String event,
+ String digest,
+ HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary evidence) {
+ assertThatThrownBy(
+ () ->
+ new AccountDeploymentEnvironmentBoundaryProvider(
+ environment, owner, event, digest, evidence))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Deployment environment evidence differs from the fixed server boundary");
+ }
+}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java
new file mode 100644
index 0000000000..d3425b1e45
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java
@@ -0,0 +1,132 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+import java.time.LocalDateTime;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState;
+import org.jooq.DSLContext;
+import org.junit.jupiter.api.Test;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+class AccountPasswordResetOperationRepositoryTest {
+ private static final UUID ACCOUNT_UUID = UUID.fromString("c6ca3e35-9ba4-46a4-967b-f83ddb0d693e");
+ private final DSLContext dsl = mock(DSLContext.class);
+ private final AccountPasswordResetOperationRepository repository =
+ new AccountPasswordResetOperationRepository(dsl);
+
+ @Test
+ void lookupsAndInsertionRequireAnOwnerTransaction() throws ReflectiveOperationException {
+ assertMandatory(
+ AccountPasswordResetOperationRepository.class.getMethod("findByTokenHash", String.class));
+ assertMandatory(
+ AccountPasswordResetOperationRepository.class.getMethod("findByRequestId", String.class));
+ assertMandatory(
+ AccountPasswordResetOperationRepository.class.getMethod(
+ "insert", AccountPasswordResetOperationRepository.PasswordResetReceipt.class));
+
+ assertThatThrownBy(() -> repository.findByTokenHash("0".repeat(64)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("active Account transaction");
+ verifyNoInteractions(dsl);
+ }
+
+ @Test
+ void receiptEvidenceRejectsMalformedOrNonAccountBindingsBeforeStorageAccess() {
+ assertThatThrownBy(() -> receipt("not-a-hash", "0".repeat(64), "0".repeat(64)))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> receipt("0".repeat(64), "bad-digest", "0".repeat(64)))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> receipt("0".repeat(64), "0".repeat(64), "bad-verifier"))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(
+ () ->
+ new AccountPasswordResetOperationRepository.PasswordResetReceipt(
+ 9L,
+ ACCOUNT_UUID,
+ "0".repeat(64),
+ "PASSWORD_RESET",
+ "wrong-request-id",
+ 1,
+ "1".repeat(64),
+ LocalDateTime.of(2030, 1, 2, 3, 4, 5, 123456789),
+ "2".repeat(64),
+ streamKey(),
+ 1L,
+ "account-password-reset-event-v1:" + "0".repeat(64),
+ "sha256:" + "3".repeat(64),
+ 2L,
+ 2L,
+ 3L,
+ 3L))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ verifyNoInteractions(dsl);
+ }
+
+ @Test
+ void committedReceiptRetainsExactLocalDeadlineAndAccountFenceEvidence() {
+ ScopeState authority =
+ new ScopeState(
+ AuthorityScope.account(ACCOUNT_UUID), 2L, 2L, new IssuanceFence(ACCOUNT_UUID, 4L, 3L));
+ LocalDateTime localDeadline = LocalDateTime.of(2030, 1, 2, 3, 4, 5, 123456789);
+ var receipt =
+ AccountPasswordResetOperationRepository.PasswordResetReceipt.committed(
+ 9L,
+ ACCOUNT_UUID,
+ "0".repeat(64),
+ "account-password-reset-request-v1:" + "0".repeat(64),
+ "1".repeat(64),
+ localDeadline,
+ "2".repeat(64),
+ streamKey(),
+ 7L,
+ "account-password-reset-event-v1:" + "0".repeat(64),
+ "sha256:" + "3".repeat(64),
+ authority,
+ authority.issuanceFence());
+
+ assertThat(receipt.tokenExpiresAt()).isEqualTo(localDeadline);
+ assertThat(receipt.issuanceFenceEvidence()).isEqualTo(new IssuanceFence(ACCOUNT_UUID, 4L, 3L));
+ assertThat(receipt.outboxSequence()).isEqualTo(7L);
+ verifyNoInteractions(dsl);
+ }
+
+ private static AccountPasswordResetOperationRepository.PasswordResetReceipt receipt(
+ String tokenHash, String requestDigest, String verifierDigest) {
+ return new AccountPasswordResetOperationRepository.PasswordResetReceipt(
+ 9L,
+ ACCOUNT_UUID,
+ tokenHash,
+ "PASSWORD_RESET",
+ "account-password-reset-request-v1:" + tokenHash,
+ 1,
+ requestDigest,
+ LocalDateTime.of(2030, 1, 2, 3, 4, 5),
+ verifierDigest,
+ streamKey(),
+ 1L,
+ "account-password-reset-event-v1:" + tokenHash,
+ "sha256:" + "3".repeat(64),
+ 2L,
+ 2L,
+ 3L,
+ 3L);
+ }
+
+ private static String streamKey() {
+ return "account:auth-authority:v1:account/" + ACCOUNT_UUID;
+ }
+
+ private void assertMandatory(java.lang.reflect.Method method) {
+ Transactional annotation = method.getAnnotation(Transactional.class);
+ assertThat(annotation).isNotNull();
+ assertThat(annotation.propagation()).isEqualTo(Propagation.MANDATORY);
+ }
+}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java
new file mode 100644
index 0000000000..018de0893d
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java
@@ -0,0 +1,116 @@
+package net.firedevops.firemud.accountservice.service;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository;
+import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository;
+import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.GameTenantCreationDigest;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+@ExtendWith(MockitoExtension.class)
+class AccountCreatorMembershipSourceReaderTest {
+ @Mock private AccountRepository accounts;
+ @Mock private AccountJoinOperationRepository joins;
+ @Mock private AccountTenantMembershipRepository memberships;
+ @Mock private AccountMembershipPairAuthorityRepository pairs;
+ @Mock private AccountTenantMembershipRoleSnapshotRepository roles;
+ @Mock private FreshTenantIdentityAssociationRepository fresh;
+ @Mock private AccountAuthorityGenerationRepository generations;
+ @Mock private AccountAuthorityOutboxRepository outbox;
+ @Mock private AccountAuthoritySourceEvidenceRepository sources;
+ @Mock private AccountTenantCreationBootstrapOperationRepository operations;
+ @Mock private CompositeSnapshot upstream;
+ @InjectMocks private AccountCreatorMembershipSourceReader reader;
+
+ @AfterEach
+ void clearTransactionState() {
+ TransactionSynchronizationManager.setActualTransactionActive(false);
+ TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
+ }
+
+ @Test
+ void requiresWritableOwnerTransactionBeforeReadingOrEnrollingAnything() {
+ assertThatThrownBy(
+ () ->
+ reader.readFreshNeverJoinedMembershipSnapshot(UUID.randomUUID(), UUID.randomUUID()))
+ .isInstanceOf(IllegalStateException.class);
+ verifyNoInteractions(
+ accounts,
+ joins,
+ memberships,
+ pairs,
+ roles,
+ fresh,
+ generations,
+ outbox,
+ sources,
+ operations);
+ }
+
+ @Test
+ void missingGenuineUpstreamSourcesCannotCreateAnAbsenceBaseline() {
+ UUID accountUuid = UUID.randomUUID();
+ UUID tenantUuid = UUID.randomUUID();
+ Account account = new Account();
+ account.setId(17L);
+ account.setAccountUuid(accountUuid);
+ account.setAccountUuidSourceNumericId(17L);
+ account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT);
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+ when(accounts.findByAccountUuidForUpdate(accountUuid)).thenReturn(Optional.of(account));
+ when(fresh.read(tenantUuid)).thenReturn(Optional.of(creation(tenantUuid)));
+ when(generations.readCompositeSnapshot(
+ "firemud-account-service", accountUuid, List.of(tenantUuid), List.of()))
+ .thenReturn(upstream);
+ when(sources.readCurrentIssuerAccountSources("firemud-account-service", accountUuid))
+ .thenThrow(new IllegalStateException("Genuine Account source baseline is unavailable"));
+ assertThatThrownBy(() -> reader.readFreshNeverJoinedMembershipSnapshot(accountUuid, tenantUuid))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("source baseline is unavailable");
+ verifyNoInteractions(memberships, pairs, roles, outbox, operations);
+ }
+
+ private static FreshTenantCreationEvidence creation(UUID tenantUuid) {
+ UUID request = UUID.randomUUID();
+ UUID operation = UUID.randomUUID();
+ String namespace = "creator-source-proof";
+ String key = "creator-game";
+ String digest =
+ GameTenantCreationDigest.requestDigest(namespace, request, key, "Creator", null);
+ return new FreshTenantCreationEvidence(
+ 1,
+ namespace,
+ request,
+ operation,
+ digest,
+ tenantUuid,
+ 17L,
+ key,
+ "NEW_GAME_ROW",
+ GameTenantCreationDigest.evidenceDigest(
+ namespace, request, operation, digest, tenantUuid, 17L, key, "NEW_GAME_ROW"));
+ }
+}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java
new file mode 100644
index 0000000000..3b4e032e55
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java
@@ -0,0 +1,240 @@
+package unit.net.firedevops.firemud.accountservice.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest;
+import net.firedevops.firemud.accountservice.entity.Account;
+import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository;
+import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback;
+import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer;
+import net.firedevops.firemud.accountservice.service.AccountLogoutAllDraftSourceChangeRepository;
+import org.jooq.DSLContext;
+import org.junit.jupiter.api.Test;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+class AccountLogoutAllAuthorityEventProducerTest {
+ private static final UUID ACCOUNT_UUID = UUID.fromString("7439d275-a8bd-4ad2-8993-3c9d30e86472");
+ private static final String TOKEN_PROFILE = "control-ui";
+ private static final String TOKEN_HASH = "b".repeat(64);
+ private static final String REQUEST_DIGEST =
+ AccountLogoutRequestDigest.accountLogoutAll(ACCOUNT_UUID, TOKEN_PROFILE, TOKEN_HASH);
+
+ @Test
+ void pendingSourceChangeExposesOnlyItsStableRecoveryIdentity() {
+ UUID changeId = UUID.randomUUID();
+
+ var pending =
+ new AccountLogoutAllDraftSourceChangeRepository.PendingSourceChangeException(changeId);
+
+ assertThat(pending.sourceChangeId()).isEqualTo(changeId);
+ assertThat(pending.getMessage()).contains(changeId.toString()).doesNotContain(TOKEN_HASH);
+ }
+
+ @Test
+ void rejectsMalformedRequestEvidenceBeforeDatabaseOrTransactionInteraction() {
+ Collaborators collaborators = new Collaborators();
+ AccountLogoutAllAuthorityEventProducer producer = newProducer(collaborators);
+ Account account = account();
+ var expected =
+ new AccountAuthorityGenerationRepository.ScopeState(
+ AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID),
+ 1L,
+ 1L,
+ new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L));
+
+ assertThatThrownBy(
+ () ->
+ producer.commit(
+ new UUID(0L, 0L),
+ 1,
+ REQUEST_DIGEST,
+ TOKEN_PROFILE,
+ TOKEN_HASH,
+ account,
+ expected))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("non-nil");
+ assertThatThrownBy(
+ () ->
+ producer.commit(
+ UUID.randomUUID(),
+ 0,
+ REQUEST_DIGEST,
+ TOKEN_PROFILE,
+ TOKEN_HASH,
+ account,
+ expected))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("positive");
+ assertThatThrownBy(
+ () ->
+ producer.commit(
+ UUID.randomUUID(),
+ 1,
+ "A".repeat(64),
+ TOKEN_PROFILE,
+ TOKEN_HASH,
+ account,
+ expected))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("lowercase SHA-256");
+ assertThatThrownBy(
+ () ->
+ producer.commit(
+ UUID.randomUUID(),
+ 1,
+ REQUEST_DIGEST,
+ TOKEN_PROFILE,
+ "b".repeat(63),
+ account,
+ expected))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("token hash");
+ assertThatThrownBy(
+ () ->
+ producer.commit(
+ UUID.randomUUID(),
+ 1,
+ REQUEST_DIGEST,
+ "private-player-delegation",
+ TOKEN_HASH,
+ account,
+ expected))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("token profile");
+
+ collaborators.verifyUnused();
+ }
+
+ @Test
+ void rejectsAmbientTransactionAndDoesNotUseExpectedStateAsCallerAuthorization() {
+ Collaborators collaborators = new Collaborators();
+ AccountLogoutAllAuthorityEventProducer producer = newProducer(collaborators);
+ Account account = account();
+ var expected =
+ new AccountAuthorityGenerationRepository.ScopeState(
+ AccountAuthorityGenerationRepository.AuthorityScope.account(ACCOUNT_UUID),
+ 1L,
+ 1L,
+ new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L));
+ boolean previouslyActive = TransactionSynchronizationManager.isActualTransactionActive();
+ TransactionSynchronizationManager.setActualTransactionActive(true);
+
+ try {
+ assertThatThrownBy(
+ () ->
+ producer.commit(
+ UUID.randomUUID(),
+ 1,
+ REQUEST_DIGEST,
+ TOKEN_PROFILE,
+ TOKEN_HASH,
+ account,
+ expected))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("without an ambient transaction");
+ collaborators.verifyUnused();
+ } finally {
+ TransactionSynchronizationManager.setActualTransactionActive(previouslyActive);
+ }
+ }
+
+ @Test
+ void rejectsMismatchedExpectedSourceScopeBeforeDatabaseInteraction() {
+ Collaborators collaborators = new Collaborators();
+ AccountLogoutAllAuthorityEventProducer producer = newProducer(collaborators);
+ Account account = account();
+ var wrongScope =
+ new AccountAuthorityGenerationRepository.ScopeState(
+ AccountAuthorityGenerationRepository.AuthorityScope.account(UUID.randomUUID()),
+ 1L,
+ 1L,
+ new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L));
+
+ assertThatThrownBy(
+ () ->
+ producer.commit(
+ UUID.randomUUID(),
+ 1,
+ REQUEST_DIGEST,
+ TOKEN_PROFILE,
+ TOKEN_HASH,
+ account,
+ wrongScope))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Expected Account authority scope");
+
+ collaborators.verifyUnused();
+ }
+
+ private AccountLogoutAllAuthorityEventProducer newProducer(Collaborators collaborators) {
+ AccountAuthoritySourceEventReadback readback =
+ new AccountAuthoritySourceEventReadback(
+ collaborators.outboxRepository(),
+ collaborators.passwordResetRepository(),
+ collaborators.logoutAllRepository(),
+ collaborators.securityStateRepository());
+ return new AccountLogoutAllAuthorityEventProducer(
+ collaborators.accountRepository(),
+ collaborators.generationRepository(),
+ collaborators.outboxRepository(),
+ collaborators.logoutAllRepository(),
+ readback,
+ collaborators.dsl(),
+ collaborators.transactionManager());
+ }
+
+ private Account account() {
+ Account account = new Account();
+ account.setId(7L);
+ account.setAccountUuid(ACCOUNT_UUID);
+ account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT);
+ account.setAccountUuidSourceNumericId(7L);
+ return account;
+ }
+
+ private record Collaborators(
+ AccountRepository accountRepository,
+ AccountAuthorityGenerationRepository generationRepository,
+ AccountAuthorityOutboxRepository outboxRepository,
+ AccountPasswordResetOperationRepository passwordResetRepository,
+ AccountLogoutAllOperationRepository logoutAllRepository,
+ AccountSecurityStateOperationRepository securityStateRepository,
+ DSLContext dsl,
+ PlatformTransactionManager transactionManager) {
+ private Collaborators() {
+ this(
+ mock(AccountRepository.class),
+ mock(AccountAuthorityGenerationRepository.class),
+ mock(AccountAuthorityOutboxRepository.class),
+ mock(AccountPasswordResetOperationRepository.class),
+ mock(AccountLogoutAllOperationRepository.class),
+ mock(AccountSecurityStateOperationRepository.class),
+ mock(DSLContext.class),
+ mock(PlatformTransactionManager.class));
+ }
+
+ private void verifyUnused() {
+ verifyNoInteractions(
+ accountRepository,
+ generationRepository,
+ outboxRepository,
+ passwordResetRepository,
+ logoutAllRepository,
+ securityStateRepository,
+ dsl,
+ transactionManager);
+ }
+ }
+}
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 2907cccc68..f8ac0774ca 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
@@ -52,17 +52,23 @@
import net.firedevops.firemud.accountservice.mapper.AccountMapper;
import net.firedevops.firemud.accountservice.mapper.ProfileMapper;
import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository;
import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository;
import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository;
import net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository;
import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository;
import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository;
import net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository;
import net.firedevops.firemud.accountservice.repository.ExternalAccountRepository;
import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository;
import net.firedevops.firemud.accountservice.repository.ProfileRepository;
import net.firedevops.firemud.accountservice.repository.SubscriptionRepository;
+import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository;
import net.firedevops.firemud.accountservice.service.EmailService;
import net.firedevops.firemud.accountservice.service.NotificationService;
import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException;
@@ -97,6 +103,16 @@ class AccountServiceImplTest {
private static final String PLAYABLE_STATE_NAMESPACE_ID_TENANT_8 =
"a741a4b8-a2cb-405e-a330-8fbf3dfb841f";
@Mock private AccountRepository accountRepository;
+ @Mock private AccountAuthorityGenerationRepository accountAuthorityGenerationRepository;
+ @Mock private AccountAuthorityOutboxRepository accountAuthorityOutboxRepository;
+ @Mock private AccountPasswordResetOperationRepository accountPasswordResetOperationRepository;
+ @Mock private AccountLogoutAllOperationRepository accountLogoutAllOperationRepository;
+ @Mock private AccountSecurityStateOperationRepository accountSecurityStateOperationRepository;
+
+ @Mock
+ private AccountPasswordResetDraftSourceChangeRepository
+ accountPasswordResetDraftSourceChangeRepository;
+
@Mock private AccountAuditOutboxRepository accountAuditOutboxRepository;
@Mock private AccountConnectScopeRepository accountConnectScopeRepository;
@Mock private AccountJoinOperationRepository accountJoinOperationRepository;
@@ -207,6 +223,12 @@ void setup() {
service =
new AccountServiceImpl(
accountRepository,
+ accountAuthorityGenerationRepository,
+ accountAuthorityOutboxRepository,
+ accountPasswordResetOperationRepository,
+ accountLogoutAllOperationRepository,
+ accountSecurityStateOperationRepository,
+ accountPasswordResetDraftSourceChangeRepository,
accountAuditOutboxRepository,
accountConnectScopeRepository,
accountJoinOperationRepository,
@@ -2196,6 +2218,12 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() {
service =
new AccountServiceImpl(
accountRepository,
+ accountAuthorityGenerationRepository,
+ accountAuthorityOutboxRepository,
+ accountPasswordResetOperationRepository,
+ accountLogoutAllOperationRepository,
+ accountSecurityStateOperationRepository,
+ accountPasswordResetDraftSourceChangeRepository,
accountAuditOutboxRepository,
accountConnectScopeRepository,
accountJoinOperationRepository,
@@ -5697,17 +5725,30 @@ void requestPasswordResetCreatesToken() {
void missingRetainedSourceDeniesPasswordResetBeforeTokenConsumption() {
var account = new Account();
account.setId(2L);
+ account.setAccountUuid(UUID.randomUUID());
+ account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT);
+ account.setAccountUuidSourceNumericId(2L);
account.setPasswordHash("original-password-hash");
var token = new net.firedevops.firemud.accountservice.entity.PasswordResetToken();
+ token.setId(7L);
token.setAccount(account);
token.setToken("retained-reset-token");
token.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(10));
when(passwordResetTokenRepository.findByToken(token.getToken())).thenReturn(Optional.of(token));
+ when(accountRepository.findByIdForUpdate(account.getId())).thenReturn(Optional.of(account));
+ when(accountPasswordResetOperationRepository.findByTokenHash(
+ org.mockito.ArgumentMatchers.anyString()))
+ .thenReturn(Optional.empty());
+ when(accountPasswordResetDraftSourceChangeRepository.findAccountIdByTokenHash(
+ org.mockito.ArgumentMatchers.anyString()))
+ .thenReturn(Optional.empty());
org.mockito.Mockito.doThrow(
new net.firedevops.firemud.accountservice.repository
.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException())
- .when(accountRepository)
- .save(account);
+ .when(accountAuthorityGenerationRepository)
+ .read(
+ net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository
+ .AuthorityScope.account(account.getAccountUuid()));
assertThrows(
net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository
.SourceEvidenceUnavailableException.class,
@@ -5716,8 +5757,11 @@ void missingRetainedSourceDeniesPasswordResetBeforeTokenConsumption() {
new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest(
token.getToken(), "new-password")));
org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never())
- .delete(token);
- org.mockito.Mockito.verify(accountRepository).save(account);
+ .consumeIfUnexpired(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any());
+ org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()).save(account);
+ org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never())
+ .updatePasswordHashForLockedAccount(
+ org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString());
}
@Test
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java
new file mode 100644
index 0000000000..b3e2c49bf0
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java
@@ -0,0 +1,106 @@
+package unit.net.firedevops.firemud.accountservice.service.session;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence;
+import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot;
+import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint;
+import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection;
+import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile;
+import org.junit.jupiter.api.Test;
+
+class AccountGameplayDelegationAuthorityProjectionTest {
+ @Test
+ void canonicalProjectionPairMatchesDonorSequenceZeroGoldenVector() {
+ UUID accountId = UUID.fromString("b4ec84c2-50c8-4cec-8d92-a8603d1c53f0");
+ IssuerAccountSourceSnapshot source = sequenceZeroSnapshot(accountId);
+
+ byte[][] actual = AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source);
+
+ assertThat(new String(actual[0], StandardCharsets.UTF_8))
+ .isEqualTo(
+ "{\"schemaVersion\":\"account-auth-issuer-generation-projection/v1\","
+ + "\"issuerId\":\""
+ + GameSessionAccountDelegationProfile.ISSUER
+ + "\",\"issuerAuthGeneration\":\"1\",\"sourceVersion\":\"1\","
+ + "\"outboxStreamKey\":\"account:auth-authority:v1:issuer/"
+ + GameSessionAccountDelegationProfile.ISSUER
+ + "\",\"lastAppliedSourceOutboxSequence\":\"0\"}");
+ assertThat(new String(actual[1], StandardCharsets.UTF_8))
+ .isEqualTo(
+ "{\"schemaVersion\":\"account-auth-account-generation-projection/v1\","
+ + "\"accountId\":\""
+ + accountId
+ + "\",\"accountAuthorityGeneration\":\"1\",\"sourceVersion\":\"1\","
+ + "\"outboxStreamKey\":\"account:auth-authority:v1:account/"
+ + accountId
+ + "\",\"outboxSequence\":\"0\"}");
+ }
+
+ @Test
+ void canonicalProjectionPairRejectsMissingAccountProjection() {
+ UUID accountId = UUID.fromString("b4ec84c2-50c8-4cec-8d92-a8603d1c53f0");
+ IssuerAccountSourceSnapshot valid = sequenceZeroSnapshot(accountId);
+ IssuerAccountSourceSnapshot missingAccountProjection =
+ new IssuerAccountSourceSnapshot(
+ valid.issuer(),
+ valid.account(),
+ valid.issuanceFence(),
+ null,
+ valid.canonicalIssuerProjection());
+
+ assertThatThrownBy(
+ () ->
+ AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(
+ missingAccountProjection))
+ .isInstanceOf(
+ AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class);
+ }
+
+ private static IssuerAccountSourceSnapshot sequenceZeroSnapshot(UUID accountId) {
+ String issuerId = GameSessionAccountDelegationProfile.ISSUER;
+ CurrentSourceEvidence issuer =
+ new CurrentSourceEvidence(
+ AuthorityScope.issuer(issuerId),
+ 1L,
+ 1L,
+ null,
+ new SourceCheckpoint(
+ "account:auth-authority:v1:issuer/" + issuerId,
+ 0L,
+ Optional.empty(),
+ Optional.empty()),
+ Optional.empty(),
+ "ISSUER_SCOPE_INSERT",
+ null,
+ null,
+ 10L,
+ null);
+ var fence = new IssuanceFence(accountId, 1L, 1L);
+ CurrentSourceEvidence account =
+ new CurrentSourceEvidence(
+ AuthorityScope.account(accountId),
+ 1L,
+ 1L,
+ fence,
+ new SourceCheckpoint(
+ "account:auth-authority:v1:account/" + accountId,
+ 0L,
+ Optional.empty(),
+ Optional.empty()),
+ Optional.empty(),
+ "ACCOUNT_REPOSITORY_INSERT",
+ 42L,
+ AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name(),
+ 20L,
+ 20L);
+ return new IssuerAccountSourceSnapshot(issuer, account, fence);
+ }
+}
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java
new file mode 100644
index 0000000000..a9234264b4
--- /dev/null
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java
@@ -0,0 +1,355 @@
+package net.firedevops.firemud.common.account.authority;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.StreamReadFeature;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+
+/** Strict codec for committed Account logout-all authority events. */
+public final class AccountLogoutAllAuthorityEventV1Codec {
+ public static final String SCHEMA_VERSION = "account-auth-logout-all-event/v1";
+ public static final String EVENT_TYPE = "LOGOUT_ALL_COMMITTED";
+ public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:";
+ public static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:";
+
+ private static final Set PREIMAGE_FIELDS =
+ Set.of(
+ "schemaVersion",
+ "eventType",
+ "eventId",
+ "requestId",
+ "accountId",
+ "sourceScope",
+ "outboxStreamKey",
+ "outboxSequence",
+ "accountAuthorityGeneration",
+ "sourceVersion",
+ "accountSecurityCutoff");
+ private static final Set WIRE_FIELDS;
+ private static final Set ACCOUNT_CUTOFF_FIELDS =
+ Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence");
+ private static final Pattern UUID_PATTERN =
+ Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
+ private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000";
+ private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*");
+ private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}");
+ private static final ObjectMapper JSON =
+ new ObjectMapper(
+ JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build())
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
+
+ static {
+ var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS);
+ wireFields.add("eventDigest");
+ WIRE_FIELDS = Set.copyOf(wireFields);
+ }
+
+ private AccountLogoutAllAuthorityEventV1Codec() {}
+
+ /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */
+ public static AccountLogoutAllAuthorityEvent seal(Map preimage) {
+ Objects.requireNonNull(preimage, "preimage must not be null");
+ JsonNode tree = JSON.valueToTree(preimage);
+ if (!(tree instanceof ObjectNode object)) {
+ throw invalid("event", "must be a JSON object");
+ }
+ validatePreimage(object);
+ String digest = digest(object);
+ ObjectNode wire = object.deepCopy();
+ wire.put("eventDigest", digest);
+ return toEvidence(wire, digest, canonicalJson(wire));
+ }
+
+ /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */
+ public static AccountLogoutAllAuthorityEvent verify(String wireJson) {
+ Objects.requireNonNull(wireJson, "wireJson must not be null");
+ final JsonNode tree;
+ try {
+ // Canonicalization rejects duplicate JSON object properties before Jackson builds a tree.
+ Rfc8785CanonicalJson.canonicalizeUtf8(wireJson);
+ tree = JSON.readTree(wireJson);
+ } catch (IOException exception) {
+ throw new IllegalArgumentException("event JSON is malformed", exception);
+ }
+ if (!(tree instanceof ObjectNode wire)) {
+ throw invalid("event", "must be a JSON object");
+ }
+ return verifyWireNode(wire);
+ }
+
+ private static AccountLogoutAllAuthorityEvent verifyWireNode(ObjectNode wire) {
+ requireExactFields(wire, WIRE_FIELDS, "event");
+ String suppliedDigest = requireText(wire, "eventDigest", "event");
+ if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) {
+ throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits");
+ }
+ ObjectNode preimage = wire.deepCopy();
+ preimage.remove("eventDigest");
+ validatePreimage(preimage);
+ String expectedDigest = digest(preimage);
+ if (!MessageDigest.isEqual(
+ suppliedDigest.getBytes(StandardCharsets.US_ASCII),
+ expectedDigest.getBytes(StandardCharsets.US_ASCII))) {
+ throw invalid("eventDigest", "does not match the canonical event preimage");
+ }
+ return toEvidence(wire, suppliedDigest, canonicalJson(wire));
+ }
+
+ private static void validatePreimage(ObjectNode event) {
+ requireExactFields(event, PREIMAGE_FIELDS, "event preimage");
+ requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event");
+ requireExactText(event, "eventType", EVENT_TYPE, "event");
+
+ String requestId = requireUuid(event, "requestId", "event");
+ requireExactText(event, "eventId", EVENT_ID_PREFIX + requestId, "event");
+ String accountId = requireUuid(event, "accountId", "event");
+ String sourceScope = "account/" + accountId;
+ String streamKey = EVENT_STREAM_PREFIX + sourceScope;
+ requireExactText(event, "sourceScope", sourceScope, "event");
+ requireExactText(event, "outboxStreamKey", streamKey, "event");
+
+ String outboxSequence = requirePositiveDecimal(event, "outboxSequence", "event");
+ String accountAuthorityGeneration =
+ requirePositiveDecimal(event, "accountAuthorityGeneration", "event");
+ requirePositiveDecimal(event, "sourceVersion", "event");
+
+ JsonNode cutoffNode = event.get("accountSecurityCutoff");
+ if (!(cutoffNode instanceof ObjectNode cutoff)) {
+ throw invalid("accountSecurityCutoff", "must be a required JSON object");
+ }
+ requireExactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, "accountSecurityCutoff");
+ String cutoffGeneration =
+ requirePositiveDecimal(cutoff, "accountAuthorityGeneration", "accountSecurityCutoff");
+ String cutoffStream = requireText(cutoff, "outboxStreamKey", "accountSecurityCutoff");
+ String cutoffSequence =
+ requirePositiveDecimal(cutoff, "outboxSequence", "accountSecurityCutoff");
+ if (!accountAuthorityGeneration.equals(cutoffGeneration)) {
+ throw invalid(
+ "accountSecurityCutoff.accountAuthorityGeneration",
+ "must equal event.accountAuthorityGeneration");
+ }
+ if (!streamKey.equals(cutoffStream)) {
+ throw invalid("accountSecurityCutoff.outboxStreamKey", "must equal event.outboxStreamKey");
+ }
+ if (!outboxSequence.equals(cutoffSequence)) {
+ throw invalid("accountSecurityCutoff.outboxSequence", "must equal event.outboxSequence");
+ }
+ }
+
+ private static AccountLogoutAllAuthorityEvent toEvidence(
+ ObjectNode wire, String digest, String canonicalJson) {
+ ObjectNode cutoff = (ObjectNode) wire.get("accountSecurityCutoff");
+ return new AccountLogoutAllAuthorityEvent(
+ wire.path("schemaVersion").textValue(),
+ wire.path("eventType").textValue(),
+ wire.path("eventId").textValue(),
+ wire.path("requestId").textValue(),
+ wire.path("accountId").textValue(),
+ wire.path("sourceScope").textValue(),
+ wire.path("outboxStreamKey").textValue(),
+ wire.path("outboxSequence").textValue(),
+ wire.path("accountAuthorityGeneration").textValue(),
+ wire.path("sourceVersion").textValue(),
+ new AccountSecurityCutoff(
+ cutoff.path("accountAuthorityGeneration").textValue(),
+ cutoff.path("outboxStreamKey").textValue(),
+ cutoff.path("outboxSequence").textValue()),
+ digest,
+ canonicalJson);
+ }
+
+ private static void requireExactFields(ObjectNode object, Set required, String path) {
+ Set actual = new java.util.HashSet<>();
+ object.fieldNames().forEachRemaining(actual::add);
+ if (!actual.equals(required)) {
+ Set missing = new java.util.HashSet<>(required);
+ missing.removeAll(actual);
+ Set unexpected = new java.util.HashSet<>(actual);
+ unexpected.removeAll(required);
+ StringBuilder message = new StringBuilder("must contain exactly the declared fields");
+ if (!missing.isEmpty()) {
+ message.append("; missing ").append(missing);
+ }
+ if (!unexpected.isEmpty()) {
+ message.append("; unexpected ").append(unexpected);
+ }
+ throw invalid(path, message.toString());
+ }
+ }
+
+ private static String requireExactText(
+ ObjectNode object, String field, String expected, String path) {
+ String value = requireText(object, field, path);
+ if (!expected.equals(value)) {
+ throw invalid(path + "." + field, "must equal " + expected);
+ }
+ return value;
+ }
+
+ private static String requireText(ObjectNode object, String field, String path) {
+ JsonNode value = object.get(field);
+ if (value == null || !value.isTextual()) {
+ throw invalid(path + "." + field, "must be a required string");
+ }
+ return value.textValue();
+ }
+
+ private static String requireUuid(ObjectNode object, String field, String path) {
+ String value = requireText(object, field, path);
+ if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) {
+ throw invalid(path + "." + field, "must be a canonical lowercase non-nil UUID");
+ }
+ return value;
+ }
+
+ private static String requirePositiveDecimal(ObjectNode object, String field, String path) {
+ String value = requireText(object, field, path);
+ if (!POSITIVE_DECIMAL_PATTERN.matcher(value).matches()) {
+ throw invalid(path + "." + field, "must be a positive canonical decimal string");
+ }
+ return value;
+ }
+
+ private static String digest(ObjectNode preimage) {
+ try {
+ byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString());
+ byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical);
+ return "sha256:" + java.util.HexFormat.of().formatHex(hash);
+ } catch (IOException exception) {
+ throw new IllegalArgumentException("event preimage cannot be canonicalized", exception);
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is unavailable", exception);
+ }
+ }
+
+ private static String canonicalJson(ObjectNode wire) {
+ try {
+ return new String(
+ Rfc8785CanonicalJson.canonicalizeUtf8(wire.toString()), StandardCharsets.UTF_8);
+ } catch (IOException exception) {
+ throw new IllegalArgumentException("event cannot be canonicalized", exception);
+ }
+ }
+
+ private static IllegalArgumentException invalid(String path, String message) {
+ return new IllegalArgumentException(path + " " + message);
+ }
+
+ /** Immutable verified or producer-sealed logout-all event evidence. */
+ public static final class AccountLogoutAllAuthorityEvent {
+ private final String schemaVersion;
+ private final String eventType;
+ private final String eventId;
+ private final String requestId;
+ private final String accountId;
+ private final String sourceScope;
+ private final String outboxStreamKey;
+ private final String outboxSequence;
+ private final String accountAuthorityGeneration;
+ private final String sourceVersion;
+ private final AccountSecurityCutoff accountSecurityCutoff;
+ private final String eventDigest;
+ private final String canonicalJson;
+
+ private AccountLogoutAllAuthorityEvent(
+ String schemaVersion,
+ String eventType,
+ String eventId,
+ String requestId,
+ String accountId,
+ String sourceScope,
+ String outboxStreamKey,
+ String outboxSequence,
+ String accountAuthorityGeneration,
+ String sourceVersion,
+ AccountSecurityCutoff accountSecurityCutoff,
+ String eventDigest,
+ String canonicalJson) {
+ this.schemaVersion = schemaVersion;
+ this.eventType = eventType;
+ this.eventId = eventId;
+ this.requestId = requestId;
+ this.accountId = accountId;
+ this.sourceScope = sourceScope;
+ this.outboxStreamKey = outboxStreamKey;
+ this.outboxSequence = outboxSequence;
+ this.accountAuthorityGeneration = accountAuthorityGeneration;
+ this.sourceVersion = sourceVersion;
+ this.accountSecurityCutoff = accountSecurityCutoff;
+ this.eventDigest = eventDigest;
+ this.canonicalJson = canonicalJson;
+ }
+
+ public String schemaVersion() {
+ return schemaVersion;
+ }
+
+ public String eventType() {
+ return eventType;
+ }
+
+ public String eventId() {
+ return eventId;
+ }
+
+ public String requestId() {
+ return requestId;
+ }
+
+ public String accountId() {
+ return accountId;
+ }
+
+ public String sourceScope() {
+ return sourceScope;
+ }
+
+ public String outboxStreamKey() {
+ return outboxStreamKey;
+ }
+
+ public String outboxSequence() {
+ return outboxSequence;
+ }
+
+ public String accountAuthorityGeneration() {
+ return accountAuthorityGeneration;
+ }
+
+ public String sourceVersion() {
+ return sourceVersion;
+ }
+
+ public AccountSecurityCutoff accountSecurityCutoff() {
+ return accountSecurityCutoff;
+ }
+
+ public String eventDigest() {
+ return eventDigest;
+ }
+
+ public String canonicalJson() {
+ return canonicalJson;
+ }
+
+ /** Returns a caller-owned copy of the canonical complete wire event bytes. */
+ public byte[] canonicalJsonUtf8() {
+ return canonicalJson.getBytes(StandardCharsets.UTF_8);
+ }
+ }
+
+ /** Immutable Account security cutoff checkpoint. */
+ public record AccountSecurityCutoff(
+ String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {}
+}
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java
new file mode 100644
index 0000000000..c9ebc30d2f
--- /dev/null
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java
@@ -0,0 +1,391 @@
+package net.firedevops.firemud.common.account.authority;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.StreamReadFeature;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+
+/** Closed source evidence for one Account-owned, non-password security-state mutation. */
+public final class AccountSecurityStateAuthorityEventV1Codec {
+ public static final String SCHEMA_VERSION = "account-auth-account-security-state-event/v1";
+ public static final String EVENT_TYPE = "ACCOUNT_SECURITY_STATE_CHANGED";
+ public static final String EVENT_ID_PREFIX = "account-security-state-event-v1:";
+ public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:";
+
+ private static final Set PREIMAGE_FIELDS =
+ Set.of(
+ "schemaVersion",
+ "eventType",
+ "eventId",
+ "requestId",
+ "accountId",
+ "sourceScope",
+ "outboxStreamKey",
+ "outboxSequence",
+ "accountAuthorityGeneration",
+ "sourceVersion",
+ "accountSecurityCutoff",
+ "mutationKinds",
+ "accountState");
+ private static final Set WIRE_FIELDS;
+ private static final Set CUTOFF_FIELDS =
+ Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence");
+ private static final Set STATE_FIELDS =
+ Set.of("emailVerified", "loginAuthModes", "globalRoles", "lifecycleState");
+ private static final Set MUTATION_KINDS =
+ Set.of(
+ "EMAIL_LOGIN_ELIGIBILITY_CHANGED",
+ "LOGIN_AUTH_MODES_CHANGED",
+ "GLOBAL_ROLE_CHANGED",
+ "LIFECYCLE_STATE_CHANGED");
+ private static final Set LOGIN_MODES = Set.of("EMAIL_OTP", "PASSWORD");
+ private static final Set GLOBAL_ROLES =
+ Set.of("platformAdmin", "support", "billingAdmin");
+ private static final Set LIFECYCLE_STATES =
+ Set.of("ACTIVE", "SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED");
+ private static final Pattern UUID_PATTERN =
+ Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
+ private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*");
+ private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}");
+ private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000";
+ private static final ObjectMapper JSON =
+ new ObjectMapper(
+ JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build())
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
+
+ static {
+ var fields = new java.util.HashSet<>(PREIMAGE_FIELDS);
+ fields.add("eventDigest");
+ WIRE_FIELDS = Set.copyOf(fields);
+ }
+
+ private AccountSecurityStateAuthorityEventV1Codec() {}
+
+ /** Seals the complete declared preimage; caller authorization and receipt proof are separate. */
+ public static AccountSecurityStateAuthorityEvent seal(Map preimage) {
+ Objects.requireNonNull(preimage, "event preimage is required");
+ JsonNode tree = JSON.valueToTree(preimage);
+ if (!(tree instanceof ObjectNode object)) {
+ throw invalid("event preimage must be an object");
+ }
+ validatePreimage(object);
+ String digest = digest(object);
+ ObjectNode wire = object.deepCopy();
+ wire.put("eventDigest", digest);
+ return evidence(wire, digest);
+ }
+
+ /** Verifies the closed payload and digest, returning complete immutable canonical evidence. */
+ public static AccountSecurityStateAuthorityEvent verify(String wireJson) {
+ Objects.requireNonNull(wireJson, "event JSON is required");
+ final JsonNode tree;
+ try {
+ Rfc8785CanonicalJson.canonicalizeUtf8(wireJson);
+ tree = JSON.readTree(wireJson);
+ } catch (IOException exception) {
+ throw new IllegalArgumentException("event JSON is malformed", exception);
+ }
+ if (!(tree instanceof ObjectNode wire)) {
+ throw invalid("event must be an object");
+ }
+ exactFields(wire, WIRE_FIELDS);
+ String supplied = text(wire, "eventDigest");
+ if (!DIGEST_PATTERN.matcher(supplied).matches()) {
+ throw invalid("eventDigest must be canonical sha256 hexadecimal");
+ }
+ ObjectNode preimage = wire.deepCopy();
+ preimage.remove("eventDigest");
+ validatePreimage(preimage);
+ if (!MessageDigest.isEqual(
+ supplied.getBytes(StandardCharsets.US_ASCII),
+ digest(preimage).getBytes(StandardCharsets.US_ASCII))) {
+ throw invalid("eventDigest does not match the complete canonical preimage");
+ }
+ return evidence(wire, supplied);
+ }
+
+ private static void validatePreimage(ObjectNode event) {
+ exactFields(event, PREIMAGE_FIELDS);
+ equalText(event, "schemaVersion", SCHEMA_VERSION);
+ equalText(event, "eventType", EVENT_TYPE);
+ String requestId = uuid(event, "requestId");
+ equalText(event, "eventId", EVENT_ID_PREFIX + requestId);
+ String scope = "account/" + uuid(event, "accountId");
+ equalText(event, "sourceScope", scope);
+ equalText(event, "outboxStreamKey", EVENT_STREAM_PREFIX + scope);
+ positive(event, "outboxSequence");
+ positive(event, "accountAuthorityGeneration");
+ positive(event, "sourceVersion");
+ ObjectNode cutoff = object(event, "accountSecurityCutoff");
+ exactFields(cutoff, CUTOFF_FIELDS);
+ positive(cutoff, "accountAuthorityGeneration");
+ positive(cutoff, "outboxSequence");
+ for (String field : CUTOFF_FIELDS) {
+ equalText(cutoff, field, text(event, field));
+ }
+ orderedValues(event.get("mutationKinds"), MUTATION_KINDS, "mutationKinds");
+ ObjectNode state = object(event, "accountState");
+ exactFields(state, STATE_FIELDS);
+ if (!state.get("emailVerified").isBoolean()) {
+ throw invalid("accountState.emailVerified must be a boolean");
+ }
+ orderedValues(state.get("loginAuthModes"), LOGIN_MODES, "accountState.loginAuthModes");
+ orderedValues(state.get("globalRoles"), GLOBAL_ROLES, "accountState.globalRoles", true);
+ if (!LIFECYCLE_STATES.contains(text(state, "lifecycleState"))) {
+ throw invalid("accountState.lifecycleState is unsupported");
+ }
+ }
+
+ private static List orderedValues(JsonNode array, Set allowed, String field) {
+ return orderedValues(array, allowed, field, false);
+ }
+
+ private static List orderedValues(
+ JsonNode array, Set allowed, String field, boolean allowEmpty) {
+ if (array == null || !array.isArray() || (!allowEmpty && array.isEmpty())) {
+ throw invalid(field + " must be a declared array with supported cardinality");
+ }
+ List values = new ArrayList<>();
+ String previous = null;
+ for (JsonNode item : array) {
+ if (!item.isTextual() || !allowed.contains(item.textValue())) {
+ throw invalid(field + " contains an unsupported value");
+ }
+ String value = item.textValue();
+ if (previous != null && previous.compareTo(value) >= 0) {
+ throw invalid(field + " must be sorted and unique");
+ }
+ values.add(value);
+ previous = value;
+ }
+ return List.copyOf(values);
+ }
+
+ private static ObjectNode object(ObjectNode parent, String field) {
+ if (!(parent.get(field) instanceof ObjectNode value)) {
+ throw invalid(field + " must be a required object");
+ }
+ return value;
+ }
+
+ private static void exactFields(ObjectNode object, Set expected) {
+ Set actual = new java.util.HashSet<>();
+ object.fieldNames().forEachRemaining(actual::add);
+ if (!actual.equals(expected)) {
+ throw invalid("object must contain exactly the declared fields");
+ }
+ }
+
+ private static String text(ObjectNode object, String field) {
+ JsonNode value = object.get(field);
+ if (value == null || !value.isTextual()) {
+ throw invalid(field + " must be a required string");
+ }
+ return value.textValue();
+ }
+
+ private static void equalText(ObjectNode object, String field, String expected) {
+ if (!expected.equals(text(object, field))) {
+ throw invalid(field + " does not match its exact binding");
+ }
+ }
+
+ private static String uuid(ObjectNode object, String field) {
+ String value = text(object, field);
+ if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) {
+ throw invalid(field + " must be a canonical lowercase non-nil UUID");
+ }
+ return value;
+ }
+
+ private static void positive(ObjectNode object, String field) {
+ if (!POSITIVE_DECIMAL.matcher(text(object, field)).matches()) {
+ throw invalid(field + " must be a positive canonical decimal string");
+ }
+ }
+
+ private static String canonicalJson(ObjectNode object) {
+ try {
+ return new String(
+ Rfc8785CanonicalJson.canonicalizeUtf8(object.toString()), StandardCharsets.UTF_8);
+ } catch (IOException exception) {
+ throw new IllegalArgumentException("event cannot be canonicalized", exception);
+ }
+ }
+
+ private static String digest(ObjectNode object) {
+ try {
+ return "sha256:"
+ + HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256")
+ .digest(canonicalJson(object).getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is unavailable", exception);
+ }
+ }
+
+ private static AccountSecurityStateAuthorityEvent evidence(ObjectNode wire, String digest) {
+ ObjectNode state = object(wire, "accountState");
+ ObjectNode cutoff = object(wire, "accountSecurityCutoff");
+ return new AccountSecurityStateAuthorityEvent(
+ text(wire, "eventId"),
+ text(wire, "requestId"),
+ text(wire, "accountId"),
+ text(wire, "outboxStreamKey"),
+ text(wire, "outboxSequence"),
+ text(wire, "accountAuthorityGeneration"),
+ text(wire, "sourceVersion"),
+ new AccountSecurityCutoff(
+ text(cutoff, "accountAuthorityGeneration"),
+ text(cutoff, "outboxStreamKey"),
+ text(cutoff, "outboxSequence")),
+ orderedValues(wire.get("mutationKinds"), MUTATION_KINDS, "mutationKinds"),
+ new AccountState(
+ state.get("emailVerified").booleanValue(),
+ orderedValues(state.get("loginAuthModes"), LOGIN_MODES, "loginAuthModes"),
+ orderedValues(state.get("globalRoles"), GLOBAL_ROLES, "globalRoles", true),
+ text(state, "lifecycleState")),
+ digest,
+ canonicalJson(wire));
+ }
+
+ private static IllegalArgumentException invalid(String message) {
+ return new IllegalArgumentException(message);
+ }
+
+ public record AccountSecurityCutoff(
+ String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {}
+
+ public record AccountState(
+ boolean emailVerified,
+ List loginAuthModes,
+ List globalRoles,
+ String lifecycleState) {
+ public AccountState {
+ loginAuthModes = List.copyOf(loginAuthModes);
+ globalRoles = List.copyOf(globalRoles);
+ }
+ }
+
+ /** Immutable evidence constructible only by sealing or verifying this exact schema. */
+ public static final class AccountSecurityStateAuthorityEvent {
+ private final String eventId;
+ private final String requestId;
+ private final String accountId;
+ private final String outboxStreamKey;
+ private final String outboxSequence;
+ private final String accountAuthorityGeneration;
+ private final String sourceVersion;
+ private final AccountSecurityCutoff accountSecurityCutoff;
+ private final List mutationKinds;
+ private final AccountState accountState;
+ private final String eventDigest;
+ private final String canonicalJson;
+
+ private AccountSecurityStateAuthorityEvent(
+ String eventId,
+ String requestId,
+ String accountId,
+ String outboxStreamKey,
+ String outboxSequence,
+ String accountAuthorityGeneration,
+ String sourceVersion,
+ AccountSecurityCutoff accountSecurityCutoff,
+ List mutationKinds,
+ AccountState accountState,
+ String eventDigest,
+ String canonicalJson) {
+ this.eventId = eventId;
+ this.requestId = requestId;
+ this.accountId = accountId;
+ this.outboxStreamKey = outboxStreamKey;
+ this.outboxSequence = outboxSequence;
+ this.accountAuthorityGeneration = accountAuthorityGeneration;
+ this.sourceVersion = sourceVersion;
+ this.accountSecurityCutoff = accountSecurityCutoff;
+ this.mutationKinds = List.copyOf(mutationKinds);
+ this.accountState = accountState;
+ this.eventDigest = eventDigest;
+ this.canonicalJson = canonicalJson;
+ }
+
+ public String schemaVersion() {
+ return SCHEMA_VERSION;
+ }
+
+ public String eventType() {
+ return EVENT_TYPE;
+ }
+
+ public String eventId() {
+ return eventId;
+ }
+
+ public String requestId() {
+ return requestId;
+ }
+
+ public String accountId() {
+ return accountId;
+ }
+
+ public String sourceScope() {
+ return "account/" + accountId;
+ }
+
+ public String outboxStreamKey() {
+ return outboxStreamKey;
+ }
+
+ public String outboxSequence() {
+ return outboxSequence;
+ }
+
+ public String accountAuthorityGeneration() {
+ return accountAuthorityGeneration;
+ }
+
+ public String sourceVersion() {
+ return sourceVersion;
+ }
+
+ public AccountSecurityCutoff accountSecurityCutoff() {
+ return accountSecurityCutoff;
+ }
+
+ public List mutationKinds() {
+ return mutationKinds;
+ }
+
+ public AccountState accountState() {
+ return accountState;
+ }
+
+ public String eventDigest() {
+ return eventDigest;
+ }
+
+ public String canonicalJson() {
+ return canonicalJson;
+ }
+
+ public byte[] canonicalJsonUtf8() {
+ return canonicalJson.getBytes(StandardCharsets.UTF_8);
+ }
+ }
+}
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java
new file mode 100644
index 0000000000..f2068dcc0f
--- /dev/null
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java
@@ -0,0 +1,372 @@
+package net.firedevops.firemud.common.account.authority;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.StreamReadFeature;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+
+/** Strict codec for committed Account password-reset authority events. */
+public final class PasswordResetAuthorityEventV1Codec {
+ public static final String SCHEMA_VERSION = "account-auth-password-reset-event/v1";
+ public static final String EVENT_TYPE = "PASSWORD_RESET_COMMITTED";
+ public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:";
+
+ private static final Set PREIMAGE_FIELDS =
+ Set.of(
+ "schemaVersion",
+ "eventType",
+ "eventId",
+ "requestId",
+ "accountId",
+ "sourceScope",
+ "outboxStreamKey",
+ "outboxSequence",
+ "accountAuthorityGeneration",
+ "sourceVersion",
+ "accountSecurityCutoff");
+ private static final Set WIRE_FIELDS;
+ private static final Set ACCOUNT_CUTOFF_FIELDS =
+ Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence");
+ private static final Pattern UUID_PATTERN =
+ Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
+ private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000";
+ private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*");
+ private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}");
+ private static final ObjectMapper JSON =
+ new ObjectMapper(
+ JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build())
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
+
+ static {
+ var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS);
+ wireFields.add("eventDigest");
+ WIRE_FIELDS = Set.copyOf(wireFields);
+ }
+
+ private PasswordResetAuthorityEventV1Codec() {}
+
+ /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */
+ public static PasswordResetAuthorityEvent seal(Map preimage) {
+ Objects.requireNonNull(preimage, "preimage must not be null");
+ JsonNode tree = JSON.valueToTree(preimage);
+ if (!(tree instanceof ObjectNode object)) {
+ throw invalid("event", "must be a JSON object");
+ }
+ validatePreimage(object);
+ String digest = digest(object);
+ ObjectNode wire = object.deepCopy();
+ wire.put("eventDigest", digest);
+ return toEvidence(wire, digest, canonicalJson(wire));
+ }
+
+ /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */
+ public static PasswordResetAuthorityEvent verify(String wireJson) {
+ Objects.requireNonNull(wireJson, "wireJson must not be null");
+ final JsonNode tree;
+ try {
+ // JCS parsing rejects duplicate JSON object properties before Jackson builds a tree.
+ Rfc8785CanonicalJson.canonicalizeUtf8(wireJson);
+ tree = JSON.readTree(wireJson);
+ } catch (IOException exception) {
+ throw new IllegalArgumentException("event JSON is malformed", exception);
+ }
+ if (!(tree instanceof ObjectNode wire)) {
+ throw invalid("event", "must be a JSON object");
+ }
+ return verifyWireNode(wire);
+ }
+
+ /** Validates and verifies one wire event supplied as JSON-compatible map data. */
+ public static PasswordResetAuthorityEvent verify(Map wireEvent) {
+ Objects.requireNonNull(wireEvent, "wireEvent must not be null");
+ JsonNode tree = JSON.valueToTree(wireEvent);
+ if (!(tree instanceof ObjectNode wire)) {
+ throw invalid("event", "must be a JSON object");
+ }
+ return verifyWireNode(wire);
+ }
+
+ private static PasswordResetAuthorityEvent verifyWireNode(ObjectNode wire) {
+ requireExactFields(wire, WIRE_FIELDS, "event");
+ String suppliedDigest = requireText(wire, "eventDigest", "event");
+ if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) {
+ throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits");
+ }
+ ObjectNode preimage = wire.deepCopy();
+ preimage.remove("eventDigest");
+ validatePreimage(preimage);
+ String expectedDigest = digest(preimage);
+ if (!MessageDigest.isEqual(
+ suppliedDigest.getBytes(StandardCharsets.US_ASCII),
+ expectedDigest.getBytes(StandardCharsets.US_ASCII))) {
+ throw invalid("eventDigest", "does not match the canonical event preimage");
+ }
+ return toEvidence(wire, suppliedDigest, canonicalJson(wire));
+ }
+
+ private static void validatePreimage(ObjectNode event) {
+ requireExactFields(event, PREIMAGE_FIELDS, "event preimage");
+ requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event");
+ requireExactText(event, "eventType", EVENT_TYPE, "event");
+ requireNonEmptyText(event, "eventId", "event");
+ requireNonEmptyText(event, "requestId", "event");
+
+ String accountId = requireUuid(event, "accountId", "event");
+ String sourceScope = "account/" + accountId;
+ String streamKey = EVENT_STREAM_PREFIX + sourceScope;
+ requireExactText(event, "sourceScope", sourceScope, "event");
+ requireExactText(event, "outboxStreamKey", streamKey, "event");
+
+ String outboxSequence = requirePositiveDecimal(event, "outboxSequence", "event");
+ String accountAuthorityGeneration =
+ requirePositiveDecimal(event, "accountAuthorityGeneration", "event");
+ requirePositiveDecimal(event, "sourceVersion", "event");
+
+ JsonNode cutoffNode = event.get("accountSecurityCutoff");
+ if (!(cutoffNode instanceof ObjectNode cutoff)) {
+ throw invalid("accountSecurityCutoff", "must be a required JSON object");
+ }
+ requireExactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, "accountSecurityCutoff");
+ String cutoffGeneration =
+ requirePositiveDecimal(cutoff, "accountAuthorityGeneration", "accountSecurityCutoff");
+ String cutoffStream = requireText(cutoff, "outboxStreamKey", "accountSecurityCutoff");
+ String cutoffSequence =
+ requirePositiveDecimal(cutoff, "outboxSequence", "accountSecurityCutoff");
+ if (!accountAuthorityGeneration.equals(cutoffGeneration)) {
+ throw invalid(
+ "accountSecurityCutoff.accountAuthorityGeneration",
+ "must equal event.accountAuthorityGeneration");
+ }
+ if (!streamKey.equals(cutoffStream)) {
+ throw invalid("accountSecurityCutoff.outboxStreamKey", "must equal event.outboxStreamKey");
+ }
+ if (!outboxSequence.equals(cutoffSequence)) {
+ throw invalid("accountSecurityCutoff.outboxSequence", "must equal event.outboxSequence");
+ }
+ }
+
+ private static PasswordResetAuthorityEvent toEvidence(
+ ObjectNode wire, String digest, String canonicalJson) {
+ ObjectNode cutoff = (ObjectNode) wire.get("accountSecurityCutoff");
+ return new PasswordResetAuthorityEvent(
+ wire.path("schemaVersion").textValue(),
+ wire.path("eventType").textValue(),
+ wire.path("eventId").textValue(),
+ wire.path("requestId").textValue(),
+ wire.path("accountId").textValue(),
+ wire.path("sourceScope").textValue(),
+ wire.path("outboxStreamKey").textValue(),
+ wire.path("outboxSequence").textValue(),
+ wire.path("accountAuthorityGeneration").textValue(),
+ wire.path("sourceVersion").textValue(),
+ new AccountSecurityCutoff(
+ cutoff.path("accountAuthorityGeneration").textValue(),
+ cutoff.path("outboxStreamKey").textValue(),
+ cutoff.path("outboxSequence").textValue()),
+ digest,
+ canonicalJson);
+ }
+
+ private static void requireExactFields(ObjectNode object, Set required, String path) {
+ Set actual = new java.util.HashSet<>();
+ object.fieldNames().forEachRemaining(actual::add);
+ if (!actual.equals(required)) {
+ Set missing = new java.util.HashSet<>(required);
+ missing.removeAll(actual);
+ Set unexpected = new java.util.HashSet<>(actual);
+ unexpected.removeAll(required);
+ StringBuilder message = new StringBuilder("must contain exactly the declared fields");
+ if (!missing.isEmpty()) {
+ message.append("; missing ").append(missing);
+ }
+ if (!unexpected.isEmpty()) {
+ message.append("; unexpected ").append(unexpected);
+ }
+ throw invalid(path, message.toString());
+ }
+ }
+
+ private static String requireExactText(
+ ObjectNode object, String field, String expected, String path) {
+ String value = requireText(object, field, path);
+ if (!expected.equals(value)) {
+ throw invalid(path + "." + field, "must equal " + expected);
+ }
+ return value;
+ }
+
+ private static String requireNonEmptyText(ObjectNode object, String field, String path) {
+ String value = requireText(object, field, path);
+ if (value.isEmpty()) {
+ throw invalid(path + "." + field, "must be nonempty");
+ }
+ return value;
+ }
+
+ private static String requireText(ObjectNode object, String field, String path) {
+ JsonNode value = object.get(field);
+ if (value == null || !value.isTextual()) {
+ throw invalid(path + "." + field, "must be a required string");
+ }
+ return value.textValue();
+ }
+
+ private static String requireUuid(ObjectNode object, String field, String path) {
+ String value = requireText(object, field, path);
+ if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) {
+ throw invalid(path + "." + field, "must be a canonical lowercase non-nil UUID");
+ }
+ return value;
+ }
+
+ private static String requirePositiveDecimal(ObjectNode object, String field, String path) {
+ String value = requireText(object, field, path);
+ if (!POSITIVE_DECIMAL_PATTERN.matcher(value).matches()) {
+ throw invalid(path + "." + field, "must be a positive canonical decimal string");
+ }
+ return value;
+ }
+
+ private static String digest(ObjectNode preimage) {
+ try {
+ byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString());
+ byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical);
+ return "sha256:" + java.util.HexFormat.of().formatHex(hash);
+ } catch (IOException exception) {
+ throw new IllegalArgumentException("event preimage cannot be canonicalized", exception);
+ } catch (NoSuchAlgorithmException exception) {
+ throw new IllegalStateException("SHA-256 is unavailable", exception);
+ }
+ }
+
+ private static String canonicalJson(ObjectNode wire) {
+ try {
+ return new String(
+ Rfc8785CanonicalJson.canonicalizeUtf8(wire.toString()), StandardCharsets.UTF_8);
+ } catch (IOException exception) {
+ throw new IllegalArgumentException("event cannot be canonicalized", exception);
+ }
+ }
+
+ private static IllegalArgumentException invalid(String path, String message) {
+ return new IllegalArgumentException(path + " " + message);
+ }
+
+ /** Immutable verified or producer-sealed event evidence. */
+ public static final class PasswordResetAuthorityEvent {
+ private final String schemaVersion;
+ private final String eventType;
+ private final String eventId;
+ private final String requestId;
+ private final String accountId;
+ private final String sourceScope;
+ private final String outboxStreamKey;
+ private final String outboxSequence;
+ private final String accountAuthorityGeneration;
+ private final String sourceVersion;
+ private final AccountSecurityCutoff accountSecurityCutoff;
+ private final String eventDigest;
+ private final String canonicalJson;
+
+ private PasswordResetAuthorityEvent(
+ String schemaVersion,
+ String eventType,
+ String eventId,
+ String requestId,
+ String accountId,
+ String sourceScope,
+ String outboxStreamKey,
+ String outboxSequence,
+ String accountAuthorityGeneration,
+ String sourceVersion,
+ AccountSecurityCutoff accountSecurityCutoff,
+ String eventDigest,
+ String canonicalJson) {
+ this.schemaVersion = schemaVersion;
+ this.eventType = eventType;
+ this.eventId = eventId;
+ this.requestId = requestId;
+ this.accountId = accountId;
+ this.sourceScope = sourceScope;
+ this.outboxStreamKey = outboxStreamKey;
+ this.outboxSequence = outboxSequence;
+ this.accountAuthorityGeneration = accountAuthorityGeneration;
+ this.sourceVersion = sourceVersion;
+ this.accountSecurityCutoff = accountSecurityCutoff;
+ this.eventDigest = eventDigest;
+ this.canonicalJson = canonicalJson;
+ }
+
+ public String schemaVersion() {
+ return schemaVersion;
+ }
+
+ public String eventType() {
+ return eventType;
+ }
+
+ public String eventId() {
+ return eventId;
+ }
+
+ public String requestId() {
+ return requestId;
+ }
+
+ public String accountId() {
+ return accountId;
+ }
+
+ public String sourceScope() {
+ return sourceScope;
+ }
+
+ public String outboxStreamKey() {
+ return outboxStreamKey;
+ }
+
+ public String outboxSequence() {
+ return outboxSequence;
+ }
+
+ public String accountAuthorityGeneration() {
+ return accountAuthorityGeneration;
+ }
+
+ public String sourceVersion() {
+ return sourceVersion;
+ }
+
+ public AccountSecurityCutoff accountSecurityCutoff() {
+ return accountSecurityCutoff;
+ }
+
+ public String eventDigest() {
+ return eventDigest;
+ }
+
+ public String canonicalJson() {
+ return canonicalJson;
+ }
+
+ /** Returns a caller-owned copy of the canonical complete wire event bytes. */
+ public byte[] canonicalJsonUtf8() {
+ return canonicalJson.getBytes(StandardCharsets.UTF_8);
+ }
+ }
+
+ /** Immutable Account security cutoff checkpoint. */
+ public record AccountSecurityCutoff(
+ String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {}
+}
diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java
new file mode 100644
index 0000000000..eb12b42d85
--- /dev/null
+++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java
@@ -0,0 +1,685 @@
+package net.firedevops.firemud.common.account.authority;
+
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent;
+
+/**
+ * Validates the content and cross-binding of one current runtime membership evidence snapshot.
+ *
+ * This does not authenticate the source or authorize gameplay admission. The membership event is
+ * immutable historical evidence; a caller supplies the separate current tuple, fence and
+ * checkpoints. Private-realm grant and tenant-billing tuple evidence are not supported by this
+ * candidate and are rejected until their source contracts are available. An empty result for a
+ * missing membership is only a local statement about the supplied snapshot, not proof that the
+ * account has never joined.
+ */
+public final class RuntimeMembershipAuthorityEvidenceValidator {
+ private static final String EVENT_STREAM_PREFIX =
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX;
+ private static final Pattern UUID_PATTERN =
+ Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
+ private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000";
+ private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*");
+ private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]*)");
+ private static final Set MEMBERSHIP_LIFECYCLES = Set.of("ACTIVE", "INACTIVE");
+
+ private RuntimeMembershipAuthorityEvidenceValidator() {}
+
+ /**
+ * Verifies every supplied source event and binds the immutable membership event to the current
+ * recipient carrier. Returns empty only for a well-formed snapshot whose membership checkpoint is
+ * zero and whose current membership state is explicitly missing and nonadmitting.
+ *
+ * @throws IllegalArgumentException if the snapshot is malformed, incomplete, inconsistent, or
+ * contains unsupported authority evidence
+ */
+ public static Optional validate(Snapshot evidence) {
+ Objects.requireNonNull(evidence, "evidence must not be null");
+
+ requireCanonicalUuid(evidence.accountId(), "accountId");
+ requireCanonicalUuid(evidence.tenantId(), "tenantId");
+ requireNonBlank(evidence.issuerId(), "issuerId");
+ requirePositiveDecimal(
+ evidence.membershipAuthorityGeneration(), "membershipAuthorityGeneration");
+ requirePositiveDecimal(evidence.issuanceFence(), "issuanceFence");
+ requireExactTenantValue(evidence.membershipVersion(), evidence.tenantId(), "membershipVersion");
+
+ AuthorityTuple currentTuple = evidence.authorityTuple();
+ requireTupleShape(
+ currentTuple,
+ evidence.accountId(),
+ evidence.tenantId(),
+ evidence.membershipAuthorityGeneration(),
+ "authorityTuple");
+
+ String issuerStream = EVENT_STREAM_PREFIX + "issuer/" + evidence.issuerId();
+ String accountStream = EVENT_STREAM_PREFIX + "account/" + evidence.accountId();
+ String tenantStream = EVENT_STREAM_PREFIX + "tenant/" + evidence.tenantId();
+ String membershipStream =
+ EVENT_STREAM_PREFIX + "membership/" + evidence.accountId() + "/" + evidence.tenantId();
+ List expectedStreams =
+ new ArrayList<>(List.of(issuerStream, accountStream, tenantStream, membershipStream));
+ expectedStreams.sort(RuntimeMembershipAuthorityEvidenceValidator::compareUtf8);
+
+ Map checkpoints =
+ validateCheckpoints(evidence.checkpoints(), expectedStreams);
+ Map