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 sources = + validateSourceInventory(evidence.sourceEvidence(), checkpoints); + + verifyIssuerSource( + sources.get(issuerStream), + checkpoints.get(issuerStream), + evidence.issuerId(), + currentTuple.issuerAuthGeneration()); + AccountSource accountSource = + verifyAccountSource( + sources.get(accountStream), + checkpoints.get(accountStream), + evidence.accountId(), + currentTuple.accountAuthorityGeneration()); + verifyTenantSource( + sources.get(tenantStream), + checkpoints.get(tenantStream), + evidence.tenantId(), + currentTuple.tenantAuthorityGeneration().get(evidence.tenantId())); + + validateCurrentAccountCutoff( + currentTuple, accountSource, checkpoints.get(accountStream), accountStream); + + Checkpoint membershipCheckpoint = checkpoints.get(membershipStream); + if (membershipCheckpoint.outboxSequence().equals("0")) { + validateMissingMembership(evidence); + return Optional.empty(); + } + + MembershipEvent membershipEvent = + verifyMembershipSource( + sources.get(membershipStream), + membershipCheckpoint, + evidence.accountId(), + evidence.tenantId()); + validateMembershipCarrier(evidence, membershipEvent, currentTuple, accountSource); + + return Optional.of(membershipEvent); + } + + private static Map validateCheckpoints( + List supplied, List expectedStreams) { + if (supplied.size() != expectedStreams.size()) { + throw invalid("checkpoints", "must contain exactly the four authority streams"); + } + Map checkpoints = new HashMap<>(); + String previousStream = null; + for (Checkpoint checkpoint : supplied) { + if (!expectedStreams.contains(checkpoint.outboxStreamKey())) { + throw invalid("checkpoints", "contains an unexpected authority stream"); + } + if (previousStream != null + && compareUtf8(previousStream, checkpoint.outboxStreamKey()) >= 0) { + throw invalid("checkpoints", "must be sorted by stream key and contain no duplicates"); + } + if (checkpoints.putIfAbsent(checkpoint.outboxStreamKey(), checkpoint) != null) { + throw invalid("checkpoints", "contains a duplicate authority stream"); + } + requireNonNegativeDecimal(checkpoint.outboxSequence(), "checkpoint.outboxSequence"); + previousStream = checkpoint.outboxStreamKey(); + } + if (!checkpoints.keySet().equals(Set.copyOf(expectedStreams))) { + throw invalid("checkpoints", "must cover each expected authority stream exactly once"); + } + return Map.copyOf(checkpoints); + } + + private static Map validateSourceInventory( + List supplied, Map checkpoints) { + Map sources = new HashMap<>(); + String previousStream = null; + for (SourceEvidence source : supplied) { + if (previousStream != null && compareUtf8(previousStream, source.outboxStreamKey()) >= 0) { + throw invalid("sourceEvidence", "must be sorted by stream key and contain no duplicates"); + } + Checkpoint checkpoint = checkpoints.get(source.outboxStreamKey()); + if (checkpoint == null || checkpoint.outboxSequence().equals("0")) { + throw invalid("sourceEvidence", "contains evidence without a positive checkpoint"); + } + if (!checkpoint.outboxSequence().equals(source.outboxSequence())) { + throw invalid("sourceEvidence", "sequence must equal its exact current checkpoint"); + } + if (sources.putIfAbsent(source.outboxStreamKey(), source) != null) { + throw invalid("sourceEvidence", "contains a duplicate authority stream"); + } + previousStream = source.outboxStreamKey(); + } + + for (Checkpoint checkpoint : checkpoints.values()) { + boolean hasSource = sources.containsKey(checkpoint.outboxStreamKey()); + if (checkpoint.outboxSequence().equals("0") == hasSource) { + throw invalid( + "sourceEvidence", "must contain one source for each positive checkpoint only"); + } + } + return Map.copyOf(sources); + } + + private static void verifyIssuerSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedIssuerId, + String currentGeneration) { + if (checkpoint.outboxSequence().equals("0")) { + requireEquals("1", currentGeneration, "authorityTuple.issuerAuthGeneration baseline"); + return; + } + var verified = AccountAuthoritySourceEventV1Codec.verify(supplied.canonicalEventJson()); + if (!(verified instanceof AccountAuthoritySourceEventV1Codec.IssuerEvent event)) { + throw invalid("issuer source", "must use the current issuer owner schema"); + } + requireSourceIdentity( + supplied, + checkpoint, + event.eventId(), + event.eventDigest(), + event.canonicalJson(), + event.outboxSequence(), + event.outboxStreamKey()); + requireEquals(expectedIssuerId, event.issuerId(), "issuer source issuerId"); + requireEquals(currentGeneration, event.issuerAuthGeneration(), "current issuer generation"); + } + + private static void verifyTenantSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedTenantId, + String currentGeneration) { + if (checkpoint.outboxSequence().equals("0")) { + requireEquals("1", currentGeneration, "authorityTuple.tenantAuthorityGeneration baseline"); + return; + } + throw invalid( + "tenant source", "advanced tenant authority requires its supported owner source contract"); + } + + private static AccountSource verifyAccountSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedAccountId, + String currentGeneration) { + if (checkpoint.outboxSequence().equals("0")) { + requireEquals("1", currentGeneration, "authorityTuple.accountAuthorityGeneration baseline"); + return null; + } + + AccountSource event; + try { + var verified = AccountAuthoritySourceEventV1Codec.verify(supplied.canonicalEventJson()); + if (!(verified instanceof AccountAuthoritySourceEventV1Codec.AccountEvent account)) { + throw invalid("account source", "must be an Account event"); + } + event = + new AccountSource( + account.eventId(), + account.eventDigest(), + account.canonicalJson(), + account.outboxStreamKey(), + account.outboxSequence(), + account.accountId(), + account.accountAuthorityGeneration(), + account.accountSecurityCutoff().accountAuthorityGeneration(), + account.accountSecurityCutoff().outboxStreamKey(), + account.accountSecurityCutoff().outboxSequence()); + } catch (IllegalArgumentException currentSchemaMismatch) { + try { + var reset = PasswordResetAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + event = + new AccountSource( + reset.eventId(), + reset.eventDigest(), + reset.canonicalJson(), + reset.outboxStreamKey(), + reset.outboxSequence(), + reset.accountId(), + reset.accountAuthorityGeneration(), + reset.accountSecurityCutoff().accountAuthorityGeneration(), + reset.accountSecurityCutoff().outboxStreamKey(), + reset.accountSecurityCutoff().outboxSequence()); + } catch (IllegalArgumentException resetFailure) { + try { + var logout = AccountLogoutAllAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + event = + new AccountSource( + logout.eventId(), + logout.eventDigest(), + logout.canonicalJson(), + logout.outboxStreamKey(), + logout.outboxSequence(), + logout.accountId(), + logout.accountAuthorityGeneration(), + logout.accountSecurityCutoff().accountAuthorityGeneration(), + logout.accountSecurityCutoff().outboxStreamKey(), + logout.accountSecurityCutoff().outboxSequence()); + } catch (IllegalArgumentException logoutFailure) { + var security = + AccountSecurityStateAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + event = + new AccountSource( + security.eventId(), + security.eventDigest(), + security.canonicalJson(), + security.outboxStreamKey(), + security.outboxSequence(), + security.accountId(), + security.accountAuthorityGeneration(), + security.accountSecurityCutoff().accountAuthorityGeneration(), + security.accountSecurityCutoff().outboxStreamKey(), + security.accountSecurityCutoff().outboxSequence()); + } + } + } + requireSourceIdentity( + supplied, + checkpoint, + event.eventId(), + event.eventDigest(), + event.canonicalJson(), + event.outboxSequence(), + event.outboxStreamKey()); + requireEquals(expectedAccountId, event.accountId(), "account source accountId"); + requireEquals( + currentGeneration, event.accountAuthorityGeneration(), "current account generation"); + requireEquals( + event.accountAuthorityGeneration(), event.cutoffGeneration(), "account cutoff generation"); + requireEquals(event.outboxStreamKey(), event.cutoffStream(), "account cutoff stream key"); + requireEquals(event.outboxSequence(), event.cutoffSequence(), "account cutoff sequence"); + return event; + } + + private static MembershipEvent verifyMembershipSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedAccountId, + String expectedTenantId) { + MembershipEvent event = MembershipAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + requireSourceIdentity( + supplied, + checkpoint, + event.eventId(), + event.eventDigest(), + event.canonicalJson(), + event.outboxSequence(), + event.outboxStreamKey()); + requireEquals(expectedAccountId, event.accountId(), "membership source accountId"); + requireEquals(expectedTenantId, event.tenantId(), "membership source tenantId"); + return event; + } + + private static void requireSourceIdentity( + SourceEvidence supplied, + Checkpoint checkpoint, + String eventId, + String eventDigest, + String canonicalJson, + String eventSequence, + String eventStreamKey) { + requireEquals(checkpoint.outboxStreamKey(), eventStreamKey, "source event stream key"); + requireEquals( + checkpoint.outboxStreamKey(), supplied.outboxStreamKey(), "source carrier stream key"); + requireEquals( + checkpoint.outboxSequence(), supplied.outboxSequence(), "source carrier sequence"); + requireEquals(checkpoint.outboxSequence(), eventSequence, "source event sequence"); + requireEquals(eventId, supplied.eventId(), "source carrier eventId"); + requireEquals(eventDigest, supplied.eventDigest(), "source carrier eventDigest"); + requireEquals( + canonicalJson, supplied.canonicalEventJson(), "source carrier canonical event bytes"); + } + + private static void validateCurrentAccountCutoff( + AuthorityTuple tuple, + AccountSource source, + Checkpoint checkpoint, + String expectedAccountStream) { + Optional cutoff = tuple.accountSecurityCutoff(); + if (checkpoint.outboxSequence().equals("0")) { + if (cutoff.isPresent()) { + throw invalid( + "authorityTuple.accountSecurityCutoff", "must be absent at the account baseline"); + } + return; + } + if (cutoff.isEmpty() || source == null) { + throw invalid( + "authorityTuple.accountSecurityCutoff", "must bind the current account source event"); + } + AccountSecurityCutoff current = cutoff.orElseThrow(); + requireEquals( + tuple.accountAuthorityGeneration(), + current.accountAuthorityGeneration(), + "current account cutoff generation"); + requireEquals( + expectedAccountStream, current.outboxStreamKey(), "current account cutoff stream key"); + requireEquals( + checkpoint.outboxSequence(), current.outboxSequence(), "current account cutoff sequence"); + requireEquals( + source.cutoffGeneration(), + current.accountAuthorityGeneration(), + "current account cutoff source generation"); + requireEquals( + source.cutoffStream(), current.outboxStreamKey(), "current account cutoff source stream"); + requireEquals( + source.cutoffSequence(), + current.outboxSequence(), + "current account cutoff source sequence"); + } + + private static void validateMissingMembership(Snapshot evidence) { + if (evidence.membershipExists() + || !"MISSING".equals(evidence.membershipLifecycleState()) + || evidence.gameplayAdmissionAllowed() + || !evidence.roles().isEmpty()) { + throw invalid( + "membership", "zero checkpoint requires MISSING, absent, empty-role, nonadmitting state"); + } + // The absent-row representation still carries positive persisted defaults. This check is + // content validation only and cannot establish that a prior membership never existed. + requirePositiveDecimal( + evidence.membershipVersion().get(evidence.tenantId()), "membershipVersion"); + requirePositiveDecimal( + evidence.membershipAuthorityGeneration(), "membershipAuthorityGeneration"); + requirePositiveDecimal(evidence.issuanceFence(), "issuanceFence"); + } + + private static void validateMembershipCarrier( + Snapshot evidence, + MembershipEvent event, + AuthorityTuple currentTuple, + AccountSource currentAccountSource) { + if (!evidence.membershipExists()) { + throw invalid("membershipExists", "must be true for a positive membership checkpoint"); + } + if (!MEMBERSHIP_LIFECYCLES.contains(evidence.membershipLifecycleState())) { + throw invalid( + "membershipLifecycleState", "must be ACTIVE or INACTIVE for an existing membership"); + } + requireEquals( + event.membershipLifecycleState(), + evidence.membershipLifecycleState(), + "membershipLifecycleState"); + requireEquals( + event.gameplayAdmissionAllowed(), + evidence.gameplayAdmissionAllowed(), + "gameplayAdmissionAllowed"); + requireEquals(event.roles(), evidence.roles(), "roles"); + requireEquals(event.membershipVersion(), evidence.membershipVersion(), "membershipVersion"); + requireEquals( + event.membershipAuthorityGeneration(), + evidence.membershipAuthorityGeneration(), + "membershipAuthorityGeneration"); + requireEquals( + event.membershipAuthorityGeneration(), + currentTuple.membershipAuthorityGeneration().get(evidence.tenantId()), + "current membership authority generation"); + + AuthorityTuple eventTuple = event.authorityTuple(); + requireSupportedTupleExtensions(eventTuple, "membership source authorityTuple"); + requireAtMost( + eventTuple.issuerAuthGeneration(), + currentTuple.issuerAuthGeneration(), + "membership source issuerAuthGeneration"); + requireAtMost( + eventTuple.accountAuthorityGeneration(), + currentTuple.accountAuthorityGeneration(), + "membership source accountAuthorityGeneration"); + requireAtMost( + eventTuple.tenantAuthorityGeneration().get(evidence.tenantId()), + currentTuple.tenantAuthorityGeneration().get(evidence.tenantId()), + "membership source tenantAuthorityGeneration"); + requireAtMost( + event.issuanceFence(), evidence.issuanceFence(), "membership source issuanceFence"); + validateHistoricalAccountCutoff(eventTuple, currentTuple, currentAccountSource); + } + + private static void validateHistoricalAccountCutoff( + AuthorityTuple eventTuple, AuthorityTuple currentTuple, AccountSource currentAccountSource) { + Optional historicalCutoff = eventTuple.accountSecurityCutoff(); + Optional currentCutoff = currentTuple.accountSecurityCutoff(); + int accountGenerationOrder = + compareDecimal( + eventTuple.accountAuthorityGeneration(), currentTuple.accountAuthorityGeneration()); + if (accountGenerationOrder == 0) { + if (historicalCutoff.isPresent() != currentCutoff.isPresent()) { + throw invalid( + "membership source accountSecurityCutoff", + "must match cutoff presence at the same generation"); + } + if (historicalCutoff.isPresent() + && !historicalCutoff.orElseThrow().equals(currentCutoff.orElseThrow())) { + throw invalid( + "membership source accountSecurityCutoff", + "must equal the current cutoff at the same generation"); + } + } + if (historicalCutoff.isEmpty()) { + requireEquals( + "1", + eventTuple.accountAuthorityGeneration(), + "membership source accountAuthorityGeneration without a cutoff"); + return; + } + if (currentCutoff.isEmpty() || currentAccountSource == null) { + throw invalid( + "membership source accountSecurityCutoff", + "cannot exceed or outlive current account cutoff evidence"); + } + AccountSecurityCutoff historical = historicalCutoff.orElseThrow(); + AccountSecurityCutoff current = currentCutoff.orElseThrow(); + requireEquals( + current.outboxStreamKey(), + historical.outboxStreamKey(), + "historical account cutoff stream key"); + requireAtMost( + historical.accountAuthorityGeneration(), + current.accountAuthorityGeneration(), + "historical account cutoff generation"); + requireAtMost( + historical.outboxSequence(), + current.outboxSequence(), + "historical account cutoff sequence"); + } + + private static void requireTupleShape( + AuthorityTuple tuple, + String accountId, + String tenantId, + String membershipGeneration, + String path) { + requirePositiveDecimal(tuple.issuerAuthGeneration(), path + ".issuerAuthGeneration"); + requirePositiveDecimal( + tuple.accountAuthorityGeneration(), path + ".accountAuthorityGeneration"); + requireExactTenantValue( + tuple.tenantAuthorityGeneration(), tenantId, path + ".tenantAuthorityGeneration"); + requireExactTenantValue( + tuple.membershipAuthorityGeneration(), tenantId, path + ".membershipAuthorityGeneration"); + requireEquals( + membershipGeneration, + tuple.membershipAuthorityGeneration().get(tenantId), + path + ".membershipAuthorityGeneration"); + requireSupportedTupleExtensions(tuple, path); + tuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> { + requirePositiveDecimal( + cutoff.accountAuthorityGeneration(), + path + ".accountSecurityCutoff.accountAuthorityGeneration"); + requireEquals( + EVENT_STREAM_PREFIX + "account/" + accountId, + cutoff.outboxStreamKey(), + path + ".accountSecurityCutoff.outboxStreamKey"); + requirePositiveDecimal( + cutoff.outboxSequence(), path + ".accountSecurityCutoff.outboxSequence"); + requireEquals( + tuple.accountAuthorityGeneration(), + cutoff.accountAuthorityGeneration(), + path + ".accountSecurityCutoff.accountAuthorityGeneration"); + }); + } + + private static void requireSupportedTupleExtensions(AuthorityTuple tuple, String path) { + if (!tuple.privateRealmGrantVersions().isEmpty()) { + throw invalid(path + ".privateRealmGrantVersions", "is not supported by this candidate"); + } + if (tuple.tenantBillingCutoff().isPresent()) { + throw invalid(path + ".tenantBillingCutoff", "is not supported by this candidate"); + } + } + + private static void requireExactTenantValue( + Map values, String tenantId, String path) { + if (values.size() != 1 || !values.containsKey(tenantId)) { + throw invalid(path, "must contain exactly the current tenantId key"); + } + requirePositiveDecimal(values.get(tenantId), path + "." + tenantId); + } + + private static void requireCanonicalUuid(String value, String path) { + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(path, "must be a canonical lowercase non-nil UUID"); + } + } + + private static void requireNonBlank(String value, String path) { + if (value.isBlank()) { + throw invalid(path, "must be nonblank"); + } + } + + private static void requirePositiveDecimal(String value, String path) { + if (!POSITIVE_DECIMAL.matcher(value).matches()) { + throw invalid(path, "must be a positive canonical decimal string"); + } + } + + private static void requireNonNegativeDecimal(String value, String path) { + if (!NON_NEGATIVE_DECIMAL.matcher(value).matches()) { + throw invalid(path, "must be a non-negative canonical decimal string"); + } + } + + private static void requireAtMost(String lowerOrEqual, String upper, String path) { + requirePositiveDecimal(lowerOrEqual, path); + requirePositiveDecimal(upper, path + " current"); + if (compareDecimal(lowerOrEqual, upper) > 0) { + throw invalid(path, "must not be ahead of current authority"); + } + } + + private static int compareDecimal(String left, String right) { + return new BigInteger(left).compareTo(new BigInteger(right)); + } + + private static int compareUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int comparison = + Integer.compare( + Byte.toUnsignedInt(leftBytes[index]), Byte.toUnsignedInt(rightBytes[index])); + if (comparison != 0) { + return comparison; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static void requireEquals(Object expected, Object actual, String path) { + if (!Objects.equals(expected, actual)) { + throw invalid(path, "does not match its bound evidence"); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + private record AccountSource( + String eventId, + String eventDigest, + String canonicalJson, + String outboxStreamKey, + String outboxSequence, + String accountId, + String accountAuthorityGeneration, + String cutoffGeneration, + String cutoffStream, + String cutoffSequence) {} + + /** Immutable sequence checkpoint for one exact Account authority stream. */ + public record Checkpoint(String outboxStreamKey, String outboxSequence) { + public Checkpoint { + Objects.requireNonNull(outboxStreamKey, "outboxStreamKey must not be null"); + Objects.requireNonNull(outboxSequence, "outboxSequence must not be null"); + } + } + + /** Immutable source-event carrier bound to its exact stream and checkpoint. */ + public record SourceEvidence( + String outboxStreamKey, + String outboxSequence, + String eventId, + String eventDigest, + String canonicalEventJson) { + public SourceEvidence { + Objects.requireNonNull(outboxStreamKey, "outboxStreamKey must not be null"); + Objects.requireNonNull(outboxSequence, "outboxSequence must not be null"); + Objects.requireNonNull(eventId, "eventId must not be null"); + Objects.requireNonNull(eventDigest, "eventDigest must not be null"); + Objects.requireNonNull(canonicalEventJson, "canonicalEventJson must not be null"); + } + } + + /** Immutable current recipient carrier plus the exact source evidence it claims to summarize. */ + public record Snapshot( + String issuerId, + String accountId, + String tenantId, + boolean membershipExists, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + Map membershipVersion, + String membershipAuthorityGeneration, + List roles, + AuthorityTuple authorityTuple, + String issuanceFence, + List checkpoints, + List sourceEvidence) { + public Snapshot { + Objects.requireNonNull(issuerId, "issuerId must not be null"); + Objects.requireNonNull(accountId, "accountId must not be null"); + Objects.requireNonNull(tenantId, "tenantId must not be null"); + Objects.requireNonNull(membershipLifecycleState, "membershipLifecycleState must not be null"); + membershipVersion = + Map.copyOf( + Objects.requireNonNull(membershipVersion, "membershipVersion must not be null")); + Objects.requireNonNull( + membershipAuthorityGeneration, "membershipAuthorityGeneration must not be null"); + roles = List.copyOf(Objects.requireNonNull(roles, "roles must not be null")); + Objects.requireNonNull(authorityTuple, "authorityTuple must not be null"); + Objects.requireNonNull(issuanceFence, "issuanceFence must not be null"); + checkpoints = + List.copyOf(Objects.requireNonNull(checkpoints, "checkpoints must not be null")); + sourceEvidence = + List.copyOf(Objects.requireNonNull(sourceEvidence, "sourceEvidence must not be null")); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java new file mode 100644 index 0000000000..8a153c841e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.common.tenant; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; + +/** Canonical digest for the distinct Account-initiator qualification on fresh tenant creation. */ +public final class FreshTenantCreatorDigest { + private static final int SCHEMA_VERSION = 1; + private static final String QUALIFICATION_DOMAIN = "game-design-tenant-creator-qualification/v1"; + private static final String DIGEST_PREFIX = "sha256:"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private FreshTenantCreatorDigest() {} + + /** + * Digests every original creation-evidence field, then the initiating Account and Account-owned + * authorization identity/digest, using decimal-byte-length-prefixed UTF-8 segments. + */ + public static String evidenceDigest( + int schemaVersion, + FreshTenantCreationEvidence creationEvidence, + UUID initiatingAccountId, + UUID accountAuthorizationOperationId, + String accountAuthorizationDigest) { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported fresh tenant creator evidence version"); + } + Objects.requireNonNull(creationEvidence, "creationEvidence"); + requireNonNil(initiatingAccountId, "initiatingAccountId"); + requireNonNil(accountAuthorizationOperationId, "accountAuthorizationOperationId"); + if (!GameTenantCreationDigest.isDigest(accountAuthorizationDigest)) { + throw new IllegalArgumentException( + "accountAuthorizationDigest must be a lowercase SHA-256 digest"); + } + + return digest( + QUALIFICATION_DOMAIN, + Integer.toString(schemaVersion), + Integer.toString(creationEvidence.schemaVersion()), + creationEvidence.targetNamespace(), + creationEvidence.creationRequestId().toString(), + creationEvidence.operationId().toString(), + creationEvidence.requestDigest(), + creationEvidence.canonicalTenantId().toString(), + Long.toString(creationEvidence.sourceGameRowId()), + creationEvidence.sourceGameTenantKey(), + creationEvidence.provenanceKind(), + creationEvidence.evidenceDigest(), + initiatingAccountId.toString(), + accountAuthorizationOperationId.toString(), + accountAuthorizationDigest); + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + } + + private static String digest(String... segments) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + for (String segment : segments) { + byte[] bytes = encodeUtf8(segment); + byte[] length = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8); + preimage.writeBytes(length); + preimage.write(':'); + preimage.writeBytes(bytes); + } + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray()); + return DIGEST_PREFIX + HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] encodeUtf8(String value) { + Objects.requireNonNull(value, "digest segment"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Creator evidence must contain valid Unicode", exception); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java new file mode 100644 index 0000000000..ebdc4bc8a3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; + +/** + * Immutable creator-qualification evidence bound to one exact fresh tenant source operation. + * + *

This record validates a closed digest-bound tuple. The Account UUID and authorization + * operation fields are data, not authenticated proof by themselves; the Account-owned producer must + * supply and protect their authority. + */ +public record FreshTenantCreatorEvidence( + int schemaVersion, + FreshTenantCreationEvidence creationEvidence, + UUID initiatingAccountId, + UUID accountAuthorizationOperationId, + String accountAuthorizationDigest, + String evidenceDigest) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public FreshTenantCreatorEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported fresh tenant creator evidence version"); + } + Objects.requireNonNull(creationEvidence, "creationEvidence"); + requireNonNil(initiatingAccountId, "initiatingAccountId"); + requireNonNil(accountAuthorizationOperationId, "accountAuthorizationOperationId"); + if (!GameTenantCreationDigest.isDigest(accountAuthorizationDigest)) { + throw new IllegalArgumentException( + "accountAuthorizationDigest must be a lowercase SHA-256 digest"); + } + Objects.requireNonNull(evidenceDigest, "evidenceDigest"); + String expectedDigest = + FreshTenantCreatorDigest.evidenceDigest( + schemaVersion, + creationEvidence, + initiatingAccountId, + accountAuthorizationOperationId, + accountAuthorizationDigest); + if (!expectedDigest.equals(evidenceDigest)) { + throw new IllegalArgumentException( + "Creator evidence digest does not match the immutable qualification tuple"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must not be nil"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..552b2b9195 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1CodecTest.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.security.MessageDigest; +import java.util.Map; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; + +class AccountLogoutAllAuthorityEventV1CodecTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private static final String REQUEST_ID = "22222222-2222-4222-8222-222222222222"; + private static final String STREAM = + AccountLogoutAllAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + ACCOUNT_ID; + private static final String LARGE_COUNTER = "9223372036854775807"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void sealsAndVerifiesRequestDerivedLogoutIdentityAndLargeCounters() throws Exception { + var sealed = AccountLogoutAllAuthorityEventV1Codec.seal(preimage(LARGE_COUNTER)); + var verified = AccountLogoutAllAuthorityEventV1Codec.verify(sealed.canonicalJson()); + + assertThat(verified.schemaVersion()) + .isEqualTo(AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION); + assertThat(verified.eventType()).isEqualTo(AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE); + assertThat(verified.eventId()) + .isEqualTo(AccountLogoutAllAuthorityEventV1Codec.EVENT_ID_PREFIX + REQUEST_ID); + assertThat(verified.requestId()).isEqualTo(REQUEST_ID); + assertThat(verified.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(verified.sourceScope()).isEqualTo("account/" + ACCOUNT_ID); + assertThat(verified.outboxStreamKey()).isEqualTo(STREAM); + assertThat(verified.outboxSequence()).isEqualTo(LARGE_COUNTER); + assertThat(verified.accountAuthorityGeneration()).isEqualTo(LARGE_COUNTER); + assertThat(verified.sourceVersion()).isEqualTo(LARGE_COUNTER); + assertThat(verified.accountSecurityCutoff()) + .isEqualTo( + new AccountLogoutAllAuthorityEventV1Codec.AccountSecurityCutoff( + LARGE_COUNTER, STREAM, LARGE_COUNTER)); + assertThat(verified.eventDigest()).isEqualTo(preimageDigest(sealed.canonicalJson())); + assertThat(verified.canonicalJsonUtf8()).isEqualTo(sealed.canonicalJsonUtf8()); + } + + @Test + void rejectsWrongRequestEventIdentityAccountScopeAndCutoff() { + var wrongEventId = new java.util.HashMap<>(preimage("1")); + wrongEventId.put("eventId", "account-logout-all-event-v1:33333333-3333-4333-8333-333333333333"); + var wrongAccount = new java.util.HashMap<>(preimage("1")); + wrongAccount.put("accountId", "33333333-3333-4333-8333-333333333333"); + var wrongCutoff = new java.util.HashMap<>(preimage("1")); + wrongCutoff.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "2", + "outboxStreamKey", STREAM, + "outboxSequence", "1")); + + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.seal(wrongEventId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventId"); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.seal(wrongAccount)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.seal(wrongCutoff)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("accountSecurityCutoff.accountAuthorityGeneration"); + } + + @Test + void rejectsUnknownDuplicateTrailingAndNoncanonicalCounterWireData() throws Exception { + String valid = AccountLogoutAllAuthorityEventV1Codec.seal(preimage("1")).canonicalJson(); + String duplicate = valid.replaceFirst("\\{", "{\"eventType\":\"duplicate\","); + String unknown = valid.replaceFirst("}$", ",\"future\":true}"); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(duplicate)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(unknown)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(valid + " false")) + .isInstanceOf(IllegalArgumentException.class); + + ObjectNode badSequence = (ObjectNode) JSON.readTree(valid); + badSequence.put("outboxSequence", "01"); + assertThatThrownBy(() -> AccountLogoutAllAuthorityEventV1Codec.verify(badSequence.toString())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Map preimage(String counter) { + return Map.ofEntries( + Map.entry("schemaVersion", AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", AccountLogoutAllAuthorityEventV1Codec.EVENT_ID_PREFIX + REQUEST_ID), + Map.entry("requestId", REQUEST_ID), + Map.entry("accountId", ACCOUNT_ID), + Map.entry("sourceScope", "account/" + ACCOUNT_ID), + Map.entry("outboxStreamKey", STREAM), + Map.entry("outboxSequence", counter), + Map.entry("accountAuthorityGeneration", counter), + Map.entry("sourceVersion", counter), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", counter, + "outboxStreamKey", STREAM, + "outboxSequence", counter))); + } + + private static String preimageDigest(String wireJson) throws Exception { + JsonNode parsed = JSON.readTree(wireJson); + ObjectNode preimage = ((ObjectNode) parsed).deepCopy(); + preimage.remove("eventDigest"); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + return "sha256:" + + java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..05689e8cf9 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java @@ -0,0 +1,157 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.security.MessageDigest; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; + +class AccountSecurityStateAuthorityEventV1CodecTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private static final String REQUEST_ID = "22222222-2222-4222-8222-222222222222"; + private static final String STREAM = + AccountSecurityStateAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + ACCOUNT_ID; + private static final String LARGE_COUNTER = "9223372036854775807"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void sealsCompleteSecurityStateAndAllowsEmptyGlobalRoles() throws Exception { + var sealed = AccountSecurityStateAuthorityEventV1Codec.seal(preimage(LARGE_COUNTER)); + var verified = AccountSecurityStateAuthorityEventV1Codec.verify(sealed.canonicalJson()); + + assertThat(verified.schemaVersion()) + .isEqualTo(AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION); + assertThat(verified.eventType()) + .isEqualTo(AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE); + assertThat(verified.eventId()) + .isEqualTo(AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + REQUEST_ID); + assertThat(verified.requestId()).isEqualTo(REQUEST_ID); + assertThat(verified.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(verified.sourceScope()).isEqualTo("account/" + ACCOUNT_ID); + assertThat(verified.outboxStreamKey()).isEqualTo(STREAM); + assertThat(verified.outboxSequence()).isEqualTo(LARGE_COUNTER); + assertThat(verified.accountAuthorityGeneration()).isEqualTo(LARGE_COUNTER); + assertThat(verified.sourceVersion()).isEqualTo(LARGE_COUNTER); + assertThat(verified.accountSecurityCutoff()) + .isEqualTo( + new AccountSecurityStateAuthorityEventV1Codec.AccountSecurityCutoff( + LARGE_COUNTER, STREAM, LARGE_COUNTER)); + assertThat(verified.mutationKinds()) + .containsExactly("EMAIL_LOGIN_ELIGIBILITY_CHANGED", "GLOBAL_ROLE_CHANGED"); + assertThat(verified.accountState().emailVerified()).isTrue(); + assertThat(verified.accountState().loginAuthModes()).containsExactly("EMAIL_OTP", "PASSWORD"); + assertThat(verified.accountState().globalRoles()).isEmpty(); + assertThat(verified.accountState().lifecycleState()).isEqualTo("ACTIVE"); + assertThat(verified.eventDigest()).isEqualTo(preimageDigest(sealed.canonicalJson())); + } + + @Test + void requiresSortedUniqueArraysAndExactScopeAndCutoffBindings() { + var unsortedKinds = new java.util.HashMap<>(preimage("1")); + unsortedKinds.put( + "mutationKinds", List.of("GLOBAL_ROLE_CHANGED", "EMAIL_LOGIN_ELIGIBILITY_CHANGED")); + var unsortedRoles = new java.util.HashMap<>(preimage("1")); + unsortedRoles.put( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("EMAIL_OTP", "PASSWORD"), + "globalRoles", + List.of("support", "platformAdmin"), + "lifecycleState", + "ACTIVE")); + var wrongEventId = new java.util.HashMap<>(preimage("1")); + wrongEventId.put( + "eventId", "account-security-state-event-v1:33333333-3333-4333-8333-333333333333"); + var wrongCutoffStream = new java.util.HashMap<>(preimage("1")); + wrongCutoffStream.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "1", + "outboxStreamKey", + "account:auth-authority:v1:account/33333333-3333-4333-8333-333333333333", + "outboxSequence", "1")); + + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.seal(unsortedKinds)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sorted and unique"); + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.seal(unsortedRoles)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sorted and unique"); + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.seal(wrongEventId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.seal(wrongCutoffStream)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsDuplicateUnknownTrailingAndDigestTampering() throws Exception { + String valid = AccountSecurityStateAuthorityEventV1Codec.seal(preimage("1")).canonicalJson(); + String duplicate = valid.replaceFirst("\\{", "{\"eventType\":\"duplicate\","); + String unknown = valid.replaceFirst("}$", ",\"future\":true}"); + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.verify(duplicate)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.verify(unknown)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.verify(valid + " null")) + .isInstanceOf(IllegalArgumentException.class); + + ObjectNode changed = (ObjectNode) JSON.readTree(valid); + changed.put("sourceVersion", "2"); + assertThatThrownBy(() -> AccountSecurityStateAuthorityEventV1Codec.verify(changed.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + + private static Map preimage(String counter) { + return Map.ofEntries( + Map.entry("schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry( + "eventId", AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + REQUEST_ID), + Map.entry("requestId", REQUEST_ID), + Map.entry("accountId", ACCOUNT_ID), + Map.entry("sourceScope", "account/" + ACCOUNT_ID), + Map.entry("outboxStreamKey", STREAM), + Map.entry("outboxSequence", counter), + Map.entry("accountAuthorityGeneration", counter), + Map.entry("sourceVersion", counter), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", counter, + "outboxStreamKey", STREAM, + "outboxSequence", counter)), + Map.entry( + "mutationKinds", List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED", "GLOBAL_ROLE_CHANGED")), + Map.entry( + "accountState", + Map.of( + "emailVerified", + true, + "loginAuthModes", + List.of("EMAIL_OTP", "PASSWORD"), + "globalRoles", + List.of(), + "lifecycleState", + "ACTIVE"))); + } + + private static String preimageDigest(String wireJson) throws Exception { + JsonNode parsed = JSON.readTree(wireJson); + ObjectNode preimage = ((ObjectNode) parsed).deepCopy(); + preimage.remove("eventDigest"); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + return "sha256:" + + java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java new file mode 100644 index 0000000000..e4c64d4a54 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1CodecTest.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.security.MessageDigest; +import java.util.Map; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; + +class PasswordResetAuthorityEventV1CodecTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private static final String STREAM = + PasswordResetAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + ACCOUNT_ID; + private static final String LARGE_COUNTER = "9223372036854775807"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void sealsAndVerifiesBoundPasswordResetEvidenceWithLargeStringCounters() throws Exception { + var sealed = PasswordResetAuthorityEventV1Codec.seal(preimage(LARGE_COUNTER, ACCOUNT_ID)); + var verified = PasswordResetAuthorityEventV1Codec.verify(sealed.canonicalJson()); + + assertThat(verified.schemaVersion()) + .isEqualTo(PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION); + assertThat(verified.eventType()).isEqualTo(PasswordResetAuthorityEventV1Codec.EVENT_TYPE); + assertThat(verified.eventId()).isEqualTo("password-reset-event-1"); + assertThat(verified.requestId()).isEqualTo("request-1"); + assertThat(verified.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(verified.sourceScope()).isEqualTo("account/" + ACCOUNT_ID); + assertThat(verified.outboxStreamKey()).isEqualTo(STREAM); + assertThat(verified.outboxSequence()).isEqualTo(LARGE_COUNTER); + assertThat(verified.accountAuthorityGeneration()).isEqualTo(LARGE_COUNTER); + assertThat(verified.sourceVersion()).isEqualTo(LARGE_COUNTER); + assertThat(verified.accountSecurityCutoff()) + .isEqualTo( + new PasswordResetAuthorityEventV1Codec.AccountSecurityCutoff( + LARGE_COUNTER, STREAM, LARGE_COUNTER)); + assertThat(verified.eventDigest()).isEqualTo(preimageDigest(sealed.canonicalJson())); + assertThat(verified.canonicalJson()).isEqualTo(sealed.canonicalJson()); + assertThat(verified.canonicalJson()).contains("\"outboxSequence\":\"" + LARGE_COUNTER + "\""); + } + + @Test + void rejectsMismatchedScopeAndCutoffBindings() { + var wrongScope = new java.util.HashMap<>(preimage("1", ACCOUNT_ID)); + wrongScope.put("sourceScope", "account/22222222-2222-4222-8222-222222222222"); + var wrongCutoffSequence = new java.util.HashMap<>(preimage("1", ACCOUNT_ID)); + wrongCutoffSequence.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", "1", + "outboxStreamKey", STREAM, + "outboxSequence", "2")); + + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.seal(wrongScope)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.seal(wrongCutoffSequence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("accountSecurityCutoff.outboxSequence"); + } + + @Test + void rejectsNoncanonicalCountersAndMalformedOrTamperedWireJson() throws Exception { + for (String invalidCounter : new String[] {"0", "01", "-1"}) { + var invalid = new java.util.HashMap<>(preimage("1", ACCOUNT_ID)); + invalid.put("outboxSequence", invalidCounter); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.seal(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + String valid = + PasswordResetAuthorityEventV1Codec.seal(preimage("1", ACCOUNT_ID)).canonicalJson(); + ObjectNode changed = (ObjectNode) JSON.readTree(valid); + changed.put("sourceVersion", "2"); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(changed.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + + String duplicate = valid.replaceFirst("\\{", "{\"eventType\":\"duplicate\","); + String unknown = valid.replaceFirst("}$", ",\"future\":true}"); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(duplicate)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(unknown)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> PasswordResetAuthorityEventV1Codec.verify(valid + " {}")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Map preimage(String counter, String accountId) { + String stream = PasswordResetAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "account/" + accountId; + return Map.ofEntries( + Map.entry("schemaVersion", PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "password-reset-event-1"), + Map.entry("requestId", "request-1"), + Map.entry("accountId", accountId), + Map.entry("sourceScope", "account/" + accountId), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", counter), + Map.entry("accountAuthorityGeneration", counter), + Map.entry("sourceVersion", counter), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", counter, + "outboxStreamKey", stream, + "outboxSequence", counter))); + } + + private static String preimageDigest(String wireJson) throws Exception { + JsonNode parsed = JSON.readTree(wireJson); + ObjectNode preimage = ((ObjectNode) parsed).deepCopy(); + preimage.remove("eventDigest"); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + return "sha256:" + + java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java new file mode 100644 index 0000000000..74af64299e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java @@ -0,0 +1,317 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import org.junit.jupiter.api.Test; + +class RuntimeMembershipAuthorityEvidenceValidatorTest { + private static final String ISSUER_ID = "firemud-account-service"; + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private static final String TENANT_ID = "33333333-3333-4333-8333-333333333333"; + private static final String OTHER_TENANT_ID = "44444444-4444-4444-8444-444444444444"; + private static final String PREFIX = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + private static final String ACCOUNT_STREAM = PREFIX + "account/" + ACCOUNT_ID; + private static final String ISSUER_STREAM = PREFIX + "issuer/" + ISSUER_ID; + private static final String TENANT_STREAM = PREFIX + "tenant/" + TENANT_ID; + private static final String MEMBERSHIP_STREAM = + PREFIX + "membership/" + ACCOUNT_ID + "/" + TENANT_ID; + private static final String LARGE_COUNTER = "9223372036854775807"; + + @Test + void validatesCurrentMembershipAgainstAccountSourceAndLargeDecimalCheckpoints() { + RuntimeMembershipAuthorityEvidenceValidator.Snapshot snapshot = currentSnapshot(); + + Optional result = + RuntimeMembershipAuthorityEvidenceValidator.validate(snapshot); + + assertThat(result).isPresent(); + assertThat(result.orElseThrow().accountId()).isEqualTo(ACCOUNT_ID); + assertThat(result.orElseThrow().tenantId()).isEqualTo(TENANT_ID); + assertThat(result.orElseThrow().outboxSequence()).isEqualTo("1"); + assertThat(snapshot.checkpoints().get(0).outboxSequence()).isEqualTo(LARGE_COUNTER); + assertThat(snapshot.authorityTuple().accountAuthorityGeneration()).isEqualTo(LARGE_COUNTER); + } + + @Test + void returnsEmptyOnlyForAWellFormedMissingMembershipBaseline() { + RuntimeMembershipAuthorityEvidenceValidator.Snapshot missing = missingMembershipSnapshot(); + + assertThat(RuntimeMembershipAuthorityEvidenceValidator.validate(missing)).isEmpty(); + + var admitting = + new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + missing.issuerId(), + missing.accountId(), + missing.tenantId(), + false, + "MISSING", + true, + missing.membershipVersion(), + missing.membershipAuthorityGeneration(), + missing.roles(), + missing.authorityTuple(), + missing.issuanceFence(), + missing.checkpoints(), + missing.sourceEvidence()); + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(admitting)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("zero checkpoint"); + } + + @Test + void deniesMismatchedSourceScopeOriginalCarrierDigestAndMembershipVersion() { + var valid = currentSnapshot(); + var currentAccount = + PasswordResetAuthorityEventV1Codec.verify( + valid.sourceEvidence().get(0).canonicalEventJson()); + var forgedAccountCarrier = + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + ACCOUNT_STREAM, + LARGE_COUNTER, + currentAccount.eventId(), + "sha256:" + "0".repeat(64), + currentAccount.canonicalJson()); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith( + valid, + valid.checkpoints(), + List.of(forgedAccountCarrier, valid.sourceEvidence().get(1))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source carrier eventDigest"); + + var alteredCanonicalBytes = + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + ACCOUNT_STREAM, + LARGE_COUNTER, + currentAccount.eventId(), + currentAccount.eventDigest(), + " " + currentAccount.canonicalJson()); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith( + valid, + valid.checkpoints(), + List.of(alteredCanonicalBytes, valid.sourceEvidence().get(1))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source carrier canonical event bytes"); + + MembershipEvent otherScope = membershipEvent(ACCOUNT_ID, OTHER_TENANT_ID); + var mismatchedScopeCarrier = + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + MEMBERSHIP_STREAM, + "1", + otherScope.eventId(), + otherScope.eventDigest(), + otherScope.canonicalJson()); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith( + valid, + valid.checkpoints(), + List.of(valid.sourceEvidence().get(0), mismatchedScopeCarrier)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source event stream key"); + + var changedVersion = + new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + valid.issuerId(), + valid.accountId(), + valid.tenantId(), + valid.membershipExists(), + valid.membershipLifecycleState(), + valid.gameplayAdmissionAllowed(), + Map.of(TENANT_ID, "2"), + valid.membershipAuthorityGeneration(), + valid.roles(), + valid.authorityTuple(), + valid.issuanceFence(), + valid.checkpoints(), + valid.sourceEvidence()); + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(changedVersion)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("membershipVersion"); + } + + @Test + void requiresSortedExactCheckpointAndSourceInventories() { + var valid = currentSnapshot(); + List reversed = + new ArrayList<>(valid.checkpoints()); + java.util.Collections.reverse(reversed); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith(valid, reversed, valid.sourceEvidence()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sorted by stream key"); + + List duplicateSource = + new ArrayList<>(valid.sourceEvidence()); + duplicateSource.add(valid.sourceEvidence().get(0)); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith(valid, valid.checkpoints(), duplicateSource))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sourceEvidence"); + } + + private static RuntimeMembershipAuthorityEvidenceValidator.Snapshot currentSnapshot() { + var accountEvent = PasswordResetAuthorityEventV1Codec.seal(accountSourcePreimage()); + MembershipEvent memberEvent = membershipEvent(ACCOUNT_ID, TENANT_ID); + var currentCutoff = new AccountSecurityCutoff(LARGE_COUNTER, ACCOUNT_STREAM, LARGE_COUNTER); + AuthorityTuple currentTuple = + new AuthorityTuple( + "1", + LARGE_COUNTER, + Map.of(TENANT_ID, "1"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.of(currentCutoff), + Optional.empty()); + return new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + ISSUER_ID, + ACCOUNT_ID, + TENANT_ID, + true, + "ACTIVE", + true, + Map.of(TENANT_ID, "1"), + "1", + List.of("player"), + currentTuple, + "1", + List.of( + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + ACCOUNT_STREAM, LARGE_COUNTER), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(ISSUER_STREAM, "0"), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(MEMBERSHIP_STREAM, "1"), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(TENANT_STREAM, "0")), + List.of( + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + ACCOUNT_STREAM, + LARGE_COUNTER, + accountEvent.eventId(), + accountEvent.eventDigest(), + accountEvent.canonicalJson()), + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + MEMBERSHIP_STREAM, + "1", + memberEvent.eventId(), + memberEvent.eventDigest(), + memberEvent.canonicalJson()))); + } + + private static RuntimeMembershipAuthorityEvidenceValidator.Snapshot missingMembershipSnapshot() { + AuthorityTuple baselineTuple = + new AuthorityTuple( + "1", + "1", + Map.of(TENANT_ID, "1"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.empty(), + Optional.empty()); + return new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + ISSUER_ID, + ACCOUNT_ID, + TENANT_ID, + false, + "MISSING", + false, + Map.of(TENANT_ID, "1"), + "1", + List.of(), + baselineTuple, + "1", + List.of( + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(ACCOUNT_STREAM, "0"), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(ISSUER_STREAM, "0"), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(MEMBERSHIP_STREAM, "0"), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(TENANT_STREAM, "0")), + List.of()); + } + + private static Map accountSourcePreimage() { + return Map.ofEntries( + Map.entry("schemaVersion", PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", PasswordResetAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "password-reset-current-source-event"), + Map.entry("requestId", "password-reset-request"), + Map.entry("accountId", ACCOUNT_ID), + Map.entry("sourceScope", "account/" + ACCOUNT_ID), + Map.entry("outboxStreamKey", ACCOUNT_STREAM), + Map.entry("outboxSequence", LARGE_COUNTER), + Map.entry("accountAuthorityGeneration", LARGE_COUNTER), + Map.entry("sourceVersion", LARGE_COUNTER), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", LARGE_COUNTER, + "outboxStreamKey", ACCOUNT_STREAM, + "outboxSequence", LARGE_COUNTER))); + } + + private static MembershipEvent membershipEvent(String accountId, String tenantId) { + String stream = PREFIX + "membership/" + accountId + "/" + tenantId; + Map event = new java.util.LinkedHashMap<>(); + event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + event.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + event.put("eventId", "membership-event-1"); + event.put("requestId", "membership-request-1"); + event.put("outboxStreamKey", stream); + event.put("outboxSequence", "1"); + event.put("sourceScope", "membership/" + accountId + "/" + tenantId); + event.put("accountId", accountId); + event.put("tenantId", tenantId); + event.put("membershipExists", true); + event.put("membershipLifecycleState", "ACTIVE"); + event.put("membershipVersion", Map.of(tenantId, "1")); + event.put("membershipAuthorityGeneration", "1"); + event.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(tenantId, "1"), + "membershipAuthorityGeneration", Map.of(tenantId, "1"), + "privateRealmGrantVersions", List.of())); + event.put("issuanceFence", "1"); + event.put("roles", List.of("player")); + event.put("gameplayAdmissionAllowed", true); + event.put("callerBoundAuthorityInvalidated", false); + return MembershipAuthorityEventV1Codec.seal(event); + } + + private static RuntimeMembershipAuthorityEvidenceValidator.Snapshot copyWith( + RuntimeMembershipAuthorityEvidenceValidator.Snapshot snapshot, + List checkpoints, + List sources) { + return new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + snapshot.issuerId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.membershipExists(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.roles(), + snapshot.authorityTuple(), + snapshot.issuanceFence(), + checkpoints, + sources); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java new file mode 100644 index 0000000000..6478afe58e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java @@ -0,0 +1,161 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class FreshTenantCreatorDigestTest { + private static final UUID ACCOUNT_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID AUTHORIZATION_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String AUTHORIZATION_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void usesTheDeclaredLengthFramedUtf8TupleIncludingTheMultibyteSourceKey() throws Exception { + FreshTenantCreationEvidence creation = creationEvidence(42L, "legacy-α"); + List segments = + List.of( + "game-design-tenant-creator-qualification/v1", + "1", + "1", + "prod", + creation.creationRequestId().toString(), + creation.operationId().toString(), + creation.requestDigest(), + creation.canonicalTenantId().toString(), + "42", + "legacy-α", + "NEW_GAME_ROW", + creation.evidenceDigest(), + ACCOUNT_ID.toString(), + AUTHORIZATION_OPERATION_ID.toString(), + AUTHORIZATION_DIGEST); + + assertThat("legacy-α".getBytes(StandardCharsets.UTF_8)).hasSize(9); + assertThat( + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST)) + .isEqualTo(lengthPrefixedSha256(segments)); + } + + @Test + void bindsEveryCreationAndAccountAuthorizationIdentityComponent() { + FreshTenantCreationEvidence creation = creationEvidence(42L, "legacy-α"); + String expected = + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST); + + assertThat( + FreshTenantCreatorDigest.evidenceDigest( + 1, + creation, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST)) + .isNotEqualTo(expected); + assertThat( + FreshTenantCreatorDigest.evidenceDigest( + 1, + creation, + ACCOUNT_ID, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + AUTHORIZATION_DIGEST)) + .isNotEqualTo(expected); + assertThat( + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, "sha256:" + "b".repeat(64))) + .isNotEqualTo(expected); + assertThat( + FreshTenantCreatorDigest.evidenceDigest( + 1, + creationEvidence(43L, "legacy-α"), + ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST)) + .isNotEqualTo(expected); + assertThat( + FreshTenantCreatorDigest.evidenceDigest( + 1, + creationEvidence(42L, "legacy-beta"), + ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST)) + .isNotEqualTo(expected); + } + + @Test + void rejectsUnsupportedVersionNilIdentityAndMalformedDigest() { + FreshTenantCreationEvidence creation = creationEvidence(42L, "legacy-α"); + + assertThatThrownBy( + () -> + FreshTenantCreatorDigest.evidenceDigest( + 2, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + FreshTenantCreatorDigest.evidenceDigest( + 1, + creation, + new UUID(0L, 0L), + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, ACCOUNT_ID, new UUID(0L, 0L), AUTHORIZATION_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, "not-a-digest")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static FreshTenantCreationEvidence creationEvidence(long rowId, String sourceKey) { + UUID requestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID operationId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID tenantId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + String requestDigest = "sha256:" + "c".repeat(64); + return new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + operationId, + requestDigest, + tenantId, + rowId, + sourceKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", + requestId, + operationId, + requestDigest, + tenantId, + rowId, + sourceKey, + "NEW_GAME_ROW")); + } + + private static String lengthPrefixedSha256(List segments) throws Exception { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + for (String segment : segments) { + byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); + preimage.write(Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8)); + preimage.write(':'); + preimage.write(bytes); + } + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java new file mode 100644 index 0000000000..56569f3c18 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.common.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class FreshTenantCreatorEvidenceTest { + private static final UUID ACCOUNT_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID AUTHORIZATION_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String AUTHORIZATION_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void acceptsCreatorQualificationBoundToFreshCreationAndAccountAuthorization() { + FreshTenantCreatorEvidence evidence = validEvidence(); + + assertThat(evidence.schemaVersion()).isEqualTo(1); + assertThat(evidence.creationEvidence()).isEqualTo(creationEvidence()); + assertThat(evidence.initiatingAccountId()).isEqualTo(ACCOUNT_ID); + assertThat(evidence.accountAuthorizationOperationId()).isEqualTo(AUTHORIZATION_OPERATION_ID); + assertThat(evidence.accountAuthorizationDigest()).isEqualTo(AUTHORIZATION_DIGEST); + assertThat(evidence.evidenceDigest()) + .isEqualTo( + FreshTenantCreatorDigest.evidenceDigest( + evidence.schemaVersion(), + evidence.creationEvidence(), + evidence.initiatingAccountId(), + evidence.accountAuthorizationOperationId(), + evidence.accountAuthorizationDigest())); + } + + @Test + void rejectsReusedOriginalDigestWhenAnyCreatorIdentityOrCreationEvidenceChanges() { + FreshTenantCreatorEvidence valid = validEvidence(); + String originalDigest = valid.evidenceDigest(); + + assertInvalid( + 1, + creationEvidence(), + UUID.fromString("66666666-6666-4666-8666-666666666666"), + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST, + originalDigest); + assertInvalid( + 1, + creationEvidence(), + ACCOUNT_ID, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + AUTHORIZATION_DIGEST, + originalDigest); + assertInvalid( + 1, + creationEvidence(), + ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + "sha256:" + "b".repeat(64), + originalDigest); + assertInvalid( + 1, + creationEvidence(43L, "legacy-α"), + ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST, + originalDigest); + assertInvalid( + 1, + creationEvidence(42L, "legacy-beta"), + ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST, + originalDigest); + } + + @Test + void rejectsUnsupportedVersionNilIdentitiesAndMalformedAuthorizationDigest() { + FreshTenantCreationEvidence creation = creationEvidence(); + String correctDigest = + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST); + + assertInvalid( + 2, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST, correctDigest); + assertInvalid( + 1, + creation, + new UUID(0L, 0L), + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST, + correctDigest); + assertInvalid(1, creation, ACCOUNT_ID, new UUID(0L, 0L), AUTHORIZATION_DIGEST, correctDigest); + assertThatThrownBy( + () -> + FreshTenantCreatorDigest.evidenceDigest( + 1, + creation, + ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + "SHA256:" + "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static FreshTenantCreatorEvidence validEvidence() { + FreshTenantCreationEvidence creation = creationEvidence(); + return new FreshTenantCreatorEvidence( + 1, + creation, + ACCOUNT_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST)); + } + + private static FreshTenantCreationEvidence creationEvidence() { + return creationEvidence(42L, "legacy-α"); + } + + private static FreshTenantCreationEvidence creationEvidence(long rowId, String sourceKey) { + UUID requestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID operationId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID tenantId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + String requestDigest = "sha256:" + "c".repeat(64); + return new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + operationId, + requestDigest, + tenantId, + rowId, + sourceKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", + requestId, + operationId, + requestDigest, + tenantId, + rowId, + sourceKey, + "NEW_GAME_ROW")); + } + + private static void assertInvalid( + int schemaVersion, + FreshTenantCreationEvidence creation, + UUID accountId, + UUID authorizationOperationId, + String authorizationDigest, + String evidenceDigest) { + assertThatThrownBy( + () -> + new FreshTenantCreatorEvidence( + schemaVersion, + creation, + accountId, + authorizationOperationId, + authorizationDigest, + evidenceDigest)) + .isInstanceOf(IllegalArgumentException.class); + } +} From 7a665c83e81f5cec85fcd7ec9a205c291bc0eba2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 08:51:06 +1300 Subject: [PATCH 02/10] Close Account security source writes and prove exact persisted guards --- .../account-service/runtime-and-data.md | 8 +- .../player-access-and-session.md | 8 +- .../DraftAuthorizationFenceRepository.java | 2 +- .../hostedterms/HostedTermsRepository.java | 47 +- ...ountAuthoritySourceEvidenceRepository.java | 67 ++- .../repository/AccountRepository.java | 7 +- .../PasswordResetTokenRepository.java | 25 + .../AccountAuthoritySourceEventReadback.java | 7 +- ...ccountLogoutAllAuthorityEventProducer.java | 12 +- ...swordResetDraftSourceChangeRepository.java | 17 +- .../service/impl/AccountServiceImpl.java | 29 +- ...ount_password_reset_operation_receipts.sql | 2 +- ..._account_logout_all_operation_receipts.sql | 2 +- ...0__account_security_event_source_guard.sql | 181 ++++++- ...count_hosted_terms_environment_binding.sql | 61 +++ ...ord_reset_pending_draft_source_changes.sql | 13 +- ..._account_control_ui_committed_issuance.sql | 119 +++++ ...unt_selected_publication_authorization.sql | 182 +++++++ ...__account_publication_pre_freeze_order.sql | 5 + ...ccount_selected_publication_settlement.sql | 167 +++++++ ...V94__selected_publication_inventory_v2.sql | 465 ++++++++++++++++++ .../V95__game_logic_intake_authorization.sql | 175 +++++++ ..._game_logic_intake_terminal_settlement.sql | 129 +++++ ...e_logic_intake_source_read_reservation.sql | 234 +++++++++ ...horityProducerPostgresIntegrationTest.java | 375 +++++++++++++- ...ntBindingFencePostgresIntegrationTest.java | 365 ++++++++++++++ ...rceEvidencePersistenceIntegrationTest.java | 214 +++++--- .../AccountRepositoryIntegrationTest.java | 161 +++++- ...urceOwnerGuardPostgresIntegrationTest.java | 357 ++++++++++++++ ...wardMigrationsPostgresIntegrationTest.java | 25 +- ...tionV73UpgradePostgresIntegrationTest.java | 24 +- .../HostedTermsRepositoryTest.java | 99 ++++ ...AuthoritySourceEvidenceRepositoryTest.java | 76 ++- .../repository/AccountRepositoryTest.java | 52 ++ ...countAuthoritySourceEventReadbackTest.java | 67 +++ ...ntLogoutAllAuthorityEventProducerTest.java | 5 + .../service/impl/AccountServiceImplTest.java | 165 +++++++ 37 files changed, 3745 insertions(+), 204 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql create mode 100644 services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql create mode 100644 services/account-service/src/main/resources/db/migration/V92__account_publication_pre_freeze_order.sql create mode 100644 services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql create mode 100644 services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql create mode 100644 services/account-service/src/main/resources/db/migration/V95__game_logic_intake_authorization.sql create mode 100644 services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql create mode 100644 services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingFencePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index daaa9dfd63..22be237528 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,7 +8,9 @@ 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; 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 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. V90–V97 add Account persistence relations and guards for committed control-UI issuance, selected-publication authorization/settlement, Game Logic intake settlement, and preliminary Game Logic source-read reservations. These DDL stages establish source-writer fence relationships; they do not activate owner writers or prove a positive owner receipt. 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 remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. 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. + +Proof qualification: the counts in the preceding paragraph are historical local results at `1f5045fe0a8e66f33f0e6c046f77f099e749c45b`. Its hosted Account physical suite ran 88 cases and reported 26 failures, leading to the current corrections. The corrected batch passed the consolidated Account check, including 636 unit cases with no failures or skips, production and integration-test compilation, formatting, Checkstyle and SpotBugs; all 245 Common Platform Core unit cases remain green with their unchanged outputs reused. The local integration run reports 85 cases: two executed and 83 skipped without Docker. The corrected migration set passes `generateJooq`, and documentation checks passed 10,464 links and 549 Markdown files. Physical fresh-install/V73-upgrade PostgreSQL proof remains pending on corrected-head CI; skipped cases and synthetic owner inputs do not prove activation or playable closure. 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 +28,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. -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. +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 Draft fence references for `account_hosted_terms_disclosure_handoffs` and `account_hosted_terms_disclosure_sources` have no donor schema or canonical implemented journal in the migration history; reserve, claim, and publication paths requiring hosted-terms disclosure checks remain unavailable; this does not disable source-fence paths that do not involve hosted terms or establish activation. 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 +36,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. 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). +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 and returns retryable `AUTH_UNAVAILABLE` until an exact retry can establish its outcome. `AccountAuthoritySourceEventReadback` accepts only the supported closed-operation event shapes with their exact immutable operation receipts; generic Account authority events without that receipt remain unreadable as current source evidence and fail closed as `AUTH_UNAVAILABLE`. This does not establish complete LOGIN/currentness closure. Reset-driven revocation and the broader recovery/session/logout family remain incomplete. 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). 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 3e6846526b..1bd6e7798a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca 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). +Proof qualification for the Account source/currentness cut: the earlier local results above belong to `1f5045fe0a8e66f33f0e6c046f77f099e749c45b`, whose hosted Account physical suite ran 88 cases with 26 failures. The corrected batch passes the consolidated Account check with 636 unit cases, compilation and static analysis, while all 245 unchanged Common unit cases remain green. Its local integration run executed two cases and skipped 83 without Docker; physical fresh-install/V73-upgrade proof remains pending on corrected-head CI. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for exact proof scope and limitations. + Canonical first-JOIN membership-event production requires current public-JOIN entitlement; a bare fresh tenant 1/1 baseline is denied and does not preserve admission. Tenant authority requires Account's exact typed tenant event, fresh Game Design provenance, and matching composite generation/source-version and billing coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Historical gate 108 passed 593 Account unit cases and five focused shared World hold cases. Later gate 123 passed 598 Account unit cases, and gate 124 passed 27 focused shared-evidence cases across a broader selection; these are distinct executed snapshots and suite scopes, not conflicting totals. jOOQ generation and integration-test compilation passed. Published checkpoint `b5234acd7f93440170178d1b808e19b4a00ac644` subsequently passed required CI. PostgreSQL-backed integration sources, including the later-generation JOIN and exact outbox replay cases, remain unexecuted locally; neither unit proof nor historical CI establishes fresh-image playable proof for subsequent corrections. Earlier Account checkpoints `d619948920469228814d8d2ef60f9dac8672e7ea` and `f086de2896f885e33745d1482872ec2ae1c480c2` have reported green required CI, including full-stack Smoke. Reported local validation passed 535 Account unit tests, integration-test source compilation, and documentation checks; local physical PostgreSQL validation was not run. The newer reconciled head `5deaf573be3774b4eb8285ff857907f03b2ba5e0` and subsequent retained-source denial correction do not inherit an exact-head green claim. The correction passed 249 focused Account unit tests, integration-test source compilation, and documentation checks; exact-head required CI and physical PostgreSQL proof remain pending. @@ -30,7 +32,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. 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. +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 or an earlier source intent remains `WAITING`, the owner transaction rolls back and returns retryable `AUTH_UNAVAILABLE`; the handler does not wait for source settlement on a thread. An exact retry preserves the original intent and may proceed after its owner-fence outcome is known. The `WAITING` intent retains the Argon2 password verifier required for that retry; terminal source commit or abort clears the verifier while retaining its digest and immutable source binding and receipt. No finite receipt lifetime is selected; receipt retention remains an owning-policy gap. Retained pre-V40 rows remain denied and are neither backfilled nor admitted; unrelated transaction or database failures are not converted by this handler. + +For AA-1.3 source-currentness, [AccountAuthoritySourceEventReadback](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java) and the source-fenced reset path in [AccountServiceImpl](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) are production anchors; [AccountAuthoritySourceEventReadbackTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java), [AccountServiceImplTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java), [PasswordResetAuthorityProducerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java), and [AccountAuthoritySourceEvidencePersistenceIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) are focused proof anchors. The Account authority-event reader still rejects generic source events that lack a supported exact closed-operation receipt as `AUTH_UNAVAILABLE`, so this does not claim complete LOGIN/currentness closure. Reset-driven revocation and the broader recovery/session/logout family remain incomplete; physical PostgreSQL proof remains unestablished. 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). @@ -48,7 +52,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | -| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql) [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. The finite namespace controller-index migration-driver source and packaging prefix have focused source/protocol, packaging, resource-integrity, and static image-contract evidence, but do not prove namespace-aware atomic takeover. The V34.3 PostgreSQL fixture is unrun; physical PostgreSQL and Redis execution, final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Namespace-aware binding and [SESSION-02 atomic transfer](../../architecture/system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) remain incomplete; issuer-index and region reconciliation plus retained-binding inventory/conversion remain open. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 66099c9f28..dd5178be70 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -711,7 +711,7 @@ private SourceChangeAbortReason abortReason(String 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. + * neither condition is a terminal authorization outcome. V87 establishes real-source lock rows. */ public void lockProducerSourcesNowait(List sources) { requireTransaction(); 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 index b23696c6b5..e782c07586 100644 --- 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 @@ -506,32 +506,31 @@ private HostedTermsCatalogVersion catalog(Record row) { } 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))) { + byte[] individualPartySource = row.get("individual_party_source", byte[].class); + String individualPartySourceDigest = row.get("individual_party_source_digest", String.class); + byte[] affirmativeActionEvidence = row.get("affirmative_action_evidence", byte[].class); + String affirmativeActionDigest = row.get("affirmative_action_digest", String.class); + if (!HostedTermsEncoding.digest(affirmativeActionEvidence).equals(affirmativeActionDigest) + || !HostedTermsEncoding.digest(individualPartySource).equals(individualPartySourceDigest)) { throw new IllegalStateException("Stored acceptance evidence digest conflicts"); } - return acceptance; + return 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), + individualPartySource, + individualPartySourceDigest, + affirmativeActionEvidence, + affirmativeActionDigest, + row.get("accepted_at", OffsetDateTime.class)); } private void requireTransaction() { 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 34f9e93da8..5aab9a1d92 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 @@ -298,6 +298,31 @@ public ScopeState prepareClosedAccountAdvance(UUID accountUuid, CurrentSourceEvi return advanced; } + /** + * Reads current source evidence for one exact Account against a caller-captured owner state. The + * generation state is freshly locked and must still equal the supplied snapshot; this API does + * not initialize missing baselines or treat generic history as a closed operation receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CurrentSourceEvidence readCurrentAccountSource(UUID accountUuid, ScopeState 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 + || !accountUuid.equals(expected.issuanceFence().accountId())) { + throw new SourceEvidenceUnavailableException(); + } + AuthorityScope scope = AuthorityScope.account(accountUuid); + ScopeState current = generations.read(scope); + if (!expected.equals(current)) { + throw new SourceEvidenceUnavailableException(); + } + return readCurrentSource(scope, current); + } + /** * 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. @@ -562,9 +587,7 @@ private CurrentSourceEvidence readCurrentSource( if (scope.kind() == ScopeKind.ACCOUNT) { if (fence == null || positive(source, "current_issuance_fence") != fence.value() - || positive(source, "current_issuance_fence_source_version") != fence.sourceVersion() - || fence.value() != sequence + 1L - || fence.sourceVersion() != sequence + 1L) { + || positive(source, "current_issuance_fence_source_version") != fence.sourceVersion()) { throw new SourceEvidenceUnavailableException(); } } else if (fence != null) { @@ -675,8 +698,8 @@ private VerifiedSourceHistory verifyLatestEvent( ScopeState authority, IssuanceFence fence) { // V38/V40 enforce immutable events, contiguous stream advances, and committed head/history - // consistency. The read path therefore verifies the exact current event rather than replaying - // an ever-growing retained history. + // consistency. Issuer source reads use this exact latest-event check; Account source reads + // verify the retained mixed event/receipt history through verifyEventHistory instead. Event stored = outbox .findEvent(streamKey, sequence) @@ -710,16 +733,21 @@ private VerifiedSourceHistory verifyLatestEvent( || Long.parseLong(account.outboxSequence()) != sequence || Long.parseLong(account.accountAuthorityGeneration()) != sequence + 1L || Long.parseLong(account.sourceVersion()) != sequence + 1L - || Long.parseLong(account.issuanceFence()) != sequence + 1L - || Long.parseLong(account.issuanceFenceSourceVersion()) != sequence + 1L)) { + || Long.parseLong(account.issuanceFence()) <= 0L + || Long.parseLong(account.issuanceFenceSourceVersion()) <= 0L)) { throw new SourceEvidenceUnavailableException(); } if (authority.generation() != sequence + 1L || authority.sourceVersion() != sequence + 1L || (scope.kind() == ScopeKind.ACCOUNT && (fence == null - || fence.value() != sequence + 1L - || fence.sourceVersion() != sequence + 1L))) { + || !scope.accountId().equals(fence.accountId()) + || fence.value() <= 0L + || fence.sourceVersion() <= 0L + || (latest instanceof AccountEvent account + && (Long.parseLong(account.issuanceFence()) > fence.value() + || Long.parseLong(account.issuanceFenceSourceVersion()) + > fence.sourceVersion()))))) { throw new SourceEvidenceUnavailableException(); } return new VerifiedSourceHistory(stored, Optional.empty(), Optional.empty()); @@ -772,8 +800,11 @@ private VerifiedSourceHistory verifyEventHistory( && (!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)) { + || fence == null + || Long.parseLong(account.issuanceFence()) <= 0L + || Long.parseLong(account.issuanceFenceSourceVersion()) <= 0L + || Long.parseLong(account.issuanceFence()) > fence.value() + || Long.parseLong(account.issuanceFenceSourceVersion()) > fence.sourceVersion())) { throw new SourceEvidenceUnavailableException(); } latestLegacyAccountEvent = event instanceof AccountEvent account ? account : null; @@ -791,8 +822,11 @@ private VerifiedSourceHistory verifyEventHistory( || receiptEvidence.outboxSequence() != current || receiptEvidence.accountAuthorityGeneration() != current + 1L || receiptEvidence.sourceVersion() != current + 1L - || receiptEvidence.issuanceFence() != current + 1L - || receiptEvidence.issuanceFenceSourceVersion() != current + 1L) { + || fence == null + || receiptEvidence.issuanceFence() <= 0L + || receiptEvidence.issuanceFenceSourceVersion() <= 0L + || receiptEvidence.issuanceFence() > fence.value() + || receiptEvidence.issuanceFenceSourceVersion() > fence.sourceVersion()) { throw new SourceEvidenceUnavailableException(); } var typedCutoff = receiptEvidence.accountSecurityCutoff(); @@ -813,8 +847,9 @@ private VerifiedSourceHistory verifyEventHistory( || authority.sourceVersion() != sequence + 1L || (scope.kind() == ScopeKind.ACCOUNT && (fence == null - || fence.value() != sequence + 1L - || fence.sourceVersion() != sequence + 1L))) { + || !scope.accountId().equals(fence.accountId()) + || fence.value() <= 0L + || fence.sourceVersion() <= 0L))) { throw new SourceEvidenceUnavailableException(); } return new VerifiedSourceHistory( @@ -1285,8 +1320,6 @@ public record CurrentSourceEvidence( || accountRepositoryInsertTransactionId == null || accountRepositoryInsertTransactionId <= 0L || initializationTransactionId != accountRepositoryInsertTransactionId - || issuanceFence.value() != generation - || issuanceFence.sourceVersion() != sourceVersion || (checkpoint.sequence() == 0L && accountSecurityCutoff.isPresent()) || (checkpoint.sequence() > 0L && (accountSecurityCutoff.isEmpty() 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 3282040440..4d9769a331 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 @@ -55,11 +55,12 @@ public Optional findById(Long id) { } /** Locks one exact persisted Account row before an owner-local authority mutation. */ - @Transactional + @Transactional(propagation = Propagation.MANDATORY) public Optional findByIdForUpdate(Long id) { if (id == null || id <= 0L) { throw new IllegalArgumentException("A positive persisted Account ID is required"); } + requireWritableOwnerTransaction(); return Optional.ofNullable( dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).forUpdate().fetchOne(this::toEntity)); } @@ -142,6 +143,10 @@ public Account save(Account entity) { Objects.requireNonNull(entity, "Account is required"); entity.setEmail(EmailCanonicalization.normalize(entity.getEmail())); if (entity.getId() == null) { + if (entity.getLifecycleState() != AccountLifecycleState.ACTIVE) { + throw new IllegalArgumentException( + "Fresh Accounts must be created in the ACTIVE lifecycle state"); + } UUID expectedUuid = UUID.randomUUID(); AccountsRecord inserted = dsl.insertInto(ACCOUNTS) 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 b7a5eb5025..aea81c91bd 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 @@ -84,6 +84,31 @@ public boolean consumeIfUnexpired(PasswordResetToken token, LocalDateTime captur == 1; } + /** + * Removes only the exact original token row after a terminal password-reset source abort. Unlike + * ordinary consumption, this also removes an expired token; mismatched or absent rows remain + * untouched for reconciliation. + */ + @Transactional(propagation = Propagation.MANDATORY) + public boolean deleteExactAfterSourceAbort( + long tokenId, long accountId, String rawTokenHash, LocalDateTime originalExpiresAt) { + if (tokenId <= 0L + || accountId <= 0L + || rawTokenHash == null + || !rawTokenHash.matches("[0-9a-f]{64}") + || originalExpiresAt == null) { + return false; + } + return dsl.execute( + "DELETE FROM password_reset_token WHERE id = ? AND account_id = ? " + + "AND expires_at = ? AND encode(sha256(convert_to(token, 'UTF8')), 'hex') = ?", + tokenId, + accountId, + originalExpiresAt, + rawTokenHash) + == 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 index 8413b44ed1..a6a6ea3958 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java @@ -18,6 +18,7 @@ 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.SourceEvidenceUnavailableException; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; @@ -464,7 +465,7 @@ private static VerifiedSourceEvent verifyEvent(Event event, UUID accountUuid) { security.canonicalJsonUtf8()); yield VerifiedSourceEvent.securityState(security); } - default -> throw new IllegalStateException("Account source event schema is unsupported"); + default -> throw new SourceEvidenceUnavailableException(); }; } catch (tools.jackson.core.JacksonException | IllegalArgumentException invalid) { throw new IllegalStateException("Account source event is invalid", invalid); @@ -651,8 +652,8 @@ public record RetainedEventEvidence( || outboxSequence <= 0L || accountAuthorityGeneration <= 0L || sourceVersion <= 0L - || issuanceFence != accountAuthorityGeneration - || issuanceFenceSourceVersion != sourceVersion + || issuanceFence <= 0L + || issuanceFenceSourceVersion <= 0L || accountSecurityCutoff == null || !outboxStreamKey.equals(accountSecurityCutoff.outboxStreamKey()) || outboxSequence != Long.parseLong(accountSecurityCutoff.outboxSequence()) 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 index 406af7927d..5cff40cfcb 100644 --- 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 @@ -18,6 +18,8 @@ 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.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; import net.firedevops.firemud.accountservice.repository.AccountRepository; @@ -46,6 +48,7 @@ public final class AccountLogoutAllAuthorityEventProducer { private final AccountRepository accountRepository; private final AccountAuthorityGenerationRepository generationRepository; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; private final AccountAuthorityOutboxRepository outboxRepository; private final AccountLogoutAllOperationRepository operationRepository; private final AccountAuthoritySourceEventReadback sourceReadback; @@ -55,6 +58,7 @@ public final class AccountLogoutAllAuthorityEventProducer { public AccountLogoutAllAuthorityEventProducer( AccountRepository accountRepository, AccountAuthorityGenerationRepository generationRepository, + AccountAuthoritySourceEvidenceRepository sourceEvidence, AccountAuthorityOutboxRepository outboxRepository, AccountLogoutAllOperationRepository operationRepository, AccountAuthoritySourceEventReadback sourceReadback, @@ -64,6 +68,8 @@ public AccountLogoutAllAuthorityEventProducer( Objects.requireNonNull(accountRepository, "Account repository is required"); this.generationRepository = Objects.requireNonNull(generationRepository, "authority-generation repository is required"); + this.sourceEvidence = + Objects.requireNonNull(sourceEvidence, "Account source-evidence repository is required"); this.outboxRepository = Objects.requireNonNull(outboxRepository, "authority outbox repository is required"); this.operationRepository = @@ -245,7 +251,10 @@ private CommitAttempt commitInOwnerTransaction( throw new IllegalStateException("Settled logout-all source change is not permitted"); } - ScopeState advanced = generationRepository.advance(current, current.issuanceFence()); + CurrentSourceEvidence currentSource = + sourceEvidence.readCurrentAccountSource(account.getAccountUuid(), current); + ScopeState advanced = + sourceEvidence.prepareClosedAccountAdvance(account.getAccountUuid(), currentSource); requireAdvancedState(current, advanced, nextGeneration, nextSourceVersion, nextIssuanceFence); Event appended = @@ -292,6 +301,7 @@ private CommitAttempt commitInOwnerTransaction( advanced, advanced.issuanceFence()); operationRepository.insert(receipt); + sourceEvidence.advanceClosedAccountHead(account.getAccountUuid(), current, advanced, appended); Event requestReadback = outboxRepository 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 index 3a52b65be1..dafdb1d7ec 100644 --- 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 @@ -31,7 +31,7 @@ @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "The transaction-aware DSLContext is an internal persistence collaborator.") -public final class AccountPasswordResetDraftSourceChangeRepository { +public 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"; @@ -43,6 +43,11 @@ public final class AccountPasswordResetDraftSourceChangeRepository { private final DSLContext dsl; private final DraftAuthorizationFenceRepository fences; + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Constructor validation guards only the injected persistence collaborator; the repository" + + " must remain non-final for Spring exception-translation proxies.") public AccountPasswordResetDraftSourceChangeRepository(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl); this.fences = new DraftAuthorizationFenceRepository(dsl); @@ -299,6 +304,14 @@ private Intent requireIntent(Record row) { Math.addExact(intent.checkpointSequence(), 1L), intent.requestId(), intent.eventId()); + boolean verifierRetentionMatches = + switch (intent.status()) { + case "WAITING" -> + intent.passwordVerifier() != null + && sha256Hex(intent.passwordVerifier()).equals(intent.passwordVerifierDigest()); + case "SOURCE_COMMITTED", "SOURCE_ABORTED" -> intent.passwordVerifier() == null; + default -> false; + }; if (intent.requestDigestVersion() != 1 || !MessageDigest.isEqual(expectedRequest, intent.requestPayload()) || !MessageDigest.isEqual(expectedMutation, intent.sourceChange().mutation()) @@ -311,7 +324,7 @@ private Intent requireIntent(Record row) { .getFirst() .key() .equals("ACCOUNT:" + intent.accountUuid()) - || !sha256Hex(intent.passwordVerifier()).equals(intent.passwordVerifierDigest()) + || !verifierRetentionMatches || !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"); 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 50b96c8b26..fd39024d97 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 @@ -150,6 +150,7 @@ public class AccountServiceImpl implements AccountService { private final AccountRepository accountRepository; private final AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; + private final AccountAuthoritySourceEvidenceRepository accountAuthoritySourceEvidenceRepository; private final AccountAuthorityOutboxRepository accountAuthorityOutboxRepository; private final AccountPasswordResetOperationRepository passwordResetOperationRepository; private final AccountAuthoritySourceEventReadback accountAuthoritySourceEventReadback; @@ -186,6 +187,7 @@ public class AccountServiceImpl implements AccountService { public AccountServiceImpl( AccountRepository accountRepository, AccountAuthorityGenerationRepository accountAuthorityGenerationRepository, + AccountAuthoritySourceEvidenceRepository accountAuthoritySourceEvidenceRepository, AccountAuthorityOutboxRepository accountAuthorityOutboxRepository, AccountPasswordResetOperationRepository passwordResetOperationRepository, AccountLogoutAllOperationRepository logoutAllOperationRepository, @@ -217,6 +219,7 @@ public AccountServiceImpl( PlatformTransactionManager transactionManager) { this.accountRepository = accountRepository; this.accountAuthorityGenerationRepository = accountAuthorityGenerationRepository; + this.accountAuthoritySourceEvidenceRepository = accountAuthoritySourceEvidenceRepository; this.accountAuthorityOutboxRepository = accountAuthorityOutboxRepository; this.passwordResetOperationRepository = passwordResetOperationRepository; this.accountAuthoritySourceEventReadback = @@ -2429,6 +2432,9 @@ private PasswordResetAttempt completePasswordResetInOwnerTransaction( || !originalIntent.accountUuid().equals(account.getAccountUuid()))) { throw new IllegalStateException("Password-reset Draft intent Account binding changed"); } + if (originalIntent != null && "SOURCE_ABORTED".equals(originalIntent.status())) { + return PasswordResetAttempt.aborted("Invalid token"); + } net.firedevops.firemud.accountservice.entity.PasswordResetToken token = passwordResetTokenRepository.findByToken(request.token()).orElse(null); @@ -2510,6 +2516,7 @@ private PasswordResetAttempt completePasswordResetInOwnerTransaction( intent, net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository .SourceChangeAbortReason.DEFINITIVE_ABORT); + deleteAbortedPasswordResetToken(intent); return PasswordResetAttempt.aborted("Invalid token"); } if (token == null @@ -2520,6 +2527,7 @@ private PasswordResetAttempt completePasswordResetInOwnerTransaction( intent, net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository .SourceChangeAbortReason.DEFINITIVE_ABORT); + deleteAbortedPasswordResetToken(intent); return PasswordResetAttempt.aborted("Invalid token"); } LocalDateTime claimTime = LocalDateTime.now(); @@ -2528,6 +2536,7 @@ private PasswordResetAttempt completePasswordResetInOwnerTransaction( intent, net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository .SourceChangeAbortReason.EXPIRED); + deleteAbortedPasswordResetToken(intent); return PasswordResetAttempt.aborted("Token expired"); } if (!passwordResetTokenRepository.consumeIfUnexpired(token, claimTime)) { @@ -2535,16 +2544,21 @@ private PasswordResetAttempt completePasswordResetInOwnerTransaction( intent, net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository .SourceChangeAbortReason.DEFINITIVE_ABORT); + deleteAbortedPasswordResetToken(intent); return PasswordResetAttempt.aborted("Invalid token"); } + AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence currentSource = + accountAuthoritySourceEvidenceRepository.readCurrentAccountSource( + account.getAccountUuid(), currentAuthority); + ScopeState advancedAuthority = + accountAuthoritySourceEvidenceRepository.prepareClosedAccountAdvance( + account.getAccountUuid(), currentSource); + requireAdvancedPasswordResetAuthority(accountScope, currentAuthority, advancedAuthority); + 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( @@ -2589,6 +2603,8 @@ private PasswordResetAttempt completePasswordResetInOwnerTransaction( advancedAuthority, advancedAuthority.issuanceFence()); passwordResetOperationRepository.insert(receipt); + accountAuthoritySourceEvidenceRepository.advanceClosedAccountHead( + account.getAccountUuid(), currentAuthority, advancedAuthority, appended); passwordResetDraftSourceChanges.markSourceCommitted(intent, appended); Account finalAccount = @@ -2911,6 +2927,11 @@ private String passwordResetRequestDigest( } } + private void deleteAbortedPasswordResetToken(Intent intent) { + passwordResetTokenRepository.deleteExactAfterSourceAbort( + intent.tokenId(), intent.accountId(), intent.tokenHash(), intent.tokenExpiresAt()); + } + private void updateLengthPrefixed(MessageDigest digest, String value) { if (value == null) { throw new IllegalArgumentException("Password-reset request field is required"); 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 index 33b0cb2992..718850abf2 100644 --- 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 @@ -88,4 +88,4 @@ $$; 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] +-- [jooq ignore stop] 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 index 09ae1789ae..00ab9cc390 100644 --- 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 @@ -87,4 +87,4 @@ $$; 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] +-- [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 index 59aadb67c7..1e0906da9a 100644 --- 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 @@ -1,5 +1,5 @@ --- 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. +-- Extend the V40 source-head and Account security guards for the immutable V77/V78 operation +-- receipts without changing historical migrations or treating scalar Account role as authority. -- [jooq ignore start] CREATE OR REPLACE FUNCTION account_authority_source_record_update_guard() RETURNS TRIGGER @@ -14,8 +14,11 @@ DECLARE fence_row RECORD; role_source_row RECORD; operation_row RECORD; + reset_row RECORD; + logout_row RECORD; account_state JSONB; security_request_id UUID; + logout_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 @@ -71,8 +74,8 @@ BEGIN 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 + SELECT id, account_uuid_provenance, account_uuid_source_numeric_id, email, + username, password_hash, 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 @@ -84,6 +87,14 @@ BEGIN RAISE EXCEPTION 'Account source event has no exact Account identity/provenance' USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_account_state'; END IF; + SELECT issuance_fence, source_version INTO fence_row + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid; + IF 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 THEN + RAISE EXCEPTION 'Account source event does not match the exact current shared issuance fence' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_fence_consistent'; + END IF; IF event_payload->>'eventType' = 'ACCOUNT_AUTHORITY_CHANGED' THEN -- Preserve the pre-V78 Account source event contract exactly. @@ -174,6 +185,75 @@ BEGIN RAISE EXCEPTION 'Security-state source event has no exact committed owner receipt' USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; END IF; + ELSIF event_payload->>'eventType' = 'PASSWORD_RESET_COMMITTED' THEN + SELECT * INTO reset_row FROM account_password_reset_operation_receipts + WHERE request_id = event_payload->>'requestId'; + IF event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-password-reset-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 reset_row.token_hash IS NULL + OR reset_row.account_id IS DISTINCT FROM account_row.id + OR reset_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR reset_row.operation_kind IS DISTINCT FROM 'PASSWORD_RESET' + OR reset_row.request_digest_version IS DISTINCT FROM 1 + OR reset_row.request_id IS DISTINCT FROM 'account-password-reset-request-v1:' || encode(reset_row.token_hash, 'hex') + OR reset_row.request_id IS DISTINCT FROM event_payload->>'requestId' + OR reset_row.outbox_stream_key IS DISTINCT FROM NEW.outbox_stream_key + OR reset_row.outbox_sequence IS DISTINCT FROM NEW.last_outbox_sequence + OR reset_row.event_id IS DISTINCT FROM NEW.last_event_id + OR reset_row.event_id IS DISTINCT FROM 'account-password-reset-event-v1:' || encode(reset_row.token_hash, 'hex') + OR reset_row.event_digest IS DISTINCT FROM NEW.last_event_digest + OR reset_row.event_digest IS DISTINCT FROM event_row.event_digest + OR reset_row.account_authority_generation IS DISTINCT FROM NEW.current_generation + OR reset_row.account_source_version IS DISTINCT FROM NEW.current_source_version + OR reset_row.issuance_fence IS DISTINCT FROM NEW.current_issuance_fence + OR reset_row.issuance_fence_source_version IS DISTINCT FROM NEW.current_issuance_fence_source_version + OR reset_row.password_verifier_digest + IS DISTINCT FROM sha256(convert_to(account_row.password_hash, 'UTF8')) THEN + RAISE EXCEPTION 'Password-reset source event has no exact immutable Account operation receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF; + ELSIF event_payload->>'eventType' = 'LOGOUT_ALL_COMMITTED' THEN + 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 'Logout-all source event request identity is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF; + logout_request_id := (event_payload->>'requestId')::UUID; + SELECT * INTO logout_row FROM account_logout_all_operation_receipts + WHERE request_id = logout_request_id; + IF event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-logout-all-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 logout_row.request_id IS DISTINCT FROM logout_request_id + OR logout_row.account_id IS DISTINCT FROM account_row.id + OR logout_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR logout_row.operation_kind IS DISTINCT FROM 'ACCOUNT_LOGOUT_ALL' + OR logout_row.request_digest_version IS DISTINCT FROM 1 + OR logout_row.lifecycle_result IS DISTINCT FROM 'LOGOUT_ALL_COMMITTED' + OR event_payload->>'eventId' IS DISTINCT FROM 'account-logout-all-event-v1:' || logout_request_id::TEXT + OR logout_row.event_id IS DISTINCT FROM event_payload->>'eventId' + OR logout_row.outbox_stream_key IS DISTINCT FROM NEW.outbox_stream_key + OR logout_row.outbox_sequence IS DISTINCT FROM NEW.last_outbox_sequence + OR logout_row.event_digest IS DISTINCT FROM NEW.last_event_digest + OR logout_row.event_digest IS DISTINCT FROM event_row.event_digest + OR logout_row.account_authority_generation IS DISTINCT FROM NEW.current_generation + OR logout_row.account_source_version IS DISTINCT FROM NEW.current_source_version + OR logout_row.issuance_fence IS DISTINCT FROM NEW.current_issuance_fence + OR logout_row.issuance_fence_source_version IS DISTINCT FROM NEW.current_issuance_fence_source_version THEN + RAISE EXCEPTION 'Logout-all source event has no exact immutable Account operation 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'; @@ -198,12 +278,15 @@ DECLARE fence_row RECORD; role_source_row RECORD; operation_row RECORD; + reset_row RECORD; + logout_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; + logout_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 @@ -223,7 +306,7 @@ BEGIN USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_required'; END IF; - SELECT payload INTO event_row + SELECT event_id, event_digest, 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 @@ -232,7 +315,93 @@ BEGIN 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); + FROM unnest(string_to_array(NEW.login_auth_modes, ',')) AS modes(login_mode); + + IF event_payload->>'eventType' = 'PASSWORD_RESET_COMMITTED' THEN + SELECT * INTO reset_row FROM account_password_reset_operation_receipts + WHERE request_id = event_payload->>'requestId'; + IF OLD.password_hash IS NOT DISTINCT FROM NEW.password_hash + OR (to_jsonb(OLD) - 'password_hash') IS DISTINCT FROM + (to_jsonb(NEW) - 'password_hash') + OR event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-password-reset-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 reset_row.token_hash IS NULL + OR reset_row.account_id IS DISTINCT FROM NEW.id + OR reset_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR reset_row.operation_kind IS DISTINCT FROM 'PASSWORD_RESET' + OR reset_row.request_digest_version IS DISTINCT FROM 1 + OR reset_row.request_id IS DISTINCT FROM 'account-password-reset-request-v1:' || encode(reset_row.token_hash, 'hex') + OR reset_row.request_id IS DISTINCT FROM event_payload->>'requestId' + OR reset_row.outbox_stream_key IS DISTINCT FROM source_row.outbox_stream_key + OR reset_row.outbox_sequence IS DISTINCT FROM source_row.last_outbox_sequence + OR reset_row.event_id IS DISTINCT FROM source_row.last_event_id + OR reset_row.event_id IS DISTINCT FROM 'account-password-reset-event-v1:' || encode(reset_row.token_hash, 'hex') + OR reset_row.event_digest IS DISTINCT FROM source_row.last_event_digest + OR reset_row.event_digest IS DISTINCT FROM event_row.event_digest + OR reset_row.account_authority_generation IS DISTINCT FROM source_row.current_generation + OR reset_row.account_source_version IS DISTINCT FROM source_row.current_source_version + OR reset_row.issuance_fence IS DISTINCT FROM source_row.current_issuance_fence + OR reset_row.issuance_fence_source_version IS DISTINCT FROM source_row.current_issuance_fence_source_version + OR reset_row.password_verifier_digest IS DISTINCT FROM sha256(convert_to(NEW.password_hash, 'UTF8')) THEN + RAISE EXCEPTION 'Password-reset source event does not authorize the exact Account password update' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + RETURN NULL; + END IF; + + IF event_payload->>'eventType' = 'LOGOUT_ALL_COMMITTED' THEN + 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 'Logout-all source event request identity is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + logout_request_id := (event_payload->>'requestId')::UUID; + SELECT * INTO logout_row FROM account_logout_all_operation_receipts + WHERE request_id = logout_request_id; + IF event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-logout-all-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 logout_row.request_id IS DISTINCT FROM logout_request_id + OR logout_row.account_id IS DISTINCT FROM NEW.id + OR logout_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR logout_row.operation_kind IS DISTINCT FROM 'ACCOUNT_LOGOUT_ALL' + OR logout_row.request_digest_version IS DISTINCT FROM 1 + OR logout_row.lifecycle_result IS DISTINCT FROM 'LOGOUT_ALL_COMMITTED' + OR event_payload->>'eventId' IS DISTINCT FROM 'account-logout-all-event-v1:' || logout_request_id::TEXT + OR logout_row.event_id IS DISTINCT FROM source_row.last_event_id + OR logout_row.outbox_stream_key IS DISTINCT FROM source_row.outbox_stream_key + OR logout_row.outbox_sequence IS DISTINCT FROM source_row.last_outbox_sequence + OR logout_row.event_digest IS DISTINCT FROM source_row.last_event_digest + OR logout_row.event_digest IS DISTINCT FROM event_row.event_digest + OR logout_row.account_authority_generation IS DISTINCT FROM source_row.current_generation + OR logout_row.account_source_version IS DISTINCT FROM source_row.current_source_version + OR logout_row.issuance_fence IS DISTINCT FROM source_row.current_issuance_fence + OR logout_row.issuance_fence_source_version IS DISTINCT FROM source_row.current_issuance_fence_source_version THEN + RAISE EXCEPTION 'Logout-all source event has no exact immutable Account operation receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + RAISE EXCEPTION 'Logout-all source events cannot authorize Account security state changes' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; IF event_payload->>'eventType' = 'ACCOUNT_SECURITY_STATE_CHANGED' THEN SELECT generation, source_version INTO authority_row 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 index 35c21bb8a9..7b2862e2b7 100644 --- 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 @@ -285,4 +285,65 @@ 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(); + +CREATE FUNCTION account_hosted_terms_environment_binding_fence_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE predecessor UUID; +DECLARE predecessor_scope UUID; +DECLARE candidate_scope UUID; +BEGIN + IF NEW.status = 'COMMITTED' THEN + SELECT candidate.predecessor_binding_id, prior.hosted_scope_id, candidate.hosted_scope_id + INTO predecessor, predecessor_scope, candidate_scope + FROM account_hosted_terms_environment_bindings candidate + LEFT JOIN account_hosted_terms_environment_bindings prior + ON prior.environment_boundary = candidate.environment_boundary + AND prior.binding_id = candidate.predecessor_binding_id + WHERE candidate.environment_boundary = NEW.environment_boundary + AND candidate.binding_id = NEW.candidate_binding_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:environment-boundary/' || NEW.environment_boundary) + OR predecessor_scope IS NULL OR candidate_scope IS NULL + OR EXISTS ( + SELECT 1 FROM account_hosted_terms_scopes scope + WHERE scope.hosted_scope_id IN (predecessor_scope, candidate_scope) + AND scope.current_version_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + WHERE changed.change_id = NEW.request_id + AND changed.source_key = 'HOSTED_TERMS:' || scope.hosted_scope_id::TEXT)) + OR (SELECT count(*) FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.request_id) <> 1 + ( + SELECT count(DISTINCT scope.hosted_scope_id) + FROM account_hosted_terms_scopes scope + WHERE scope.hosted_scope_id IN (predecessor_scope, candidate_scope) + AND scope.current_version_id IS NOT NULL) + OR EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + WHERE changed.change_id = NEW.request_id + AND changed.source_key <> + 'HOSTED_TERMS:environment-boundary/' || NEW.environment_boundary + AND changed.source_key NOT IN ( + SELECT 'HOSTED_TERMS:' || scope.hosted_scope_id::TEXT + FROM account_hosted_terms_scopes scope + WHERE scope.hosted_scope_id IN (predecessor_scope, candidate_scope) + AND scope.current_version_id IS NOT NULL))) THEN + RAISE EXCEPTION 'Updated environment binding requires fully settled exact Draft source change'; + END IF; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_hosted_terms_environment_binding_fence_complete + AFTER INSERT OR UPDATE ON account_hosted_terms_environment_binding_publications + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_fence_complete_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 index fa5e2218c3..3ea00737b6 100644 --- 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 @@ -10,7 +10,7 @@ CREATE TABLE account_password_reset_draft_source_changes ( 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 VARCHAR(255) CHECK (password_verifier IS NULL OR 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), @@ -48,14 +48,15 @@ CREATE TABLE account_password_reset_draft_source_changes ( 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) + AND event_digest IS NULL AND event_payload IS NULL AND password_verifier IS NOT 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) + AND event_payload IS NOT NULL AND octet_length(event_payload) > 0 + AND password_verifier IS NULL) 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)) + AND event_digest IS NULL AND event_payload IS NULL AND password_verifier IS NULL)) ); -- [jooq ignore start] @@ -138,6 +139,7 @@ BEGIN END IF; NEW.aborted_at = CURRENT_TIMESTAMP; END IF; + NEW.password_verifier = NULL; RETURN NEW; END IF; @@ -336,7 +338,8 @@ BEGIN 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 + AND account_uuid = journal.account_uuid + AND sha256(convert_to(password_hash, 'UTF8')) = journal.password_verifier_digest)) THEN RAISE EXCEPTION 'Committed password-reset intent lacks exact receipt, event, token, or Account readback' USING ERRCODE = '23514'; END IF; diff --git a/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql b/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql new file mode 100644 index 0000000000..3371d9d86a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql @@ -0,0 +1,119 @@ +CREATE SEQUENCE account_control_ui_source_fence START WITH 1; + +CREATE TABLE account_control_ui_issuance_operations ( + request_id UUID PRIMARY KEY, + operation_id UUID NOT NULL UNIQUE, + token_jti UUID NOT NULL UNIQUE, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + caller_workload VARCHAR(256) NOT NULL, + caller_context_id UUID NOT NULL, + request_mac_key_id VARCHAR(32) NOT NULL, + request_digest VARCHAR(64) NOT NULL CHECK (request_digest ~ '^[0-9a-f]{64}$'), + claims_payload BYTEA NOT NULL CHECK (octet_length(claims_payload) BETWEEN 1 AND 16384), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + bundle_payload BYTEA NOT NULL CHECK (octet_length(bundle_payload) BETWEEN 1 AND 131072), + signer_receipt BYTEA NOT NULL CHECK (octet_length(signer_receipt) BETWEEN 1 AND 65536), + issued_at_epoch_second BIGINT NOT NULL CHECK (issued_at_epoch_second > 0), + expires_at_epoch_second BIGINT NOT NULL, + recovery_expires_at TIMESTAMPTZ NOT NULL, + status VARCHAR(16) NOT NULL CHECK (status IN ('PREPARED', 'CANDIDATE', 'COMMITTED', 'FAILED', 'REVOKING', 'REVOKED')), + token_hash VARCHAR(64) UNIQUE CHECK (token_hash ~ '^[0-9a-f]{64}$'), + pending_registry BYTEA, + active_registry BYTEA, + pending_receipt BYTEA, + committed_at TIMESTAMPTZ, + recovery_failed_at TIMESTAMPTZ, + revocation_receipt BYTEA, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (expires_at_epoch_second > issued_at_epoch_second + AND expires_at_epoch_second <= issued_at_epoch_second + 300), + CHECK ((status IN ('PREPARED','FAILED') AND token_hash IS NULL AND pending_registry IS NULL + AND active_registry IS NULL AND pending_receipt IS NULL AND committed_at IS NULL) + OR (status = 'CANDIDATE' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL AND pending_receipt IS NULL AND committed_at IS NULL) + OR (status = 'COMMITTED' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL AND pending_receipt IS NOT NULL AND committed_at IS NOT NULL) + OR (status IN ('REVOKING','REVOKED') AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL + AND ((pending_receipt IS NULL AND committed_at IS NULL) + OR (pending_receipt IS NOT NULL AND committed_at IS NOT NULL)))), + CHECK ((status IN ('FAILED','REVOKING','REVOKED')) = (recovery_failed_at IS NOT NULL)), + CHECK ((status = 'REVOKED') = (revocation_receipt IS NOT NULL)) +); + +CREATE TABLE account_control_ui_response_envelopes ( + operation_id UUID PRIMARY KEY REFERENCES account_control_ui_issuance_operations(operation_id), + encrypted_response BYTEA NOT NULL CHECK (octet_length(encrypted_response) BETWEEN 1 AND 65536), + owner_binding BYTEA NOT NULL CHECK (octet_length(owner_binding) BETWEEN 1 AND 8192), + recovery_expires_at TIMESTAMPTZ NOT NULL +); + +-- [jooq ignore start] +ALTER TABLE account_control_ui_issuance_operations + ADD CONSTRAINT account_control_ui_recovery_expiry_bound CHECK ( + recovery_expires_at > to_timestamp(issued_at_epoch_second) + AND recovery_expires_at <= to_timestamp(issued_at_epoch_second + 60) + AND recovery_expires_at <= to_timestamp(expires_at_epoch_second)); + +CREATE FUNCTION account_control_ui_issuance_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Control-ui issuance evidence cannot be deleted' USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['status','token_hash','pending_registry','active_registry', + 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['status','token_hash','pending_registry','active_registry', + 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) + OR NOT ((OLD.status = 'PREPARED' AND NEW.status = 'CANDIDATE') + OR (OLD.status = 'CANDIDATE' AND NEW.status = 'COMMITTED') + OR (OLD.status = 'PREPARED' AND NEW.status = 'FAILED') + OR (OLD.status IN ('CANDIDATE','COMMITTED') AND NEW.status = 'REVOKING') + OR (OLD.status = 'REVOKING' AND NEW.status = 'REVOKED')) + OR (OLD.status <> 'PREPARED' AND + (NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.pending_registry IS DISTINCT FROM OLD.pending_registry + OR NEW.active_registry IS DISTINCT FROM OLD.active_registry)) + OR (NEW.status IN ('REVOKING','REVOKED') AND + (NEW.pending_receipt IS DISTINCT FROM OLD.pending_receipt + OR NEW.committed_at IS DISTINCT FROM OLD.committed_at)) + OR (OLD.status = 'REVOKING' AND NEW.recovery_failed_at IS DISTINCT FROM OLD.recovery_failed_at) THEN + RAISE EXCEPTION 'Control-ui original operation or candidate cannot change' USING ERRCODE = '23514'; + END IF; + IF NEW.status = 'COMMITTED' AND NOT EXISTS ( + SELECT 1 FROM account_control_ui_response_envelopes e + WHERE e.operation_id = NEW.operation_id AND e.recovery_expires_at = NEW.recovery_expires_at) THEN + RAISE EXCEPTION 'Protected original control-ui response is absent' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_control_ui_issuance_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-ui issuance evidence cannot be truncated' USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_control_ui_response_immutable_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-ui response evidence is immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_control_ui_issuance_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_guard(); +CREATE TRIGGER account_control_ui_issuance_no_truncate + BEFORE TRUNCATE ON account_control_ui_issuance_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_issuance_no_truncate(); +CREATE TRIGGER account_control_ui_response_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_response_envelopes + FOR EACH ROW EXECUTE FUNCTION account_control_ui_response_immutable_guard(); +CREATE TRIGGER account_control_ui_response_no_truncate + BEFORE TRUNCATE ON account_control_ui_response_envelopes + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_response_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql b/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql new file mode 100644 index 0000000000..30afe17861 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql @@ -0,0 +1,182 @@ +-- Distinct non-activating publication order. There is deliberately no terminal-write surface: +-- authenticated publication-owner readback is a subsequent integration boundary. +CREATE TABLE account_selected_publication_authorizations ( + operation_id UUID PRIMARY KEY, + fence_id UUID NOT NULL UNIQUE, + actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + publish_request_id VARCHAR(256) NOT NULL CHECK (length(publish_request_id) > 0 AND octet_length(publish_request_id) <= 256), + input_digest VARCHAR(71) NOT NULL CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + binding BYTEA NOT NULL CHECK (octet_length(binding) BETWEEN 1 AND 1048576), + world_evidence BYTEA NOT NULL CHECK (octet_length(world_evidence) BETWEEN 1 AND 4194304), + issuance_operation_id UUID NOT NULL REFERENCES account_control_ui_issuance_operations(operation_id), + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + issuance_bundle BYTEA NOT NULL CHECK (octet_length(issuance_bundle) BETWEEN 1 AND 131072), + outbox_checkpoints BYTEA NOT NULL CHECK (octet_length(outbox_checkpoints) BETWEEN 1 AND 131072), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + ordered_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (tenant_uuid, publish_request_id) +); + +CREATE TABLE account_selected_publication_sources ( + operation_id UUID NOT NULL REFERENCES account_selected_publication_authorizations(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) BETWEEN 1 AND 131072), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_selected_publication_source_lookup ON account_selected_publication_sources(source_key, operation_id); + +-- [jooq ignore start] +CREATE FUNCTION account_selected_publication_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_selected_publication_authorizations + WHERE operation_id = NEW.operation_id AND producer_xid = txid_current()) THEN + RAISE EXCEPTION 'Publication sources must accompany the original owner transaction' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_selected_publication_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + p INTEGER := 1; + parsed BYTEA; + input_bytes BYTEA; + source_bytes BYTEA; + source_position INTEGER; + kind TEXT; + scope TEXT; + source_key_value TEXT; + seen TEXT[] := ARRAY[]::TEXT[]; + source_count INTEGER; + issuer account_control_ui_issuance_operations%ROWTYPE; +BEGIN + SELECT * INTO issuer FROM account_control_ui_issuance_operations WHERE operation_id = NEW.issuance_operation_id; + IF issuer.status IS DISTINCT FROM 'COMMITTED' OR issuer.account_uuid <> NEW.actor_account_uuid + OR issuer.tenant_uuid <> NEW.tenant_uuid OR issuer.source_payload <> NEW.source_payload + OR issuer.bundle_payload <> NEW.issuance_bundle + OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT <> NEW.issuance_fence + OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' + IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB + OR NEW.producer_xid <> txid_current() + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'accountId' <> NEW.actor_account_uuid::TEXT + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'tenantId' <> NEW.tenant_uuid::TEXT THEN + RAISE EXCEPTION 'Publication requires exact original committed issuance evidence' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> 'account-publication-authorization/v1' THEN + RAISE EXCEPTION 'Invalid publication schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.operation_id::TEXT THEN + RAISE EXCEPTION 'Changed publication operation' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.fence_id::TEXT THEN + RAISE EXCEPTION 'Changed publication fence' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO input_bytes, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF 'sha256:' || encode(sha256(input_bytes), 'hex') <> NEW.input_digest THEN + RAISE EXCEPTION 'Changed publication input digest' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(input_bytes, 1); + IF convert_from(parsed, 'UTF8') <> 'account-publication-input/v1' THEN + RAISE EXCEPTION 'Invalid publication input schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(input_bytes, source_position); + IF convert_from(parsed, 'UTF8') <> NEW.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Changed publication actor' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(input_bytes, source_position); + IF convert_from(parsed, 'UTF8')::JSONB->'intent'->>'canonicalTenantId' <> NEW.tenant_uuid::TEXT + OR convert_from(parsed, 'UTF8')::JSONB->'intent'->>'publishRequestId' <> NEW.publish_request_id THEN + RAISE EXCEPTION 'Changed publication selection identity' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + source_count := convert_from(parsed, 'UTF8')::INTEGER; + IF source_count < 1 OR source_count <> (SELECT count(*) FROM account_selected_publication_sources WHERE operation_id = NEW.operation_id) + OR source_count <> jsonb_array_length(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources') THEN + RAISE EXCEPTION 'Incomplete publication sources' USING ERRCODE = '23514'; + END IF; + FOR i IN 1..source_count LOOP + SELECT frame_value, next_position INTO source_bytes, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF source_bytes <> decode(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'->>(i - 1), 'base64') THEN + RAISE EXCEPTION 'Publication source differs from original complete issuance vector' USING ERRCODE = '23514'; + END IF; + 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 + RAISE EXCEPTION 'Invalid publication source schema' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO kind, source_position FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO scope, source_position FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := kind || ':' || scope; + IF source_key_value = ANY(seen) OR NOT EXISTS (SELECT 1 FROM account_selected_publication_sources + WHERE operation_id = NEW.operation_id AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Changed publication source participation' USING ERRCODE = '23514'; + END IF; + seen := array_append(seen, source_key_value); + END LOOP; + IF p <> octet_length(NEW.binding) + 1 THEN + RAISE EXCEPTION 'Trailing publication evidence' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_selected_publication_complete + AFTER INSERT ON account_selected_publication_authorizations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_selected_publication_complete_guard(); +CREATE TRIGGER account_selected_publication_source_insert + BEFORE INSERT ON account_selected_publication_sources FOR EACH ROW + EXECUTE FUNCTION account_selected_publication_source_insert_guard(); +CREATE TRIGGER account_selected_publication_immutable + BEFORE UPDATE OR DELETE ON account_selected_publication_authorizations + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_publication_sources_immutable + BEFORE UPDATE OR DELETE ON account_selected_publication_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_publication_no_truncate + BEFORE TRUNCATE ON account_selected_publication_authorizations + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_publication_sources_no_truncate + BEFORE TRUNCATE ON account_selected_publication_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +-- Preserve original Draft ordering and add the separate publication participants. A Draft +-- terminal readback can never clear this publication hold. +CREATE OR REPLACE 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; + FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_selected_publication_sources s WHERE s.source_key = ANY(source_keys) + ORDER BY s.operation_id LOOP + PERFORM operation_id FROM account_selected_publication_authorizations + WHERE operation_id = operation_value FOR UPDATE NOWAIT; + RAISE EXCEPTION 'Distinct selected-publication operation remains pending' USING ERRCODE = '55P03'; + END LOOP; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V92__account_publication_pre_freeze_order.sql b/services/account-service/src/main/resources/db/migration/V92__account_publication_pre_freeze_order.sql new file mode 100644 index 0000000000..dd79acb039 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V92__account_publication_pre_freeze_order.sql @@ -0,0 +1,5 @@ +-- The Account publication order is acquired from the authenticated immutable Draft selection +-- before World capture. Existing World evidence remains retained and immutable; new orders +-- leave the optional later-correlation evidence absent. +ALTER TABLE account_selected_publication_authorizations + ALTER COLUMN world_evidence DROP NOT NULL; diff --git a/services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql b/services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql new file mode 100644 index 0000000000..d324037ee3 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql @@ -0,0 +1,167 @@ +-- Internal persistence after authenticated exact reads from BOTH publication owners. Decoding +-- these bytes does not authenticate either remote owner and is not an external write surface. +CREATE TABLE account_selected_publication_settlements ( + operation_id UUID PRIMARY KEY REFERENCES account_selected_publication_authorizations(operation_id), + fence_id UUID NOT NULL, + account_binding BYTEA NOT NULL CHECK (octet_length(account_binding) BETWEEN 1 AND 1048576), + publication_operation BYTEA NOT NULL CHECK (octet_length(publication_operation) BETWEEN 1 AND 8388608), + game_design_outcome VARCHAR(32) NOT NULL CHECK (game_design_outcome IN ('PUBLISHED', 'NO_PUBLICATION')), + game_design_terminal BYTEA NOT NULL CHECK (octet_length(game_design_terminal) BETWEEN 1 AND 16777216), + world_outcome VARCHAR(16) NOT NULL CHECK (world_outcome IN ('PUBLISHED', 'ABORTED')), + world_terminal BYTEA NOT NULL CHECK (world_terminal = game_design_terminal), + receipt BYTEA NOT NULL CHECK (octet_length(receipt) BETWEEN 1 AND 50331648), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + settled_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK ((game_design_outcome = 'PUBLISHED' AND world_outcome = 'PUBLISHED') + OR (game_design_outcome = 'NO_PUBLICATION' AND world_outcome = 'ABORTED')) +); + +-- [jooq ignore start] +CREATE FUNCTION account_selected_publication_settlement_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_selected_publication_authorizations%ROWTYPE; + issuer account_control_ui_issuance_operations%ROWTYPE; + source_key_value TEXT; + p INTEGER; + parsed BYTEA; + world_bytes BYTEA; + world JSONB; + selection JSONB; + input_bytes BYTEA; + terminal_frames BYTEA[] := ARRAY[]::BYTEA[]; + receipt_frames BYTEA[] := ARRAY[]::BYTEA[]; + i INTEGER; +BEGIN + -- Same canonical source-before-operation order as source writers. Never wait backwards on + -- issuance, whose producers take it before sources. Nothing here performs a remote read. + FOR source_key_value IN SELECT source_key FROM account_selected_publication_sources + WHERE operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(source_key) LOOP + PERFORM source_key FROM account_draft_authorization_source_locks + WHERE source_key = source_key_value FOR UPDATE; + END LOOP; + SELECT * INTO STRICT original FROM account_selected_publication_authorizations + WHERE operation_id = NEW.operation_id FOR UPDATE; + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations + WHERE operation_id = original.issuance_operation_id FOR UPDATE NOWAIT; + IF NEW.producer_xid <> txid_current() OR NEW.fence_id <> original.fence_id + OR NEW.account_binding <> original.binding OR issuer.status <> 'COMMITTED' + OR issuer.source_payload <> original.source_payload + OR issuer.bundle_payload <> original.issuance_bundle THEN + RAISE EXCEPTION 'Settlement differs from exact original committed Account order' USING ERRCODE = '23514'; + END IF; + p := 1; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF parsed <> convert_to('game-design-publication-operation/v1', 'UTF8') THEN + RAISE EXCEPTION 'Invalid publication operation schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF parsed <> original.binding THEN + RAISE EXCEPTION 'Substituted original Account order' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_bytes, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF p <> octet_length(NEW.publication_operation) + 1 OR octet_length(world_bytes) = 0 THEN + RAISE EXCEPTION 'Incomplete publication operation' USING ERRCODE = '23514'; + END IF; + world := convert_from(world_bytes, 'UTF8')::JSONB; + -- Retrieve the original immutable selection, without recapturing current authority. + p := 1; + FOR i IN 1..4 LOOP + SELECT frame_value, next_position INTO input_bytes, p FROM account_publication_authorization_read_frame(original.binding, p); + END LOOP; + p := 1; + FOR i IN 1..3 LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(input_bytes, p); + END LOOP; + selection := convert_from(parsed, 'UTF8')::JSONB; + IF world->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR world->'request'->>'canonicalTenantId' IS DISTINCT FROM original.tenant_uuid::TEXT + OR world->'request'->>'canonicalVersionId' IS DISTINCT FROM selection->'intent'->>'canonicalVersionId' + OR world->'request'->>'publicationRequestId' IS DISTINCT FROM original.publish_request_id + OR world->'request'->>'versionStateEpoch' IS DISTINCT FROM selection->'intent'->>'expectedVersionStateEpoch' + OR world->'request'->>'appliedCommitId' IS DISTINCT FROM selection->'intent'->>'selectedCommitId' + OR 'sha256:' || (world->'request'->>'requestDigest') IS DISTINCT FROM + 'sha256:' || encode(sha256(parsed), 'hex') + OR (original.world_evidence IS NOT NULL AND original.world_evidence <> world_bytes) THEN + RAISE EXCEPTION 'Publication World evidence differs from original selected order' USING ERRCODE = '23514'; + END IF; + p := 1; + WHILE p <= octet_length(NEW.game_design_terminal) LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.game_design_terminal, p); + terminal_frames := array_append(terminal_frames, parsed); + IF cardinality(terminal_frames) > 5 THEN + RAISE EXCEPTION 'Trailing publication terminal fields' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF terminal_frames[1] IS DISTINCT FROM convert_to('game-design-publication-terminal/v1', 'UTF8') + OR terminal_frames[2] IS DISTINCT FROM NEW.publication_operation + OR terminal_frames[3] IS DISTINCT FROM convert_to(NEW.game_design_outcome, 'UTF8') + OR cardinality(terminal_frames) <> (CASE WHEN NEW.game_design_outcome = 'PUBLISHED' THEN 5 ELSE 3 END) THEN + RAISE EXCEPTION 'Changed complete publication terminal relationship' USING ERRCODE = '23514'; + END IF; + IF NEW.game_design_outcome = 'PUBLISHED' THEN + IF convert_from(terminal_frames[5], 'UTF8') !~ '^[1-9][0-9]*$' + OR convert_from(terminal_frames[5], 'UTF8')::BIGINT <> + (world->'request'->>'versionStateEpoch')::BIGINT + 1 THEN + RAISE EXCEPTION 'Changed committed publication epoch' USING ERRCODE = '23514'; + END IF; + -- Game Design owns release semantics. Its canonical codec and the authenticated owner + -- read validate the opaque complete content; Account binds all its exact bytes here. + IF octet_length(terminal_frames[4]) = 0 THEN + RAISE EXCEPTION 'Missing complete published release content' USING ERRCODE = '23514'; + END IF; + END IF; + p := 1; + WHILE p <= octet_length(NEW.receipt) LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.receipt, p); + receipt_frames := array_append(receipt_frames, parsed); + IF cardinality(receipt_frames) > 6 THEN + RAISE EXCEPTION 'Trailing settlement receipt' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF receipt_frames IS DISTINCT FROM ARRAY[convert_to('account-selected-publication-settlement/v1', 'UTF8'), + NEW.account_binding, NEW.publication_operation, NEW.game_design_terminal, + convert_to(NEW.world_outcome, 'UTF8'), NEW.world_terminal] THEN + RAISE EXCEPTION 'Changed exact settlement receipt' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_selected_publication_settlement_insert BEFORE INSERT + ON account_selected_publication_settlements FOR EACH ROW + EXECUTE FUNCTION account_selected_publication_settlement_guard(); +CREATE TRIGGER account_selected_publication_settlement_immutable BEFORE UPDATE OR DELETE + ON account_selected_publication_settlements FOR EACH ROW + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_publication_settlement_no_truncate BEFORE TRUNCATE + ON account_selected_publication_settlements FOR EACH STATEMENT + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +-- No old authorization/source row is rewritten or qualified. Only receipts committed through +-- the insert guard settle their exact original order; every other order remains pending. +CREATE FUNCTION account_selected_publication_is_settled(operation_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT EXISTS (SELECT 1 FROM account_selected_publication_settlements s + JOIN account_selected_publication_authorizations a ON a.operation_id = s.operation_id + WHERE s.operation_id = operation_value AND s.account_binding = a.binding AND s.fence_id = a.fence_id); +$$; + +-- Keep every V107 Draft/order/source/terms guard and change only publication pending detection. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ RAISE EXCEPTION 'Distinct selected-publication operation remains pending' USING ERRCODE = '55P03';$anchor$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V107 pending publication guard'; + END IF; + EXECUTE replace(original, anchor, + ' IF NOT account_selected_publication_is_settled(operation_value) THEN' || chr(10) + || anchor || chr(10) || ' END IF;'); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql b/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql new file mode 100644 index 0000000000..3a61bd3ef4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql @@ -0,0 +1,465 @@ +-- Mandatory v2 inventory applies to new settlements only; immutable retained rows are not upgraded. +-- [jooq ignore start] +CREATE FUNCTION selected_inventory_operation_frame(operation_bytes BYTEA, frame_offset INTEGER) RETURNS BYTEA AS $$ +DECLARE length_bytes BIGINT; +BEGIN + IF frame_offset < 0 OR frame_offset > octet_length(operation_bytes) - 4 THEN + RAISE EXCEPTION 'Truncated publication inventory frame' USING ERRCODE = '23514'; END IF; + length_bytes := get_byte(operation_bytes, frame_offset)::BIGINT * 16777216 + + get_byte(operation_bytes, frame_offset + 1)::BIGINT * 65536 + + get_byte(operation_bytes, frame_offset + 2)::BIGINT * 256 + + get_byte(operation_bytes, frame_offset + 3)::BIGINT; + IF length_bytes > 4194304 OR length_bytes > octet_length(operation_bytes) - frame_offset - 4 THEN + RAISE EXCEPTION 'Oversized publication inventory frame' USING ERRCODE = '23514'; END IF; + RETURN substring(operation_bytes FROM frame_offset + 5 FOR length_bytes::INTEGER); +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION selected_inventory_operation_nth(operation_bytes BYTEA, frame_index INTEGER) RETURNS BYTEA AS $$ +DECLARE offset_bytes INTEGER := 0; value BYTEA; i INTEGER; +BEGIN + IF frame_index < 0 THEN RAISE EXCEPTION 'Negative frame index' USING ERRCODE = '23514'; END IF; + FOR i IN 0..frame_index LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + END LOOP; + RETURN value; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION require_selected_inventory_operation_v2(operation_bytes BYTEA) RETURNS VOID AS $$ +DECLARE frames BYTEA[] := ARRAY[]::BYTEA[]; value BYTEA; offset_bytes INTEGER := 0; + account_bytes BYTEA; input_bytes BYTEA; selection_bytes BYTEA; + selector JSONB; inventory JSONB; selected JSONB; selected_binding JSONB; + applied JSONB; applied_bytes BYTEA; applied_operation BYTEA; original_account BYTEA; + owner JSONB; application JSONB; account_order JSONB; frozen JSONB; checkpoint JSONB; + model JSONB; expected_epochs JSONB; expected_tuples JSONB; i INTEGER; + shape RECORD; member RECORD; item JSONB; previous_key TEXT; + counts INTEGER[] := ARRAY[]::INTEGER[]; +BEGIN + IF operation_bytes IS NULL OR octet_length(operation_bytes) NOT BETWEEN 1 AND 4194304 THEN + RAISE EXCEPTION 'Complete bounded v2 publication operation required' USING ERRCODE = '23514'; END IF; + FOR i IN 0..4 LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + frames := array_append(frames, value); + END LOOP; + IF offset_bytes <> octet_length(operation_bytes) OR frames[1] <> convert_to('game-design-publication-operation/v2', 'UTF8') + OR frames[5] IS DISTINCT FROM convert_to('sha256:' || encode(sha256(frames[4]), 'hex'), 'UTF8') THEN + RAISE EXCEPTION 'Publication v2 schema, exact frame count or inventory digest invalid' USING ERRCODE = '23514'; END IF; + account_bytes := frames[2]; + input_bytes := selected_inventory_operation_nth(account_bytes, 3); + selection_bytes := selected_inventory_operation_nth(input_bytes, 2); + IF NOT (convert_from(selection_bytes, 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'Original Account selection requires unique closed JSON members' USING ERRCODE = '23514'; END IF; + selected := convert_from(selection_bytes, 'UTF8')::JSONB; + IF NOT ((selected->>'selectedCommitBindingJson') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'Selected Account commit binding requires unique closed JSON members' USING ERRCODE = '23514'; END IF; + selected_binding := (selected->>'selectedCommitBindingJson')::JSONB; + IF octet_length(frames[3]) = 0 OR octet_length(frames[4]) = 0 + OR NOT (convert_from(frames[3], 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) + OR NOT (convert_from(frames[4], 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'Complete unique World selector and public inventory required' USING ERRCODE = '23514'; END IF; + selector := convert_from(frames[3], 'UTF8')::JSONB; + inventory := convert_from(frames[4], 'UTF8')::JSONB; + applied_bytes := decode(selector->>'appliedResultBytesBase64', 'base64'); + IF NOT (convert_from(applied_bytes, 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'APPLIED result requires unique closed JSON members' USING ERRCODE = '23514'; END IF; + applied := convert_from(applied_bytes, 'UTF8')::JSONB; + applied_operation := decode(applied->>'operationBytesBase64', 'base64'); + original_account := decode(selector->>'originalAccountBindingBytesBase64', 'base64'); + owner := inventory->'ownerScope'; application := inventory->'selectedApplication'; + account_order := inventory->'accountOrder'; frozen := inventory->'freeze'; + checkpoint := inventory->'checkpoint'; model := inventory->'sourceModel'; + FOR shape IN SELECT * FROM (VALUES + (inventory, ARRAY['schema','schemaVersion','completeness','ownerScope','selectedApplication','accountOrder','freeze','checkpoint','sourceModel','artifactDecisions']), + (owner, ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId','versionIdentityOperationId','intakeRequestId','intakeOperationId','intakeRequestDigest','sourceOperationId','sourceEvidenceDigest','intakeReceiptDigest']), + (application, ARRAY['applicationOperationId','applicationRequestId','appliedCommitId','bindingDigest','appliedResultDigest']), + (account_order, ARRAY['operationId','fenceId','actorAccountId','publicationRequestId','selectionDigest','selectedCommitId','bindingDigest']), + (frozen, ARRAY['publicationFence','publicationRequestId','requestDigest','versionStateEpoch','publishWorkflowId']), + (checkpoint, ARRAY['appliedCommitId','contentDigest','digestSchemaVersion']), + (model, ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs']) + ) AS shapes(value, keys) LOOP + IF jsonb_typeof(shape.value) IS DISTINCT FROM 'object' + OR NOT shape.value ?& shape.keys + OR (SELECT count(*) FROM jsonb_object_keys(shape.value)) <> cardinality(shape.keys) + OR EXISTS (SELECT 1 FROM jsonb_each(shape.value) entry WHERE entry.value = 'null'::JSONB) THEN + RAISE EXCEPTION 'Incomplete or unknown public inventory members' USING ERRCODE = '23514'; END IF; + END LOOP; + FOR shape IN SELECT * FROM (VALUES (owner), (application), (account_order), (frozen), (checkpoint)) AS shapes(value) LOOP + FOR member IN SELECT * FROM jsonb_each(shape.value) LOOP + IF member.key <> 'digestSchemaVersion' AND jsonb_typeof(member.value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Inventory binding members require exact string types' USING ERRCODE = '23514'; END IF; + IF member.key IN ('canonicalTenantId','canonicalVersionId','versionIdentityOperationId','intakeRequestId','intakeOperationId','sourceOperationId','applicationOperationId','applicationRequestId','appliedCommitId','operationId','fenceId','actorAccountId','selectedCommitId','publicationFence') + AND ((member.value #>> '{}') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (member.value #>> '{}') = '00000000-0000-0000-0000-000000000000') THEN + RAISE EXCEPTION 'Canonical nonzero inventory UUID required' USING ERRCODE = '23514'; END IF; + IF member.key IN ('intakeRequestDigest','sourceEvidenceDigest','intakeReceiptDigest','bindingDigest','appliedResultDigest','selectionDigest') + AND (member.value #>> '{}') !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Canonical inventory digest required' USING ERRCODE = '23514'; END IF; + END LOOP; + END LOOP; + IF owner->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' OR length(owner->>'targetNamespace') > 63 + OR frozen->>'versionStateEpoch' !~ '^[1-9][0-9]*$' OR (frozen->>'versionStateEpoch')::NUMERIC > 9223372036854775807 + OR frozen->>'requestDigest' !~ '^[0-9a-f]{64}$' OR checkpoint->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR jsonb_typeof(checkpoint->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR checkpoint->>'digestSchemaVersion' !~ '^[1-9][0-9]*$' OR (checkpoint->>'digestSchemaVersion')::NUMERIC > 2147483647 + OR btrim(account_order->>'publicationRequestId') = '' OR btrim(account_order->>'publicationRequestId') <> account_order->>'publicationRequestId' + OR btrim(frozen->>'publicationRequestId') = '' OR btrim(frozen->>'publicationRequestId') <> frozen->>'publicationRequestId' + OR btrim(frozen->>'publishWorkflowId') = '' OR btrim(frozen->>'publishWorkflowId') <> frozen->>'publishWorkflowId' + OR model->>'graphDigest' !~ '^sha256:[0-9a-f]{64}$' OR model->>'topologyResultDigest' !~ '^sha256:[0-9a-f]{64}$' + OR jsonb_typeof(model->'modelId') IS DISTINCT FROM 'string' + OR jsonb_typeof(model->'graphSchemaVersion') IS DISTINCT FROM 'number' + OR jsonb_typeof(model->'graphDigest') IS DISTINCT FROM 'string' + OR jsonb_typeof(model->'topologyResultDigest') IS DISTINCT FROM 'string' + OR model->'generationRuleFields' IS DISTINCT FROM '["id","name","scopeType","scopeId","value"]'::JSONB + OR model->'regionFields' IS DISTINCT FROM '["id","shardId","name","weather","generationSeed","generatorType","generatorParams","spacingMultiplier"]'::JSONB + OR model->'zoneFields' IS DISTINCT FROM '["id","regionId","name"]'::JSONB + OR model->'roomFields' IS DISTINCT FROM '["id","zoneId","name","description","nameLocalizedVariantsJson","descriptionLocalizedVariantsJson"]'::JSONB + OR model->'roomExitFields' IS DISTINCT FROM '["id","fromRoomId","toRoomId","direction","cost"]'::JSONB + OR model->'spawnBindingFields' IS DISTINCT FROM '["id","roomId","entityTemplateType","entityReference.kind","entityReference.tenantId","entityReference.versionId","entityReference.templateId","spawnCount","respawnDelaySeconds"]'::JSONB + OR jsonb_typeof(model->'familyCounts') IS DISTINCT FROM 'array' OR jsonb_array_length(model->'familyCounts') IS DISTINCT FROM 6 + OR jsonb_typeof(model->'regionGeneratorInputs') IS DISTINCT FROM 'array' + OR jsonb_typeof(model->'spawnBindingInputs') IS DISTINCT FROM 'array' + OR jsonb_typeof(model->'appliedEpochs') IS DISTINCT FROM 'array' + OR jsonb_typeof(model->'generationRuleInputCount') IS DISTINCT FROM 'number' + OR model->>'generationRuleInputCount' IS DISTINCT FROM '0' + OR jsonb_typeof(model->'spawnBindingCount') IS DISTINCT FROM 'number' + OR model->>'spawnBindingCount' !~ '^(0|[1-9][0-9]*)$' + OR (model->>'spawnBindingCount')::NUMERIC > 2147483647 THEN + RAISE EXCEPTION 'Unsupported public inventory source profile' USING ERRCODE = '23514'; END IF; + FOR i IN 0..5 LOOP + item := model->'familyCounts'->i; + IF jsonb_typeof(item) IS DISTINCT FROM 'object' OR NOT item ?& ARRAY['family','rowCount'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 2 + OR item->'family' IS DISTINCT FROM to_jsonb((ARRAY['REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING'])[i+1]) + OR jsonb_typeof(item->'rowCount') IS DISTINCT FROM 'number' OR item->>'rowCount' !~ '^(0|[1-9][0-9]*)$' + OR (item->>'rowCount')::NUMERIC > 2147483647 THEN + RAISE EXCEPTION 'Incomplete source family enumeration' USING ERRCODE = '23514'; END IF; + counts := array_append(counts, (item->>'rowCount')::INTEGER); + END LOOP; + IF counts[3] < 1 OR counts[5] <> 0 + OR counts[1] <> jsonb_array_length(model->'regionGeneratorInputs') + OR counts[6] <> jsonb_array_length(model->'spawnBindingInputs') + OR counts[6] <> (model->>'spawnBindingCount')::INTEGER THEN + RAISE EXCEPTION 'Source inventory counts differ from explicit inputs' USING ERRCODE = '23514'; END IF; + previous_key := NULL; + FOR item IN SELECT * FROM jsonb_array_elements(model->'regionGeneratorInputs') LOOP + IF jsonb_typeof(item) IS DISTINCT FROM 'object' OR NOT item ?& ARRAY['regionTemplateId','generatorType','generatorParams'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 3 + OR jsonb_typeof(item->'regionTemplateId') IS DISTINCT FROM 'string' + OR item->>'regionTemplateId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR item->>'regionTemplateId' = '00000000-0000-0000-0000-000000000000' + OR previous_key COLLATE "C" >= (item->>'regionTemplateId') COLLATE "C" + OR item->'generatorType' IS DISTINCT FROM '""'::JSONB + OR item->'generatorParams' IS DISTINCT FROM '""'::JSONB THEN + RAISE EXCEPTION 'Unsupported or unordered region generator input' USING ERRCODE = '23514'; END IF; + previous_key := item->>'regionTemplateId'; + END LOOP; + previous_key := NULL; + FOR item IN SELECT * FROM jsonb_array_elements(model->'spawnBindingInputs') LOOP + IF jsonb_typeof(item) IS DISTINCT FROM 'object' OR NOT item ?& ARRAY['bindingTemplateId','roomTemplateId','entityTemplateType','entityReferenceKind','entityTenantId','entityVersionId','entityTemplateId','spawnCount','respawnDelaySeconds'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 9 THEN + RAISE EXCEPTION 'Incomplete spawn input' USING ERRCODE = '23514'; END IF; + FOR member IN SELECT * FROM jsonb_each(item) LOOP + IF member.key NOT IN ('spawnCount','respawnDelaySeconds') AND jsonb_typeof(member.value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Spawn reference exact string required' USING ERRCODE = '23514'; END IF; + IF member.key IN ('bindingTemplateId','roomTemplateId','entityTenantId','entityVersionId','entityTemplateId') + AND ((member.value #>> '{}') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (member.value #>> '{}') = '00000000-0000-0000-0000-000000000000') THEN + RAISE EXCEPTION 'Canonical spawn UUID required' USING ERRCODE = '23514'; END IF; + END LOOP; + IF item->>'entityReferenceKind' IS DISTINCT FROM 'ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID' + OR item->>'entityTenantId' IS DISTINCT FROM owner->>'canonicalTenantId' + OR item->>'entityVersionId' IS DISTINCT FROM owner->>'canonicalVersionId' + OR item->>'entityTemplateType' NOT IN ('ITEM','NPC') + OR jsonb_typeof(item->'spawnCount') IS DISTINCT FROM 'number' OR item->>'spawnCount' !~ '^[1-9][0-9]*$' + OR (item->>'spawnCount')::NUMERIC > 2147483647 + OR jsonb_typeof(item->'respawnDelaySeconds') IS DISTINCT FROM 'number' OR item->>'respawnDelaySeconds' !~ '^(0|[1-9][0-9]*)$' + OR (item->>'respawnDelaySeconds')::NUMERIC > 2147483647 + OR previous_key COLLATE "C" >= (item->>'bindingTemplateId') COLLATE "C" THEN + RAISE EXCEPTION 'Unsupported or unordered scoped spawn input' USING ERRCODE = '23514'; END IF; + previous_key := item->>'bindingTemplateId'; + END LOOP; + SELECT coalesce(jsonb_agg(unit ORDER BY unit->>'owner', unit->>'aggregateType', unit->>'aggregateId', + unit->>'scopeType', unit->>'scopeId', unit->>'expectedEpoch'), '[]'::JSONB) + INTO expected_tuples FROM jsonb_array_elements(selected_binding->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + SELECT coalesce(jsonb_agg((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT) + ORDER BY unit->>'aggregateType', unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId'), '[]'::JSONB) + INTO expected_epochs FROM jsonb_array_elements(selected_binding->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF NOT (convert_from(frames[3], 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) + OR NOT (convert_from(frames[4], 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) + OR jsonb_typeof(selector) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selector)) <> 5 + OR selector->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR NOT (selector ?& ARRAY['schema', 'request', 'selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64', 'appliedResultBytesBase64']) + OR jsonb_typeof(selector->'request') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selector->'request')) <> 13 + OR NOT ((selector->'request') ?& ARRAY['targetNamespace', 'canonicalTenantId', + 'canonicalVersionId', 'intakeRequestId', 'publicationFence', 'publicationRequestId', + 'requestDigest', 'versionStateEpoch', 'publishWorkflowId', 'appliedCommitId', + 'contentDigest', 'digestSchemaVersion', 'worldAffectedTuples']) + OR jsonb_typeof(selector->'request'->'worldAffectedTuples') IS DISTINCT FROM 'array' + OR jsonb_typeof(selector->'request'->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR EXISTS (SELECT 1 FROM jsonb_each(selector->'request') field + WHERE field.key NOT IN ('digestSchemaVersion','worldAffectedTuples') + AND jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR EXISTS (SELECT 1 FROM jsonb_array_elements(selector->'request'->'worldAffectedTuples') tuple + WHERE jsonb_typeof(tuple) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(tuple)) <> 6 + OR NOT (tuple ?& ARRAY['owner','aggregateType','aggregateId','scopeType','scopeId','expectedEpoch']) + OR EXISTS (SELECT 1 FROM jsonb_each(tuple) field WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR tuple->>'owner' IS DISTINCT FROM 'WORLD_MANAGEMENT' + OR tuple->>'expectedEpoch' !~ '^(0|[1-9][0-9]*)$') + OR selected_inventory_operation_nth(account_bytes, 0) IS DISTINCT FROM convert_to('account-publication-authorization/v1', 'UTF8') + OR selected_inventory_operation_nth(input_bytes, 0) IS DISTINCT FROM convert_to('account-publication-input/v1', 'UTF8') + OR selected_inventory_operation_nth(input_bytes, 3) IS DISTINCT FROM + convert_to('sha256:' || encode(sha256(selection_bytes), 'hex'), 'UTF8') + OR selected->>'schemaVersion' IS DISTINCT FROM '1' + OR (SELECT count(*) FROM jsonb_object_keys(selected)) <> 6 + OR NOT (selected ?& ARRAY['schemaVersion','intent','target','selectedCommitBindingJson','selectedCommitDigest','synchronizedFence']) + OR jsonb_typeof(selected->'intent') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selected->'intent')) <> 8 + OR NOT (selected->'intent' ?& ARRAY['canonicalTenantId','canonicalVersionId','publishRequestId','expectedVersionStateEpoch','notes','selectedCommitRequestId','selectedCommitId','selectedCommitDigest']) + OR jsonb_typeof(selected->'target') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selected->'target')) <> 7 + OR NOT (selected->'target' ?& ARRAY['canonicalTenantId','canonicalVersionId','gameDesignVersionRowId','gameDesignVersionTenantKey','sourceGameRowId','sourceGameTenantKey','sourceProvenanceKind']) + OR jsonb_typeof(selected->'synchronizedFence') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selected->'synchronizedFence')) <> 5 + OR NOT (selected->'synchronizedFence' ?& ARRAY['requestId','commitId','inputDigest','resultVectorJson','createdAt']) + OR applied->>'status' IS DISTINCT FROM 'APPLIED' + OR jsonb_typeof(inventory) IS DISTINCT FROM 'object' + OR inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE' + OR (SELECT count(*) FROM jsonb_object_keys(inventory)) <> 10 + OR NOT (inventory ?& ARRAY['schema', 'schemaVersion', 'completeness', 'ownerScope', + 'selectedApplication', 'accountOrder', 'freeze', 'checkpoint', 'sourceModel', 'artifactDecisions']) + OR jsonb_typeof(owner) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(owner)) <> 10 + OR NOT (owner ?& ARRAY['targetNamespace', 'canonicalTenantId', 'canonicalVersionId', + 'versionIdentityOperationId', 'intakeRequestId', 'intakeOperationId', 'intakeRequestDigest', + 'sourceOperationId', 'sourceEvidenceDigest', 'intakeReceiptDigest']) + OR jsonb_typeof(application) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(application)) <> 5 + OR NOT (application ?& ARRAY['applicationOperationId', 'applicationRequestId', 'appliedCommitId', + 'bindingDigest', 'appliedResultDigest']) + OR jsonb_typeof(account_order) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(account_order)) <> 7 + OR NOT (account_order ?& ARRAY['operationId', 'fenceId', 'actorAccountId', + 'publicationRequestId', 'selectionDigest', 'selectedCommitId', 'bindingDigest']) + OR jsonb_typeof(frozen) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(frozen)) <> 5 + OR NOT (frozen ?& ARRAY['publicationFence', 'publicationRequestId', 'requestDigest', + 'versionStateEpoch', 'publishWorkflowId']) + OR jsonb_typeof(checkpoint) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(checkpoint)) <> 3 + OR NOT (checkpoint ?& ARRAY['appliedCommitId', 'contentDigest', 'digestSchemaVersion']) + OR jsonb_typeof(model) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(model)) <> 16 + OR NOT (model ?& ARRAY['modelId', 'graphSchemaVersion', 'graphDigest', 'topologyResultDigest', + 'familyCounts', 'regionGeneratorInputs', 'generationRuleFields', 'regionFields', 'zoneFields', + 'roomFields', 'roomExitFields', 'spawnBindingFields', 'spawnBindingInputs', + 'generationRuleInputCount', 'spawnBindingCount', 'appliedEpochs']) + OR jsonb_typeof(model->'familyCounts') IS DISTINCT FROM 'array' + OR jsonb_array_length(model->'familyCounts') IS DISTINCT FROM 6 + OR jsonb_typeof(model->'regionGeneratorInputs') IS DISTINCT FROM 'array' + OR jsonb_typeof(model->'spawnBindingInputs') IS DISTINCT FROM 'array' + OR jsonb_typeof(model->'appliedEpochs') IS DISTINCT FROM 'array' + OR (SELECT jsonb_agg(entry->>'family' ORDER BY ordinal) FROM + jsonb_array_elements(model->'familyCounts') WITH ORDINALITY AS entries(entry, ordinal)) + IS DISTINCT FROM '["REGION","ZONE","ROOM","ROOM_EXIT","GENERATION_RULE","WORLD_ENTITY_SPAWN_BINDING"]'::JSONB + OR EXISTS (SELECT 1 FROM jsonb_array_elements(model->'familyCounts') entry + WHERE jsonb_typeof(entry) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(entry)) <> 2 + OR NOT (entry ?& ARRAY['family', 'rowCount']) + OR jsonb_typeof(entry->'rowCount') IS DISTINCT FROM 'number' + OR (entry->>'rowCount')::NUMERIC < 0) + OR (SELECT jsonb_agg(entry ORDER BY entry->>'regionTemplateId') FROM + jsonb_array_elements(model->'regionGeneratorInputs') entry) + IS DISTINCT FROM model->'regionGeneratorInputs' + OR EXISTS (SELECT 1 FROM jsonb_array_elements(model->'regionGeneratorInputs') entry + WHERE jsonb_typeof(entry) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(entry)) <> 3 + OR NOT (entry ?& ARRAY['regionTemplateId', 'generatorType', 'generatorParams']) + OR entry->>'generatorType' IS DISTINCT FROM '' + OR entry->>'generatorParams' IS DISTINCT FROM '') + OR (SELECT jsonb_agg(entry ORDER BY entry->>'bindingTemplateId') FROM + jsonb_array_elements(model->'spawnBindingInputs') entry) + IS DISTINCT FROM model->'spawnBindingInputs' + OR EXISTS (SELECT 1 FROM jsonb_array_elements(model->'spawnBindingInputs') entry + WHERE jsonb_typeof(entry) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(entry)) <> 9 + OR NOT (entry ?& ARRAY['bindingTemplateId', 'roomTemplateId', 'entityTemplateType', + 'entityReferenceKind', 'entityTenantId', 'entityVersionId', 'entityTemplateId', + 'spawnCount', 'respawnDelaySeconds']) + OR entry->>'entityReferenceKind' IS DISTINCT FROM 'ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID' + OR entry->>'entityTenantId' IS DISTINCT FROM owner->>'canonicalTenantId' + OR entry->>'entityVersionId' IS DISTINCT FROM owner->>'canonicalVersionId' + OR entry->>'entityTemplateType' NOT IN ('ITEM', 'NPC') + OR (entry->>'spawnCount')::NUMERIC <= 0 + OR (entry->>'respawnDelaySeconds')::NUMERIC < 0) + OR model->'generationRuleFields' IS DISTINCT FROM '["id","name","scopeType","scopeId","value"]'::JSONB + OR model->'regionFields' IS DISTINCT FROM '["id","shardId","name","weather","generationSeed","generatorType","generatorParams","spacingMultiplier"]'::JSONB + OR model->'zoneFields' IS DISTINCT FROM '["id","regionId","name"]'::JSONB + OR model->'roomFields' IS DISTINCT FROM '["id","zoneId","name","description","nameLocalizedVariantsJson","descriptionLocalizedVariantsJson"]'::JSONB + OR model->'roomExitFields' IS DISTINCT FROM '["id","fromRoomId","toRoomId","direction","cost"]'::JSONB + OR model->'spawnBindingFields' IS DISTINCT FROM '["id","roomId","entityTemplateType","entityReference.kind","entityReference.tenantId","entityReference.versionId","entityReference.templateId","spawnCount","respawnDelaySeconds"]'::JSONB + OR (SELECT count(*) FROM jsonb_array_elements(model->'regionGeneratorInputs')) IS DISTINCT FROM + (SELECT (entry->>'rowCount')::INTEGER FROM jsonb_array_elements(model->'familyCounts') entry WHERE entry->>'family' = 'REGION') + OR (SELECT count(*) FROM jsonb_array_elements(model->'spawnBindingInputs')) IS DISTINCT FROM + (SELECT (entry->>'rowCount')::INTEGER FROM jsonb_array_elements(model->'familyCounts') entry WHERE entry->>'family' = 'WORLD_ENTITY_SPAWN_BINDING') + OR (SELECT (entry->>'rowCount')::INTEGER FROM jsonb_array_elements(model->'familyCounts') entry WHERE entry->>'family' = 'ROOM') < 1 + OR (SELECT (entry->>'rowCount')::INTEGER FROM jsonb_array_elements(model->'familyCounts') entry WHERE entry->>'family' = 'GENERATION_RULE') <> 0 + OR model->'generationRuleInputCount' IS DISTINCT FROM '0'::JSONB + OR model->'spawnBindingCount' IS DISTINCT FROM + (SELECT entry->'rowCount' FROM jsonb_array_elements(model->'familyCounts') entry WHERE entry->>'family' = 'WORLD_ENTITY_SPAWN_BINDING') + OR selector->'request'->'worldAffectedTuples' IS DISTINCT FROM expected_tuples + OR owner->>'targetNamespace' IS DISTINCT FROM selector->'request'->>'targetNamespace' + OR owner->>'canonicalTenantId' IS DISTINCT FROM selector->'request'->>'canonicalTenantId' + OR owner->>'canonicalVersionId' IS DISTINCT FROM selector->'request'->>'canonicalVersionId' + OR owner->>'intakeRequestId' IS DISTINCT FROM selector->'request'->>'intakeRequestId' + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(applied_operation, 1), 'UTF8') + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(original_account, 1), 'UTF8') + OR application->>'applicationRequestId' IS DISTINCT FROM selected->'intent'->>'selectedCommitRequestId' + OR application->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR application->>'bindingDigest' IS DISTINCT FROM selected->'intent'->>'selectedCommitDigest' + OR application->>'appliedResultDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(applied_bytes), 'hex') + OR account_order->>'operationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 1), 'UTF8') + OR account_order->>'fenceId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 2), 'UTF8') + OR account_order->>'actorAccountId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 1), 'UTF8') + OR account_order->>'publicationRequestId' IS DISTINCT FROM selected->'intent'->>'publishRequestId' + OR account_order->>'selectionDigest' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 3), 'UTF8') + OR account_order->>'selectedCommitId' IS DISTINCT FROM selected->'intent'->>'selectedCommitId' + OR account_order->>'bindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes), 'hex') + OR frozen->>'publicationFence' IS DISTINCT FROM selector->'request'->>'publicationFence' + OR frozen->>'publicationRequestId' IS DISTINCT FROM selector->'request'->>'publicationRequestId' + OR frozen->>'requestDigest' IS DISTINCT FROM selector->'request'->>'requestDigest' + OR frozen->>'versionStateEpoch' IS DISTINCT FROM selector->'request'->>'versionStateEpoch' + OR frozen->>'publishWorkflowId' IS DISTINCT FROM selector->'request'->>'publishWorkflowId' + OR checkpoint->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR checkpoint->>'contentDigest' IS DISTINCT FROM selector->'request'->>'contentDigest' + OR checkpoint->'digestSchemaVersion' IS DISTINCT FROM selector->'request'->'digestSchemaVersion' + OR model->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR model->'appliedEpochs' IS DISTINCT FROM expected_epochs OR expected_epochs = '[]'::JSONB + OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB + OR model->'generationRuleInputCount' IS DISTINCT FROM '0'::JSONB + OR inventory->'artifactDecisions' IS DISTINCT FROM + '[{"artifactKind":"NAVMESH","state":"NOT_REQUIRED","rule":"ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"},{"artifactKind":"PATH_GRAPH","state":"NOT_REQUIRED","rule":"AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"}]'::JSONB THEN + RAISE EXCEPTION 'Inventory differs from exact original selected Account, APPLIED graph or freeze' USING ERRCODE = '23514'; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE OR REPLACE FUNCTION account_selected_publication_settlement_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_selected_publication_authorizations%ROWTYPE; + issuer account_control_ui_issuance_operations%ROWTYPE; + source_key_value TEXT; + p INTEGER; + parsed BYTEA; + world_bytes BYTEA; + world JSONB; + selection JSONB; + input_bytes BYTEA; + terminal_frames BYTEA[] := ARRAY[]::BYTEA[]; + receipt_frames BYTEA[] := ARRAY[]::BYTEA[]; + i INTEGER; +BEGIN + -- Same canonical source-before-operation order as source writers. Never wait backwards on + -- issuance, whose producers take it before sources. Nothing here performs a remote read. + FOR source_key_value IN SELECT source_key FROM account_selected_publication_sources + WHERE operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(source_key) LOOP + PERFORM source_key FROM account_draft_authorization_source_locks + WHERE source_key = source_key_value FOR UPDATE; + END LOOP; + SELECT * INTO STRICT original FROM account_selected_publication_authorizations + WHERE operation_id = NEW.operation_id FOR UPDATE; + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations + WHERE operation_id = original.issuance_operation_id FOR UPDATE NOWAIT; + IF NEW.producer_xid <> txid_current() OR NEW.fence_id <> original.fence_id + OR NEW.account_binding <> original.binding OR issuer.status <> 'COMMITTED' + OR issuer.source_payload <> original.source_payload + OR issuer.bundle_payload <> original.issuance_bundle THEN + RAISE EXCEPTION 'Settlement differs from exact original committed Account order' USING ERRCODE = '23514'; + END IF; + PERFORM require_selected_inventory_operation_v2(NEW.publication_operation); + p := 1; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF parsed <> convert_to('game-design-publication-operation/v2', 'UTF8') THEN + RAISE EXCEPTION 'Invalid publication operation schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF parsed <> original.binding THEN + RAISE EXCEPTION 'Substituted original Account order' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_bytes, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF octet_length(world_bytes) = 0 THEN + RAISE EXCEPTION 'Incomplete publication operation' USING ERRCODE = '23514'; + END IF; + world := convert_from(world_bytes, 'UTF8')::JSONB; + -- Retrieve the original immutable selection, without recapturing current authority. + p := 1; + FOR i IN 1..4 LOOP + SELECT frame_value, next_position INTO input_bytes, p FROM account_publication_authorization_read_frame(original.binding, p); + END LOOP; + p := 1; + FOR i IN 1..3 LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(input_bytes, p); + END LOOP; + selection := convert_from(parsed, 'UTF8')::JSONB; + IF world->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR world->'request'->>'canonicalTenantId' IS DISTINCT FROM original.tenant_uuid::TEXT + OR world->'request'->>'canonicalVersionId' IS DISTINCT FROM selection->'intent'->>'canonicalVersionId' + OR world->'request'->>'publicationRequestId' IS DISTINCT FROM original.publish_request_id + OR world->'request'->>'versionStateEpoch' IS DISTINCT FROM selection->'intent'->>'expectedVersionStateEpoch' + OR world->'request'->>'appliedCommitId' IS DISTINCT FROM selection->'intent'->>'selectedCommitId' + OR 'sha256:' || (world->'request'->>'requestDigest') IS DISTINCT FROM + 'sha256:' || encode(sha256(parsed), 'hex') + OR (original.world_evidence IS NOT NULL AND original.world_evidence <> world_bytes) THEN + RAISE EXCEPTION 'Publication World evidence differs from original selected order' USING ERRCODE = '23514'; + END IF; + p := 1; + WHILE p <= octet_length(NEW.game_design_terminal) LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.game_design_terminal, p); + terminal_frames := array_append(terminal_frames, parsed); + IF cardinality(terminal_frames) > 5 THEN + RAISE EXCEPTION 'Trailing publication terminal fields' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF terminal_frames[1] IS DISTINCT FROM convert_to('game-design-publication-terminal/v1', 'UTF8') + OR terminal_frames[2] IS DISTINCT FROM NEW.publication_operation + OR terminal_frames[3] IS DISTINCT FROM convert_to(NEW.game_design_outcome, 'UTF8') + OR cardinality(terminal_frames) <> (CASE WHEN NEW.game_design_outcome = 'PUBLISHED' THEN 5 ELSE 3 END) THEN + RAISE EXCEPTION 'Changed complete publication terminal relationship' USING ERRCODE = '23514'; + END IF; + IF NEW.game_design_outcome = 'PUBLISHED' THEN + IF convert_from(terminal_frames[5], 'UTF8') !~ '^[1-9][0-9]*$' + OR convert_from(terminal_frames[5], 'UTF8')::BIGINT <> + (world->'request'->>'versionStateEpoch')::BIGINT + 1 THEN + RAISE EXCEPTION 'Changed committed publication epoch' USING ERRCODE = '23514'; + END IF; + -- Game Design owns release semantics. Its canonical codec and the authenticated owner + -- read validate the opaque complete content; Account binds all its exact bytes here. + IF octet_length(terminal_frames[4]) = 0 THEN + RAISE EXCEPTION 'Missing complete published release content' USING ERRCODE = '23514'; + END IF; + END IF; + p := 1; + WHILE p <= octet_length(NEW.receipt) LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.receipt, p); + receipt_frames := array_append(receipt_frames, parsed); + IF cardinality(receipt_frames) > 6 THEN + RAISE EXCEPTION 'Trailing settlement receipt' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF receipt_frames IS DISTINCT FROM ARRAY[convert_to('account-selected-publication-settlement/v1', 'UTF8'), + NEW.account_binding, NEW.publication_operation, NEW.game_design_terminal, + convert_to(NEW.world_outcome, 'UTF8'), NEW.world_terminal] THEN + RAISE EXCEPTION 'Changed exact settlement receipt' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V95__game_logic_intake_authorization.sql b/services/account-service/src/main/resources/db/migration/V95__game_logic_intake_authorization.sql new file mode 100644 index 0000000000..82cfbdbc36 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V95__game_logic_intake_authorization.sql @@ -0,0 +1,175 @@ +-- Unregistered distinct intake order. Every retained order remains pending: no settlement writer. +CREATE TABLE account_game_logic_intake_authorizations ( + operation_id UUID PRIMARY KEY, + fence_id UUID NOT NULL UNIQUE, + actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + version_uuid UUID NOT NULL, + intake_request_id UUID NOT NULL, + source_digest VARCHAR(71) NOT NULL CHECK (source_digest ~ '^sha256:[0-9a-f]{64}$'), + binding BYTEA NOT NULL CHECK (octet_length(binding) BETWEEN 1 AND 4194304), + issuance_operation_id UUID NOT NULL REFERENCES account_control_ui_issuance_operations(operation_id), + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + issuance_bundle BYTEA NOT NULL CHECK (octet_length(issuance_bundle) BETWEEN 1 AND 131072), + outbox_checkpoints BYTEA NOT NULL CHECK (octet_length(outbox_checkpoints) BETWEEN 1 AND 131072), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + ordered_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (tenant_uuid, intake_request_id) +); +CREATE TABLE account_game_logic_intake_sources ( + operation_id UUID NOT NULL REFERENCES account_game_logic_intake_authorizations(operation_id), + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_game_logic_intake_source_lookup ON account_game_logic_intake_sources(source_key, operation_id); + +-- [jooq ignore start] +CREATE FUNCTION account_game_logic_intake_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_game_logic_intake_authorizations + WHERE operation_id = NEW.operation_id AND producer_xid = txid_current()) THEN + RAISE EXCEPTION 'Intake sources must accompany the original owner transaction' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_game_logic_intake_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + p INTEGER := 1; + parsed BYTEA; + source_bytes BYTEA; + source_position INTEGER; + kind TEXT; + scope TEXT; + source_key_value TEXT; + seen TEXT[] := ARRAY[]::TEXT[]; + source_count INTEGER; + snapshot JSONB; + selected JSONB; + issuer account_control_ui_issuance_operations%ROWTYPE; +BEGIN + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations + WHERE operation_id = NEW.issuance_operation_id; + IF issuer.status IS DISTINCT FROM 'COMMITTED' OR issuer.account_uuid IS DISTINCT FROM NEW.actor_account_uuid + OR issuer.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid OR issuer.source_payload IS DISTINCT FROM NEW.source_payload + OR issuer.bundle_payload IS DISTINCT FROM NEW.issuance_bundle + OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT IS DISTINCT FROM NEW.issuance_fence + OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' + IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB + OR NEW.producer_xid <> txid_current() + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'accountId' IS DISTINCT FROM NEW.actor_account_uuid::TEXT + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT THEN + RAISE EXCEPTION 'Intake requires exact committed creator issuance evidence' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> 'account-game-logic-intake-authorization/v1' THEN + RAISE EXCEPTION 'Invalid intake schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.operation_id::TEXT THEN + RAISE EXCEPTION 'Changed intake operation' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.fence_id::TEXT THEN + RAISE EXCEPTION 'Changed intake fence' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.intake_request_id::TEXT THEN + RAISE EXCEPTION 'Changed intake request' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Changed intake actor' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF 'sha256:' || encode(sha256(parsed), 'hex') <> NEW.source_digest THEN + RAISE EXCEPTION 'Changed complete intake source digest' USING ERRCODE = '23514'; + END IF; + snapshot := convert_from(parsed, 'UTF8')::JSONB; + selected := (snapshot->>'bindingJson')::JSONB; + IF snapshot->>'schema' IS DISTINCT FROM 'game-design-gameplay-rule-source-snapshot/v1' + OR selected->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR selected->>'canonicalVersionId' IS DISTINCT FROM NEW.version_uuid::TEXT + OR snapshot->>'bindingDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(convert_to(snapshot->>'bindingJson', 'UTF8')), 'hex') THEN + RAISE EXCEPTION 'Changed selected source identity' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + source_count := convert_from(parsed, 'UTF8')::INTEGER; + IF source_count < 1 OR source_count <> (SELECT count(*) FROM account_game_logic_intake_sources WHERE operation_id = NEW.operation_id) + OR source_count IS DISTINCT FROM jsonb_array_length(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources') THEN + RAISE EXCEPTION 'Incomplete intake source participation' USING ERRCODE = '23514'; + END IF; + FOR i IN 1..source_count LOOP + SELECT frame_value, next_position INTO source_bytes, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF source_bytes IS DISTINCT FROM decode(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'->>(i - 1), 'base64') THEN + RAISE EXCEPTION 'Intake source differs from original complete issuance vector' USING ERRCODE = '23514'; + END IF; + 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 + RAISE EXCEPTION 'Invalid intake authority source schema' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO kind, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO scope, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := kind || ':' || scope; + IF source_key_value = ANY(seen) OR NOT EXISTS (SELECT 1 FROM account_game_logic_intake_sources + WHERE operation_id = NEW.operation_id AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Changed intake authority participation' USING ERRCODE = '23514'; + END IF; + seen := array_append(seen, source_key_value); + END LOOP; + IF p <> octet_length(NEW.binding) + 1 THEN + RAISE EXCEPTION 'Trailing intake authorization evidence' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER account_game_logic_intake_complete + AFTER INSERT ON account_game_logic_intake_authorizations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_game_logic_intake_complete_guard(); +CREATE TRIGGER account_game_logic_intake_source_insert + BEFORE INSERT ON account_game_logic_intake_sources FOR EACH ROW + EXECUTE FUNCTION account_game_logic_intake_source_insert_guard(); +CREATE TRIGGER account_game_logic_intake_immutable + BEFORE UPDATE OR DELETE ON account_game_logic_intake_authorizations FOR EACH ROW + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_sources_immutable + BEFORE UPDATE OR DELETE ON account_game_logic_intake_sources FOR EACH ROW + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_no_truncate + BEFORE TRUNCATE ON account_game_logic_intake_authorizations FOR EACH STATEMENT + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_sources_no_truncate + BEFORE TRUNCATE ON account_game_logic_intake_sources FOR EACH STATEMENT + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +-- Preserve the existing source-writer locks and Draft/publication decisions exactly. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_selected_publication_sources s WHERE s.source_key = ANY(source_keys)$anchor$; + intake_guard TEXT := $guard$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_game_logic_intake_sources s WHERE s.source_key = ANY(source_keys) + ORDER BY s.operation_id LOOP + PERFORM operation_id FROM account_game_logic_intake_authorizations + WHERE operation_id = operation_value FOR UPDATE NOWAIT; + RAISE EXCEPTION 'Distinct Game Logic intake remains pending' USING ERRCODE = '55P03'; + END LOOP; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one existing publication source-writer guard'; + END IF; + EXECUTE replace(original, anchor, intake_guard || anchor); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql new file mode 100644 index 0000000000..e1bcb15889 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql @@ -0,0 +1,129 @@ +-- Forward-only exact Game Logic terminal settlement. Original orders/participation stay immutable. +CREATE TABLE account_game_logic_intake_settlements ( + operation_id UUID PRIMARY KEY REFERENCES account_game_logic_intake_authorizations(operation_id), + target_namespace VARCHAR(63) NOT NULL CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('RETAINED', 'ABORTED')), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 16777216), + terminal_digest VARCHAR(71) NOT NULL CHECK (terminal_digest ~ '^sha256:[0-9a-f]{64}$'), + receipt_bytes BYTEA NOT NULL CHECK (octet_length(receipt_bytes) BETWEEN 1 AND 16778240), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + settled_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- [jooq ignore start] +CREATE FUNCTION account_game_logic_intake_settlement_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_game_logic_intake_authorizations%ROWTYPE; + p INTEGER := 1; + q INTEGER := 1; + parsed BYTEA; + operation_bytes BYTEA; + selected_source BYTEA; + manifest BYTEA; + expected_source BYTEA; + marker TEXT; +BEGIN + -- Same sorted original source locks as Account's producer/source writers. + SELECT * INTO STRICT original FROM account_game_logic_intake_authorizations WHERE operation_id = NEW.operation_id; + PERFORM l.source_key FROM account_draft_authorization_source_locks l + JOIN account_game_logic_intake_sources s ON s.source_key = l.source_key + WHERE s.operation_id = NEW.operation_id ORDER BY l.source_key FOR UPDATE OF l; + PERFORM operation_id FROM account_game_logic_intake_authorizations WHERE operation_id = NEW.operation_id FOR UPDATE; + IF NEW.terminal_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') + OR NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') THEN + RAISE EXCEPTION 'Changed intake settlement digest' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF convert_from(parsed, 'UTF8') <> 'account-game-logic-intake-settlement/v1' THEN + RAISE EXCEPTION 'Invalid intake settlement schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF parsed IS DISTINCT FROM NEW.terminal_bytes OR p <> octet_length(NEW.receipt_bytes) + 1 THEN + RAISE EXCEPTION 'Changed original settlement terminal' USING ERRCODE = '23514'; + END IF; + + p := 1; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF convert_from(parsed, 'UTF8') <> 'game-logic-gameplay-rule-intake-terminal/v1' THEN + RAISE EXCEPTION 'Invalid Game Logic terminal schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.outcome THEN + RAISE EXCEPTION 'Changed Game Logic terminal outcome' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO operation_bytes, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(operation_bytes, q); + IF convert_from(parsed, 'UTF8') <> 'game-logic-gameplay-rule-intake-operation/v1' THEN + RAISE EXCEPTION 'Invalid Game Logic operation schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(operation_bytes, q); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.target_namespace THEN + RAISE EXCEPTION 'Changed Game Logic operation namespace' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(operation_bytes, q); + IF parsed IS DISTINCT FROM original.binding OR q <> octet_length(operation_bytes) + 1 THEN + RAISE EXCEPTION 'Changed original Game Logic operation authorization' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF parsed IS DISTINCT FROM original.binding THEN + RAISE EXCEPTION 'Changed Game Logic terminal authorization' USING ERRCODE = '23514'; + END IF; + -- Original binding: schema, four UUID frames, then the exact complete selected source. + q := 1; + FOR i IN 1..5 LOOP + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(original.binding, q); + END LOOP; + SELECT frame_value, next_position INTO expected_source, q FROM account_publication_authorization_read_frame(original.binding, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF NEW.outcome = 'RETAINED' THEN + IF marker <> 'PRESENT' THEN RAISE EXCEPTION 'Retained terminal missing source' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO selected_source, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF marker <> 'PRESENT' THEN RAISE EXCEPTION 'Retained terminal missing manifest' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO manifest, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF selected_source IS DISTINCT FROM expected_source + OR manifest IS DISTINCT FROM convert_to(convert_from(expected_source, 'UTF8')::JSONB->>'manifestJson', 'UTF8') THEN + RAISE EXCEPTION 'Changed retained source or manifest' USING ERRCODE = '23514'; + END IF; + ELSE + IF marker <> 'ABSENT' THEN RAISE EXCEPTION 'Aborted terminal claims retained source' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF marker <> 'ABSENT' THEN RAISE EXCEPTION 'Aborted terminal claims manifest' USING ERRCODE = '23514'; END IF; + END IF; + IF p <> octet_length(NEW.terminal_bytes) + 1 THEN + RAISE EXCEPTION 'Trailing Game Logic terminal bytes' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_game_logic_intake_settlement_validate + BEFORE INSERT ON account_game_logic_intake_settlements FOR EACH ROW + EXECUTE FUNCTION account_game_logic_intake_settlement_guard(); +CREATE TRIGGER account_game_logic_intake_settlement_immutable + BEFORE UPDATE OR DELETE ON account_game_logic_intake_settlements FOR EACH ROW + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_settlement_no_truncate + BEFORE TRUNCATE ON account_game_logic_intake_settlements FOR EACH STATEMENT + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +CREATE FUNCTION account_game_logic_intake_is_settled(operation_value UUID) +RETURNS BOOLEAN LANGUAGE sql STABLE AS $$ + SELECT EXISTS (SELECT 1 FROM account_game_logic_intake_settlements WHERE operation_id = operation_value); +$$; + +-- Release only this exact receipt's participation; preserve every other writer/disclosure guard. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$FROM account_game_logic_intake_sources s WHERE s.source_key = ANY(source_keys)$anchor$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one existing intake source-writer guard'; + END IF; + EXECUTE replace(original, anchor, anchor || ' AND NOT account_game_logic_intake_is_settled(s.operation_id)'); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql b/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql new file mode 100644 index 0000000000..3564861a6d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql @@ -0,0 +1,234 @@ +-- Forward-only preliminary source-read authority. Existing final v1 orders are never rewritten. +CREATE TABLE account_game_logic_intake_source_read_reservations ( + operation_id UUID PRIMARY KEY, + fence_id UUID NOT NULL UNIQUE, + intake_request_id UUID NOT NULL, + actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + version_uuid UUID NOT NULL, + scope_bytes BYTEA NOT NULL CHECK (octet_length(scope_bytes) BETWEEN 1 AND 4194304), + scope_digest VARCHAR(71) NOT NULL CHECK (scope_digest ~ '^sha256:[0-9a-f]{64}$'), + issuance_operation_id UUID NOT NULL REFERENCES account_control_ui_issuance_operations(operation_id), + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + issuance_bundle BYTEA NOT NULL CHECK (octet_length(issuance_bundle) BETWEEN 1 AND 131072), + outbox_checkpoints BYTEA NOT NULL CHECK (octet_length(outbox_checkpoints) BETWEEN 1 AND 131072), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + reserved_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (tenant_uuid, intake_request_id) +); +CREATE TABLE account_game_logic_intake_source_read_sources ( + operation_id UUID NOT NULL REFERENCES account_game_logic_intake_source_read_reservations(operation_id), + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_game_logic_intake_source_read_lookup + ON account_game_logic_intake_source_read_sources(source_key, operation_id); +CREATE TABLE account_game_logic_intake_source_read_aborts ( + operation_id UUID PRIMARY KEY REFERENCES account_game_logic_intake_source_read_reservations(operation_id), + aborted_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- [jooq ignore start] +CREATE FUNCTION account_game_logic_intake_source_read_is_pending(operation_value UUID) +RETURNS BOOLEAN LANGUAGE sql STABLE AS $$ + SELECT EXISTS (SELECT 1 FROM account_game_logic_intake_source_read_reservations r + WHERE r.operation_id = operation_value + AND NOT EXISTS (SELECT 1 FROM account_game_logic_intake_source_read_aborts a WHERE a.operation_id = r.operation_id) + AND NOT EXISTS (SELECT 1 FROM account_game_logic_intake_authorizations f WHERE f.operation_id = r.operation_id)); +$$; + +CREATE FUNCTION account_game_logic_intake_source_read_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + p INTEGER := 1; + q INTEGER := 1; + parsed BYTEA; + selected_bytes BYTEA; + selected JSONB; + namespace_value TEXT; + source_bytes BYTEA; + source_kind TEXT; + source_scope TEXT; + source_key_value TEXT; + seen TEXT[] := ARRAY[]::TEXT[]; + issuer account_control_ui_issuance_operations%ROWTYPE; + original account_draft_authorization_fences%ROWTYPE; + vector JSONB; +BEGIN + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations WHERE operation_id = NEW.issuance_operation_id; + IF NEW.producer_xid <> txid_current() OR issuer.status IS DISTINCT FROM 'COMMITTED' + OR extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second + OR issuer.account_uuid IS DISTINCT FROM NEW.actor_account_uuid + OR issuer.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR issuer.source_payload IS DISTINCT FROM NEW.source_payload + OR issuer.bundle_payload IS DISTINCT FROM NEW.issuance_bundle + OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT IS DISTINCT FROM NEW.issuance_fence + OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' + IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB + OR NEW.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.scope_bytes), 'hex') THEN + RAISE EXCEPTION 'Preliminary scope requires exact current committed creator evidence' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') <> 'account-game-logic-intake-source-read/v1' THEN + RAISE EXCEPTION 'Invalid preliminary scope schema' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF namespace_value !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' THEN + RAISE EXCEPTION 'Invalid preliminary scope namespace' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.operation_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary operation' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.fence_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary fence' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.intake_request_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary request' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Changed preliminary actor' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO selected_bytes, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + selected := convert_from(selected_bytes, 'UTF8')::JSONB; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'sha256:' || encode(sha256(selected_bytes), 'hex') + OR selected->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR selected->>'canonicalVersionId' IS DISTINCT FROM NEW.version_uuid::TEXT THEN + RAISE EXCEPTION 'Changed preliminary selection' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'spiffe://firemud/ns/' || namespace_value || '/sa/account-service' THEN + RAISE EXCEPTION 'Invalid preliminary intended reader' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') <> 'GAME_LOGIC_INTAKE_SOURCE' OR p <> octet_length(NEW.scope_bytes) + 1 THEN + RAISE EXCEPTION 'Invalid preliminary purpose or trailing bytes' USING ERRCODE = '23514'; END IF; + + SELECT * INTO STRICT original FROM account_draft_authorization_fences + WHERE request_id = (selected->>'requestId')::UUID AND commit_id = (selected->>'commitId')::UUID; + FOR i IN 1..12 LOOP + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(original.binding, q); + END LOOP; + IF parsed IS DISTINCT FROM selected_bytes OR original.ordering <> 'COMMIT_ORDER' + OR NOT account_draft_authorization_is_settled(original.operation_id) + OR EXISTS (SELECT 1 FROM account_draft_authorization_owner_readbacks WHERE operation_id = original.operation_id AND outcome <> 'COMMITTED') THEN + RAISE EXCEPTION 'Exact original author must have committed settlement before source scope' USING ERRCODE = '23514'; END IF; + + vector := convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'; + IF jsonb_array_length(vector) < 1 OR jsonb_array_length(vector) <> + (SELECT count(*) FROM account_game_logic_intake_source_read_sources WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Incomplete preliminary source participation' USING ERRCODE = '23514'; END IF; + FOR source_bytes IN SELECT decode(value, 'base64') FROM jsonb_array_elements_text(vector) LOOP + q := 1; + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(source_bytes, q); + IF convert_from(parsed, 'UTF8') <> 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Invalid preliminary source schema' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_kind, q FROM account_publication_authorization_read_frame(source_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_scope, q FROM account_publication_authorization_read_frame(source_bytes, q); + source_key_value := source_kind || ':' || source_scope; + IF source_key_value = ANY(seen) OR NOT EXISTS (SELECT 1 FROM account_game_logic_intake_source_read_sources + WHERE operation_id = NEW.operation_id AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Changed preliminary complete source vector' USING ERRCODE = '23514'; END IF; + seen := array_append(seen, source_key_value); + END LOOP; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER account_game_logic_intake_source_read_complete + AFTER INSERT ON account_game_logic_intake_source_read_reservations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_game_logic_intake_source_read_complete_guard(); + +CREATE FUNCTION account_game_logic_intake_source_read_source_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_game_logic_intake_source_read_reservations + WHERE operation_id = NEW.operation_id AND producer_xid = txid_current()) THEN + RAISE EXCEPTION 'Preliminary sources must accompany original reservation transaction' USING ERRCODE = '23514'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_game_logic_intake_source_read_source_validate BEFORE INSERT ON account_game_logic_intake_source_read_sources + FOR EACH ROW EXECUTE FUNCTION account_game_logic_intake_source_read_source_guard(); + +CREATE FUNCTION account_game_logic_intake_source_read_terminal_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_game_logic_intake_source_read_reservations%ROWTYPE; + issuer account_control_ui_issuance_operations%ROWTYPE; + p INTEGER := 1; + q INTEGER := 1; + parsed BYTEA; + selected_bytes BYTEA; + source_bytes BYTEA; +BEGIN + PERFORM l.source_key FROM account_draft_authorization_source_locks l + JOIN account_game_logic_intake_source_read_sources s ON s.source_key = l.source_key + WHERE s.operation_id = NEW.operation_id ORDER BY account_publication_authorization_source_sort_key(l.source_key) FOR UPDATE OF l; + SELECT * INTO STRICT original FROM account_game_logic_intake_source_read_reservations WHERE operation_id = NEW.operation_id FOR UPDATE; + IF TG_TABLE_NAME = 'account_game_logic_intake_source_read_aborts' THEN + IF EXISTS (SELECT 1 FROM account_game_logic_intake_authorizations WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Finalized intake cannot be preliminarily aborted' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations WHERE operation_id = original.issuance_operation_id; + IF EXISTS (SELECT 1 FROM account_game_logic_intake_source_read_aborts WHERE operation_id = NEW.operation_id) + OR extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second OR issuer.status <> 'COMMITTED' + OR NEW.fence_id IS DISTINCT FROM original.fence_id OR NEW.intake_request_id IS DISTINCT FROM original.intake_request_id + OR NEW.actor_account_uuid IS DISTINCT FROM original.actor_account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM original.tenant_uuid OR NEW.version_uuid IS DISTINCT FROM original.version_uuid + OR NEW.issuance_operation_id IS DISTINCT FROM original.issuance_operation_id + OR NEW.issuance_fence IS DISTINCT FROM original.issuance_fence OR NEW.source_payload IS DISTINCT FROM original.source_payload + OR NEW.issuance_bundle IS DISTINCT FROM original.issuance_bundle OR NEW.outbox_checkpoints IS DISTINCT FROM original.outbox_checkpoints THEN + RAISE EXCEPTION 'Finalization requires original current un-aborted source scope' USING ERRCODE = '23514'; END IF; + FOR i IN 1..7 LOOP + SELECT frame_value, next_position INTO selected_bytes, p FROM account_publication_authorization_read_frame(original.scope_bytes, p); + END LOOP; + FOR i IN 1..6 LOOP + SELECT frame_value, next_position INTO source_bytes, q FROM account_publication_authorization_read_frame(NEW.binding, q); + END LOOP; + IF selected_bytes IS DISTINCT FROM convert_to(convert_from(source_bytes, 'UTF8')::JSONB->>'bindingJson', 'UTF8') THEN + RAISE EXCEPTION 'Finalization selected source differs from preliminary scope' USING ERRCODE = '23514'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_game_logic_intake_source_read_abort_validate BEFORE INSERT ON account_game_logic_intake_source_read_aborts + FOR EACH ROW EXECUTE FUNCTION account_game_logic_intake_source_read_terminal_guard(); +-- A constraint trigger also enforces expiry at the final owner transaction's commit checks. +CREATE CONSTRAINT TRIGGER account_game_logic_intake_source_read_finalize_validate + AFTER INSERT ON account_game_logic_intake_authorizations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_game_logic_intake_source_read_terminal_guard(); + +CREATE TRIGGER account_game_logic_intake_source_read_immutable BEFORE UPDATE OR DELETE ON account_game_logic_intake_source_read_reservations + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_source_read_no_truncate BEFORE TRUNCATE ON account_game_logic_intake_source_read_reservations + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_source_read_sources_immutable BEFORE UPDATE OR DELETE ON account_game_logic_intake_source_read_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_source_read_sources_no_truncate BEFORE TRUNCATE ON account_game_logic_intake_source_read_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_source_read_aborts_immutable BEFORE UPDATE OR DELETE ON account_game_logic_intake_source_read_aborts + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_source_read_aborts_no_truncate BEFORE TRUNCATE ON account_game_logic_intake_source_read_aborts + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_game_logic_intake_sources s WHERE s.source_key = ANY(source_keys)$anchor$; + preliminary_guard TEXT := $guard$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_game_logic_intake_source_read_sources s WHERE s.source_key = ANY(source_keys) + AND account_game_logic_intake_source_read_is_pending(s.operation_id) ORDER BY s.operation_id LOOP + PERFORM operation_id FROM account_game_logic_intake_source_read_reservations + WHERE operation_id = operation_value FOR UPDATE NOWAIT; + RAISE EXCEPTION 'Preliminary Game Logic source read remains pending' USING ERRCODE = '55P03'; + END LOOP; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one existing intake source-writer guard'; END IF; + EXECUTE replace(original, anchor, preliminary_guard || anchor); +END; +$migration$; +-- [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 index c7122f94ea..9915cfd605 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -27,6 +28,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.OperationConflictException; @@ -34,6 +36,7 @@ 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.AccountAuthoritySourceEventReadback.LatestSourceSnapshot; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; @@ -72,6 +75,7 @@ class PasswordResetAuthorityProducerPostgresIntegrationTest { @Test void commitsPasswordTokenAuthorityFenceClosedEventAndImmutableReceiptTogether() { Fixture fixture = newFixture(); + assertRealDraftOwnerFenceStorage(fixture); Seed seed = seedAccountAndToken(fixture, "initial-password"); reset(fixture, seed.rawToken(), "new-password-one"); @@ -90,6 +94,18 @@ void commitsPasswordTokenAuthorityFenceClosedEventAndImmutableReceiptTogether() transaction( fixture.transaction(), () -> fixture.outbox().findEvent(streamKey, receipt.outboxSequence()).orElseThrow()); + var sourceHead = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT current_generation, current_source_version, current_issuance_fence, " + + "current_issuance_fence_source_version, last_outbox_sequence, " + + "last_event_id, last_event_digest, cutoff_generation, cutoff_stream_key, " + + "cutoff_sequence FROM account_authority_source_records " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + seed.accountUuid()), + "The reset must advance the real Account source head"); var decoded = PasswordResetAuthorityEventV1Codec.verify( new String(event.payload(), StandardCharsets.UTF_8)); @@ -112,6 +128,20 @@ void commitsPasswordTokenAuthorityFenceClosedEventAndImmutableReceiptTogether() assertThat(checkpoint.outboxSequence()).isEqualTo(receipt.outboxSequence()); assertThat(checkpoint.sourceEventId()).isEqualTo(receipt.eventId()); assertThat(checkpoint.sourceEventDigest()).isEqualTo(receipt.eventDigest()); + assertThat(sourceHead.get("current_generation", Long.class)).isEqualTo(authority.generation()); + assertThat(sourceHead.get("current_source_version", Long.class)) + .isEqualTo(authority.sourceVersion()); + assertThat(sourceHead.get("current_issuance_fence", Long.class)) + .isEqualTo(authority.issuanceFence().value()); + assertThat(sourceHead.get("current_issuance_fence_source_version", Long.class)) + .isEqualTo(authority.issuanceFence().sourceVersion()); + assertThat(sourceHead.get("last_outbox_sequence", Long.class)) + .isEqualTo(receipt.outboxSequence()); + assertThat(sourceHead.get("last_event_id", String.class)).isEqualTo(receipt.eventId()); + assertThat(sourceHead.get("last_event_digest", String.class)).isEqualTo(receipt.eventDigest()); + assertThat(sourceHead.get("cutoff_generation", Long.class)).isEqualTo(authority.generation()); + assertThat(sourceHead.get("cutoff_stream_key", String.class)).isEqualTo(streamKey); + assertThat(sourceHead.get("cutoff_sequence", Long.class)).isEqualTo(receipt.outboxSequence()); assertThat(decoded.accountId()).isEqualTo(seed.accountUuid().toString()); assertThat(decoded.accountAuthorityGeneration()).isEqualTo("2"); assertThat(decoded.sourceVersion()).isEqualTo("2"); @@ -151,9 +181,37 @@ void exactRetryRecoversLostResponseWithoutAnySecondMutation() { reset(fixture, seed.rawToken(), "recovered-password"); StoredState committed = snapshot(fixture, seed); + var journalBeforeRetry = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT password_verifier, password_verifier_digest, request_digest, " + + "request_payload, source_change_binding " + + "FROM account_password_reset_draft_source_changes WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))); + assertThat(journalBeforeRetry.get("password_verifier", String.class)).isNull(); reset(fixture, seed.rawToken(), "recovered-password"); assertThat(snapshot(fixture, seed)).isEqualTo(committed); + var journalAfterRetry = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT password_verifier, password_verifier_digest, request_digest, " + + "request_payload, source_change_binding " + + "FROM account_password_reset_draft_source_changes WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))); + assertThat(journalAfterRetry.get("password_verifier", String.class)).isNull(); + assertThat(journalAfterRetry.get("password_verifier_digest", byte[].class)) + .isEqualTo(journalBeforeRetry.get("password_verifier_digest", byte[].class)); + assertThat(journalAfterRetry.get("request_digest", byte[].class)) + .isEqualTo(journalBeforeRetry.get("request_digest", byte[].class)); + assertThat(journalAfterRetry.get("request_payload", byte[].class)) + .isEqualTo(journalBeforeRetry.get("request_payload", byte[].class)); + assertThat(journalAfterRetry.get("source_change_binding", byte[].class)) + .isEqualTo(journalBeforeRetry.get("source_change_binding", byte[].class)); } @Test @@ -208,7 +266,8 @@ void waitingResetRetainsExactIntentAndSettlesOnlyAfterOriginalOwnersDeny() { fixture .setupDsl() .fetchOne( - "SELECT status, request_payload, source_evidence, source_change_binding " + "SELECT status, request_payload, source_evidence, source_change_binding, " + + "password_verifier, password_verifier_digest " + "FROM account_password_reset_draft_source_changes WHERE token_hash = ?", HexFormat.of().parseHex(tokenHash(seed.rawToken()))), "Waiting password-reset source intent must be persisted"); @@ -216,9 +275,23 @@ void waitingResetRetainsExactIntentAndSettlesOnlyAfterOriginalOwnersDeny() { 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); + String waitingVerifier = intentBeforeSettlement.get("password_verifier", String.class); + byte[] verifierDigest = intentBeforeSettlement.get("password_verifier_digest", byte[].class); assertThat(requestBytes).isNotEmpty(); assertThat(capturedSource).isNotEmpty(); assertThat(changeBinding).isNotEmpty(); + assertThat(waitingVerifier).isNotBlank(); + assertThat(verifierDigest).hasSize(32); + assertThat(sha256Hex(waitingVerifier)).isEqualTo(HexFormat.of().formatHex(verifierDigest)); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_password_reset_draft_source_changes " + + "SET password_verifier = NULL WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))) + .isInstanceOf(DataAccessException.class); var persistedTokenBinding = Objects.requireNonNull( fixture @@ -263,11 +336,30 @@ void waitingResetRetainsExactIntentAndSettlesOnlyAfterOriginalOwnersDeny() { fixture .setupDsl() .fetchOne( - "SELECT status FROM account_password_reset_draft_source_changes " + "SELECT status, password_verifier, password_verifier_digest, request_digest, " + + "request_payload, source_change_binding " + + "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"); + assertThat(committedResetIntent.get("password_verifier", String.class)).isNull(); + assertThat(committedResetIntent.get("password_verifier_digest", byte[].class)) + .isEqualTo(verifierDigest); + assertThat(committedResetIntent.get("request_digest", byte[].class)).hasSize(32); + assertThat(committedResetIntent.get("request_payload", byte[].class)).isEqualTo(requestBytes); + assertThat(committedResetIntent.get("source_change_binding", byte[].class)) + .isEqualTo(changeBinding); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_password_reset_draft_source_changes " + + "SET password_verifier_digest = password_verifier_digest " + + "WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))) + .isInstanceOf(DataAccessException.class); var committedV76Change = Objects.requireNonNull( fixture @@ -281,6 +373,127 @@ void waitingResetRetainsExactIntentAndSettlesOnlyAfterOriginalOwnersDeny() { assertThat(committedV76Change.get("status", String.class)).isEqualTo("SOURCE_COMMITTED"); } + @Test + void expiredWaitingResetAbortsAndDeletesOnlyItsExactOriginalToken() { + Fixture fixture = newFixture(); + Seed seed = + seedAccountAndToken(fixture, "initial-password", LocalDateTime.now().minusMinutes(1)); + DraftAuthorizationFenceBinding binding = draftBinding(seed); + transaction( + fixture.transaction(), + () -> { + fixture.fences().reserve(binding); + return null; + }); + + String verifier = hashPasswordForTest("expired-password"); + String tokenHash = tokenHash(seed.rawToken()); + String requestDigest = passwordResetRequestDigest(seed, sha256Hex(verifier)); + transaction( + fixture.transaction(), + () -> { + Account account = fixture.accounts().findById(seed.accountId()).orElseThrow(); + PasswordResetToken token = fixture.tokens().findByToken(seed.rawToken()).orElseThrow(); + ScopeState current = readAuthority(fixture, seed.accountUuid()); + fixture + .sourceChanges() + .participate( + account, + token.getId(), + tokenHash, + seed.deadline(), + requestDigest, + verifier, + current, + new LatestSourceSnapshot(0L, Optional.empty())); + return null; + }); + var waitingIntent = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT request_digest, password_verifier_digest, request_payload, " + + "source_change_binding FROM account_password_reset_draft_source_changes " + + "WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash)), + "Expired waiting intent must persist its exact request"); + boolean wrongHashDeleted = + transaction( + fixture.transaction(), + () -> { + PasswordResetToken token = + fixture.tokens().findByToken(seed.rawToken()).orElseThrow(); + return fixture + .tokens() + .deleteExactAfterSourceAbort( + token.getId(), seed.accountId(), "0".repeat(64), seed.deadline()); + }); + assertThat(wrongHashDeleted).isFalse(); + assertThat(tokenExists(fixture, seed.rawToken())).isTrue(); + transaction( + fixture.transaction(), + () -> { + fixture.fences().recordOwnerReadback(binding, ownerDenial(binding, Owner.GAME_DESIGN)); + fixture.fences().recordOwnerReadback(binding, ownerDenial(binding, Owner.WORLD)); + return null; + }); + + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "expired-password")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Token expired"); + + assertThat(tokenExists(fixture, seed.rawToken())).isFalse(); + assertThat(snapshot(fixture, seed)) + .isEqualTo(new StoredState(seed.originalVerifier(), 1L, 1L, 1L, 0L, 0L, 0L)); + var abortedIntent = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT status, abort_reason, password_verifier, password_verifier_digest, " + + "request_digest, request_payload, source_change_binding " + + "FROM account_password_reset_draft_source_changes WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash)), + "Aborted source intent must remain readable after exact token deletion"); + assertThat(abortedIntent.get("status", String.class)).isEqualTo("SOURCE_ABORTED"); + assertThat(abortedIntent.get("abort_reason", String.class)).isEqualTo("EXPIRED"); + assertThat(abortedIntent.get("password_verifier", String.class)).isNull(); + assertThat(abortedIntent.get("password_verifier_digest", byte[].class)) + .isEqualTo(waitingIntent.get("password_verifier_digest", byte[].class)); + assertThat(abortedIntent.get("request_digest", byte[].class)) + .isEqualTo(waitingIntent.get("request_digest", byte[].class)); + assertThat(abortedIntent.get("request_payload", byte[].class)) + .isEqualTo(waitingIntent.get("request_payload", byte[].class)); + assertThat(abortedIntent.get("source_change_binding", byte[].class)) + .isEqualTo(waitingIntent.get("source_change_binding", byte[].class)); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_password_reset_draft_source_changes " + + "SET status = 'WAITING' WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_password_reset_draft_source_changes " + + "WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash))) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "expired-password")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid token"); + assertThat(tokenExists(fixture, seed.rawToken())).isFalse(); + assertThat(snapshot(fixture, seed)) + .isEqualTo(new StoredState(seed.originalVerifier(), 1L, 1L, 1L, 0L, 0L, 0L)); + } + @Test void changedRetryConflictsAndConsecutiveResetsRequireExactPriorSourceProof() { Fixture fixture = newFixture(); @@ -364,32 +577,22 @@ public Optional findByTokenHash(String tokenHash) { } @Test - void issuanceFenceOverflowRollsBackTokenPasswordAuthorityAndOutbox() { + void issuanceFenceRejectsAnUnbackedOverflowAdvance() { 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); + assertThatThrownBy( + () -> + fixture + .setupDsl() + .execute( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = ?, source_version = ? WHERE account_uuid = ?", + Long.MAX_VALUE, + 11L, + seed.accountUuid())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("lacks exact owner source evidence"); + assertUnchangedAfterRollback(fixture, seed, 1L, 1L); } private boolean concurrentReset( @@ -453,6 +656,11 @@ private Fixture newFixture() { } private Seed seedAccountAndToken(Fixture fixture, String initialVerifier) { + return seedAccountAndToken(fixture, initialVerifier, LocalDateTime.now().plusHours(2)); + } + + private Seed seedAccountAndToken( + Fixture fixture, String initialVerifier, LocalDateTime deadline) { return transaction( fixture.transaction(), () -> { @@ -464,7 +672,6 @@ private Seed seedAccountAndToken(Fixture fixture, String 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); @@ -482,6 +689,8 @@ private AccountServiceImpl newService( return new AccountServiceImpl( fixture.accounts(), fixture.authority(), + new AccountAuthoritySourceEvidenceRepository( + fixture.transactionDsl(), fixture.authority(), fixture.outbox()), fixture.outbox(), operations, fixture.logoutAllOperations(), @@ -663,6 +872,87 @@ private long countEvents(Fixture fixture, String streamKey) { "Password-reset event count readback is missing"); } + private void assertRealDraftOwnerFenceStorage(Fixture fixture) { + var installed = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT to_regclass('account_control_ui_issuance_operations') IS NOT NULL " + + "AS issuance_operations, " + + "to_regclass('account_selected_publication_authorizations') IS NOT NULL " + + "AS publication_authorizations, " + + "to_regclass('account_selected_publication_sources') IS NOT NULL " + + "AS publication_sources, " + + "to_regclass('account_selected_publication_settlements') IS NOT NULL " + + "AS publication_settlements, " + + "to_regclass('account_game_logic_intake_authorizations') IS NOT NULL " + + "AS game_logic_authorizations, " + + "to_regclass('account_game_logic_intake_sources') IS NOT NULL " + + "AS game_logic_sources, " + + "to_regclass('account_game_logic_intake_settlements') IS NOT NULL " + + "AS game_logic_settlements, " + + "to_regclass('account_game_logic_intake_source_read_reservations') " + + "IS NOT NULL AS source_read_reservations, " + + "to_regclass('account_game_logic_intake_source_read_sources') " + + "IS NOT NULL AS source_read_sources, " + + "to_regclass('account_game_logic_intake_source_read_aborts') " + + "IS NOT NULL AS source_read_aborts, " + + "to_regprocedure('account_selected_publication_is_settled(uuid)') " + + "IS NOT NULL AS publication_settlement_function, " + + "to_regprocedure('account_game_logic_intake_is_settled(uuid)') " + + "IS NOT NULL AS game_logic_settlement_function, " + + "to_regprocedure('account_game_logic_intake_source_read_is_pending(uuid)') " + + "IS NOT NULL AS source_read_pending_function, " + + "to_regprocedure('require_selected_inventory_operation_v2(bytea)') " + + "IS NOT NULL AS selected_inventory_guard, " + + "NOT EXISTS (SELECT 1 FROM account_control_ui_issuance_operations) " + + "AND NOT EXISTS (SELECT 1 FROM account_selected_publication_authorizations) " + + "AND NOT EXISTS (SELECT 1 FROM account_game_logic_intake_authorizations) " + + "AND NOT EXISTS (SELECT 1 FROM account_game_logic_intake_source_read_reservations) " + + "AS owner_operations_absent"), + "Real inactive owner-fence storage must be installed"); + for (String column : + List.of( + "issuance_operations", + "publication_authorizations", + "publication_sources", + "publication_settlements", + "game_logic_authorizations", + "game_logic_sources", + "game_logic_settlements", + "source_read_reservations", + "source_read_sources", + "source_read_aborts", + "publication_settlement_function", + "game_logic_settlement_function", + "source_read_pending_function", + "selected_inventory_guard", + "owner_operations_absent")) { + assertThat(installed.get(column, Boolean.class)).as(column).isTrue(); + } + + UUID unknownOperation = UUID.randomUUID(); + var unknown = + Objects.requireNonNull( + fixture + .setupDsl() + .fetchOne( + "SELECT account_selected_publication_is_settled(?::uuid) " + + "AS publication_settled, " + + "account_game_logic_intake_is_settled(?::uuid) " + + "AS game_logic_settled, " + + "account_game_logic_intake_source_read_is_pending(?::uuid) " + + "AS source_read_pending", + unknownOperation, + unknownOperation, + unknownOperation), + "Unknown external owner operation state must be readable"); + assertThat(unknown.get("publication_settled", Boolean.class)).isFalse(); + assertThat(unknown.get("game_logic_settled", Boolean.class)).isFalse(); + assertThat(unknown.get("source_read_pending", Boolean.class)).isFalse(); + } + private String streamKey(UUID accountUuid) { return STREAM_PREFIX + accountUuid; } @@ -671,6 +961,37 @@ private String tokenHash(String rawToken) { return sha256Hex(rawToken); } + private String passwordResetRequestDigest(Seed seed, String verifierDigest) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (String field : + List.of( + "account-password-reset-request/v1", + "PASSWORD_RESET", + seed.accountUuid().toString(), + tokenHash(seed.rawToken()), + seed.deadline().toString(), + verifierDigest)) { + byte[] encoded = field.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private String hashPasswordForTest(String password) { + de.mkammerer.argon2.Argon2 argon2 = de.mkammerer.argon2.Argon2Factory.create(); + char[] chars = password.toCharArray(); + try { + return argon2.hash(1, 8192, 1, chars); + } finally { + argon2.wipeArray(chars); + } + } + private String sha256Hex(String value) { try { return HexFormat.of() diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingFencePostgresIntegrationTest.java new file mode 100644 index 0000000000..af0206dee2 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingFencePostgresIntegrationTest.java @@ -0,0 +1,365 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion.Materiality; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding.PublicationEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +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.postgresql.util.PSQLException; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Isolated PostgreSQL proof for exact V86 predecessor/Draft source binding. All hosted catalog, + * publisher, legal identity, and environment-owner values here are explicitly synthetic fixtures; + * these tests prove only the Account-owned SQL guard and do not prove external owner authority. + */ +class HostedTermsEnvironmentBindingFencePostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @Test + void initialBindingNeedsNoInventedPredecessorSourceChange() { + TestContext context = context(); + CatalogSources catalogs = seedCatalogs(context); + String boundary = "test-environment-" + UUID.randomUUID(); + HostedTermsEnvironmentBinding binding = + publishInitialBinding(context, boundary, catalogs.first()); + + assertThat(binding.predecessorBindingId()).isNull(); + assertThat(binding.sourceVersion()).isEqualTo(1L); + assertThat( + context + .dsl() + .resultQuery("SELECT count(*) FROM account_draft_authorization_source_changes") + .fetchOne(0, Long.class)) + .isZero(); + } + + @Test + void predecessorBindingCommitsWithTheExactSettledEnvironmentAndCatalogSourceSet() { + TestContext context = context(); + CatalogSources catalogs = seedCatalogs(context); + String boundary = "test-environment-" + UUID.randomUUID(); + HostedTermsEnvironmentBinding predecessor = + publishInitialBinding(context, boundary, catalogs.first()); + + HostedTermsEnvironmentBinding committed = + publishSuccessor(context, boundary, predecessor, catalogs, ChangeShape.EXACT); + + assertThat(committed.predecessorBindingId()).isEqualTo(predecessor.bindingId()); + assertThat(committed.sourceVersion()).isEqualTo(2L); + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM account_draft_authorization_changed_scopes changed " + + "JOIN account_draft_authorization_source_changes change USING (change_id) " + + "WHERE change.change_id = ? AND change.status = 'SOURCE_COMMITTED'", + committed.publicationRequestId()) + .fetchOne(0, Long.class)) + .isEqualTo(3L); + } + + @Test + void predecessorBindingRejectsWaitingWrongIdentityAndInexactSourceSets() { + for (ChangeShape shape : + List.of( + ChangeShape.WAITING, + ChangeShape.WRONG_CHANGE_ID, + ChangeShape.WRONG_BOUNDARY, + ChangeShape.MISSING_PREDECESSOR_CATALOG, + ChangeShape.MISSING_TARGET_CATALOG, + ChangeShape.EXTRA_SCOPE)) { + TestContext context = context(); + CatalogSources catalogs = seedCatalogs(context); + String boundary = "test-environment-" + UUID.randomUUID(); + HostedTermsEnvironmentBinding predecessor = + publishInitialBinding(context, boundary, catalogs.first()); + + assertThatThrownBy(() -> publishSuccessor(context, boundary, predecessor, catalogs, shape)) + .as("V86 rejects %s source-change fixture", shape) + .isInstanceOf(TransactionSystemException.class) + .rootCause() + .isInstanceOf(PSQLException.class) + .hasMessageContaining("fully settled exact Draft source change"); + } + } + + private CatalogSources seedCatalogs(TestContext context) { + HostedTermsRepository repository = new HostedTermsRepository(context.dsl()); + CatalogVersion first = insertInitialCatalog(context, repository); + CatalogVersion second = insertInitialCatalog(context, repository); + return new CatalogSources(first, second); + } + + private CatalogVersion insertInitialCatalog( + TestContext context, HostedTermsRepository repository) { + UUID scopeId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + String legalIdentity = "TEST FIXTURE ONLY - no legal identity claim"; + byte[] document = + "synthetic fixture only; not legal terms, review, or a publication" + .getBytes(StandardCharsets.UTF_8); + Instant effectiveAt = Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MICROS); + AccountHostedTermsService.PublicationEvidence evidence = + new AccountHostedTermsService.PublicationEvidence( + scopeId, + legalIdentity, + 1L, + document, + Materiality.INITIAL, + null, + null, + "TEST FIXTURE ONLY - synthetic publication reference", + 1L, + "TEST FIXTURE ONLY - synthetic notice reference", + 1L, + effectiveAt); + byte[] request = HostedTermsEncoding.publication(requestId, evidence); + HostedTermsCatalogVersion candidate = + new HostedTermsCatalogVersion( + UUID.randomUUID(), + scopeId, + null, + legalIdentity, + 1L, + document, + HostedTermsEncoding.digest(document), + 1L, + 1L, + Materiality.INITIAL, + null, + null, + evidence.publicationEvidenceReference(), + evidence.publicationEvidenceVersion(), + evidence.noticeEvidenceReference(), + evidence.noticeEvidenceVersion(), + effectiveAt); + + context + .transaction() + .executeWithoutResult( + status -> { + repository.ensureScope(scopeId); + repository.claimPublication(requestId, scopeId, request); + repository.lockScope(scopeId); + repository.insertCandidate(candidate); + repository.markScheduled(requestId, candidate); + repository.completePublication( + requestId, candidate, HostedTermsEncoding.catalog(candidate), null); + }); + return new CatalogVersion(candidate); + } + + private HostedTermsEnvironmentBinding publishInitialBinding( + TestContext context, String boundary, CatalogVersion catalog) { + HostedTermsEnvironmentBindingRepository repository = + new HostedTermsEnvironmentBindingRepository(context.dsl()); + UUID requestId = UUID.randomUUID(); + PublicationEvidence evidence = publicationEvidence(boundary, catalog, null); + byte[] request = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence); + HostedTermsEnvironmentBinding[] candidate = new HostedTermsEnvironmentBinding[1]; + context + .transaction() + .executeWithoutResult( + status -> { + repository.ensureHead(boundary); + repository.claimPublication(requestId, boundary, request); + repository.lockHead(boundary); + candidate[0] = + repository.insertCandidate(UUID.randomUUID(), requestId, evidence, null); + repository.completePublication(requestId, candidate[0], null, null); + }); + return candidate[0]; + } + + private HostedTermsEnvironmentBinding publishSuccessor( + TestContext context, + String boundary, + HostedTermsEnvironmentBinding predecessor, + CatalogSources catalogs, + ChangeShape shape) { + HostedTermsEnvironmentBindingRepository bindings = + new HostedTermsEnvironmentBindingRepository(context.dsl()); + DraftAuthorizationFenceRepository fences = new DraftAuthorizationFenceRepository(context.dsl()); + UUID requestId = UUID.randomUUID(); + UUID changeId = shape == ChangeShape.WRONG_CHANGE_ID ? UUID.randomUUID() : requestId; + PublicationEvidence evidence = publicationEvidence(boundary, catalogs.second(), predecessor); + byte[] request = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence); + HostedTermsEnvironmentBinding[] committed = new HostedTermsEnvironmentBinding[1]; + + context + .transaction() + .executeWithoutResult( + status -> { + bindings.claimPublication(requestId, boundary, request); + HostedTermsEnvironmentBindingRepository.HeadSnapshot head = + bindings.lockHead(boundary); + if (!predecessor.equals(head.current())) { + throw new IllegalStateException("Test predecessor differs from exact binding head"); + } + HostedTermsEnvironmentBinding candidate = + bindings.insertCandidate(UUID.randomUUID(), requestId, evidence, head.current()); + SourceEvidence predecessorSource = predecessor.sourceEvidence(); + SourceEvidence priorCatalogSource = catalogSource(catalogs.first()); + SourceEvidence targetCatalogSource = catalogSource(catalogs.second()); + List expectedSources = + List.of(predecessorSource, priorCatalogSource, targetCatalogSource); + List changedSources = + changedSources(shape, expectedSources, predecessor); + DraftAuthorizationFenceRepository.SourceChange change = + new DraftAuthorizationFenceRepository.SourceChange( + changeId, + changedSources, + HostedTermsEnvironmentBindingEncoding.receipt(candidate)); + if (!fences.requestSourceChange(change) || !fences.sourceMutationPermitted(change)) { + throw new IllegalStateException("Run-owned Draft source fixture did not settle"); + } + bindings.markOwnerSettlementPending(requestId, candidate, change.canonicalBytes()); + bindings.completePublication( + requestId, candidate, change.canonicalBytes(), head.current()); + if (shape != ChangeShape.WAITING) { + fences.markSourceCommitted(change); + } + committed[0] = candidate; + }); + return committed[0]; + } + + private List changedSources( + ChangeShape shape, + List expectedSources, + HostedTermsEnvironmentBinding predecessor) { + List sources = new ArrayList<>(expectedSources); + return switch (shape) { + case EXACT, WAITING, WRONG_CHANGE_ID -> sources; + case WRONG_BOUNDARY -> { + sources.removeIf(source -> source.key().equals(predecessor.sourceEvidence().key())); + sources.add( + new SourceEvidence( + SourceKind.HOSTED_TERMS, + "environment-boundary/wrong-fixture-boundary", + null, + Long.toString(predecessor.sourceVersion()), + null, + null, + HostedTermsEnvironmentBindingEncoding.receipt(predecessor))); + yield sources; + } + case MISSING_PREDECESSOR_CATALOG -> List.of(expectedSources.get(0), expectedSources.get(2)); + case MISSING_TARGET_CATALOG -> List.of(expectedSources.get(0), expectedSources.get(1)); + case EXTRA_SCOPE -> { + sources.add( + new SourceEvidence( + SourceKind.CREATOR_PARTY, + "test-only-extra-scope", + null, + "1", + null, + null, + "synthetic extra source only".getBytes(StandardCharsets.UTF_8))); + yield sources; + } + }; + } + + private SourceEvidence catalogSource(CatalogVersion catalog) { + HostedTermsCatalogVersion version = catalog.version(); + return new SourceEvidence( + SourceKind.HOSTED_TERMS, + version.hostedScopeId().toString(), + Long.toString(version.materialGeneration()), + Long.toString(version.sourceVersion()), + null, + null, + HostedTermsEncoding.catalog(version)); + } + + private PublicationEvidence publicationEvidence( + String boundary, CatalogVersion catalog, HostedTermsEnvironmentBinding predecessor) { + HostedTermsCatalogVersion version = catalog.version(); + return new PublicationEvidence( + boundary, + version.hostedScopeId(), + version.operatorLegalIdentity(), + version.operatorIdentityVersion(), + version.versionId(), + version.sourceVersion(), + "TEST FIXTURE ONLY - not an authenticated publisher", + "TEST FIXTURE ONLY - synthetic publication event", + predecessor == null ? null : predecessor.bindingId(), + predecessor == null ? null : predecessor.sourceVersion()); + } + + private TestContext context() { + String schema = "hosted_terms_fence_" + 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))); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + return context; + } + + private record CatalogVersion(HostedTermsCatalogVersion version) {} + + private record CatalogSources(CatalogVersion first, CatalogVersion second) {} + + private record TestContext( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transaction) {} + + private enum ChangeShape { + EXACT, + WAITING, + WRONG_CHANGE_ID, + WRONG_BOUNDARY, + MISSING_PREDECESSOR_CATALOG, + MISSING_TARGET_CATALOG, + EXTRA_SCOPE + } +} 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 460c8cb80e..ae33bacbc9 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 @@ -16,6 +16,7 @@ import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; @@ -96,13 +97,17 @@ void preV40RetainedPasswordResetFailsTypedAndRollsBackWithoutInventingSource() { var accounts = new AccountRepository(dsl); var resetTokens = new net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository(dsl); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); var manager = new DataSourceTransactionManager(dataSource); var transaction = new TransactionTemplate(manager); var service = new net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl( accounts, - new AccountAuthorityGenerationRepository(dsl), - new AccountAuthorityOutboxRepository(dsl), + generations, + sourceEvidence, + outbox, new net.firedevops.firemud.accountservice.repository .AccountPasswordResetOperationRepository(dsl), new net.firedevops.firemud.accountservice.repository @@ -182,7 +187,7 @@ void preV40RetainedPasswordResetFailsTypedAndRollsBackWithoutInventingSource() { } @Test - void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws Exception { + void freshAccountGenericSecurityEventsRemainNonCurrentWithExactSourceEvidence() throws Exception { TestContext context = newTestContext(); DSLContext dsl = context.dsl(); TransactionTemplate transaction = context.transaction(); @@ -238,45 +243,65 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws account.setEmailVerified(true); transaction.executeWithoutResult(status -> accounts.save(account)); - var changed = + assertThatThrownBy( + () -> + transaction.execute( + status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class) + .hasMessage("Account authority source evidence is unavailable or inconsistent"); + String accountStream = baseline.account().checkpoint().outboxStreamKey(); + var changedState = transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); - assertThat(changed.account().generation()).isEqualTo(3L); - assertThat(changed.account().sourceVersion()).isEqualTo(3L); - assertThat(changed.account().issuanceFence().value()).isEqualTo(3L); - assertThat(changed.account().checkpoint().sequence()).isEqualTo(2L); - assertThat(changed.account().accountSecurityCutoff()).isPresent(); - assertThat(changed.account().accountSecurityCutoff().orElseThrow().accountAuthorityGeneration()) - .isEqualTo("3"); - assertThat(changed.account().accountSecurityCutoff().orElseThrow().outboxSequence()) - .isEqualTo("2"); - AccountEvent passwordReset = + status -> generations.read(AuthorityScope.account(account.getAccountUuid()))); + var changedCheckpoint = + transaction.execute(status -> outbox.readCheckpoint(accountStream).orElseThrow()); + assertThat(changedState.generation()).isEqualTo(3L); + assertThat(changedState.sourceVersion()).isEqualTo(3L); + assertThat(changedState.issuanceFence().value()).isEqualTo(3L); + assertThat(changedState.issuanceFence().sourceVersion()).isEqualTo(3L); + assertThat(changedCheckpoint.outboxSequence()).isEqualTo(2L); + AccountEvent passwordEvent = (AccountEvent) AccountAuthoritySourceEventV1Codec.verify( new String( transaction.execute( - status -> - outbox - .findEvent(changed.account().checkpoint().outboxStreamKey(), 1L) - .orElseThrow() - .payload()), + status -> outbox.findEvent(accountStream, 1L).orElseThrow().payload()), java.nio.charset.StandardCharsets.UTF_8)); - assertThat(passwordReset.mutationKinds()).containsExactly("PASSWORD_RESET"); - assertThat(passwordReset.canonicalJson()).doesNotContain("changed-password-hash-not-for-event"); - AccountEvent latest = + assertThat(passwordEvent.mutationKinds()).containsExactly("PASSWORD_RESET"); + AccountAuthorityOutboxRepository.Event firstEvent = + transaction.execute(status -> outbox.findEvent(accountStream, 1L).orElseThrow()); + assertThat(passwordEvent.outboxStreamKey()).isEqualTo(accountStream); + assertThat(passwordEvent.outboxSequence()).isEqualTo("1"); + assertThat(passwordEvent.eventId()).isEqualTo(firstEvent.eventId()); + assertThat(passwordEvent.eventDigest()).isEqualTo(firstEvent.eventDigest()); + assertThat(passwordEvent.accountAuthorityGeneration()).isEqualTo("2"); + assertThat(passwordEvent.sourceVersion()).isEqualTo("2"); + assertThat(passwordEvent.issuanceFence()).isEqualTo("2"); + assertThat(passwordEvent.canonicalJson()).doesNotContain("changed-password-hash-not-for-event"); + AccountEvent eligibilityEvent = (AccountEvent) AccountAuthoritySourceEventV1Codec.verify( new String( transaction.execute( - status -> - outbox - .findEvent(changed.account().checkpoint().outboxStreamKey(), 2L) - .orElseThrow() - .payload()), + status -> outbox.findEvent(accountStream, 2L).orElseThrow().payload()), java.nio.charset.StandardCharsets.UTF_8)); - assertThat(latest.mutationKinds()).containsExactly("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); - assertThat(latest.accountSecurityCutoff().outboxSequence()).isEqualTo("2"); - assertThat(latest.canonicalJson()).doesNotContain("changed-password-hash-not-for-event"); + assertThat(eligibilityEvent.mutationKinds()).containsExactly("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); + assertThat(eligibilityEvent.outboxStreamKey()).isEqualTo(accountStream); + assertThat(eligibilityEvent.outboxSequence()).isEqualTo("2"); + AccountAuthorityOutboxRepository.Event latestStoredEvent = + transaction.execute(status -> outbox.findEvent(accountStream, 2L).orElseThrow()); + assertThat(eligibilityEvent.eventId()).isEqualTo(latestStoredEvent.eventId()); + assertThat(eligibilityEvent.eventDigest()).isEqualTo(latestStoredEvent.eventDigest()); + assertThat(latestStoredEvent.eventId()).isEqualTo(changedCheckpoint.sourceEventId()); + assertThat(latestStoredEvent.eventDigest()).isEqualTo(changedCheckpoint.sourceEventDigest()); + assertThat(eligibilityEvent.accountAuthorityGeneration()).isEqualTo("3"); + assertThat(eligibilityEvent.sourceVersion()).isEqualTo("3"); + assertThat(eligibilityEvent.issuanceFence()).isEqualTo("3"); + assertThat(eligibilityEvent.accountSecurityCutoff().outboxSequence()).isEqualTo("2"); + assertThat(eligibilityEvent.canonicalJson()) + .doesNotContain("changed-password-hash-not-for-event"); Account rollbackAttempt = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); rollbackAttempt.setPasswordHash("rollback-only-password-hash"); @@ -289,20 +314,30 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("force Account source event rollback"); + assertThatThrownBy( + () -> + transaction.execute( + status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class) + .hasMessage("Account authority source evidence is unavailable or inconsistent"); var afterRollback = transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); + status -> generations.read(AuthorityScope.account(account.getAccountUuid()))); + var checkpointAfterRollback = + transaction.execute(status -> outbox.readCheckpoint(accountStream).orElseThrow()); + assertThat(checkpointAfterRollback).isEqualTo(changedCheckpoint); assertThat( accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow().getLifecycleState()) .isEqualTo(AccountLifecycleState.ACTIVE); - assertThat(afterRollback.account().generation()).isEqualTo(3L); - assertThat(afterRollback.account().issuanceFence().value()).isEqualTo(3L); - assertThat(afterRollback.account().checkpoint().sequence()).isEqualTo(2L); - assertThat(afterRollback.account().accountSecurityCutoff().orElseThrow().outboxSequence()) - .isEqualTo("2"); + assertThat(afterRollback.generation()).isEqualTo(3L); + assertThat(afterRollback.sourceVersion()).isEqualTo(3L); + assertThat(afterRollback.issuanceFence().value()).isEqualTo(3L); + assertThat(afterRollback.issuanceFence().sourceVersion()).isEqualTo(3L); + assertThat(checkpointAfterRollback.outboxSequence()).isEqualTo(2L); Optional rolledBackEvent = - transaction.execute( - status -> outbox.findEvent(changed.account().checkpoint().outboxStreamKey(), 3L)); + transaction.execute(status -> outbox.findEvent(accountStream, 3L)); assertThat(rolledBackEvent).isEmpty(); Account lifecycleUpdate = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); lifecycleUpdate.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); @@ -312,7 +347,10 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws .hasMessageContaining("lifecycle changes are unavailable"); var afterLifecycleUpdate = transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); + status -> generations.read(AuthorityScope.account(account.getAccountUuid()))); + var checkpointAfterLifecycleRejection = + transaction.execute(status -> outbox.readCheckpoint(accountStream).orElseThrow()); + assertThat(checkpointAfterLifecycleRejection).isEqualTo(changedCheckpoint); Account persistedAfterLifecycleRejection = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); assertThat(persistedAfterLifecycleRejection.getLifecycleState()) @@ -321,14 +359,12 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws .isEqualTo(account.getPasswordHash()); assertThat(lifecycleUpdate.getLifecycleState()) .isEqualTo(AccountLifecycleState.SECURITY_LOCKED); - assertThat(afterLifecycleUpdate.account().generation()).isEqualTo(3L); - assertThat(afterLifecycleUpdate.account().issuanceFence().value()).isEqualTo(3L); - assertThat(afterLifecycleUpdate.account().checkpoint().sequence()).isEqualTo(2L); - var absentLifecycleEvent = - transaction.execute( - status -> - outbox.findEvent( - afterLifecycleUpdate.account().checkpoint().outboxStreamKey(), 3L)); + assertThat(afterLifecycleUpdate.generation()).isEqualTo(3L); + assertThat(afterLifecycleUpdate.sourceVersion()).isEqualTo(3L); + assertThat(afterLifecycleUpdate.issuanceFence().value()).isEqualTo(3L); + assertThat(afterLifecycleUpdate.issuanceFence().sourceVersion()).isEqualTo(3L); + assertThat(checkpointAfterLifecycleRejection.outboxSequence()).isEqualTo(2L); + var absentLifecycleEvent = transaction.execute(status -> outbox.findEvent(accountStream, 3L)); assertThat(absentLifecycleEvent).isEmpty(); assertThatThrownBy(() -> accounts.delete(account)) @@ -346,7 +382,7 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws } @Test - void freshAccountWithNullGlobalRoleCanCommitSecurityMutationSourceEvent() { + void freshAccountWithNullGlobalRoleKeepsGenericEventOutOfCurrentness() { TestContext context = newTestContext(); DSLContext dsl = context.dsl(); TransactionTemplate transaction = context.transaction(); @@ -367,22 +403,43 @@ void freshAccountWithNullGlobalRoleCanCommitSecurityMutationSourceEvent() { account.setPasswordHash("changed-null-role-account-password-hash"); transaction.executeWithoutResult(status -> accounts.save(account)); - var changed = + assertThatThrownBy( + () -> + transaction.execute( + status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class) + .hasMessage("Account authority source evidence is unavailable or inconsistent"); + var changedState = transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); - assertThat(changed.account().checkpoint().sequence()).isEqualTo(1L); + status -> generations.read(AuthorityScope.account(account.getAccountUuid()))); + assertThat(changedState.generation()).isEqualTo(2L); + assertThat(changedState.sourceVersion()).isEqualTo(2L); + assertThat(changedState.issuanceFence().value()).isEqualTo(2L); + assertThat(changedState.issuanceFence().sourceVersion()).isEqualTo(2L); + String accountStream = baseline.account().checkpoint().outboxStreamKey(); + var changedCheckpoint = + transaction.execute(status -> outbox.readCheckpoint(accountStream).orElseThrow()); + assertThat(changedCheckpoint.outboxSequence()).isEqualTo(1L); AccountAuthorityOutboxRepository.Event storedEvent = - transaction.execute( - status -> - outbox - .findEvent(changed.account().checkpoint().outboxStreamKey(), 1L) - .orElseThrow()); + transaction.execute(status -> outbox.findEvent(accountStream, 1L).orElseThrow()); + assertThat(storedEvent.eventId()).isEqualTo(changedCheckpoint.sourceEventId()); + assertThat(storedEvent.eventDigest()).isEqualTo(changedCheckpoint.sourceEventDigest()); AccountEvent event = (AccountEvent) AccountAuthoritySourceEventV1Codec.verify( new String(storedEvent.payload(), StandardCharsets.UTF_8)); assertThat(event.mutationKinds()).containsExactly("PASSWORD_RESET"); + assertThat(event.accountId()).isEqualTo(account.getAccountUuid().toString()); + assertThat(event.outboxStreamKey()).isEqualTo(accountStream); + assertThat(event.outboxSequence()).isEqualTo("1"); + assertThat(event.accountAuthorityGeneration()).isEqualTo("2"); + assertThat(event.sourceVersion()).isEqualTo("2"); + assertThat(event.issuanceFence()).isEqualTo("2"); + assertThat(event.eventId()).isEqualTo(storedEvent.eventId()); + assertThat(event.eventDigest()).isEqualTo(storedEvent.eventDigest()); assertThat(event.accountState().globalRole()).isNull(); assertThat(event.canonicalJson()).contains("\"globalRole\":null"); assertThat(event.canonicalJson()).doesNotContain("changed-null-role-account-password-hash"); @@ -545,32 +602,45 @@ void concurrentAccountMutationAndAuthorityReadUseAccountRowBeforeGenerationLocks awaitLockWait(dsl, readerPid, writerPid); releaseWriter.countDown(); writer.get(45, TimeUnit.SECONDS); - var readback = snapshot.get(45, TimeUnit.SECONDS); - assertThat(readback.account().generation()).isEqualTo(2L); - assertThat(readback.account().sourceVersion()).isEqualTo(2L); - assertThat(readback.account().issuanceFence().value()).isEqualTo(2L); - assertThat(readback.account().issuanceFence().sourceVersion()).isEqualTo(2L); - assertThat(readback.account().checkpoint().sequence()).isEqualTo(1L); - AccountAuthorityOutboxRepository.Event committedEvent = + assertThatThrownBy(() -> snapshot.get(45, TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .satisfies( + failure -> { + assertThat(failure.getCause()) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException + .class); + assertThat(failure.getCause()) + .hasMessage("Account authority source evidence is unavailable or inconsistent"); + }); + var committedState = transaction.execute( - status -> - outbox - .findEvent(readback.account().checkpoint().outboxStreamKey(), 1L) - .orElseThrow()); - assertThat(committedEvent.eventId()) - .isEqualTo(readback.account().checkpoint().sourceEventId().orElseThrow()); - assertThat(committedEvent.eventDigest()) - .isEqualTo(readback.account().checkpoint().sourceEventDigest().orElseThrow()); + status -> generations.read(AuthorityScope.account(account.getAccountUuid()))); + assertThat(committedState.generation()).isEqualTo(2L); + assertThat(committedState.sourceVersion()).isEqualTo(2L); + assertThat(committedState.issuanceFence().value()).isEqualTo(2L); + assertThat(committedState.issuanceFence().sourceVersion()).isEqualTo(2L); + String accountStream = "account:auth-authority:v1:account/" + account.getAccountUuid(); + var committedCheckpoint = + transaction.execute(status -> outbox.readCheckpoint(accountStream).orElseThrow()); + assertThat(committedCheckpoint.outboxSequence()).isEqualTo(1L); + AccountAuthorityOutboxRepository.Event committedEvent = + transaction.execute(status -> outbox.findEvent(accountStream, 1L).orElseThrow()); + assertThat(committedEvent.eventId()).isEqualTo(committedCheckpoint.sourceEventId()); + assertThat(committedEvent.eventDigest()).isEqualTo(committedCheckpoint.sourceEventDigest()); AccountEvent event = (AccountEvent) AccountAuthoritySourceEventV1Codec.verify( new String(committedEvent.payload(), StandardCharsets.UTF_8)); assertThat(event.accountId()).isEqualTo(account.getAccountUuid().toString()); + assertThat(event.outboxStreamKey()).isEqualTo(accountStream); assertThat(event.outboxSequence()).isEqualTo("1"); assertThat(event.accountAuthorityGeneration()).isEqualTo("2"); assertThat(event.sourceVersion()).isEqualTo("2"); assertThat(event.issuanceFence()).isEqualTo("2"); assertThat(event.mutationKinds()).containsExactly("PASSWORD_RESET"); + assertThat(event.eventId()).isEqualTo(committedEvent.eventId()); + assertThat(event.eventDigest()).isEqualTo(committedEvent.eventDigest()); } finally { startLockPhase.countDown(); releaseWriter.countDown(); 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 d217a400f0..f4c6db1c7c 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 @@ -116,7 +116,11 @@ void dropTestOwnedSchemas() { COLLISION_MIGRATION_PROOF_SCHEMA, PROFILE_IDENTITY_MIGRATION_PROOF_SCHEMA, GLOBAL_REGISTRATION_MIGRATION_PROOF_SCHEMA, - ACCOUNT_UUID_MIGRATION_PROOF_SCHEMA)) { + ACCOUNT_UUID_MIGRATION_PROOF_SCHEMA, + legacyLifecycleMigrationSchema(AccountLifecycleState.ACTIVE), + legacyLifecycleMigrationSchema(AccountLifecycleState.SECURITY_LOCKED), + legacyLifecycleMigrationSchema(AccountLifecycleState.DEACTIVATED_PENDING_DELETE), + legacyLifecycleMigrationSchema(AccountLifecycleState.DELETED))) { if (!schema.matches("account_[a-z_]+_[a-f0-9]{12}") || !schema.endsWith("_" + SCHEMA_SUFFIX)) { throw new IllegalStateException("Refusing to dispose an unowned PostgreSQL schema"); @@ -603,15 +607,20 @@ void privateRealmGrantRevocationRetainsMonotonicCurrentnessForRevalidation() { DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); AccountRealmAccessGrantRepository grants = new AccountRealmAccessGrantRepository(transactionAwareDsl); + AccountAuthorityGenerationRepository authority = + new AccountAuthorityGenerationRepository(transactionAwareDsl); + AccountAuthorityOutboxRepository outbox = + new AccountAuthorityOutboxRepository(transactionAwareDsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository(transactionAwareDsl, authority, outbox); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transaction = new TransactionTemplate(transactionManager); AccountServiceImpl accountService = new AccountServiceImpl( new AccountRepository(transactionAwareDsl), - new net.firedevops.firemud.accountservice.repository - .AccountAuthorityGenerationRepository(transactionAwareDsl), - new net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository( - transactionAwareDsl), + authority, + sourceEvidence, + outbox, new net.firedevops.firemud.accountservice.repository .AccountPasswordResetOperationRepository(transactionAwareDsl), new net.firedevops.firemud.accountservice.repository @@ -711,6 +720,89 @@ private Account saveInTransaction(Account account) { .execute(status -> repository.save(account))); } + private RetainedAccountFixture retainedAccountAtV39(AccountLifecycleState lifecycleState) { + String migrationSchema = legacyLifecycleMigrationSchema(lifecycleState); + DriverManagerDataSource retainedDataSource = postgres.dataSource(migrationSchema); + Flyway.configure() + .dataSource(retainedDataSource) + .schemas(migrationSchema) + .defaultSchema(migrationSchema) + .placeholders(Map.of("serviceSchema", migrationSchema)) + .locations(MIGRATION_LOCATION) + .target("39") + .load() + .migrate(); + + DSLContext retainedDsl = + DSL.using(new TransactionAwareDataSourceProxy(retainedDataSource), SQLDialect.POSTGRES); + String suffix = UUID.randomUUID().toString(); + Long accountId = + Objects.requireNonNull( + retainedDsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash, role, lifecycle_state) " + + "VALUES (?, ?, ?, 'player', ?) RETURNING id", + "legacy-" + suffix, + suffix.replace("-", "") + "@example.test", + "retained-password-hash", + lifecycleState.storageValue()), + "expected retained pre-source Account row") + .get(0, Long.class); + + Flyway.configure() + .dataSource(retainedDataSource) + .schemas(migrationSchema) + .defaultSchema(migrationSchema) + .placeholders(Map.of("serviceSchema", migrationSchema)) + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + AccountRepository retainedRepository = new AccountRepository(retainedDsl); + Account retainedAccount = retainedRepository.findById(accountId).orElseThrow(); + assertThat(retainedAccount.getLifecycleState()).isEqualTo(lifecycleState); + assertThat(retainedAccount.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + return new RetainedAccountFixture( + retainedDsl, + retainedRepository, + retainedAccount, + new TransactionTemplate(new DataSourceTransactionManager(retainedDataSource))); + } + + private String legacyLifecycleMigrationSchema(AccountLifecycleState lifecycleState) { + return "account_legacy_lifecycle_" + lifecycleState.storageValue() + "_" + SCHEMA_SUFFIX; + } + + private static void assertNoAuthorityBirthEvidence(DSLContext dsl, UUID accountUuid) { + Long accountSourceRecordCount = + dsl.resultQuery( + "SELECT count(*) FROM account_authority_source_records " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class); + Long globalRoleSourceCount = + dsl.resultQuery( + "SELECT count(*) FROM account_global_role_sources WHERE account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class); + Long restrictionBirthCount = + dsl.resultQuery( + "SELECT count(*) FROM account_platform_restriction_births WHERE account_uuid = ?", + accountUuid) + .fetchOne(0, Long.class); + Long authorityEventCount = + dsl.resultQuery( + "SELECT count(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + accountUuid) + .fetchOne(0, Long.class); + + assertThat(accountSourceRecordCount).isZero(); + assertThat(globalRoleSourceCount).isZero(); + assertThat(restrictionBirthCount).isZero(); + assertThat(authorityEventCount).isZero(); + } + @Test void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { JdbcTemplate jdbc = new JdbcTemplate(dataSource); @@ -937,18 +1029,14 @@ private static VerifiedJoinScope joinScope( } @ParameterizedTest - @EnumSource(AccountLifecycleState.class) + @EnumSource(value = AccountLifecycleState.class, mode = EnumSource.Mode.EXCLUDE, names = "ACTIVE") void genericUpdateRejectsLifecycleChangeWithoutMutatingAccountOrAuthorityEvidence( - AccountLifecycleState lifecycleState) { - Account persisted = account("original", "original@example.com", lifecycleState); + AccountLifecycleState requestedLifecycleState) { + Account persisted = account("original", "original@example.com", AccountLifecycleState.ACTIVE); persisted.setPasswordHash("original-password-hash"); Account saved = saveInTransaction(persisted); UUID accountUuid = saved.getAccountUuid(); - AccountLifecycleState requestedLifecycleState = - lifecycleState == AccountLifecycleState.ACTIVE - ? AccountLifecycleState.SECURITY_LOCKED - : AccountLifecycleState.ACTIVE; Account staleUpdate = account("updated", "updated@example.com", requestedLifecycleState); staleUpdate.setPasswordHash("updated-password-hash"); staleUpdate.setId(saved.getId()); @@ -1032,24 +1120,47 @@ void genericUpdateRejectsLifecycleChangeWithoutMutatingAccountOrAuthorityEvidenc @ParameterizedTest @EnumSource(AccountLifecycleState.class) - void genericUpdateAllowsOrdinaryChangesWhenLifecycleMatches( - AccountLifecycleState lifecycleState) { - Account persisted = account("original", "original@example.com", lifecycleState); - Account saved = saveInTransaction(persisted); + void genericUpdateAllowsProfileChangesWhenLifecycleMatches(AccountLifecycleState lifecycleState) { + AccountRepository lifecycleRepository = repository; + TransactionTemplate lifecycleTransaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + DSLContext lifecycleDsl = dsl; + Account saved; + if (lifecycleState == AccountLifecycleState.ACTIVE) { + saved = + saveInTransaction( + account("original", "original@example.com", AccountLifecycleState.ACTIVE)); + } else { + RetainedAccountFixture retained = retainedAccountAtV39(lifecycleState); + lifecycleRepository = retained.repository(); + lifecycleTransaction = retained.transaction(); + lifecycleDsl = retained.dsl(); + saved = retained.account(); + assertNoAuthorityBirthEvidence(lifecycleDsl, saved.getAccountUuid()); + } + AccountRepository selectedRepository = lifecycleRepository; + TransactionTemplate selectedTransaction = lifecycleTransaction; + DSLContext selectedDsl = lifecycleDsl; UUID accountUuid = saved.getAccountUuid(); + String passwordBefore = saved.getPasswordHash(); - Account ordinaryUpdate = account("updated", " Updated@Example.COM ", lifecycleState); - ordinaryUpdate.setPasswordHash("updated-password-hash"); - ordinaryUpdate.setId(saved.getId()); - Account updated = saveInTransaction(ordinaryUpdate); + Account ordinaryUpdate = selectedRepository.findById(saved.getId()).orElseThrow(); + ordinaryUpdate.setUsername("updated"); + ordinaryUpdate.setEmail(" Updated@Example.COM "); + Account updated = + Objects.requireNonNull( + selectedTransaction.execute(status -> selectedRepository.save(ordinaryUpdate))); - Account loaded = repository.findById(saved.getId()).orElseThrow(); + Account loaded = selectedRepository.findById(saved.getId()).orElseThrow(); assertThat(loaded.getUsername()).isEqualTo("updated"); assertThat(loaded.getEmail()).isEqualTo("updated@example.com"); - assertThat(loaded.getPasswordHash()).isEqualTo("updated-password-hash"); + assertThat(loaded.getPasswordHash()).isEqualTo(passwordBefore); assertThat(loaded.getLifecycleState()).isEqualTo(lifecycleState); assertThat(updated.getAccountUuid()).isEqualTo(accountUuid); assertThat(updated.getLifecycleState()).isEqualTo(lifecycleState); + if (lifecycleState != AccountLifecycleState.ACTIVE) { + assertNoAuthorityBirthEvidence(selectedDsl, accountUuid); + } } @Test @@ -2076,4 +2187,10 @@ private Account account(String username, String email, AccountLifecycleState lif private String jsonRow(String query, Object... bindings) { return Objects.requireNonNull(dsl.fetchOne(query, bindings)).get(0, String.class); } + + private record RetainedAccountFixture( + DSLContext dsl, + AccountRepository repository, + Account account, + TransactionTemplate transaction) {} } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java new file mode 100644 index 0000000000..37e1cfda6f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java @@ -0,0 +1,357 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.HexFormat; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.PasswordResetToken; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountLogoutAllAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.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.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * PostgreSQL proof for the closed reset/logout source paths and their Account SQL guards. + * + *

Token bindings below are synthetic test inputs to unwired owner primitives. This proves only + * Account-owned source/receipt consistency; it is not external caller-authentication evidence or + * proof that either primitive is activated by an API. + */ +class AccountSecuritySourceOwnerGuardPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "acct_sec_owner_guard"; + private static final String TOKEN_PROFILE = "control-ui"; + private static final HexFormat HEX = HexFormat.of(); + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void configureDatabase() { + POSTGRES.start(); + } + + @AfterAll + static void stopOwnedContainer() { + POSTGRES.stop(); + } + + @Test + void closedResetAndLogoutEventsPassExactGuardsAndRejectUnbackedMutations() { + TestContext context = newTestContext(); + DSLContext dsl = context.dsl(); + TransactionTemplate transaction = context.transaction(); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountPasswordResetOperationRepository resetOperations = + new AccountPasswordResetOperationRepository(dsl); + AccountLogoutAllOperationRepository logoutOperations = + new AccountLogoutAllOperationRepository(dsl); + AccountSecurityStateOperationRepository securityOperations = + new AccountSecurityStateOperationRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + AccountRepository accounts = new AccountRepository(dsl, sources); + PasswordResetTokenRepository tokens = new PasswordResetTokenRepository(dsl); + AccountPasswordResetDraftSourceChangeRepository resetSourceChanges = + new AccountPasswordResetDraftSourceChangeRepository(dsl); + + Seed seed = seedAccountAndResetToken(transaction, accounts, tokens); + AccountServiceImpl passwordResetService = + newPasswordResetService( + accounts, + generations, + sources, + outbox, + resetOperations, + logoutOperations, + securityOperations, + resetSourceChanges, + tokens, + context); + + passwordResetService.completePasswordReset( + new CompletePasswordResetRequest(seed.rawResetToken(), "test replacement password")); + + Account afterReset = accounts.findByAccountUuid(seed.account().getAccountUuid()).orElseThrow(); + PasswordResetReceipt resetReceipt = + transaction.execute( + status -> + resetOperations.findByTokenHash(sha256Hex(seed.rawResetToken())).orElseThrow()); + ScopeState resetState = readState(transaction, generations, seed.account().getAccountUuid()); + CurrentSourceEvidence resetEvidence = + transaction.execute( + status -> + sources.readCurrentAccountSource(seed.account().getAccountUuid(), resetState)); + var resetEvent = + transaction.execute( + status -> + outbox + .findEvent(resetReceipt.outboxStreamKey(), resetReceipt.outboxSequence()) + .orElseThrow()); + var decodedReset = + PasswordResetAuthorityEventV1Codec.verify( + new String(resetEvent.payload(), StandardCharsets.UTF_8)); + + assertThat(decodedReset.accountId()).isEqualTo(seed.account().getAccountUuid().toString()); + assertThat(decodedReset.accountAuthorityGeneration()).isEqualTo("2"); + assertThat(resetReceipt.accountUuid()).isEqualTo(seed.account().getAccountUuid()); + assertThat(resetReceipt.outboxSequence()).isEqualTo(1L); + assertThat(resetReceipt.eventId()).isEqualTo(resetEvent.eventId()); + assertThat(resetReceipt.eventDigest()).isEqualTo(resetEvent.eventDigest()); + assertThat(resetReceipt.passwordVerifierDigest()) + .isEqualTo(sha256Hex(afterReset.getPasswordHash())); + assertThat(resetEvidence.checkpoint().sequence()).isEqualTo(1L); + assertThat(afterReset.getPasswordHash()).startsWith("$argon2"); + + assertDatabaseWriteRejected( + () -> + dsl.execute( + "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", + "unbacked-password-verifier", + seed.account().getAccountUuid())); + assertThat( + accounts + .findByAccountUuid(seed.account().getAccountUuid()) + .orElseThrow() + .getPasswordHash()) + .isEqualTo(afterReset.getPasswordHash()); + + assertDatabaseWriteRejected( + () -> + dsl.execute( + "UPDATE account_password_reset_operation_receipts " + + "SET request_digest = request_digest WHERE token_hash = ?", + HEX.parseHex(resetReceipt.tokenHash()))); + assertDatabaseWriteRejected( + () -> + dsl.execute( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = issuance_fence + 1, source_version = source_version + 1 " + + "WHERE account_uuid = ?", + seed.account().getAccountUuid())); + assertThat(readState(transaction, generations, seed.account().getAccountUuid())) + .isEqualTo(resetState); + + String syntheticPresentedTokenHash = sha256Hex("test-only presented logout token"); + UUID logoutRequestId = UUID.randomUUID(); + String logoutRequestDigest = + AccountLogoutRequestDigest.accountLogoutAll( + seed.account().getAccountUuid(), TOKEN_PROFILE, syntheticPresentedTokenHash); + Account persistedAccount = accounts.findById(seed.account().getId()).orElseThrow(); + ScopeState expectedLogoutState = + readState(transaction, generations, seed.account().getAccountUuid()); + AccountLogoutAllAuthorityEventProducer logoutProducer = + new AccountLogoutAllAuthorityEventProducer( + accounts, + generations, + sources, + outbox, + logoutOperations, + new AccountAuthoritySourceEventReadback( + outbox, resetOperations, logoutOperations, securityOperations), + dsl, + context.transactionManager()); + + assertThat( + logoutProducer.commit( + logoutRequestId, + 1, + logoutRequestDigest, + TOKEN_PROFILE, + syntheticPresentedTokenHash, + persistedAccount, + expectedLogoutState)) + .isEqualTo(AccountLogoutAllAuthorityEventProducer.LogoutAllResult.LOGOUT_ALL_COMMITTED); + + var logoutReceipt = + transaction.execute( + status -> logoutOperations.findByRequestId(logoutRequestId).orElseThrow()); + var logoutEvent = + transaction.execute( + status -> + outbox + .findEvent(logoutReceipt.outboxStreamKey(), logoutReceipt.outboxSequence()) + .orElseThrow()); + var decodedLogout = + AccountLogoutAllAuthorityEventV1Codec.verify( + new String(logoutEvent.payload(), StandardCharsets.UTF_8)); + ScopeState finalState = readState(transaction, generations, seed.account().getAccountUuid()); + CurrentSourceEvidence finalEvidence = + transaction.execute( + status -> + sources.readCurrentAccountSource(seed.account().getAccountUuid(), finalState)); + + assertThat(decodedLogout.accountId()).isEqualTo(seed.account().getAccountUuid().toString()); + assertThat(decodedLogout.accountAuthorityGeneration()).isEqualTo("3"); + assertThat(logoutReceipt.outboxSequence()).isEqualTo(2L); + assertThat(logoutReceipt.accountUuid()).isEqualTo(seed.account().getAccountUuid()); + assertThat(logoutReceipt.eventId()).isEqualTo(logoutEvent.eventId()); + assertThat(logoutReceipt.eventDigest()).isEqualTo(logoutEvent.eventDigest()); + assertThat(finalEvidence.checkpoint().sequence()).isEqualTo(2L); + assertThat(finalState.generation()).isEqualTo(3L); + assertThat(finalState.sourceVersion()).isEqualTo(3L); + assertThat(finalState.issuanceFence().value()).isEqualTo(3L); + + assertDatabaseWriteRejected( + () -> + dsl.execute( + "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", + "logout-is-not-password-reset-authority", + seed.account().getAccountUuid())); + assertThat( + accounts + .findByAccountUuid(seed.account().getAccountUuid()) + .orElseThrow() + .getPasswordHash()) + .isEqualTo(afterReset.getPasswordHash()); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + return new TestContext(dsl, new TransactionTemplate(transactionManager), transactionManager); + } + + private Seed seedAccountAndResetToken( + TransactionTemplate transaction, + AccountRepository accounts, + PasswordResetTokenRepository tokens) { + return transaction.execute( + status -> { + String suffix = UUID.randomUUID().toString(); + Account account = new Account(); + account.setUsername("source-guard-" + suffix); + account.setEmail("source-guard-" + suffix + "@example.test"); + account.setPasswordHash("initial-password-verifier-" + suffix); + account.setRole("player"); + Account saved = accounts.save(account); + + String rawToken = "reset-token-" + suffix; + PasswordResetToken token = new PasswordResetToken(); + token.setAccount(saved); + token.setToken(rawToken); + token.setExpiresAt(LocalDateTime.now().plusHours(2)); + tokens.save(token); + return new Seed(saved, rawToken); + }); + } + + private AccountServiceImpl newPasswordResetService( + AccountRepository accounts, + AccountAuthorityGenerationRepository generations, + AccountAuthoritySourceEvidenceRepository sources, + AccountAuthorityOutboxRepository outbox, + AccountPasswordResetOperationRepository resetOperations, + AccountLogoutAllOperationRepository logoutOperations, + AccountSecurityStateOperationRepository securityOperations, + AccountPasswordResetDraftSourceChangeRepository resetSourceChanges, + PasswordResetTokenRepository tokens, + TestContext context) { + return new AccountServiceImpl( + accounts, + generations, + sources, + outbox, + resetOperations, + logoutOperations, + securityOperations, + resetSourceChanges, + 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 + tokens, + null, // email verification tokens + null, // notifications + null, + null, + null, + null, + null, + null, + null, + null, + context.transactionManager()); + } + + private ScopeState readState( + TransactionTemplate transaction, + AccountAuthorityGenerationRepository generations, + UUID accountUuid) { + return transaction.execute(status -> generations.read(AuthorityScope.account(accountUuid))); + } + + private static void assertDatabaseWriteRejected(Runnable write) { + assertThatThrownBy(write::run).isInstanceOf(DataAccessException.class); + } + + private static String sha256Hex(String value) { + try { + return HEX.formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private record Seed(Account account, String rawResetToken) {} + + private record TestContext( + DSLContext dsl, + TransactionTemplate transaction, + DataSourceTransactionManager transactionManager) {} +} 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 index 075d0d4ca9..42e1aea56d 100644 --- 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 @@ -61,25 +61,25 @@ static void stopPostgres() { } @Test - void freshInstallAppliesEveryForwardMigrationThroughV89() { + void freshInstallAppliesEveryForwardMigrationThroughV97() { TestContext context = context(null); assertThat( context .dsl() .resultQuery( - "SELECT version FROM flyway_schema_history WHERE success " - + "ORDER BY installed_rank DESC LIMIT 1") + "SELECT version FROM flyway_schema_history " + + "WHERE success AND version = '97'") .fetchOne(0, String.class)) - .isEqualTo("89"); + .isEqualTo("97"); assertThat( context .dsl() .resultQuery( "SELECT count(*) FROM flyway_schema_history " - + "WHERE version BETWEEN '74' AND '89' AND success") + + "WHERE version::numeric BETWEEN 74 AND 97 AND success") .fetchOne(0, Long.class)) - .isEqualTo(16L); + .isEqualTo(24L); for (String relation : new String[] { @@ -98,7 +98,10 @@ void freshInstallAppliesEveryForwardMigrationThroughV89() { "account_hosted_terms_catalog_versions", "account_hosted_terms_environment_binding_heads", "account_logout_all_draft_source_changes", - "account_password_reset_draft_source_changes" + "account_password_reset_draft_source_changes", + "account_game_logic_intake_source_read_reservations", + "account_game_logic_intake_source_read_sources", + "account_game_logic_intake_source_read_aborts" }) { assertThat( context @@ -114,7 +117,11 @@ void freshInstallAppliesEveryForwardMigrationThroughV89() { "account_draft_authorization_is_settled(uuid)", "account_creator_party_initial_receipt_guard()", "account_hosted_terms_acceptance_insert_guard()", - "account_password_reset_draft_link_guard()" + "account_password_reset_draft_link_guard()", + "account_game_logic_intake_source_read_is_pending(uuid)", + "account_game_logic_intake_source_read_complete_guard()", + "account_game_logic_intake_source_read_source_guard()", + "account_game_logic_intake_source_read_terminal_guard()" }) { assertThat( context @@ -590,7 +597,7 @@ private static FreshTenantCreatorEvidence creatorEvidence(UUID accountUuid) { private static Account account(String role) { String suffix = UUID.randomUUID().toString(); Account account = new Account(); - account.setUsername("forward-source-" + suffix); + account.setUsername("forward-source-" + suffix.replace("-", "")); account.setEmail(suffix.replace("-", "") + "@example.test"); account.setPasswordHash("test-only-password-hash"); account.setRole(role); 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 index fd87ec9478..6cf405f176 100644 --- 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 @@ -51,7 +51,7 @@ void retainedPreV40AccountAtV73GetsSerializationLocksButNoInventedAuthoritySourc "INSERT INTO accounts (username, email, password_hash, role) " + "VALUES (?, ?, ?, 'player') RETURNING id", Long.class, - "retained-source-" + suffix, + "retained-source-" + suffix.replace("-", ""), suffix + "@example.test", "retained-password-" + suffix)); UUID accountUuid = @@ -85,6 +85,28 @@ void retainedPreV40AccountAtV73GetsSerializationLocksButNoInventedAuthoritySourc .load() .migrate(); + assertThat( + jdbc.queryForObject( + "SELECT version FROM flyway_schema_history WHERE success AND version = '97'", + String.class)) + .isEqualTo("97"); + for (String relation : + new String[] { + "account_game_logic_intake_source_read_reservations", + "account_game_logic_intake_source_read_sources", + "account_game_logic_intake_source_read_aborts" + }) { + assertThat(jdbc.queryForObject("SELECT to_regclass(?)::TEXT", String.class, relation)) + .as("forward relation %s", relation) + .isNotNull(); + } + assertThat( + jdbc.queryForObject( + "SELECT to_regprocedure(?)::TEXT", + String.class, + "account_game_logic_intake_source_read_is_pending(uuid)")) + .isNotNull(); + assertThat( jdbc.queryForObject( "SELECT count(*) FROM account_authority_source_records " diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepositoryTest.java new file mode 100644 index 0000000000..241f3a8ca1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepositoryTest.java @@ -0,0 +1,99 @@ +package unit.net.firedevops.firemud.accountservice.hostedterms; + +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.doReturn; +import static org.mockito.Mockito.mock; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class HostedTermsRepositoryTest { + @Test + void acceptanceReadbackRejectsAffirmativeActionEvidenceDigestMismatch() { + byte[] actionEvidence = new byte[] {1, 2, 3}; + HostedTermsRepository repository = repository(row(actionEvidence, "sha256:" + "a".repeat(64))); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> repository.readAcceptanceByRequest(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("digest"); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void acceptanceReadbackAcceptsTheStoredAffirmativeActionDigest() { + byte[] actionEvidence = new byte[] {1, 2, 3}; + String actionDigest = digest(actionEvidence); + HostedTermsRepository repository = repository(row(actionEvidence, actionDigest)); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + var acceptance = repository.readAcceptanceByRequest(UUID.randomUUID()).orElseThrow(); + assertThat(acceptance.affirmativeActionEvidence()).containsExactly(actionEvidence); + assertThat(acceptance.affirmativeActionDigest()).isEqualTo(actionDigest); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private HostedTermsRepository repository(Record acceptanceRow) { + DSLContext dsl = mock(DSLContext.class); + doReturn(acceptanceRow).when(dsl).fetchOne(anyString(), any(Object[].class)); + return new HostedTermsRepository(dsl); + } + + private Record row(byte[] actionEvidence, String actionDigest) { + byte[] partyEvidence = new byte[] {4, 5, 6}; + Map values = new HashMap<>(); + values.put("evidence_id", UUID.randomUUID()); + values.put("action_request_id", UUID.randomUUID()); + values.put("creator_party_id", UUID.randomUUID()); + values.put("account_uuid", UUID.randomUUID()); + values.put("hosted_scope_id", UUID.randomUUID()); + values.put("terms_version_id", UUID.randomUUID()); + values.put("document_digest", "sha256:" + "b".repeat(64)); + values.put("operator_legal_identity", "FireMUD Hosting LLC"); + values.put("operator_identity_version", 1L); + values.put("source_version", 2L); + values.put("material_generation", 1L); + values.put("individual_party_source", partyEvidence); + values.put("individual_party_source_digest", digest(partyEvidence)); + values.put("affirmative_action_evidence", actionEvidence); + values.put("affirmative_action_digest", actionDigest); + values.put("accepted_at", OffsetDateTime.now()); + return mock( + Record.class, + invocation -> { + if (invocation.getMethod().getName().equals("get") + && invocation.getArguments().length > 0) { + return values.get(invocation.getArgument(0)); + } + return null; + }); + } + + private String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new AssertionError("SHA-256 must be available", impossible); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java index 320abd7d6a..51212ab6c7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java @@ -14,16 +14,19 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; 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; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; import org.jooq.DSLContext; import org.jooq.Record; import org.junit.jupiter.api.Test; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountAuthoritySourceEvidenceRepositoryTest { private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); @@ -130,6 +133,50 @@ issuer, account, new IssuanceFence(UUID.randomUUID(), 1L, 1L))) .isInstanceOf(IllegalArgumentException.class); } + @Test + void accountScopeEvidenceAllowsIssuanceFenceToAdvanceIndependently() { + String stream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + var current = + new AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + 4L, + 4L, + new IssuanceFence(ACCOUNT_ID, 10L, 13L), + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + stream, + 3L, + Optional.of("account-event-3"), + Optional.of("sha256:" + "c".repeat(64))), + Optional.of(new AccountSecurityCutoff("4", stream, "3")), + "ACCOUNT_REPOSITORY_INSERT", + 9L, + "ACCOUNT_REPOSITORY_INSERT", + 1L, + 1L); + + assertThat(current.generation()).isEqualTo(4L); + assertThat(current.issuanceFence().value()).isEqualTo(10L); + assertThat(current.issuanceFence().sourceVersion()).isEqualTo(13L); + } + + @Test + void retainedReceiptEvidenceKeepsIndependentPositiveFenceCoordinates() { + String stream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + var evidence = + new net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback + .RetainedEventEvidence( + stream, 3L, 4L, 4L, 10L, 13L, new AccountSecurityCutoff("4", stream, "3")); + + assertThat(evidence.issuanceFence()).isEqualTo(10L); + assertThat(evidence.issuanceFenceSourceVersion()).isEqualTo(13L); + assertThatThrownBy( + () -> + new net.firedevops.firemud.accountservice.service + .AccountAuthoritySourceEventReadback.RetainedEventEvidence( + stream, 3L, 4L, 4L, 0L, 13L, new AccountSecurityCutoff("4", stream, "3"))) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void issuerEnrollmentRequiresValidIdentityAndMandatoryOwnerTransaction() throws ReflectiveOperationException { @@ -142,6 +189,31 @@ void issuerEnrollmentRequiresValidIdentityAndMandatoryOwnerTransaction() verifyNoInteractions(dsl); } + @Test + void currentAccountSourceReadRequiresAWritableMandatoryOwnerTransaction() + throws ReflectiveOperationException { + assertMandatory("readCurrentAccountSource", UUID.class, ScopeState.class); + ScopeState expected = + new ScopeState( + AuthorityScope.account(ACCOUNT_ID), 1L, 1L, new IssuanceFence(ACCOUNT_ID, 1L, 1L)); + + assertThatThrownBy(() -> repository.readCurrentAccountSource(ACCOUNT_ID, expected)) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + verifyNoInteractions(dsl); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy(() -> repository.readCurrentAccountSource(ACCOUNT_ID, expected)) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + } finally { + TransactionSynchronizationManager.clear(); + } + verifyNoInteractions(dsl); + } + @Test void sourceEvidenceIsRestrictedToIssuerAndAccountScopes() { assertThat(ScopeKind.valueOf("ISSUER")).isEqualTo(ScopeKind.ISSUER); @@ -382,11 +454,11 @@ private static AccountAuthoritySourceEvidenceRepository.SourceCheckpoint zeroChe "account:auth-authority:v1:" + suffix, 0L, Optional.empty(), Optional.empty()); } - private static void assertMandatory(String methodName, Class parameterType) + private static void assertMandatory(String methodName, Class... parameterTypes) throws ReflectiveOperationException { Transactional transactional = AccountAuthoritySourceEvidenceRepository.class - .getMethod(methodName, parameterType) + .getMethod(methodName, parameterTypes) .getAnnotation(Transactional.class); assertThat(transactional).isNotNull(); assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java index b3d246fc37..4d90039bab 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java @@ -1,5 +1,6 @@ package unit.net.firedevops.firemud.accountservice.repository; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doReturn; @@ -17,6 +18,9 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountRepositoryTest { @Test @@ -59,4 +63,52 @@ void genericSaveRejectsLifecycleChangeBeforeUpdateOrSourceEvidenceMutation() { verify(dsl, never()).update(Tables.ACCOUNTS); verifyNoInteractions(sourceEvidence); } + + @Test + void freshNonActiveAccountIsRejectedBeforeInsertOrSourceInitialization() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountRepository repository = new AccountRepository(dsl, sourceEvidence); + Account account = new Account(); + account.setEmail("inactive-fresh@example.test"); + account.setLifecycleState(AccountLifecycleState.DEACTIVATED_PENDING_DELETE); + + assertThatThrownBy(() -> repository.save(account)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Fresh Accounts must be created in the ACTIVE lifecycle state"); + + verifyNoInteractions(dsl, sourceEvidence); + } + + @Test + void findByIdForUpdateRequiresAnActiveWritableOwnerTransaction() + throws ReflectiveOperationException { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountRepository repository = new AccountRepository(dsl, sourceEvidence); + + assertThatThrownBy(() -> repository.findByIdForUpdate(42L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active writable owner transaction"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy(() -> repository.findByIdForUpdate(42L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active writable owner transaction"); + } finally { + TransactionSynchronizationManager.clear(); + } + + Transactional transactional = + AccountRepository.class + .getMethod("findByIdForUpdate", Long.class) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + verifyNoInteractions(dsl, sourceEvidence); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java new file mode 100644 index 0000000000..e37cf0ac83 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java @@ -0,0 +1,67 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +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.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.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import org.junit.jupiter.api.Test; + +class AccountAuthoritySourceEventReadbackTest { + @Test + void unsupportedGenericAccountEventMapsToTypedUnavailableEvidence() { + UUID accountUuid = UUID.fromString("11111111-1111-4111-8111-111111111111"); + String stream = "account:auth-authority:v1:account/" + accountUuid; + String eventId = "generic-account-event-1"; + String eventDigest = "sha256:" + "c".repeat(64); + Event event = + new Event( + stream, + "generic-account-request-1", + 1L, + eventId, + eventDigest, + "{\"schemaVersion\":\"account-auth-authority-source-event/v1\"}" + .getBytes(StandardCharsets.UTF_8)); + AccountAuthorityOutboxRepository outbox = mock(AccountAuthorityOutboxRepository.class); + AccountPasswordResetOperationRepository passwordResets = + mock(AccountPasswordResetOperationRepository.class); + AccountLogoutAllOperationRepository logoutAll = mock(AccountLogoutAllOperationRepository.class); + AccountSecurityStateOperationRepository securityState = + mock(AccountSecurityStateOperationRepository.class); + when(outbox.readCheckpoint(stream)) + .thenReturn(Optional.of(new Checkpoint(stream, 1L, eventId, eventDigest))); + when(outbox.findEvent(stream, 1L)).thenReturn(Optional.of(event)); + var readback = + new AccountAuthoritySourceEventReadback(outbox, passwordResets, logoutAll, securityState); + Account account = new Account(); + account.setId(42L); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(42L); + ScopeState current = + new ScopeState( + AuthorityScope.account(accountUuid), 2L, 2L, new IssuanceFence(accountUuid, 5L, 8L)); + + assertThatThrownBy(() -> readback.requireCurrentLatest(account, current)) + .isExactlyInstanceOf(SourceEvidenceUnavailableException.class); + + verifyNoInteractions(passwordResets, logoutAll, securityState); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java index 3b4e032e55..06bc3dd11e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java @@ -11,6 +11,7 @@ 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.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; @@ -188,6 +189,7 @@ private AccountLogoutAllAuthorityEventProducer newProducer(Collaborators collabo return new AccountLogoutAllAuthorityEventProducer( collaborators.accountRepository(), collaborators.generationRepository(), + collaborators.sourceEvidence(), collaborators.outboxRepository(), collaborators.logoutAllRepository(), readback, @@ -207,6 +209,7 @@ private Account account() { private record Collaborators( AccountRepository accountRepository, AccountAuthorityGenerationRepository generationRepository, + AccountAuthoritySourceEvidenceRepository sourceEvidence, AccountAuthorityOutboxRepository outboxRepository, AccountPasswordResetOperationRepository passwordResetRepository, AccountLogoutAllOperationRepository logoutAllRepository, @@ -217,6 +220,7 @@ private Collaborators() { this( mock(AccountRepository.class), mock(AccountAuthorityGenerationRepository.class), + mock(AccountAuthoritySourceEvidenceRepository.class), mock(AccountAuthorityOutboxRepository.class), mock(AccountPasswordResetOperationRepository.class), mock(AccountLogoutAllOperationRepository.class), @@ -229,6 +233,7 @@ private void verifyUnused() { verifyNoInteractions( accountRepository, generationRepository, + sourceEvidence, outboxRepository, passwordResetRepository, logoutAllRepository, 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 f8ac0774ca..d02e361f69 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 @@ -54,6 +54,7 @@ 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.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; @@ -104,6 +105,7 @@ class AccountServiceImplTest { "a741a4b8-a2cb-405e-a330-8fbf3dfb841f"; @Mock private AccountRepository accountRepository; @Mock private AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; + @Mock private AccountAuthoritySourceEvidenceRepository accountAuthoritySourceEvidenceRepository; @Mock private AccountAuthorityOutboxRepository accountAuthorityOutboxRepository; @Mock private AccountPasswordResetOperationRepository accountPasswordResetOperationRepository; @Mock private AccountLogoutAllOperationRepository accountLogoutAllOperationRepository; @@ -224,6 +226,7 @@ void setup() { new AccountServiceImpl( accountRepository, accountAuthorityGenerationRepository, + accountAuthoritySourceEvidenceRepository, accountAuthorityOutboxRepository, accountPasswordResetOperationRepository, accountLogoutAllOperationRepository, @@ -2219,6 +2222,7 @@ void listBootstrapWorldsDoesNotMaskUnexpectedJwtParserRuntimeFailure() { new AccountServiceImpl( accountRepository, accountAuthorityGenerationRepository, + accountAuthoritySourceEvidenceRepository, accountAuthorityOutboxRepository, accountPasswordResetOperationRepository, accountLogoutAllOperationRepository, @@ -5764,6 +5768,167 @@ void missingRetainedSourceDeniesPasswordResetBeforeTokenConsumption() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString()); } + @Test + void passwordResetIssuanceFenceOverflowStopsBeforeTokenPasswordOrEventMutation() { + UUID accountUuid = UUID.randomUUID(); + var account = new Account(); + account.setId(2L); + account.setAccountUuid(accountUuid); + 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("overflow-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()); + var accountScope = + net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository + .AuthorityScope.account(accountUuid); + when(accountAuthorityGenerationRepository.read(accountScope)) + .thenReturn( + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.ScopeState( + accountScope, + 1L, + 1L, + new net.firedevops.firemud.accountservice.repository + .AccountAuthorityGenerationRepository.IssuanceFence( + accountUuid, Long.MAX_VALUE, 1L))); + when(accountAuthorityOutboxRepository.readCheckpoint(org.mockito.ArgumentMatchers.anyString())) + .thenReturn(Optional.empty()); + + org.jooq.DSLContext dsl = org.mockito.Mockito.mock(org.jooq.DSLContext.class); + var sourceChanges = new AccountPasswordResetDraftSourceChangeRepository(dsl); + when(accountPasswordResetDraftSourceChangeRepository.participate( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> + sourceChanges.participate( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3), + invocation.getArgument(4), + invocation.getArgument(5), + invocation.getArgument(6), + invocation.getArgument(7))); + + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + try { + assertThrows( + ArithmeticException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + token.getToken(), "overflow-password"))); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager.clear(); + } + + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .consumeIfUnexpired(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .deleteExactAfterSourceAbort( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .updatePasswordHashForLockedAccount( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountPasswordResetOperationRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountAuthorityOutboxRepository, org.mockito.Mockito.never()) + .append( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(byte[].class)); + org.mockito.Mockito.verify(dsl, org.mockito.Mockito.never()) + .execute( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(Object[].class)); + } + + @Test + void abortedPasswordResetRetryReturnsInvalidTokenWithoutReplayingMutation() { + UUID accountUuid = UUID.randomUUID(); + var account = new Account(); + account.setId(2L); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(2L); + account.setPasswordHash("original-password-hash"); + var abortedIntent = + org.mockito.Mockito.mock(AccountPasswordResetDraftSourceChangeRepository.Intent.class); + when(accountPasswordResetOperationRepository.findByTokenHash( + org.mockito.ArgumentMatchers.anyString())) + .thenReturn(Optional.empty()); + when(accountPasswordResetDraftSourceChangeRepository.findAccountIdByTokenHash( + org.mockito.ArgumentMatchers.anyString())) + .thenReturn(Optional.of(account.getId())); + when(accountRepository.findByIdForUpdate(account.getId())).thenReturn(Optional.of(account)); + when(accountPasswordResetDraftSourceChangeRepository.findByTokenHash( + org.mockito.ArgumentMatchers.anyString())) + .thenReturn(Optional.of(abortedIntent)); + when(abortedIntent.accountId()).thenReturn(account.getId()); + when(abortedIntent.accountUuid()).thenReturn(accountUuid); + when(abortedIntent.status()).thenReturn("SOURCE_ABORTED"); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "aborted-reset-token", "retry-password"))); + + assertEquals("Invalid token", error.getMessage()); + verifyNoInteractions(accountAuthorityGenerationRepository, accountAuthorityOutboxRepository); + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .findByToken(org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .consumeIfUnexpired(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(passwordResetTokenRepository, org.mockito.Mockito.never()) + .deleteExactAfterSourceAbort( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify( + accountPasswordResetDraftSourceChangeRepository, org.mockito.Mockito.never()) + .participate( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .updatePasswordHashForLockedAccount( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString()); + } + @Test void requestPasswordResetUnknownEmailIsNeutral() { when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); From 90396376da49e5f2dacf7004f5b53fc438adf21f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:22:21 +1300 Subject: [PATCH 03/10] Restore disclosure journal persistence and correct PostgreSQL fixtures --- .../account-service/runtime-and-data.md | 6 +- .../player-access-and-session.md | 10 +- ...count_hosted_terms_disclosure_handoffs.sql | 157 +++++++ ...horityProducerPostgresIntegrationTest.java | 3 +- .../AccountRepositoryIntegrationTest.java | 13 +- ...wardMigrationsPostgresIntegrationTest.java | 392 +++++++++++++++++- 6 files changed, 562 insertions(+), 19 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 22be237528..f384d01b10 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,9 +8,9 @@ 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; 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. V90–V97 add Account persistence relations and guards for committed control-UI issuance, selected-publication authorization/settlement, Game Logic intake settlement, and preliminary Game Logic source-read reservations. These DDL stages establish source-writer fence relationships; they do not activate owner writers or prove a positive owner receipt. 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 remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. 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 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. V90–V97 add persistence relations and guards for source-currentness work across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds durable hosted-terms disclosure handoff and immutable source-evidence relations with database transition guards. These DDL stages establish persistence and source-writer fence relationships; they do not activate owner writers, legal authority verification, dispatch, or consumers. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion 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 remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Exact physical and local proof limits are recorded in 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. -Proof qualification: the counts in the preceding paragraph are historical local results at `1f5045fe0a8e66f33f0e6c046f77f099e749c45b`. Its hosted Account physical suite ran 88 cases and reported 26 failures, leading to the current corrections. The corrected batch passed the consolidated Account check, including 636 unit cases with no failures or skips, production and integration-test compilation, formatting, Checkstyle and SpotBugs; all 245 Common Platform Core unit cases remain green with their unchanged outputs reused. The local integration run reports 85 cases: two executed and 83 skipped without Docker. The corrected migration set passes `generateJooq`, and documentation checks passed 10,464 links and 549 Markdown files. Physical fresh-install/V73-upgrade PostgreSQL proof remains pending on corrected-head CI; skipped cases and synthetic owner inputs do not prove activation or playable closure. +Proof qualification: at `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2`, physical PostgreSQL execution established partial evidence: fresh installation through V97, V73 upgrade, and selected V80/V86 cases passed, while other cases failed. V98 and its disclosure persistence proof remain unrun. See the tracker for exact counts, failures, and local results; this evidence does not establish activation or playable closure. 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. @@ -28,7 +28,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. -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 Draft fence references for `account_hosted_terms_disclosure_handoffs` and `account_hosted_terms_disclosure_sources` have no donor schema or canonical implemented journal in the migration history; reserve, claim, and publication paths requiring hosted-terms disclosure checks remain unavailable; this does not disable source-fence paths that do not involve hosted terms or establish activation. 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. +Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion; no Account writer, external observer, authenticated legal publication verifier, dispatch RPC, consumer, registry/runtime binding, creator UI, or Game Design evidence binding is active. Reserve, claim, and publication paths that require hosted-terms disclosure checks remain unavailable; unrelated source-fence paths are unaffected. 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. 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 1bd6e7798a..197406b389 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,9 +6,9 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -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). +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. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. 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. The 7a physical and local proof scopes, failures, and V98 limitation are detailed below and 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. Hosted-terms acceptance, 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). -Proof qualification for the Account source/currentness cut: the earlier local results above belong to `1f5045fe0a8e66f33f0e6c046f77f099e749c45b`, whose hosted Account physical suite ran 88 cases with 26 failures. The corrected batch passes the consolidated Account check with 636 unit cases, compilation and static analysis, while all 245 unchanged Common unit cases remain green. Its local integration run executed two cases and skipped 83 without Docker; physical fresh-install/V73-upgrade proof remains pending on corrected-head CI. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for exact proof scope and limitations. +Proof qualification for the Account source/currentness cut: at `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2`, the physical Account suite ran 92 cases with zero skips. Fresh installation through V97, V73 upgrade, the closed reset/logout V80 case, and the terms-binding V86 case passed. Three other cases failed: a fixture supplied `varchar` where `timestamptz` was expected, a schema identifier exceeded PostgreSQL's 63-character limit, and a rejection-message expectation differed. Subsequent local repairs passed the consolidated Account check in 28 seconds; the unchanged 636 Account unit outputs and 245 Common unit outputs were reused. The local integration run executed two cases and skipped 83 without Docker. Smoke run `37983056841` passed against 7a in 15m36s. V98 and the new disclosure persistence proof have not yet been physically executed, so the physical run does not qualify that migration. These bounded results do not establish whole-suite Account readiness or activation. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for exact scope and limitations. 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. @@ -20,7 +20,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 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. +Official-hosted creator-content acceptance remains an unregistered target workflow. Source-only persistence now includes Creator Party and hosted-terms/environment-binding evidence plus V98 disclosure handoff and source-evidence tables; these relations do not supply external environment observation, authenticated publication, a legal authority verifier, dispatch, a consumer, 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). @@ -34,9 +34,9 @@ SEC-04 does not move player session ownership into Logging & Admin. Game Session 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 or an earlier source intent remains `WAITING`, the owner transaction rolls back and returns retryable `AUTH_UNAVAILABLE`; the handler does not wait for source settlement on a thread. An exact retry preserves the original intent and may proceed after its owner-fence outcome is known. The `WAITING` intent retains the Argon2 password verifier required for that retry; terminal source commit or abort clears the verifier while retaining its digest and immutable source binding and receipt. No finite receipt lifetime is selected; receipt retention remains an owning-policy gap. Retained pre-V40 rows remain denied and are neither backfilled nor admitted; unrelated transaction or database failures are not converted by this handler. -For AA-1.3 source-currentness, [AccountAuthoritySourceEventReadback](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java) and the source-fenced reset path in [AccountServiceImpl](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) are production anchors; [AccountAuthoritySourceEventReadbackTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java), [AccountServiceImplTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java), [PasswordResetAuthorityProducerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java), and [AccountAuthoritySourceEvidencePersistenceIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) are focused proof anchors. The Account authority-event reader still rejects generic source events that lack a supported exact closed-operation receipt as `AUTH_UNAVAILABLE`, so this does not claim complete LOGIN/currentness closure. Reset-driven revocation and the broader recovery/session/logout family remain incomplete; physical PostgreSQL proof remains unestablished. +For AA-1.3 source-currentness, [AccountAuthoritySourceEventReadback](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java) and the source-fenced reset path in [AccountServiceImpl](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) are production anchors; [AccountAuthoritySourceEventReadbackTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java), [AccountServiceImplTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java), [PasswordResetAuthorityProducerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java), and [AccountAuthoritySourceEvidencePersistenceIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) are focused proof anchors. The Account authority-event reader still rejects generic source events that lack a supported exact closed-operation receipt as `AUTH_UNAVAILABLE`, so this does not claim complete LOGIN/currentness closure. The selected V80 closed reset/logout PostgreSQL case passed at 7a, but physical-suite proof remains incomplete and V98 disclosure persistence proof is unrun. Reset-driven revocation and the broader recovery/session/logout family remain incomplete. -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). +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. Physical fresh-install-through-V97/V73-upgrade and selected V80/V86 cases passed on 7a, but three other physical cases failed and V98 remains unexecuted; see the proof qualification above. 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/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql new file mode 100644 index 0000000000..115b0f57ba --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql @@ -0,0 +1,157 @@ +-- Account-owned exact intent only. No legal authority verifier, dispatch RPC, or consumer is +-- enabled by this journal. +CREATE TABLE account_hosted_terms_disclosure_handoffs ( + handoff_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + kind VARCHAR(32) NOT NULL CHECK (kind IN ('CATALOG', 'ENVIRONMENT_BINDING')), + source_key VARCHAR(512) NOT NULL CHECK (length(source_key) > 0 AND octet_length(source_key) <= 512), + predecessor_digest VARCHAR(71) NOT NULL CHECK (predecessor_digest ~ '^sha256:[0-9a-f]{64}$'), + candidate_digest VARCHAR(71) NOT NULL CHECK (candidate_digest ~ '^sha256:[0-9a-f]{64}$'), + effective_at TIMESTAMPTZ NOT NULL, + binding BYTEA NOT NULL CHECK (octet_length(binding) > 0), + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + status VARCHAR(32) NOT NULL + CHECK (status IN ('PREPARED', 'DISPATCH_AUTHORIZED', 'AMBIGUOUS', 'DISCLOSED', 'DEFINITIVELY_NOT_DISCLOSED')), + dispatch_attempts INTEGER NOT NULL DEFAULT 0 CHECK (dispatch_attempts >= 0), + result_outcome VARCHAR(32) CHECK (result_outcome IN ('DISCLOSED', 'DEFINITIVELY_NOT_DISCLOSED')), + result_payload BYTEA, + result_digest VARCHAR(71) CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + result_recorded_at TIMESTAMPTZ, + CHECK ( + (status = 'PREPARED' AND dispatch_attempts = 0 + AND result_outcome IS NULL AND result_payload IS NULL + AND result_digest IS NULL AND result_recorded_at IS NULL) + OR (status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS') AND dispatch_attempts > 0 + AND result_outcome IS NULL AND result_payload IS NULL + AND result_digest IS NULL AND result_recorded_at IS NULL) + OR (status = 'DISCLOSED' AND dispatch_attempts > 0 + AND result_outcome = 'DISCLOSED' AND result_payload IS NOT NULL + AND octet_length(result_payload) > 0 + AND result_digest IS NOT NULL AND result_recorded_at IS NOT NULL) + OR (status = 'DEFINITIVELY_NOT_DISCLOSED' AND dispatch_attempts > 0 + AND result_outcome = 'DEFINITIVELY_NOT_DISCLOSED' + AND result_payload IS NOT NULL AND octet_length(result_payload) > 0 + AND result_digest IS NOT NULL + AND result_recorded_at IS NOT NULL) + ) +); + +CREATE TABLE account_hosted_terms_disclosure_sources ( + handoff_id UUID NOT NULL REFERENCES account_hosted_terms_disclosure_handoffs(handoff_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), + source_evidence_digest VARCHAR(71) NOT NULL + CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (handoff_id, source_key) +); +CREATE INDEX account_hosted_terms_disclosure_sources_by_key + ON account_hosted_terms_disclosure_sources(source_key, handoff_id); + +-- [jooq ignore start] +CREATE FUNCTION account_hosted_terms_disclosure_handoff_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Hosted terms disclosure handoff cannot be deleted' + USING ERRCODE = '23514'; + END IF; + IF NEW.handoff_id IS DISTINCT FROM OLD.handoff_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.kind IS DISTINCT FROM OLD.kind + OR NEW.source_key IS DISTINCT FROM OLD.source_key + OR NEW.predecessor_digest IS DISTINCT FROM OLD.predecessor_digest + OR NEW.candidate_digest IS DISTINCT FROM OLD.candidate_digest + OR NEW.effective_at IS DISTINCT FROM OLD.effective_at + OR NEW.binding IS DISTINCT FROM OLD.binding + OR NEW.binding_digest IS DISTINCT FROM OLD.binding_digest + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Hosted terms disclosure handoff binding is immutable' + USING ERRCODE = '23514'; + END IF; + + IF OLD.result_payload IS NOT NULL THEN + IF NEW.status IS DISTINCT FROM OLD.status + OR NEW.dispatch_attempts IS DISTINCT FROM OLD.dispatch_attempts + OR NEW.result_outcome IS DISTINCT FROM OLD.result_outcome + OR NEW.result_payload IS DISTINCT FROM OLD.result_payload + OR NEW.result_digest IS DISTINCT FROM OLD.result_digest + OR NEW.result_recorded_at IS DISTINCT FROM OLD.result_recorded_at THEN + RAISE EXCEPTION 'Hosted terms disclosure result is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED' + AND OLD.dispatch_attempts = 0 AND NEW.dispatch_attempts = 1 + AND NEW.result_outcome IS NULL AND NEW.result_payload IS NULL + AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL THEN + RETURN NEW; + ELSIF OLD.status = 'DISPATCH_AUTHORIZED' AND NEW.status = 'AMBIGUOUS' + AND NEW.dispatch_attempts = OLD.dispatch_attempts + AND NEW.result_outcome IS NULL AND NEW.result_payload IS NULL + AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL THEN + RETURN NEW; + ELSIF OLD.status = 'AMBIGUOUS' AND NEW.status = 'DISPATCH_AUTHORIZED' + AND NEW.dispatch_attempts = OLD.dispatch_attempts + 1 + AND NEW.result_outcome IS NULL AND NEW.result_payload IS NULL + AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL THEN + RETURN NEW; + ELSIF OLD.status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS') + AND NEW.status IN ('DISCLOSED', 'DEFINITIVELY_NOT_DISCLOSED') + AND NEW.dispatch_attempts = OLD.dispatch_attempts + AND NEW.result_payload IS NOT NULL AND octet_length(NEW.result_payload) > 0 + AND NEW.result_digest IS NOT NULL AND NEW.result_recorded_at IS NOT NULL + AND ((NEW.status = 'DISCLOSED' AND NEW.result_outcome = 'DISCLOSED') + OR (NEW.status = 'DEFINITIVELY_NOT_DISCLOSED' + AND NEW.result_outcome = 'DEFINITIVELY_NOT_DISCLOSED')) THEN + RETURN NEW; + END IF; + + RAISE EXCEPTION 'Invalid hosted terms disclosure handoff transition' + USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_hosted_terms_disclosure_immutable_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Hosted terms disclosure source evidence is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_hosted_terms_disclosure_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + phase TEXT; +BEGIN + SELECT status INTO phase + FROM account_hosted_terms_disclosure_handoffs + WHERE handoff_id = NEW.handoff_id FOR UPDATE; + IF phase IS DISTINCT FROM 'PREPARED' THEN + RAISE EXCEPTION 'Only a newly prepared handoff may acquire source evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_hosted_terms_disclosure_handoff_immutable + BEFORE UPDATE OR DELETE ON account_hosted_terms_disclosure_handoffs + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_disclosure_handoff_guard(); +CREATE TRIGGER account_hosted_terms_disclosure_sources_immutable + BEFORE UPDATE OR DELETE ON account_hosted_terms_disclosure_sources + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_disclosure_immutable_guard(); +CREATE TRIGGER account_hosted_terms_disclosure_sources_insert_phase + BEFORE INSERT ON account_hosted_terms_disclosure_sources + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_disclosure_source_insert_guard(); +CREATE TRIGGER account_hosted_terms_disclosure_handoffs_no_truncate + BEFORE TRUNCATE ON account_hosted_terms_disclosure_handoffs + FOR EACH STATEMENT EXECUTE FUNCTION account_hosted_terms_disclosure_immutable_guard(); +CREATE TRIGGER account_hosted_terms_disclosure_sources_no_truncate + BEFORE TRUNCATE ON account_hosted_terms_disclosure_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_hosted_terms_disclosure_immutable_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 index 9915cfd605..64cb3a1158 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -591,7 +591,8 @@ void issuanceFenceRejectsAnUnbackedOverflowAdvance() { 11L, seed.accountUuid())) .isInstanceOf(DataAccessException.class) - .hasMessageContaining("lacks exact owner source evidence"); + .hasMessageContaining( + "Account authority issuance fence and source version must advance by one"); assertUnchangedAfterRollback(fixture, seed, 1L, 1L); } 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 f4c6db1c7c..880de68061 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 @@ -121,8 +121,13 @@ void dropTestOwnedSchemas() { legacyLifecycleMigrationSchema(AccountLifecycleState.SECURITY_LOCKED), legacyLifecycleMigrationSchema(AccountLifecycleState.DEACTIVATED_PENDING_DELETE), legacyLifecycleMigrationSchema(AccountLifecycleState.DELETED))) { + boolean validLifecycleSchema = + !schema.startsWith("account_lifecycle_") + || schema.matches( + "account_lifecycle_(active|security_locked|pending_delete|deleted)_[a-f0-9]{12}"); if (!schema.matches("account_[a-z_]+_[a-f0-9]{12}") - || !schema.endsWith("_" + SCHEMA_SUFFIX)) { + || !schema.endsWith("_" + SCHEMA_SUFFIX) + || !validLifecycleSchema) { throw new IllegalStateException("Refusing to dispose an unowned PostgreSQL schema"); } jdbc.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); @@ -770,7 +775,11 @@ private RetainedAccountFixture retainedAccountAtV39(AccountLifecycleState lifecy } private String legacyLifecycleMigrationSchema(AccountLifecycleState lifecycleState) { - return "account_legacy_lifecycle_" + lifecycleState.storageValue() + "_" + SCHEMA_SUFFIX; + String lifecycleSlug = + lifecycleState == AccountLifecycleState.DEACTIVATED_PENDING_DELETE + ? "pending_delete" + : lifecycleState.storageValue(); + return "account_lifecycle_" + lifecycleSlug + "_" + SCHEMA_SUFFIX; } private static void assertNoAuthorityBirthEvidence(DSLContext dsl, UUID accountUuid) { 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 index 42e1aea56d..c645fb1347 100644 --- 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 @@ -7,14 +7,20 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.HexFormat; +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.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; @@ -26,6 +32,10 @@ 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.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; @@ -61,7 +71,7 @@ static void stopPostgres() { } @Test - void freshInstallAppliesEveryForwardMigrationThroughV97() { + void freshInstallAppliesEveryForwardMigrationThroughV98() { TestContext context = context(null); assertThat( @@ -69,17 +79,17 @@ void freshInstallAppliesEveryForwardMigrationThroughV97() { .dsl() .resultQuery( "SELECT version FROM flyway_schema_history " - + "WHERE success AND version = '97'") + + "WHERE success AND version = '98'") .fetchOne(0, String.class)) - .isEqualTo("97"); + .isEqualTo("98"); assertThat( context .dsl() .resultQuery( "SELECT count(*) FROM flyway_schema_history " - + "WHERE version::numeric BETWEEN 74 AND 97 AND success") + + "WHERE version::numeric BETWEEN 74 AND 98 AND success") .fetchOne(0, Long.class)) - .isEqualTo(24L); + .isEqualTo(25L); for (String relation : new String[] { @@ -101,7 +111,9 @@ void freshInstallAppliesEveryForwardMigrationThroughV97() { "account_password_reset_draft_source_changes", "account_game_logic_intake_source_read_reservations", "account_game_logic_intake_source_read_sources", - "account_game_logic_intake_source_read_aborts" + "account_game_logic_intake_source_read_aborts", + "account_hosted_terms_disclosure_handoffs", + "account_hosted_terms_disclosure_sources" }) { assertThat( context @@ -121,7 +133,10 @@ void freshInstallAppliesEveryForwardMigrationThroughV97() { "account_game_logic_intake_source_read_is_pending(uuid)", "account_game_logic_intake_source_read_complete_guard()", "account_game_logic_intake_source_read_source_guard()", - "account_game_logic_intake_source_read_terminal_guard()" + "account_game_logic_intake_source_read_terminal_guard()", + "account_hosted_terms_disclosure_handoff_guard()", + "account_hosted_terms_disclosure_immutable_guard()", + "account_hosted_terms_disclosure_source_insert_guard()" }) { assertThat( context @@ -131,6 +146,302 @@ void freshInstallAppliesEveryForwardMigrationThroughV97() { .as("forward SQL guard %s", function) .isNotNull(); } + for (String[] trigger : + new String[][] { + { + "account_hosted_terms_disclosure_handoffs_no_truncate", + "account_hosted_terms_disclosure_handoffs" + }, + { + "account_hosted_terms_disclosure_sources_no_truncate", + "account_hosted_terms_disclosure_sources" + } + }) { + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM pg_trigger WHERE tgname = ? " + + "AND tgrelid = ?::regclass AND NOT tgisinternal", + trigger[0], + trigger[1]) + .fetchOne(0, Long.class)) + .as("statement-level immutable trigger %s", trigger[0]) + .isEqualTo(1L); + } + } + + @Test + void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { + TestContext context = context(null); + UUID hostedScopeId = UUID.randomUUID(); + UUID termsVersionId = UUID.randomUUID(); + byte[] document = + "synthetic hosted-terms catalog fixture; not legal terms or a publication" + .getBytes(StandardCharsets.UTF_8); + HostedTermsCatalogVersion candidate = + new HostedTermsCatalogVersion( + termsVersionId, + hostedScopeId, + null, + "TEST FIXTURE ONLY - no authenticated legal identity", + 1, + document, + HostedTermsEncoding.digest(document), + 1, + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-only/no-publication", + 1, + "test-only/no-notice", + 1, + Instant.parse("2040-01-01T00:00:00Z")); + HostedTermsRepository hostedTerms = new HostedTermsRepository(context.dsl()); + byte[][] persistedCatalogEvidence = new byte[1][]; + context + .transaction() + .executeWithoutResult( + status -> { + hostedTerms.ensureScope(hostedScopeId); + hostedTerms.insertCandidate(candidate); + persistedCatalogEvidence[0] = + HostedTermsEncoding.catalog(hostedTerms.readCatalog(hostedScopeId, termsVersionId)); + }); + SourceEvidence exactSource = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + hostedScopeId.toString(), + "1", + "1", + null, + null, + persistedCatalogEvidence[0]); + byte[] exactSourceEvidence = exactSource.canonicalBytes(); + UUID handoffId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + byte[] handoffBinding = + "synthetic PREPARED disclosure intent only; no dispatch or legal authorization" + .getBytes(StandardCharsets.UTF_8); + OffsetDateTime effectiveAt = + OffsetDateTime.ofInstant(Instant.parse("2040-02-01T00:00:00Z"), ZoneOffset.UTC); + + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + exactSource.key()); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_disclosure_handoffs " + + "(handoff_id, request_id, kind, source_key, predecessor_digest, " + + "candidate_digest, effective_at, binding, binding_digest, status, " + + "dispatch_attempts) VALUES (?, ?, 'CATALOG', ?, ?, ?, ?, ?, ?, 'PREPARED', 0)", + handoffId, + requestId, + exactSource.key(), + sha256("test-only predecessor".getBytes(StandardCharsets.UTF_8)), + HostedTermsEncoding.digest(document), + effectiveAt, + handoffBinding, + sha256(handoffBinding)); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_disclosure_sources " + + "(handoff_id, source_key, source_evidence, source_evidence_digest) " + + "VALUES (?, ?, ?, ?)", + handoffId, + exactSource.key(), + exactSourceEvidence, + sha256(exactSourceEvidence)); + + var persisted = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT h.*, s.source_evidence, s.source_evidence_digest " + + "FROM account_hosted_terms_disclosure_handoffs h " + + "JOIN account_hosted_terms_disclosure_sources s " + + "ON s.handoff_id = h.handoff_id WHERE h.handoff_id = ?", + handoffId)); + assertThat(persisted.get("request_id", UUID.class)).isEqualTo(requestId); + assertThat(persisted.get("kind", String.class)).isEqualTo("CATALOG"); + assertThat(persisted.get("source_key", String.class)).isEqualTo(exactSource.key()); + assertThat(persisted.get("predecessor_digest", String.class)) + .isEqualTo(sha256("test-only predecessor".getBytes(StandardCharsets.UTF_8))); + assertThat(persisted.get("candidate_digest", String.class)) + .isEqualTo(HostedTermsEncoding.digest(document)); + assertThat(persisted.get("effective_at", OffsetDateTime.class)).isEqualTo(effectiveAt); + assertThat(persisted.get("binding", byte[].class)).containsExactly(handoffBinding); + assertThat(persisted.get("binding_digest", String.class)).isEqualTo(sha256(handoffBinding)); + assertThat(persisted.get("status", String.class)).isEqualTo("PREPARED"); + assertThat(persisted.get("dispatch_attempts", Integer.class)).isZero(); + assertThat(persisted.get("source_evidence", byte[].class)).containsExactly(exactSourceEvidence); + assertThat(persisted.get("source_evidence_digest", String.class)) + .isEqualTo(sha256(exactSourceEvidence)); + + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_sources " + + "SET source_evidence = ? WHERE handoff_id = ? AND source_key = ?", + new byte[] {1}, + handoffId, + exactSource.key())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "DELETE FROM account_hosted_terms_disclosure_sources " + + "WHERE handoff_id = ? AND source_key = ?", + handoffId, + exactSource.key())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'AMBIGUOUS', " + + "dispatch_attempts = 1 WHERE handoff_id = ?", + handoffId)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs " + + "SET binding = ? WHERE handoff_id = ?", + new byte[] {2}, + handoffId)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "DELETE FROM account_hosted_terms_disclosure_handoffs WHERE handoff_id = ?", + handoffId)) + .isInstanceOf(DataAccessException.class); + assertThat( + context + .dsl() + .resultQuery( + "SELECT status FROM account_hosted_terms_disclosure_handoffs " + + "WHERE handoff_id = ?", + handoffId) + .fetchOne(0, String.class)) + .isEqualTo("PREPARED"); + + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(context.dsl()); + DraftAuthorizationFenceBinding preparedCapture = draftBinding(exactSource); + context + .transaction() + .executeWithoutResult(status -> fences.reserve(preparedCapture)); + + // This is only a persisted test fixture state for exercising the exact-read predicate. No + // publisher is authenticated, no RPC/dispatch is performed, and no consumer is activated. + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISPATCH_AUTHORIZED', " + + "dispatch_attempts = 1 WHERE handoff_id = ?", + handoffId); + + byte[] mismatchedDocument = + "different synthetic hosted-terms candidate; not legal terms or a publication" + .getBytes(StandardCharsets.UTF_8); + HostedTermsCatalogVersion mismatchedCandidate = + new HostedTermsCatalogVersion( + UUID.randomUUID(), + hostedScopeId, + termsVersionId, + candidate.operatorLegalIdentity(), + candidate.operatorIdentityVersion(), + mismatchedDocument, + HostedTermsEncoding.digest(mismatchedDocument), + 2, + 1, + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + "test-only/materiality-evidence", + 1L, + "test-only/no-publication", + 2, + "test-only/no-notice", + 2, + Instant.parse("2041-01-01T00:00:00Z")); + SourceEvidence mismatchedSource = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + hostedScopeId.toString(), + "1", + "2", + null, + null, + HostedTermsEncoding.catalog(mismatchedCandidate)); + DraftAuthorizationFenceBinding mismatchedCapture = draftBinding(mismatchedSource); + context + .transaction() + .executeWithoutResult(status -> fences.reserve(mismatchedCapture)); + + DraftAuthorizationFenceBinding exactCapture = draftBinding(exactSource); + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult(status -> fences.reserve(exactCapture))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact hosted terms source has authorized disclosure"); + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM account_draft_authorization_fences WHERE operation_id = ?", + exactCapture.operationId()) + .fetchOne(0, Long.class)) + .isZero(); + + assertThatThrownBy( + () -> + context + .dsl() + .execute("TRUNCATE account_hosted_terms_disclosure_handoffs CASCADE")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute("TRUNCATE account_hosted_terms_disclosure_sources")) + .isInstanceOf(DataAccessException.class); + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM account_hosted_terms_disclosure_handoffs " + + "WHERE handoff_id = ?", + handoffId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM account_hosted_terms_disclosure_sources " + + "WHERE handoff_id = ? AND source_key = ?", + handoffId, + exactSource.key()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); } @Test @@ -156,6 +467,27 @@ void v73RetainedAccountStaysUnenrolledWhileFreshRepositoryAccountGetsExactBirthS .fetchOne(0, UUID.class)); migrate(context, null); + assertThat( + context + .dsl() + .resultQuery( + "SELECT version FROM flyway_schema_history " + + "WHERE success AND version = '98'") + .fetchOne(0, String.class)) + .isEqualTo("98"); + for (String relation : + new String[] { + "account_hosted_terms_disclosure_handoffs", + "account_hosted_terms_disclosure_sources" + }) { + assertThat( + context + .dsl() + .resultQuery("SELECT to_regclass(?)::TEXT", relation) + .fetchOne(0, String.class)) + .as("V98 forward relation %s", relation) + .isNotNull(); + } Account fresh = account(null); context .transaction() @@ -428,7 +760,7 @@ void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradic hostedScopeId, nonoperativeDocument, sha256(nonoperativeDocument), - OffsetDateTime.now(ZoneOffset.UTC).plusDays(1).toString(), + OffsetDateTime.now(ZoneOffset.UTC).plusDays(1), versionPayload, sha256(versionPayload)); @@ -594,6 +926,50 @@ private static FreshTenantCreatorEvidence creatorEvidence(UUID accountUuid) { 1, creation, accountUuid, authorizationOperationId, authorizationDigest, creatorDigest); } + private static DraftAuthorizationFenceBinding draftBinding(SourceEvidence source) { + DraftCommitBinding 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"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of(source)); + } + private static Account account(String role) { String suffix = UUID.randomUUID().toString(); Account account = new Account(); From 1f074314528fef08bc552cab973ccfd1989c7051 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:24:52 +1300 Subject: [PATCH 04/10] Format disclosure persistence regression --- ...wardMigrationsPostgresIntegrationTest.java | 30 ++++++------------- 1 file changed, 9 insertions(+), 21 deletions(-) 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 index c645fb1347..28322fa2e2 100644 --- 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 @@ -207,7 +207,8 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { hostedTerms.ensureScope(hostedScopeId); hostedTerms.insertCandidate(candidate); persistedCatalogEvidence[0] = - HostedTermsEncoding.catalog(hostedTerms.readCatalog(hostedScopeId, termsVersionId)); + HostedTermsEncoding.catalog( + hostedTerms.readCatalog(hostedScopeId, termsVersionId)); }); SourceEvidence exactSource = new SourceEvidence( @@ -342,12 +343,9 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { .fetchOne(0, String.class)) .isEqualTo("PREPARED"); - DraftAuthorizationFenceRepository fences = - new DraftAuthorizationFenceRepository(context.dsl()); + DraftAuthorizationFenceRepository fences = new DraftAuthorizationFenceRepository(context.dsl()); DraftAuthorizationFenceBinding preparedCapture = draftBinding(exactSource); - context - .transaction() - .executeWithoutResult(status -> fences.reserve(preparedCapture)); + context.transaction().executeWithoutResult(status -> fences.reserve(preparedCapture)); // This is only a persisted test fixture state for exercising the exact-read predicate. No // publisher is authenticated, no RPC/dispatch is performed, and no consumer is activated. @@ -390,16 +388,12 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { null, HostedTermsEncoding.catalog(mismatchedCandidate)); DraftAuthorizationFenceBinding mismatchedCapture = draftBinding(mismatchedSource); - context - .transaction() - .executeWithoutResult(status -> fences.reserve(mismatchedCapture)); + context.transaction().executeWithoutResult(status -> fences.reserve(mismatchedCapture)); DraftAuthorizationFenceBinding exactCapture = draftBinding(exactSource); assertThatThrownBy( () -> - context - .transaction() - .executeWithoutResult(status -> fences.reserve(exactCapture))) + context.transaction().executeWithoutResult(status -> fences.reserve(exactCapture))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Exact hosted terms source has authorized disclosure"); assertThat( @@ -413,15 +407,10 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { assertThatThrownBy( () -> - context - .dsl() - .execute("TRUNCATE account_hosted_terms_disclosure_handoffs CASCADE")) + context.dsl().execute("TRUNCATE account_hosted_terms_disclosure_handoffs CASCADE")) .isInstanceOf(DataAccessException.class); assertThatThrownBy( - () -> - context - .dsl() - .execute("TRUNCATE account_hosted_terms_disclosure_sources")) + () -> context.dsl().execute("TRUNCATE account_hosted_terms_disclosure_sources")) .isInstanceOf(DataAccessException.class); assertThat( context @@ -477,8 +466,7 @@ void v73RetainedAccountStaysUnenrolledWhileFreshRepositoryAccountGetsExactBirthS .isEqualTo("98"); for (String relation : new String[] { - "account_hosted_terms_disclosure_handoffs", - "account_hosted_terms_disclosure_sources" + "account_hosted_terms_disclosure_handoffs", "account_hosted_terms_disclosure_sources" }) { assertThat( context From 3123c3d883cb025eb28149bd62c99ec389c9f5fb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:45:00 +1300 Subject: [PATCH 05/10] Correct hosted terms PostgreSQL fixture bindings --- ...wardMigrationsPostgresIntegrationTest.java | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) 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 index 28322fa2e2..2ecac5a502 100644 --- 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 @@ -219,6 +219,16 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { null, null, persistedCatalogEvidence[0]); + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM account_draft_authorization_source_locks " + + "WHERE source_key = ?", + exactSource.key()) + .fetchOne(0, Long.class)) + .as("the hosted-terms scope insert creates exactly one source lock") + .isEqualTo(1L); byte[] exactSourceEvidence = exactSource.canonicalBytes(); UUID handoffId = UUID.randomUUID(); UUID requestId = UUID.randomUUID(); @@ -228,18 +238,14 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { OffsetDateTime effectiveAt = OffsetDateTime.ofInstant(Instant.parse("2040-02-01T00:00:00Z"), ZoneOffset.UTC); - context - .dsl() - .execute( - "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", - exactSource.key()); context .dsl() .execute( "INSERT INTO account_hosted_terms_disclosure_handoffs " + "(handoff_id, request_id, kind, source_key, predecessor_digest, " + "candidate_digest, effective_at, binding, binding_digest, status, " - + "dispatch_attempts) VALUES (?, ?, 'CATALOG', ?, ?, ?, ?, ?, ?, 'PREPARED', 0)", + + "dispatch_attempts) VALUES (?, ?, 'CATALOG', ?, ?, ?, ?::timestamptz, ?, ?, " + + "'PREPARED', 0)", handoffId, requestId, exactSource.key(), @@ -743,7 +749,7 @@ void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradic + "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, ?, ?, ?)", + + "'no-publication-fixture', 1, 'no-notice-fixture', 1, ?::timestamptz, ?, ?)", termsVersionId, hostedScopeId, nonoperativeDocument, From d6ca01140b676feb69c82390e4005f8b1e4a4139 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 10:18:30 +1300 Subject: [PATCH 06/10] fix(account): close reviewed source and handoff guard gaps --- .../player-access-and-session.md | 2 +- ..._account_control_ui_committed_issuance.sql | 16 +- ...unt_selected_publication_authorization.sql | 23 +- ..._game_logic_intake_terminal_settlement.sql | 3 +- ...count_hosted_terms_disclosure_handoffs.sql | 19 +- ...wardMigrationsPostgresIntegrationTest.java | 745 ++++++++++++++++++ ...eMembershipAuthorityEvidenceValidator.java | 35 +- ...bershipAuthorityEvidenceValidatorTest.java | 34 + 8 files changed, 848 insertions(+), 29 deletions(-) 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 197406b389..b269abd931 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -52,7 +52,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | -| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql) [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. The finite namespace controller-index migration-driver source and packaging prefix have focused source/protocol, packaging, resource-integrity, and static image-contract evidence, but do not prove namespace-aware atomic takeover. The V34.3 PostgreSQL fixture is unrun; physical PostgreSQL and Redis execution, final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Namespace-aware binding and [SESSION-02 atomic transfer](../../architecture/system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) remain incomplete; issuer-index and region reconciliation plus retained-binding inventory/conversion remain open. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. | diff --git a/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql b/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql index 3371d9d86a..d1da3e468f 100644 --- a/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql +++ b/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql @@ -62,6 +62,20 @@ BEGIN IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Control-ui issuance evidence cannot be deleted' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.status IS DISTINCT FROM 'PREPARED' + OR NEW.token_hash IS NOT NULL + OR NEW.pending_registry IS NOT NULL + OR NEW.active_registry IS NOT NULL + OR NEW.pending_receipt IS NOT NULL + OR NEW.committed_at IS NOT NULL + OR NEW.recovery_failed_at IS NOT NULL + OR NEW.revocation_receipt IS NOT NULL THEN + RAISE EXCEPTION 'Control-ui issuance must begin in its empty prepared state' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; IF (to_jsonb(NEW) - ARRAY['status','token_hash','pending_registry','active_registry', 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status','token_hash','pending_registry','active_registry', @@ -105,7 +119,7 @@ END; $$; CREATE TRIGGER account_control_ui_issuance_immutable - BEFORE UPDATE OR DELETE ON account_control_ui_issuance_operations + BEFORE INSERT OR UPDATE OR DELETE ON account_control_ui_issuance_operations FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_guard(); CREATE TRIGGER account_control_ui_issuance_no_truncate BEFORE TRUNCATE ON account_control_ui_issuance_operations diff --git a/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql b/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql index 30afe17861..9dce268109 100644 --- a/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql +++ b/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql @@ -21,7 +21,9 @@ CREATE TABLE account_selected_publication_authorizations ( CREATE TABLE account_selected_publication_sources ( operation_id UUID NOT NULL REFERENCES account_selected_publication_authorizations(operation_id), - source_key VARCHAR(512) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_key VARCHAR(2048) NOT NULL + CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048) + REFERENCES account_draft_authorization_source_locks(source_key), source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), PRIMARY KEY (operation_id, source_key) ); @@ -58,12 +60,12 @@ BEGIN IF issuer.status IS DISTINCT FROM 'COMMITTED' OR issuer.account_uuid <> NEW.actor_account_uuid OR issuer.tenant_uuid <> NEW.tenant_uuid OR issuer.source_payload <> NEW.source_payload OR issuer.bundle_payload <> NEW.issuance_bundle - OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT <> NEW.issuance_fence + OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT IS DISTINCT FROM NEW.issuance_fence OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB OR NEW.producer_xid <> txid_current() - OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'accountId' <> NEW.actor_account_uuid::TEXT - OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'tenantId' <> NEW.tenant_uuid::TEXT THEN + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'accountId' IS DISTINCT FROM NEW.actor_account_uuid::TEXT + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT THEN RAISE EXCEPTION 'Publication requires exact original committed issuance evidence' USING ERRCODE = '23514'; END IF; SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); @@ -91,19 +93,22 @@ BEGIN RAISE EXCEPTION 'Changed publication actor' USING ERRCODE = '23514'; END IF; SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(input_bytes, source_position); - IF convert_from(parsed, 'UTF8')::JSONB->'intent'->>'canonicalTenantId' <> NEW.tenant_uuid::TEXT - OR convert_from(parsed, 'UTF8')::JSONB->'intent'->>'publishRequestId' <> NEW.publish_request_id THEN + IF convert_from(parsed, 'UTF8')::JSONB->'intent'->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR convert_from(parsed, 'UTF8')::JSONB->'intent'->>'publishRequestId' IS DISTINCT FROM NEW.publish_request_id THEN RAISE EXCEPTION 'Changed publication selection identity' USING ERRCODE = '23514'; END IF; SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); source_count := convert_from(parsed, 'UTF8')::INTEGER; - IF source_count < 1 OR source_count <> (SELECT count(*) FROM account_selected_publication_sources WHERE operation_id = NEW.operation_id) - OR source_count <> jsonb_array_length(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources') THEN + IF source_count < 1 OR source_count IS DISTINCT FROM + (SELECT count(*)::INTEGER FROM account_selected_publication_sources WHERE operation_id = NEW.operation_id) + OR source_count IS DISTINCT FROM + jsonb_array_length(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources') THEN RAISE EXCEPTION 'Incomplete publication sources' USING ERRCODE = '23514'; END IF; FOR i IN 1..source_count LOOP SELECT frame_value, next_position INTO source_bytes, p FROM account_publication_authorization_read_frame(NEW.binding, p); - IF source_bytes <> decode(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'->>(i - 1), 'base64') THEN + IF source_bytes IS DISTINCT FROM + decode(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'->>(i - 1), 'base64') THEN RAISE EXCEPTION 'Publication source differs from original complete issuance vector' USING ERRCODE = '23514'; END IF; SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(source_bytes, 1); diff --git a/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql index e1bcb15889..bb9059cf44 100644 --- a/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql +++ b/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql @@ -28,7 +28,8 @@ BEGIN SELECT * INTO STRICT original FROM account_game_logic_intake_authorizations WHERE operation_id = NEW.operation_id; PERFORM l.source_key FROM account_draft_authorization_source_locks l JOIN account_game_logic_intake_sources s ON s.source_key = l.source_key - WHERE s.operation_id = NEW.operation_id ORDER BY l.source_key FOR UPDATE OF l; + WHERE s.operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(l.source_key) FOR UPDATE OF l; PERFORM operation_id FROM account_game_logic_intake_authorizations WHERE operation_id = NEW.operation_id FOR UPDATE; IF NEW.terminal_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') OR NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') THEN diff --git a/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql index 115b0f57ba..975fcc1772 100644 --- a/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql +++ b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql @@ -4,7 +4,7 @@ CREATE TABLE account_hosted_terms_disclosure_handoffs ( handoff_id UUID PRIMARY KEY, request_id UUID NOT NULL UNIQUE, kind VARCHAR(32) NOT NULL CHECK (kind IN ('CATALOG', 'ENVIRONMENT_BINDING')), - source_key VARCHAR(512) NOT NULL CHECK (length(source_key) > 0 AND octet_length(source_key) <= 512), + source_key VARCHAR(2048) NOT NULL CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048), predecessor_digest VARCHAR(71) NOT NULL CHECK (predecessor_digest ~ '^sha256:[0-9a-f]{64}$'), candidate_digest VARCHAR(71) NOT NULL CHECK (candidate_digest ~ '^sha256:[0-9a-f]{64}$'), effective_at TIMESTAMPTZ NOT NULL, @@ -39,7 +39,8 @@ CREATE TABLE account_hosted_terms_disclosure_handoffs ( CREATE TABLE account_hosted_terms_disclosure_sources ( handoff_id UUID NOT NULL REFERENCES account_hosted_terms_disclosure_handoffs(handoff_id), - source_key VARCHAR(512) NOT NULL + source_key VARCHAR(2048) NOT NULL + CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048) REFERENCES account_draft_authorization_source_locks(source_key), source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), source_evidence_digest VARCHAR(71) NOT NULL @@ -57,6 +58,18 @@ BEGIN RAISE EXCEPTION 'Hosted terms disclosure handoff cannot be deleted' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.status IS DISTINCT FROM 'PREPARED' + OR NEW.dispatch_attempts IS DISTINCT FROM 0 + OR NEW.result_outcome IS NOT NULL + OR NEW.result_payload IS NOT NULL + OR NEW.result_digest IS NOT NULL + OR NEW.result_recorded_at IS NOT NULL THEN + RAISE EXCEPTION 'Hosted terms disclosure handoff must begin in its empty prepared state' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; IF NEW.handoff_id IS DISTINCT FROM OLD.handoff_id OR NEW.request_id IS DISTINCT FROM OLD.request_id OR NEW.kind IS DISTINCT FROM OLD.kind @@ -140,7 +153,7 @@ END; $$; CREATE TRIGGER account_hosted_terms_disclosure_handoff_immutable - BEFORE UPDATE OR DELETE ON account_hosted_terms_disclosure_handoffs + BEFORE INSERT OR UPDATE OR DELETE ON account_hosted_terms_disclosure_handoffs FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_disclosure_handoff_guard(); CREATE TRIGGER account_hosted_terms_disclosure_sources_immutable BEFORE UPDATE OR DELETE ON account_hosted_terms_disclosure_sources 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 index 2ecac5a502..2ee3685067 100644 --- 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 @@ -4,12 +4,17 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.sql.SQLException; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Base64; import java.util.HexFormat; import java.util.List; import java.util.Map; @@ -146,6 +151,15 @@ void freshInstallAppliesEveryForwardMigrationThroughV98() { .as("forward SQL guard %s", function) .isNotNull(); } + String settlementGuard = + context + .dsl() + .resultQuery( + "SELECT pg_get_functiondef('account_game_logic_intake_settlement_guard()'::REGPROCEDURE)") + .fetchOne(0, String.class); + assertThat(settlementGuard) + .contains( + "ORDER BY account_publication_authorization_source_sort_key(l.source_key) FOR UPDATE OF l"); for (String[] trigger : new String[][] { { @@ -171,6 +185,606 @@ void freshInstallAppliesEveryForwardMigrationThroughV98() { } } + @Test + void controlUiIssuanceMustStartPreparedAndCanCommitAfterProtectedResponseReadback() { + TestContext context = context(null); + TestIdentity identity = testIdentity(context); + long issuedAt = Instant.now().getEpochSecond(); + OffsetDateTime recoveryExpiresAt = + OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAt + 30), ZoneOffset.UTC); + UUID rejectedOperationId = UUID.randomUUID(); + byte[] sourcePayload = "{}".getBytes(StandardCharsets.UTF_8); + byte[] bundlePayload = "{}".getBytes(StandardCharsets.UTF_8); + byte[] candidate = new byte[] {1}; + + // This row satisfies the table CHECKs. The INSERT guard must still reject a direct terminal + // state before it can bypass the protected response readback transition. + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "INSERT INTO account_control_ui_issuance_operations " + + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, " + + "caller_workload, caller_context_id, request_mac_key_id, request_digest, " + + "claims_payload, source_payload, bundle_payload, signer_receipt, " + + "issued_at_epoch_second, expires_at_epoch_second, recovery_expires_at, " + + "status, token_hash, pending_registry, active_registry, pending_receipt, " + + "committed_at) VALUES (?, ?, ?, ?, ?, 'test', ?, 'test-key', ?, ?, ?, ?, ?, ?, ?, " + + "?::timestamptz, 'COMMITTED', ?, ?, ?, ?, CURRENT_TIMESTAMP)", + UUID.randomUUID(), + rejectedOperationId, + UUID.randomUUID(), + identity.accountUuid(), + identity.tenantUuid(), + UUID.randomUUID(), + "a".repeat(64), + candidate, + sourcePayload, + bundlePayload, + candidate, + issuedAt, + issuedAt + 300, + recoveryExpiresAt, + "b".repeat(64), + candidate, + candidate, + candidate)) + .isInstanceOf(DataAccessException.class); + + ControlUiIssuance committed = + insertCommittedControlUiIssuance(context, identity, sourcePayload, bundlePayload); + assertThat( + context + .dsl() + .resultQuery( + "SELECT status FROM account_control_ui_issuance_operations WHERE operation_id = ?", + committed.operationId()) + .fetchOne(0, String.class)) + .isEqualTo("COMMITTED"); + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM account_control_ui_response_envelopes WHERE operation_id = ?", + committed.operationId()) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void publicationCompletenessRejectsMissingJsonValuesAndAcceptsMaximumHostedSourceKey() { + TestContext context = context(null); + TestIdentity identity = testIdentity(context); + String boundary = "e".repeat(512); + String sourceScope = "environment-boundary/" + boundary; + String sourceKey = "HOSTED_TERMS:" + sourceScope; + byte[] sourceEvidence = sourceEvidence("HOSTED_TERMS", sourceScope); + assertThat(sourceKey.getBytes(StandardCharsets.UTF_8)).hasSize(546); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + sourceKey); + + String validSources = sourceJsonArray(List.of(sourceEvidence)); + String validPayload = publicationSourcePayload(identity, true, true, validSources); + String validBundle = publicationBundle(true); + String validRequest = UUID.randomUUID().toString(); + String validIntent = publicationIntent(identity, validRequest, true, true); + exerciseSelectedPublication( + context, + identity, + sourceEvidence, + validPayload, + validBundle, + validRequest, + validIntent, + 1, + true); + + String missingFenceRequest = UUID.randomUUID().toString(); + exerciseSelectedPublication( + context, + identity, + sourceEvidence, + validPayload, + publicationBundle(false), + missingFenceRequest, + publicationIntent(identity, missingFenceRequest, true, true), + 1, + false); + + String missingAccountRequest = UUID.randomUUID().toString(); + exerciseSelectedPublication( + context, + identity, + sourceEvidence, + publicationSourcePayload(identity, false, true, validSources), + validBundle, + missingAccountRequest, + publicationIntent(identity, missingAccountRequest, true, true), + 1, + false); + + String missingTenantRequest = UUID.randomUUID().toString(); + exerciseSelectedPublication( + context, + identity, + sourceEvidence, + publicationSourcePayload(identity, true, false, validSources), + validBundle, + missingTenantRequest, + publicationIntent(identity, missingTenantRequest, true, true), + 1, + false); + + String missingCanonicalTenantRequest = UUID.randomUUID().toString(); + exerciseSelectedPublication( + context, + identity, + sourceEvidence, + validPayload, + validBundle, + missingCanonicalTenantRequest, + publicationIntent(identity, missingCanonicalTenantRequest, false, true), + 1, + false); + + String missingPublishRequest = UUID.randomUUID().toString(); + exerciseSelectedPublication( + context, + identity, + sourceEvidence, + validPayload, + validBundle, + missingPublishRequest, + publicationIntent(identity, missingPublishRequest, true, false), + 1, + false); + + String missingSourcesRequest = UUID.randomUUID().toString(); + exerciseSelectedPublication( + context, + identity, + sourceEvidence, + publicationSourcePayload(identity, true, true, null), + validBundle, + missingSourcesRequest, + publicationIntent(identity, missingSourcesRequest, true, true), + 1, + false); + + String nullSourceRequest = UUID.randomUUID().toString(); + exerciseSelectedPublication( + context, + identity, + sourceEvidence, + publicationSourcePayload(identity, true, true, "[null]"), + validBundle, + nullSourceRequest, + publicationIntent(identity, nullSourceRequest, true, true), + 1, + false); + + String mismatchedCountRequest = UUID.randomUUID().toString(); + exerciseSelectedPublication( + context, + identity, + sourceEvidence, + validPayload, + validBundle, + mismatchedCountRequest, + publicationIntent(identity, mismatchedCountRequest, true, true), + 2, + false); + } + + @Test + void gameLogicSettlementAcceptsCompleteTerminalAndUsesCanonicalSourceLockOrder() { + TestContext context = context(null); + TestIdentity identity = testIdentity(context); + UUID versionUuid = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID fenceId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + String namespace = "test"; + byte[] supplementarySource = sourceEvidence("TEST", "\uD83D\uDE00"); + byte[] bmpSource = sourceEvidence("TEST", "\uE000"); + String supplementaryKey = "TEST:\uD83D\uDE00"; + String bmpKey = "TEST:\uE000"; + List sourceVector = List.of(supplementarySource, bmpSource); + String sourcePayload = + publicationSourcePayload(identity, true, true, sourceJsonArray(sourceVector)); + String bundlePayload = publicationBundle(true); + ControlUiIssuance issuance = + insertCommittedControlUiIssuance( + context, + identity, + sourcePayload.getBytes(StandardCharsets.UTF_8), + bundlePayload.getBytes(StandardCharsets.UTF_8)); + String bindingJson = + "{\"canonicalTenantId\":\"" + + identity.tenantUuid() + + "\",\"canonicalVersionId\":\"" + + versionUuid + + "\"}"; + String snapshotJson = + "{\"schema\":\"game-design-gameplay-rule-source-snapshot/v1\"," + + "\"bindingJson\":\"" + + bindingJson.replace("\"", "\\\"") + + "\",\"bindingDigest\":\"" + + sha256(utf8(bindingJson)) + + "\",\"manifestJson\":\"{}\"}"; + byte[] snapshot = utf8(snapshotJson); + byte[] intakeBinding = + encodeFrames( + List.of( + utf8("account-game-logic-intake-authorization/v1"), + utf8(operationId.toString()), + utf8(fenceId.toString()), + utf8(requestId.toString()), + utf8(identity.accountUuid().toString()), + snapshot, + utf8("2"), + supplementarySource, + bmpSource)); + + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + supplementaryKey); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", bmpKey); + context + .transaction() + .executeWithoutResult( + status -> { + context + .dsl() + .execute( + "INSERT INTO account_game_logic_intake_authorizations " + + "(operation_id, fence_id, actor_account_uuid, tenant_uuid, version_uuid, " + + "intake_request_id, source_digest, binding, issuance_operation_id, " + + "issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + fenceId, + identity.accountUuid(), + identity.tenantUuid(), + versionUuid, + requestId, + sha256(snapshot), + intakeBinding, + issuance.operationId(), + issuance.fence(), + sourcePayload.getBytes(StandardCharsets.UTF_8), + bundlePayload.getBytes(StandardCharsets.UTF_8), + "[]".getBytes(StandardCharsets.UTF_8)); + context + .dsl() + .execute( + "INSERT INTO account_game_logic_intake_sources " + + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?), (?, ?, ?)", + operationId, + supplementaryKey, + supplementarySource, + operationId, + bmpKey, + bmpSource); + }); + + var orderedKeys = + context + .dsl() + .fetch( + "SELECT source_key FROM account_game_logic_intake_sources WHERE operation_id = ? " + + "ORDER BY account_publication_authorization_source_sort_key(source_key)", + operationId) + .getValues(0, String.class); + assertThat(orderedKeys).containsExactly(supplementaryKey, bmpKey); + + byte[] operationBinding = + encodeFrames( + List.of( + utf8("game-logic-gameplay-rule-intake-operation/v1"), + utf8(namespace), + intakeBinding)); + byte[] terminal = + encodeFrames( + List.of( + utf8("game-logic-gameplay-rule-intake-terminal/v1"), + utf8("RETAINED"), + operationBinding, + intakeBinding, + utf8("PRESENT"), + snapshot, + utf8("PRESENT"), + utf8("{}"))); + byte[] receipt = + encodeFrames(List.of(utf8("account-game-logic-intake-settlement/v1"), terminal)); + context + .dsl() + .execute( + "INSERT INTO account_game_logic_intake_settlements " + + "(operation_id, target_namespace, outcome, terminal_bytes, terminal_digest, " + + "receipt_bytes, receipt_digest) VALUES (?, ?, 'RETAINED', ?, ?, ?, ?)", + operationId, + namespace, + terminal, + sha256(terminal), + receipt, + sha256(receipt)); + assertThat( + context + .dsl() + .resultQuery( + "SELECT outcome FROM account_game_logic_intake_settlements WHERE operation_id = ?", + operationId) + .fetchOne(0, String.class)) + .isEqualTo("RETAINED"); + } + + private static TestIdentity testIdentity(TestContext context) { + Account account = account("player"); + context + .transaction() + .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(account)); + + UUID tenantUuid = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String suffix = UUID.randomUUID().toString(); + context + .dsl() + .execute( + "INSERT INTO account_fresh_tenant_identity_associations " + + "(schema_version, target_namespace, creation_request_id, operation_id, " + + "request_digest, canonical_tenant_id, source_game_row_id, source_game_tenant_key, " + + "provenance_kind, evidence_digest) " + + "VALUES (1, 'test', ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?)", + requestId, + operationId, + sha256(("request-" + suffix).getBytes(StandardCharsets.UTF_8)), + tenantUuid, + Math.max(1L, System.nanoTime() & Long.MAX_VALUE), + "fixture-" + suffix.substring(0, 8), + sha256(("evidence-" + suffix).getBytes(StandardCharsets.UTF_8))); + return new TestIdentity(account.getAccountUuid(), tenantUuid); + } + + private static ControlUiIssuance insertCommittedControlUiIssuance( + TestContext context, TestIdentity identity, byte[] sourcePayload, byte[] bundlePayload) { + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + long issuedAt = Instant.now().getEpochSecond(); + long expiresAt = issuedAt + 300; + OffsetDateTime recoveryExpiresAt = + OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAt + 30), ZoneOffset.UTC); + byte[] candidate = new byte[] {1, 2, 3}; + byte[] response = new byte[] {4, 5, 6}; + byte[] ownerBinding = new byte[] {7, 8, 9}; + String tokenHash = sha256(tokenJti.toString().getBytes(StandardCharsets.UTF_8)).substring(7); + + context + .transaction() + .executeWithoutResult( + status -> { + context + .dsl() + .execute( + "INSERT INTO account_control_ui_issuance_operations " + + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, " + + "caller_workload, caller_context_id, request_mac_key_id, request_digest, " + + "claims_payload, source_payload, bundle_payload, signer_receipt, " + + "issued_at_epoch_second, expires_at_epoch_second, recovery_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, 'test-workload', ?, 'test-key', ?, ?, ?, ?, ?, ?, ?, " + + "?::timestamptz, 'PREPARED')", + requestId, + operationId, + tokenJti, + identity.accountUuid(), + identity.tenantUuid(), + UUID.randomUUID(), + "a".repeat(64), + candidate, + sourcePayload, + bundlePayload, + candidate, + issuedAt, + expiresAt, + recoveryExpiresAt); + context + .dsl() + .execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'CANDIDATE', token_hash = ?, pending_registry = ?, " + + "active_registry = ? WHERE operation_id = ?", + tokenHash, + candidate, + candidate, + operationId); + context + .dsl() + .execute( + "INSERT INTO account_control_ui_response_envelopes " + + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " + + "VALUES (?, ?, ?, ?::timestamptz)", + operationId, + response, + ownerBinding, + recoveryExpiresAt); + context + .dsl() + .execute( + "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', " + + "pending_receipt = ?, committed_at = CURRENT_TIMESTAMP " + + "WHERE operation_id = ?", + response, + operationId); + }); + return new ControlUiIssuance(operationId, 1L); + } + + private static void exerciseSelectedPublication( + TestContext context, + TestIdentity identity, + byte[] sourceEvidence, + String sourcePayload, + String bundlePayload, + String publishRequestId, + String inputIntent, + int declaredSourceCount, + boolean accepted) { + byte[] sourcePayloadBytes = sourcePayload.getBytes(StandardCharsets.UTF_8); + byte[] bundlePayloadBytes = bundlePayload.getBytes(StandardCharsets.UTF_8); + ControlUiIssuance issuance = + insertCommittedControlUiIssuance(context, identity, sourcePayloadBytes, bundlePayloadBytes); + UUID operationId = UUID.randomUUID(); + UUID fenceId = UUID.randomUUID(); + byte[] input = + encodeFrames( + List.of( + utf8("account-publication-input/v1"), + utf8(identity.accountUuid().toString()), + utf8(inputIntent))); + byte[] binding = + encodeFrames( + List.of( + utf8("account-publication-authorization/v1"), + utf8(operationId.toString()), + utf8(fenceId.toString()), + input, + utf8(Integer.toString(declaredSourceCount)), + sourceEvidence)); + byte[] outboxCheckpoints = "[]".getBytes(StandardCharsets.UTF_8); + byte[] evidenceCopy = sourceEvidence.clone(); + String sourceKey = "HOSTED_TERMS:environment-boundary/" + "e".repeat(512); + + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) " + + "ON CONFLICT DO NOTHING", + sourceKey); + try { + context + .transaction() + .executeWithoutResult( + status -> { + context + .dsl() + .execute( + "INSERT INTO account_selected_publication_authorizations " + + "(operation_id, fence_id, actor_account_uuid, tenant_uuid, " + + "publish_request_id, input_digest, binding, world_evidence, " + + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, " + + "outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + fenceId, + identity.accountUuid(), + identity.tenantUuid(), + publishRequestId, + sha256(input), + binding, + new byte[] {1}, + issuance.operationId(), + issuance.fence(), + sourcePayloadBytes, + bundlePayloadBytes, + outboxCheckpoints); + context + .dsl() + .execute( + "INSERT INTO account_selected_publication_sources " + + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + operationId, + sourceKey, + evidenceCopy); + }); + assertThat(accepted) + .as("selected publication should satisfy its deferred completeness guard") + .isTrue(); + } catch (RuntimeException failure) { + if (accepted) { + throw failure; + } + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause) + .as("missing or contradictory JSON completeness evidence must fail in PostgreSQL") + .isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); + } + } + + private static String publicationSourcePayload( + TestIdentity identity, boolean includeAccount, boolean includeTenant, String sourcesJson) { + List fields = new ArrayList<>(); + if (includeAccount) { + fields.add("\"accountId\":\"" + identity.accountUuid() + "\""); + } + if (includeTenant) { + fields.add("\"tenantId\":\"" + identity.tenantUuid() + "\""); + } + if (sourcesJson != null) { + fields.add("\"sources\":" + sourcesJson); + } + return "{" + String.join(",", fields) + "}"; + } + + private static String publicationBundle(boolean includeIssuanceFence) { + return includeIssuanceFence + ? "{\"issuanceFence\":1,\"outboxCheckpoints\":[]}" + : "{\"outboxCheckpoints\":[]}"; + } + + private static String publicationIntent( + TestIdentity identity, + String publishRequestId, + boolean includeTenant, + boolean includeRequest) { + List fields = new ArrayList<>(); + if (includeTenant) { + fields.add("\"canonicalTenantId\":\"" + identity.tenantUuid() + "\""); + } + if (includeRequest) { + fields.add("\"publishRequestId\":\"" + publishRequestId + "\""); + } + return "{\"intent\":{" + String.join(",", fields) + "}}"; + } + + private static String sourceJsonArray(List sourceEvidence) { + return "[" + + sourceEvidence.stream() + .map(value -> "\"" + Base64.getEncoder().encodeToString(value) + "\"") + .collect(java.util.stream.Collectors.joining(",")) + + "]"; + } + + private static byte[] sourceEvidence(String kind, String scope) { + return encodeFrames(List.of(utf8("account-draft-source-evidence/v1"), utf8(kind), utf8(scope))); + } + + private static byte[] encodeFrames(List frames) { + ByteArrayOutputStream encoded = new ByteArrayOutputStream(); + for (byte[] frame : frames) { + encoded.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(frame.length).array()); + encoded.writeBytes(frame); + } + return encoded.toByteArray(); + } + + private static byte[] utf8(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + @Test void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { TestContext context = context(null); @@ -254,6 +868,50 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { effectiveAt, handoffBinding, sha256(handoffBinding)); + + byte[] directTerminalPayload = "direct terminal fixture".getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_disclosure_handoffs " + + "(handoff_id, request_id, kind, source_key, predecessor_digest, " + + "candidate_digest, effective_at, binding, binding_digest, status, " + + "dispatch_attempts, result_outcome, result_payload, result_digest, " + + "result_recorded_at) VALUES (?, ?, 'CATALOG', ?, ?, ?, ?::timestamptz, ?, ?, " + + "'DISCLOSED', 1, 'DISCLOSED', ?, ?, CURRENT_TIMESTAMP)", + UUID.randomUUID(), + UUID.randomUUID(), + exactSource.key(), + sha256("direct predecessor".getBytes(StandardCharsets.UTF_8)), + HostedTermsEncoding.digest(document), + effectiveAt, + handoffBinding, + sha256(handoffBinding), + directTerminalPayload, + sha256(directTerminalPayload))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_disclosure_handoffs " + + "(handoff_id, request_id, kind, source_key, predecessor_digest, " + + "candidate_digest, effective_at, binding, binding_digest, status, " + + "dispatch_attempts) VALUES (?, ?, 'CATALOG', ?, ?, ?, ?::timestamptz, ?, ?, " + + "'DISPATCH_AUTHORIZED', 1)", + UUID.randomUUID(), + UUID.randomUUID(), + exactSource.key(), + sha256("direct authorization predecessor".getBytes(StandardCharsets.UTF_8)), + HostedTermsEncoding.digest(document), + effectiveAt, + handoffBinding, + sha256(handoffBinding))) + .isInstanceOf(DataAccessException.class); + context .dsl() .execute( @@ -265,6 +923,52 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { exactSourceEvidence, sha256(exactSourceEvidence)); + String maximumEnvironmentBoundary = "e".repeat(512); + String maximumEnvironmentSourceKey = + "HOSTED_TERMS:environment-boundary/" + maximumEnvironmentBoundary; + assertThat(maximumEnvironmentSourceKey.getBytes(StandardCharsets.UTF_8)).hasSize(546); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + maximumEnvironmentSourceKey); + UUID maximumKeyHandoffId = UUID.randomUUID(); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_disclosure_handoffs " + + "(handoff_id, request_id, kind, source_key, predecessor_digest, candidate_digest, " + + "effective_at, binding, binding_digest, status, dispatch_attempts) " + + "VALUES (?, ?, 'ENVIRONMENT_BINDING', ?, ?, ?, ?::timestamptz, ?, ?, 'PREPARED', 0)", + maximumKeyHandoffId, + UUID.randomUUID(), + maximumEnvironmentSourceKey, + sha256("maximum environment predecessor".getBytes(StandardCharsets.UTF_8)), + HostedTermsEncoding.digest(document), + effectiveAt, + handoffBinding, + sha256(handoffBinding)); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_disclosure_sources " + + "(handoff_id, source_key, source_evidence, source_evidence_digest) " + + "VALUES (?, ?, ?, ?)", + maximumKeyHandoffId, + maximumEnvironmentSourceKey, + exactSourceEvidence, + sha256(exactSourceEvidence)); + String oversizedSourceKey = "é".repeat(1025); + assertThat(oversizedSourceKey.getBytes(StandardCharsets.UTF_8)).hasSize(2050); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + oversizedSourceKey)) + .isInstanceOf(DataAccessException.class); + var persisted = Objects.requireNonNull( context @@ -437,6 +1141,43 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { exactSource.key()) .fetchOne(0, Long.class)) .isEqualTo(1L); + + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'AMBIGUOUS' " + + "WHERE handoff_id = ?", + handoffId); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISPATCH_AUTHORIZED', " + + "dispatch_attempts = 2 WHERE handoff_id = ?", + handoffId); + byte[] disclosedPayload = + "test-only terminal disclosure result".getBytes(StandardCharsets.UTF_8); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISCLOSED', " + + "result_outcome = 'DISCLOSED', result_payload = ?, result_digest = ?, " + + "result_recorded_at = CURRENT_TIMESTAMP WHERE handoff_id = ?", + disclosedPayload, + sha256(disclosedPayload), + handoffId); + assertThat( + context + .dsl() + .resultQuery( + "SELECT status, dispatch_attempts FROM account_hosted_terms_disclosure_handoffs " + + "WHERE handoff_id = ?", + handoffId) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("status", String.class)).isEqualTo("DISCLOSED"); + assertThat(row.get("dispatch_attempts", Integer.class)).isEqualTo(2); + }); } @Test @@ -1024,4 +1765,8 @@ private record TestContext( DriverManagerDataSource dataSource, DSLContext dsl, TransactionTemplate transaction) {} + + private record TestIdentity(UUID accountUuid, UUID tenantUuid) {} + + private record ControlUiIssuance(UUID operationId, long fence) {} } 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 index eb12b42d85..9a75f78857 100644 --- 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 @@ -269,20 +269,27 @@ private static AccountSource verifyAccountSource( logout.accountSecurityCutoff().outboxStreamKey(), logout.accountSecurityCutoff().outboxSequence()); } catch (IllegalArgumentException logoutFailure) { - var security = - AccountSecurityStateAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); - event = - new AccountSource( - security.eventId(), - security.eventDigest(), - security.canonicalJson(), - security.outboxStreamKey(), - security.outboxSequence(), - security.accountId(), - security.accountAuthorityGeneration(), - security.accountSecurityCutoff().accountAuthorityGeneration(), - security.accountSecurityCutoff().outboxStreamKey(), - security.accountSecurityCutoff().outboxSequence()); + try { + var security = + AccountSecurityStateAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + event = + new AccountSource( + security.eventId(), + security.eventDigest(), + security.canonicalJson(), + security.outboxStreamKey(), + security.outboxSequence(), + security.accountId(), + security.accountAuthorityGeneration(), + security.accountSecurityCutoff().accountAuthorityGeneration(), + security.accountSecurityCutoff().outboxStreamKey(), + security.accountSecurityCutoff().outboxSequence()); + } catch (IllegalArgumentException securityFailure) { + securityFailure.addSuppressed(currentSchemaMismatch); + securityFailure.addSuppressed(resetFailure); + securityFailure.addSuppressed(logoutFailure); + throw securityFailure; + } } } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java index 74af64299e..e50b64b3c4 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java @@ -144,6 +144,40 @@ void deniesMismatchedSourceScopeOriginalCarrierDigestAndMembershipVersion() { .hasMessageContaining("membershipVersion"); } + @Test + void preservesMalformedResetDigestDiagnosticWhenSecurityStateVerificationFails() { + var valid = currentSnapshot(); + var accountSource = valid.sourceEvidence().get(0); + String malformedResetDigest = + accountSource + .canonicalEventJson() + .replaceFirst("sha256:[0-9a-f]{64}", "sha256:" + "0".repeat(64)); + var malformedSource = + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + accountSource.outboxStreamKey(), + accountSource.outboxSequence(), + accountSource.eventId(), + accountSource.eventDigest(), + malformedResetDigest); + + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith( + valid, + valid.checkpoints(), + List.of(malformedSource, valid.sourceEvidence().get(1))))) + .isInstanceOf(IllegalArgumentException.class) + .satisfies( + failure -> + assertThat(failure.getSuppressed()) + .anySatisfy( + diagnostic -> + assertThat(diagnostic.getMessage()) + .contains("eventDigest") + .contains("canonical event preimage"))); + } + @Test void requiresSortedExactCheckpointAndSourceInventories() { var valid = currentSnapshot(); From c69fa3645f3ddf16d2eaafd3838a29a52141736f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 10:52:33 +1300 Subject: [PATCH 07/10] Fix Account source overlap, immutable storage and strict codec review findings --- .../microservices/account-service/README.md | 2 +- .../player-access-and-session.md | 4 +- .../DraftAuthorizationFenceRepository.java | 30 ++- .../creatorparty/CreatorPartyEncoding.java | 5 +- .../hostedterms/HostedTermsEncoding.java | 5 +- ...HostedTermsEnvironmentBindingEncoding.java | 5 +- ...swordResetDraftSourceChangeRepository.java | 14 +- ...V79__account_security_state_operations.sql | 6 +- ...0__account_security_event_source_guard.sql | 17 +- .../V84__individual_creator_party_sources.sql | 9 + ...ogout_all_pending_draft_source_changes.sql | 4 +- ...ccount_selected_publication_settlement.sql | 4 +- ...count_hosted_terms_disclosure_handoffs.sql | 3 +- ...horityProducerPostgresIntegrationTest.java | 91 +++++++- ...wardMigrationsPostgresIntegrationTest.java | 88 +++++++- ...AccountLogoutAllAuthorityEventV1Codec.java | 116 +++-------- ...untSecurityStateAuthorityEventV1Codec.java | 50 +---- .../PasswordResetAuthorityEventV1Codec.java | 123 +++-------- ...eMembershipAuthorityEvidenceValidator.java | 12 +- .../StrictAuthorityEventSupport.java | 195 ++++++++++++++++++ 20 files changed, 507 insertions(+), 276 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/StrictAuthorityEventSupport.java diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 366b18eb51..1033909e2a 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -6,7 +6,7 @@ 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). +- 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. The latest replacement physical PostgreSQL execution remains pending; the earlier bounded execution provides partial evidence, with selected cases passing and failures outstanding. See the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) for exact proof scope and status. 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). - 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. 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 b269abd931..c5d4681609 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,9 +6,9 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -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. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. 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. The 7a physical and local proof scopes, failures, and V98 limitation are detailed below and 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. Hosted-terms acceptance, 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). +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. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. 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. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. The 7a physical and local proof scopes, failures, and V98 limitation are detailed below and 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. Hosted-terms acceptance, 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). -Proof qualification for the Account source/currentness cut: at `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2`, the physical Account suite ran 92 cases with zero skips. Fresh installation through V97, V73 upgrade, the closed reset/logout V80 case, and the terms-binding V86 case passed. Three other cases failed: a fixture supplied `varchar` where `timestamptz` was expected, a schema identifier exceeded PostgreSQL's 63-character limit, and a rejection-message expectation differed. Subsequent local repairs passed the consolidated Account check in 28 seconds; the unchanged 636 Account unit outputs and 245 Common unit outputs were reused. The local integration run executed two cases and skipped 83 without Docker. Smoke run `37983056841` passed against 7a in 15m36s. V98 and the new disclosure persistence proof have not yet been physically executed, so the physical run does not qualify that migration. These bounded results do not establish whole-suite Account readiness or activation. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for exact scope and limitations. +Proof qualification for the Account source/currentness cut: at `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2`, the physical Account suite ran 92 cases with zero skips. Fresh installation through V97, V73 upgrade, the closed reset/logout V80 case, and the terms-binding V86 case passed. Three other cases failed: a fixture supplied `varchar` where `timestamptz` was expected, a schema identifier exceeded PostgreSQL's 63-character limit, and a rejection-message expectation differed. A subsequent historical post-7a local-repair snapshot passed the consolidated Account check in 28 seconds; the unchanged 636 Account unit outputs and 245 Common unit outputs were reused. Its local integration run executed two cases and skipped 83 without Docker; those counts are not the corrected V98 batch or current-head proof. The corrected V98 batch at `3123c3d883cb025eb28149bd62c99ec389c9f5fb` reported 86 local integration cases, with two executed and 84 skipped, and made no physical PostgreSQL claim. Smoke run `37983056841` passed against 7a in 15m36s. V98 and the new disclosure persistence proof have not yet been physically executed, so the physical run does not qualify that migration. The V84 truncate-guard additions in this batch are later SQL and likewise have not been physically verified; the 7a result predates those changes. These bounded results do not establish whole-suite Account readiness or activation. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for exact scope and limitations. 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. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index dd5178be70..7be192d55e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -64,6 +64,21 @@ public enum SourceChangeAbortReason { DEFINITIVE_ABORT } + /** A distinct source mutation cannot capture the same authority source while one is waiting. */ + public static final class PendingSourceChangeException extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final UUID sourceChangeId; + + public PendingSourceChangeException(UUID sourceChangeId) { + super("Another authority source change is already pending for this source"); + this.sourceChangeId = Objects.requireNonNull(sourceChangeId); + } + + public UUID sourceChangeId() { + return sourceChangeId; + } + } + public record FenceSnapshot( Ordering ordering, byte[] binding, OffsetDateTime reservedAt, OffsetDateTime orderedAt) { public FenceSnapshot { @@ -398,7 +413,7 @@ public boolean requestSourceChange(SourceChange change) { } } else { if (hasWaitingChange(change.sources())) { - throw new IllegalStateException("Another authority source change is already pending"); + throw new PendingSourceChangeException(change.changeId()); } dsl.execute( "INSERT INTO " + CHANGES + " (change_id, binding, status) VALUES (?, ?, 'WAITING')", @@ -435,7 +450,7 @@ public boolean sourceMutationPermitted(SourceChange change) { && allAffectedSettled(change.sources()); } - /** A no-mutation cancellation is safe only after every affected owner operation is settled. */ + /** A no-mutation cancellation is safe only after every affected operation has settled. */ public boolean sourceAbortPermitted(SourceChange change) { requireTransaction(); lockSources(change.sources()); @@ -479,9 +494,9 @@ public void markSourceCommitted(SourceChange change) { } /** - * 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. + * Records a terminal no-mutation result after every affected operation settles under its own + * ordering and exact owner readbacks. Owners must agree within each operation; distinct + * operations may have different terminal outcomes. */ public void markSourceAborted(SourceChange change, SourceChangeAbortReason reason) { requireTransaction(); @@ -799,8 +814,9 @@ private List affectedOperations(List sources) { } /** - * Every original required owner must report one uniform exact terminal outcome. Missing or mixed - * evidence always remains pending. + * Every affected operation is checked independently through its exact owner settlement. Missing + * or mixed owner evidence within an operation remains pending; terminal outcomes may differ + * between affected operations. */ private boolean allAffectedSettled(List sources) { if (hasPendingPublication(sources) || hasPendingGameLogicIntake(sources)) { 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 index f0e3fb957b..038c2b31cb 100644 --- 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 @@ -16,6 +16,8 @@ /** Closed canonical encodings; every identity, reference and independent version is bound. */ public final class CreatorPartyEncoding { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private CreatorPartyEncoding() {} public static byte[] party(IndividualCreatorPartySource source) { @@ -98,8 +100,7 @@ private static String decimal(Long value) { private static byte[] canonical(Map fields) { try { - return Rfc8785CanonicalJson.canonicalizeUtf8( - JsonMapper.builder().build().writeValueAsString(fields)); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.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/hostedterms/HostedTermsEncoding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java index c74a8d55c4..6aeffce6c1 100644 --- 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 @@ -17,6 +17,8 @@ /** Exact closed encodings for Account-owned hosted terms, publication requests and acceptance. */ public final class HostedTermsEncoding { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private HostedTermsEncoding() {} public static byte[] publication( @@ -239,8 +241,7 @@ public static long requirePositive(long value, String description) { private static byte[] canonical(Map fields) { try { - return Rfc8785CanonicalJson.canonicalizeUtf8( - JsonMapper.builder().build().writeValueAsString(fields)); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.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/HostedTermsEnvironmentBindingEncoding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java index c46c2052c4..510023e83c 100644 --- 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 @@ -10,6 +10,8 @@ /** Closed canonical encodings for trusted environment-owner binding publications and receipts. */ public final class HostedTermsEnvironmentBindingEncoding { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private HostedTermsEnvironmentBindingEncoding() {} public static byte[] publication( @@ -78,8 +80,7 @@ public static String receiptDigest(HostedTermsEnvironmentBinding binding) { private static byte[] canonical(Map fields) { try { - return Rfc8785CanonicalJson.canonicalizeUtf8( - JsonMapper.builder().build().writeValueAsString(fields)); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.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/service/AccountPasswordResetDraftSourceChangeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java index dafdb1d7ec..ad3044423e 100644 --- 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 @@ -14,11 +14,13 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.PendingSourceChangeException; 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.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import org.jooq.DSLContext; @@ -105,7 +107,11 @@ public Intent participate( if (!"WAITING".equals(intent.status())) { throw new IllegalStateException("Terminal password-reset source intent has no receipt"); } - fences.requestSourceChange(intent.sourceChange()); + try { + fences.requestSourceChange(intent.sourceChange()); + } catch (PendingSourceChangeException pending) { + throw new SourceEvidenceUnavailableException(); + } return requireIntent(findRow(tokenHash)); } @@ -134,7 +140,11 @@ public Intent participate( requestId, eventId); SourceChange change = new SourceChange(UUID.randomUUID(), List.of(source), mutation); - fences.requestSourceChange(change); + try { + fences.requestSourceChange(change); + } catch (PendingSourceChangeException pending) { + throw new SourceEvidenceUnavailableException(); + } dsl.execute( "INSERT INTO " 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 index 78309fc3fd..04253717cd 100644 --- 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 @@ -205,7 +205,7 @@ BEGIN 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. + -- Reuse the exact V75/V76 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')) @@ -233,7 +233,7 @@ BEGIN 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'; + RAISE EXCEPTION 'Security-state exact V75/V76 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 @@ -245,7 +245,7 @@ BEGIN 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'; + RAISE EXCEPTION 'Security-state V75/V76 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; 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 index 1e0906da9a..7fd5361181 100644 --- 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 @@ -1,5 +1,6 @@ -- Extend the V40 source-head and Account security guards for the immutable V77/V78 operation --- receipts without changing historical migrations or treating scalar Account role as authority. +-- receipts and V79 security-state operations without changing historical migrations or treating +-- scalar Account role as authority. -- [jooq ignore start] CREATE OR REPLACE FUNCTION account_authority_source_record_update_guard() RETURNS TRIGGER @@ -114,7 +115,7 @@ BEGIN 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 + -- V79 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 @@ -420,7 +421,7 @@ BEGIN 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' + RAISE EXCEPTION 'V79 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' @@ -445,13 +446,13 @@ BEGIN 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' + RAISE EXCEPTION 'V79 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' + RAISE EXCEPTION 'V79 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; @@ -477,7 +478,7 @@ BEGIN 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' + RAISE EXCEPTION 'V79 security-state event has no exact committed Account operation receipt' USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; END IF; @@ -496,7 +497,7 @@ BEGIN 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' + RAISE EXCEPTION 'V79 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; @@ -516,7 +517,7 @@ BEGIN 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' + RAISE EXCEPTION 'V79 security-state receipt mutation families differ from the original states' USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; END IF; RETURN NULL; 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 index d717b24762..1485f13b03 100644 --- 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 @@ -73,6 +73,15 @@ CREATE TRIGGER account_creator_party_history_immutable 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 TRIGGER account_individual_creator_party_no_truncate + BEFORE TRUNCATE ON account_individual_creator_party_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard(); +CREATE TRIGGER account_creator_party_history_no_truncate + BEFORE TRUNCATE ON account_tenant_creator_party_history + FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard(); +CREATE TRIGGER account_creator_party_operation_no_truncate + BEFORE TRUNCATE ON account_fresh_creator_party_association_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard(); CREATE FUNCTION account_creator_party_history_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN 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 index e2c34a085d..175b31692e 100644 --- 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 @@ -149,7 +149,7 @@ BEGIN 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' + RAISE EXCEPTION 'Logout-all request must bind its exact V75/V76 Account source intent' USING ERRCODE = '23514'; END IF; @@ -221,7 +221,7 @@ BEGIN 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' + RAISE EXCEPTION 'Logout-all journal and V75/V76 Account source transition must commit together' USING ERRCODE = '23514'; END IF; IF journal.status = 'WAITING' AND EXISTS (SELECT 1 FROM account_authority_outbox_events diff --git a/services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql b/services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql index d324037ee3..83bbcd9d75 100644 --- a/services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql +++ b/services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql @@ -148,7 +148,7 @@ RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ WHERE s.operation_id = operation_value AND s.account_binding = a.binding AND s.fence_id = a.fence_id); $$; --- Keep every V107 Draft/order/source/terms guard and change only publication pending detection. +-- Keep every V91 Draft/order/source/terms guard and change only publication pending detection. DO $migration$ DECLARE original TEXT; @@ -157,7 +157,7 @@ BEGIN SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN - RAISE EXCEPTION 'Expected exactly one V107 pending publication guard'; + RAISE EXCEPTION 'Expected exactly one V91 pending publication guard'; END IF; EXECUTE replace(original, anchor, ' IF NOT account_selected_publication_is_settled(operation_value) THEN' || chr(10) diff --git a/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql index 975fcc1772..42942353d8 100644 --- a/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql +++ b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql @@ -34,7 +34,8 @@ CREATE TABLE account_hosted_terms_disclosure_handoffs ( AND result_payload IS NOT NULL AND octet_length(result_payload) > 0 AND result_digest IS NOT NULL AND result_recorded_at IS NOT NULL) - ) + ), + CHECK (result_digest IS NULL OR result_digest = 'sha256:' || encode(sha256(result_payload), 'hex')) ); CREATE TABLE account_hosted_terms_disclosure_sources ( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java index 64cb3a1158..f370fbc4f3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -21,6 +21,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.PasswordResetToken; @@ -373,6 +374,89 @@ void waitingResetRetainsExactIntentAndSettlesOnlyAfterOriginalOwnersDeny() { assertThat(committedV76Change.get("status", String.class)).isEqualTo("SOURCE_COMMITTED"); } + @Test + void overlappingWaitingSourceChangeMakesPasswordResetRetryableAndRollsBack() { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, "initial-password"); + DraftAuthorizationFenceBinding committed = draftBinding(seed); + DraftAuthorizationFenceBinding aborted = draftBinding(seed); + transaction( + fixture.transaction(), + () -> { + fixture.fences().reserve(committed); + fixture.fences().reserve(aborted); + fixture.fences().claimCommitOrder(committed); + fixture.fences().claimCommitOrder(aborted); + for (Owner owner : List.of(Owner.GAME_DESIGN, Owner.WORLD)) { + fixture + .fences() + .recordOwnerReadback(committed, ownerOutcome(committed, owner, Outcome.COMMITTED)); + fixture.fences().recordOwnerReadback(aborted, ownerDenial(aborted, owner)); + } + return null; + }); + + SourceChange overlappingChange = + new SourceChange( + UUID.randomUUID(), + committed.sources(), + "overlapping-source-change".getBytes(StandardCharsets.UTF_8)); + boolean settled = + transaction( + fixture.transaction(), () -> fixture.fences().requestSourceChange(overlappingChange)); + assertThat(settled).isTrue(); + assertThat( + transaction( + fixture.transaction(), + () -> fixture.fences().sourceMutationPermitted(overlappingChange))) + .isTrue(); + + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "overlapping-password")) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); + assertUnchangedAfterRollback(fixture, seed, 1L, 1L); + assertThat( + fixture + .setupDsl() + .fetchSingle( + "SELECT status FROM account_draft_authorization_source_changes " + + "WHERE change_id = ?", + overlappingChange.changeId()) + .get("status", String.class)) + .isEqualTo("WAITING"); + assertThat( + fixture + .setupDsl() + .fetchOne( + "SELECT token_hash FROM account_password_reset_draft_source_changes " + + "WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))) + .isNull(); + } + + @Test + void unrelatedSourcePersistenceFailurePropagatesAndRollsBackPasswordReset() { + Fixture fixture = newFixture(); + Seed seed = seedAccountAndToken(fixture, "initial-password"); + fixture + .setupDsl() + .execute( + "ALTER TABLE account_draft_authorization_source_changes " + + "ADD CONSTRAINT test_reject_waiting_source_change CHECK (status <> 'WAITING')"); + + assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "unrelated-failure-password")) + .isInstanceOf(DataAccessException.class); + + assertUnchangedAfterRollback(fixture, seed, 1L, 1L); + assertThat( + fixture + .setupDsl() + .fetchOne( + "SELECT change_id FROM account_draft_authorization_source_changes " + + "WHERE status = 'WAITING'")) + .isNull(); + } + @Test void expiredWaitingResetAbortsAndDeletesOnlyItsExactOriginalToken() { Fixture fixture = newFixture(); @@ -787,9 +871,14 @@ private DraftAuthorizationFenceBinding draftBinding(Seed seed) { } private OwnerReadback ownerDenial(DraftAuthorizationFenceBinding binding, Owner owner) { + return ownerOutcome(binding, owner, Outcome.DEFINITIVELY_ABORTED); + } + + private OwnerReadback ownerOutcome( + DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { return new OwnerReadback( owner, - Outcome.DEFINITIVELY_ABORTED, + outcome, binding.operationId(), binding.commitId(), binding.fenceId(), 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 index 2ee3685067..f0e6a2ed6f 100644 --- 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 @@ -1156,6 +1156,30 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { handoffId); byte[] disclosedPayload = "test-only terminal disclosure result".getBytes(StandardCharsets.UTF_8); + byte[] mismatchedDigestPayload = + "different test-only terminal disclosure result".getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISCLOSED', " + + "result_outcome = 'DISCLOSED', result_payload = ?, result_digest = ?, " + + "result_recorded_at = CURRENT_TIMESTAMP WHERE handoff_id = ?", + disclosedPayload, + sha256(mismatchedDigestPayload), + handoffId)) + .isInstanceOf(DataAccessException.class); + assertThat( + context + .dsl() + .resultQuery( + "SELECT status FROM account_hosted_terms_disclosure_handoffs " + + "WHERE handoff_id = ?", + handoffId) + .fetchOne(0, String.class)) + .isEqualTo("DISPATCH_AUTHORIZED"); + context .dsl() .execute( @@ -1405,10 +1429,7 @@ void malformedDraftOwnerEvidenceCannotSettleOrRewriteItsSourceChange() { @Test void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradictoryEvidence() { TestContext context = context(null); - Account account = account("player"); - context - .transaction() - .executeWithoutResult(status -> new AccountRepository(context.dsl()).save(account)); + TestIdentity identity = testIdentity(context); UUID creatorPartyId = UUID.randomUUID(); byte[] creatorPayload = "test-only unverified creator source".getBytes(StandardCharsets.UTF_8); @@ -1420,7 +1441,7 @@ void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradic + "source_version, source_payload, source_digest) " + "VALUES (?, ?, 'UNVERIFIED', 1, 1, ?, ?)", creatorPartyId, - account.getAccountUuid(), + identity.accountUuid(), creatorPayload, sha256(creatorPayload)); @@ -1470,6 +1491,61 @@ void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradic .fetchOne(0, Long.class)) .isZero(); + UUID retainedHistoryId = UUID.randomUUID(); + byte[] retainedHistoryPayload = + "test-only retained creator-party history".getBytes(StandardCharsets.UTF_8); + 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 (?, ?, 'RETAINED', ?, 1, ?, ?)", + retainedHistoryId, + identity.tenantUuid(), + creatorPartyId, + retainedHistoryPayload, + sha256(retainedHistoryPayload)); + + assertThatThrownBy( + () -> + context.dsl().execute("TRUNCATE account_individual_creator_party_sources CASCADE")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> context.dsl().execute("TRUNCATE account_tenant_creator_party_history CASCADE")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute("TRUNCATE account_fresh_creator_party_association_operations")) + .isInstanceOf(DataAccessException.class); + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM account_individual_creator_party_sources " + + "WHERE creator_party_id = ?", + creatorPartyId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM account_tenant_creator_party_history " + + "WHERE history_id = ?", + retainedHistoryId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM account_fresh_creator_party_association_operations") + .fetchOne(0, Long.class)) + .isZero(); + UUID hostedScopeId = UUID.randomUUID(); UUID termsVersionId = UUID.randomUUID(); byte[] nonoperativeDocument = @@ -1550,7 +1626,7 @@ void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradic UUID.randomUUID(), UUID.randomUUID(), creatorPartyId, - account.getAccountUuid(), + identity.accountUuid(), hostedScopeId, termsVersionId, sha256(nonoperativeDocument), 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 index a9234264b4..654263c872 100644 --- 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 @@ -1,19 +1,14 @@ 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. */ @@ -39,15 +34,7 @@ public final class AccountLogoutAllAuthorityEventV1Codec { 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); + private static final ObjectMapper JSON = StrictAuthorityEventSupport.strictJsonMapper(); static { var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); @@ -91,7 +78,7 @@ public static AccountLogoutAllAuthorityEvent verify(String wireJson) { private static AccountLogoutAllAuthorityEvent verifyWireNode(ObjectNode wire) { requireExactFields(wire, WIRE_FIELDS, "event"); String suppliedDigest = requireText(wire, "eventDigest", "event"); - if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + if (!StrictAuthorityEventSupport.isCanonicalSha256Digest(suppliedDigest)) { throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); } ObjectNode preimage = wire.deepCopy(); @@ -124,32 +111,20 @@ private static void validatePreimage(ObjectNode event) { 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"); - } + StrictAuthorityEventSupport.validateAccountSecurityCutoff( + event.get("accountSecurityCutoff"), + accountAuthorityGeneration, + streamKey, + outboxSequence, + ACCOUNT_CUTOFF_FIELDS, + AccountLogoutAllAuthorityEventV1Codec::invalid); } private static AccountLogoutAllAuthorityEvent toEvidence( ObjectNode wire, String digest, String canonicalJson) { - ObjectNode cutoff = (ObjectNode) wire.get("accountSecurityCutoff"); + var cutoff = + StrictAuthorityEventSupport.accountSecurityCutoffFields( + (ObjectNode) wire.get("accountSecurityCutoff")); return new AccountLogoutAllAuthorityEvent( wire.path("schemaVersion").textValue(), wire.path("eventType").textValue(), @@ -162,84 +137,43 @@ private static AccountLogoutAllAuthorityEvent toEvidence( wire.path("accountAuthorityGeneration").textValue(), wire.path("sourceVersion").textValue(), new AccountSecurityCutoff( - cutoff.path("accountAuthorityGeneration").textValue(), - cutoff.path("outboxStreamKey").textValue(), - cutoff.path("outboxSequence").textValue()), + cutoff.accountAuthorityGeneration(), cutoff.outboxStreamKey(), cutoff.outboxSequence()), 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()); - } + StrictAuthorityEventSupport.requireExactFields( + object, required, path, AccountLogoutAllAuthorityEventV1Codec::invalid); } 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; + return StrictAuthorityEventSupport.requireExactText( + object, field, expected, path, AccountLogoutAllAuthorityEventV1Codec::invalid); } 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(); + return StrictAuthorityEventSupport.requireText( + object, field, path, AccountLogoutAllAuthorityEventV1Codec::invalid); } 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; + return StrictAuthorityEventSupport.requireUuid( + object, field, path, AccountLogoutAllAuthorityEventV1Codec::invalid); } 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; + return StrictAuthorityEventSupport.requirePositiveDecimal( + object, field, path, AccountLogoutAllAuthorityEventV1Codec::invalid); } 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); - } + return StrictAuthorityEventSupport.digest(preimage, "event preimage cannot be canonicalized"); } 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); - } + return StrictAuthorityEventSupport.canonicalJson(wire, "event cannot be canonicalized"); } private static IllegalArgumentException invalid(String path, String message) { 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 index c9ebc30d2f..4515aa96a6 100644 --- 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 @@ -1,22 +1,16 @@ 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. */ @@ -57,15 +51,7 @@ public final class AccountSecurityStateAuthorityEventV1Codec { 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); + private static final ObjectMapper JSON = StrictAuthorityEventSupport.strictJsonMapper(); static { var fields = new java.util.HashSet<>(PREIMAGE_FIELDS); @@ -104,7 +90,7 @@ public static AccountSecurityStateAuthorityEvent verify(String wireJson) { } exactFields(wire, WIRE_FIELDS); String supplied = text(wire, "eventDigest"); - if (!DIGEST_PATTERN.matcher(supplied).matches()) { + if (!StrictAuthorityEventSupport.isCanonicalSha256Digest(supplied)) { throw invalid("eventDigest must be canonical sha256 hexadecimal"); } ObjectNode preimage = wire.deepCopy(); @@ -183,9 +169,7 @@ private static ObjectNode object(ObjectNode parent, String field) { } private static void exactFields(ObjectNode object, Set expected) { - Set actual = new java.util.HashSet<>(); - object.fieldNames().forEachRemaining(actual::add); - if (!actual.equals(expected)) { + if (!StrictAuthorityEventSupport.hasExactFields(object, expected)) { throw invalid("object must contain exactly the declared fields"); } } @@ -206,42 +190,30 @@ private static void equalText(ObjectNode object, String field, String expected) private static String uuid(ObjectNode object, String field) { String value = text(object, field); - if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + if (!StrictAuthorityEventSupport.isCanonicalUuid(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()) { + if (!StrictAuthorityEventSupport.isPositiveCanonicalDecimal(text(object, field))) { 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); - } + return StrictAuthorityEventSupport.canonicalJson(object, "event cannot be canonicalized"); } 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); - } + return StrictAuthorityEventSupport.digest(object, "event cannot be canonicalized"); } private static AccountSecurityStateAuthorityEvent evidence(ObjectNode wire, String digest) { ObjectNode state = object(wire, "accountState"); ObjectNode cutoff = object(wire, "accountSecurityCutoff"); + var cutoffFields = StrictAuthorityEventSupport.accountSecurityCutoffFields(cutoff); return new AccountSecurityStateAuthorityEvent( text(wire, "eventId"), text(wire, "requestId"), @@ -251,9 +223,9 @@ private static AccountSecurityStateAuthorityEvent evidence(ObjectNode wire, Stri text(wire, "accountAuthorityGeneration"), text(wire, "sourceVersion"), new AccountSecurityCutoff( - text(cutoff, "accountAuthorityGeneration"), - text(cutoff, "outboxStreamKey"), - text(cutoff, "outboxSequence")), + cutoffFields.accountAuthorityGeneration(), + cutoffFields.outboxStreamKey(), + cutoffFields.outboxSequence()), orderedValues(wire.get("mutationKinds"), MUTATION_KINDS, "mutationKinds"), new AccountState( state.get("emailVerified").booleanValue(), 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 index f2068dcc0f..f648723417 100644 --- 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 @@ -1,19 +1,14 @@ 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. */ @@ -38,15 +33,7 @@ public final class PasswordResetAuthorityEventV1Codec { 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); + private static final ObjectMapper JSON = StrictAuthorityEventSupport.strictJsonMapper(); static { var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); @@ -100,7 +87,7 @@ public static PasswordResetAuthorityEvent verify(Map wireEvent) { private static PasswordResetAuthorityEvent verifyWireNode(ObjectNode wire) { requireExactFields(wire, WIRE_FIELDS, "event"); String suppliedDigest = requireText(wire, "eventDigest", "event"); - if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + if (!StrictAuthorityEventSupport.isCanonicalSha256Digest(suppliedDigest)) { throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); } ObjectNode preimage = wire.deepCopy(); @@ -133,32 +120,20 @@ private static void validatePreimage(ObjectNode event) { 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"); - } + StrictAuthorityEventSupport.validateAccountSecurityCutoff( + event.get("accountSecurityCutoff"), + accountAuthorityGeneration, + streamKey, + outboxSequence, + ACCOUNT_CUTOFF_FIELDS, + PasswordResetAuthorityEventV1Codec::invalid); } private static PasswordResetAuthorityEvent toEvidence( ObjectNode wire, String digest, String canonicalJson) { - ObjectNode cutoff = (ObjectNode) wire.get("accountSecurityCutoff"); + var cutoff = + StrictAuthorityEventSupport.accountSecurityCutoffFields( + (ObjectNode) wire.get("accountSecurityCutoff")); return new PasswordResetAuthorityEvent( wire.path("schemaVersion").textValue(), wire.path("eventType").textValue(), @@ -171,92 +146,48 @@ private static PasswordResetAuthorityEvent toEvidence( wire.path("accountAuthorityGeneration").textValue(), wire.path("sourceVersion").textValue(), new AccountSecurityCutoff( - cutoff.path("accountAuthorityGeneration").textValue(), - cutoff.path("outboxStreamKey").textValue(), - cutoff.path("outboxSequence").textValue()), + cutoff.accountAuthorityGeneration(), cutoff.outboxStreamKey(), cutoff.outboxSequence()), 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()); - } + StrictAuthorityEventSupport.requireExactFields( + object, required, path, PasswordResetAuthorityEventV1Codec::invalid); } 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; + return StrictAuthorityEventSupport.requireExactText( + object, field, expected, path, PasswordResetAuthorityEventV1Codec::invalid); } 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; + return StrictAuthorityEventSupport.requireNonEmptyText( + object, field, path, PasswordResetAuthorityEventV1Codec::invalid); } 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(); + return StrictAuthorityEventSupport.requireText( + object, field, path, PasswordResetAuthorityEventV1Codec::invalid); } 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; + return StrictAuthorityEventSupport.requireUuid( + object, field, path, PasswordResetAuthorityEventV1Codec::invalid); } 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; + return StrictAuthorityEventSupport.requirePositiveDecimal( + object, field, path, PasswordResetAuthorityEventV1Codec::invalid); } 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); - } + return StrictAuthorityEventSupport.digest(preimage, "event preimage cannot be canonicalized"); } 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); - } + return StrictAuthorityEventSupport.canonicalJson(wire, "event cannot be canonicalized"); } private static IllegalArgumentException invalid(String path, String message) { 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 index 9a75f78857..41c80248d2 100644 --- 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 @@ -9,7 +9,6 @@ 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; @@ -27,11 +26,6 @@ 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() {} @@ -559,7 +553,7 @@ private static void requireExactTenantValue( } private static void requireCanonicalUuid(String value, String path) { - if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + if (!StrictAuthorityEventSupport.isCanonicalUuid(value)) { throw invalid(path, "must be a canonical lowercase non-nil UUID"); } } @@ -571,13 +565,13 @@ private static void requireNonBlank(String value, String path) { } private static void requirePositiveDecimal(String value, String path) { - if (!POSITIVE_DECIMAL.matcher(value).matches()) { + if (!StrictAuthorityEventSupport.isPositiveCanonicalDecimal(value)) { throw invalid(path, "must be a positive canonical decimal string"); } } private static void requireNonNegativeDecimal(String value, String path) { - if (!NON_NEGATIVE_DECIMAL.matcher(value).matches()) { + if (!StrictAuthorityEventSupport.isNonNegativeCanonicalDecimal(value)) { throw invalid(path, "must be a non-negative canonical decimal string"); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/StrictAuthorityEventSupport.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/StrictAuthorityEventSupport.java new file mode 100644 index 0000000000..208427ccc7 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/StrictAuthorityEventSupport.java @@ -0,0 +1,195 @@ +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.HashSet; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Shared strict parsing and canonical-evidence primitives for Account authority events. */ +final class StrictAuthorityEventSupport { + 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}"); + static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*"); + static final Pattern NON_NEGATIVE_DECIMAL_PATTERN = Pattern.compile("(?:0|[1-9][0-9]*)"); + private static final Pattern SHA256_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); + + private StrictAuthorityEventSupport() {} + + static ObjectMapper strictJsonMapper() { + return JSON; + } + + static boolean hasExactFields(ObjectNode object, Set expected) { + Set actual = new HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + return actual.equals(expected); + } + + static void requireExactFields( + ObjectNode object, Set required, String path, InvalidArgumentFactory invalid) { + if (!hasExactFields(object, required)) { + Set actual = new HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + Set missing = new HashSet<>(required); + missing.removeAll(actual); + Set unexpected = new 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.create(path, message.toString()); + } + } + + static String requireExactText( + ObjectNode object, + String field, + String expected, + String path, + InvalidArgumentFactory invalid) { + String value = requireText(object, field, path, invalid); + if (!expected.equals(value)) { + throw invalid.create(path + "." + field, "must equal " + expected); + } + return value; + } + + static String requireNonEmptyText( + ObjectNode object, String field, String path, InvalidArgumentFactory invalid) { + String value = requireText(object, field, path, invalid); + if (value.isEmpty()) { + throw invalid.create(path + "." + field, "must be nonempty"); + } + return value; + } + + static String requireText( + ObjectNode object, String field, String path, InvalidArgumentFactory invalid) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid.create(path + "." + field, "must be a required string"); + } + return value.textValue(); + } + + static String requireUuid( + ObjectNode object, String field, String path, InvalidArgumentFactory invalid) { + String value = requireText(object, field, path, invalid); + if (!isCanonicalUuid(value)) { + throw invalid.create(path + "." + field, "must be a canonical lowercase non-nil UUID"); + } + return value; + } + + static String requirePositiveDecimal( + ObjectNode object, String field, String path, InvalidArgumentFactory invalid) { + String value = requireText(object, field, path, invalid); + if (!isPositiveCanonicalDecimal(value)) { + throw invalid.create(path + "." + field, "must be a positive canonical decimal string"); + } + return value; + } + + static void validateAccountSecurityCutoff( + JsonNode cutoffNode, + String eventAuthorityGeneration, + String eventStreamKey, + String eventSequence, + Set cutoffFields, + InvalidArgumentFactory invalid) { + if (!(cutoffNode instanceof ObjectNode cutoff)) { + throw invalid.create("accountSecurityCutoff", "must be a required JSON object"); + } + requireExactFields(cutoff, cutoffFields, "accountSecurityCutoff", invalid); + String cutoffGeneration = + requirePositiveDecimal( + cutoff, "accountAuthorityGeneration", "accountSecurityCutoff", invalid); + String cutoffStream = requireText(cutoff, "outboxStreamKey", "accountSecurityCutoff", invalid); + String cutoffSequence = + requirePositiveDecimal(cutoff, "outboxSequence", "accountSecurityCutoff", invalid); + if (!eventAuthorityGeneration.equals(cutoffGeneration)) { + throw invalid.create( + "accountSecurityCutoff.accountAuthorityGeneration", + "must equal event.accountAuthorityGeneration"); + } + if (!eventStreamKey.equals(cutoffStream)) { + throw invalid.create( + "accountSecurityCutoff.outboxStreamKey", "must equal event.outboxStreamKey"); + } + if (!eventSequence.equals(cutoffSequence)) { + throw invalid.create( + "accountSecurityCutoff.outboxSequence", "must equal event.outboxSequence"); + } + } + + static AccountSecurityCutoffFields accountSecurityCutoffFields(ObjectNode cutoff) { + return new AccountSecurityCutoffFields( + cutoff.path("accountAuthorityGeneration").textValue(), + cutoff.path("outboxStreamKey").textValue(), + cutoff.path("outboxSequence").textValue()); + } + + static String canonicalJson(ObjectNode object, String failureMessage) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(object.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException(failureMessage, exception); + } + } + + static String digest(ObjectNode object, String canonicalizationFailureMessage) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(object.toString()); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical); + return "sha256:" + java.util.HexFormat.of().formatHex(hash); + } catch (IOException exception) { + throw new IllegalArgumentException(canonicalizationFailureMessage, exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + static boolean isCanonicalUuid(String value) { + return UUID_PATTERN.matcher(value).matches() && !NIL_UUID.equals(value); + } + + static boolean isPositiveCanonicalDecimal(String value) { + return POSITIVE_DECIMAL_PATTERN.matcher(value).matches(); + } + + static boolean isNonNegativeCanonicalDecimal(String value) { + return NON_NEGATIVE_DECIMAL_PATTERN.matcher(value).matches(); + } + + static boolean isCanonicalSha256Digest(String value) { + return SHA256_DIGEST_PATTERN.matcher(value).matches(); + } + + record AccountSecurityCutoffFields( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {} + + @FunctionalInterface + interface InvalidArgumentFactory { + IllegalArgumentException create(String path, String message); + } +} From fb6ca4dd29fa3f39407f7f2cc32a016fab155403 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:16:58 +1300 Subject: [PATCH 08/10] Fix Account source-read settlement fixture and precompute reset verifier --- .../player-access-and-session.md | 2 +- .../service/impl/AccountServiceImpl.java | 9 +- ...wardMigrationsPostgresIntegrationTest.java | 173 ++++++++++++++++-- .../service/impl/AccountServiceImplTest.java | 48 +++++ 4 files changed, 209 insertions(+), 23 deletions(-) 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 c5d4681609..8edd3ad8c6 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca 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. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. 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. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. The 7a physical and local proof scopes, failures, and V98 limitation are detailed below and 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. Hosted-terms acceptance, 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). -Proof qualification for the Account source/currentness cut: at `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2`, the physical Account suite ran 92 cases with zero skips. Fresh installation through V97, V73 upgrade, the closed reset/logout V80 case, and the terms-binding V86 case passed. Three other cases failed: a fixture supplied `varchar` where `timestamptz` was expected, a schema identifier exceeded PostgreSQL's 63-character limit, and a rejection-message expectation differed. A subsequent historical post-7a local-repair snapshot passed the consolidated Account check in 28 seconds; the unchanged 636 Account unit outputs and 245 Common unit outputs were reused. Its local integration run executed two cases and skipped 83 without Docker; those counts are not the corrected V98 batch or current-head proof. The corrected V98 batch at `3123c3d883cb025eb28149bd62c99ec389c9f5fb` reported 86 local integration cases, with two executed and 84 skipped, and made no physical PostgreSQL claim. Smoke run `37983056841` passed against 7a in 15m36s. V98 and the new disclosure persistence proof have not yet been physically executed, so the physical run does not qualify that migration. The V84 truncate-guard additions in this batch are later SQL and likewise have not been physically verified; the 7a result predates those changes. These bounded results do not establish whole-suite Account readiness or activation. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for exact scope and limitations. +Proof qualification for the Account source/currentness cut: the historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` physical Account suite ran 92 cases with zero skips. Fresh installation through V97, V73 upgrade, the closed reset/logout V80 case, and the terms-binding V86 case passed. Three other cases failed: a fixture supplied `varchar` where `timestamptz` was expected, a schema identifier exceeded PostgreSQL's 63-character limit, and a rejection-message expectation differed. A subsequent historical post-7a local-repair snapshot passed the consolidated Account check in 28 seconds; the unchanged 636 Account unit outputs and 245 Common unit outputs were reused. Its local integration run executed two cases and skipped 83 without Docker; those historical counts are not the corrected V98 batch or current-head proof. The corrected V98 batch at `3123c3d883cb025eb28149bd62c99ec389c9f5fb` reported 86 local integration cases, with two executed and 84 skipped, and made no physical PostgreSQL claim. Smoke run `37983056841` passed against 7a in 15m36s. On current head `c69fa3645f3ddf16d2eaafd3838a29a52141736f`, Account job `114042562197`, run `37996096606`, artifact `11647735581` executed 98 physical integration cases with zero skips and one failure. Fresh V98 and V73 coverage, reset-overlap and unrelated-SQL-rollback cases, and V84 creator TRUNCATE/disclosure guards passed. The canonical-order Game Logic settlement fixture failed at commit because V97's terminal guard could not find its required preliminary source-read reservation (`SELECT INTO STRICT` returned no row). A fixture correction has since been prepared locally but has not been physically rerun, so this is not a green Account gate and does not prove the unpublished correction. These bounded results do not establish whole-suite Account readiness or activation. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for exact scope and limitations. 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. 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 fd39024d97..b3218042c6 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 @@ -2346,9 +2346,12 @@ public void completePasswordReset(CompletePasswordResetRequest request) { throw new IllegalArgumentException("Password-reset token and new password are required"); } String tokenHash = sha256Hex(request.token()); + String candidatePasswordVerifier = hashPassword(request.newPassword()); PasswordResetAttempt attempt = passwordResetOwnerTransaction.execute( - status -> completePasswordResetInOwnerTransaction(request, tokenHash)); + status -> + completePasswordResetInOwnerTransaction( + request, tokenHash, candidatePasswordVerifier)); if (attempt == null) { throw new IllegalStateException("Password-reset owner transaction returned no result"); } @@ -2375,7 +2378,7 @@ public void completePasswordReset(CompletePasswordResetRequest request) { } private PasswordResetAttempt completePasswordResetInOwnerTransaction( - CompletePasswordResetRequest request, String tokenHash) { + CompletePasswordResetRequest request, String tokenHash, String candidatePasswordVerifier) { Optional resolvedReceipt = passwordResetOperationRepository.findByTokenHash(tokenHash); Optional resolvedIntentAccountId = @@ -2459,7 +2462,7 @@ private PasswordResetAttempt completePasswordResetInOwnerTransaction( if (token.getExpiresAt() == null || !token.getExpiresAt().isAfter(LocalDateTime.now())) { throw new IllegalArgumentException("Token expired"); } - newPasswordVerifier = hashPassword(request.newPassword()); + newPasswordVerifier = candidatePasswordVerifier; passwordVerifierDigest = sha256Hex(newPasswordVerifier); tokenExpiresAt = token.getExpiresAt(); requestDigest = 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 index f0e6a2ed6f..1a7ced2fcd 100644 --- 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 @@ -38,6 +38,9 @@ import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; 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; @@ -389,30 +392,84 @@ void gameLogicSettlementAcceptsCompleteTerminalAndUsesCanonicalSourceLockOrder() UUID fenceId = UUID.randomUUID(); UUID requestId = UUID.randomUUID(); String namespace = "test"; - byte[] supplementarySource = sourceEvidence("TEST", "\uD83D\uDE00"); - byte[] bmpSource = sourceEvidence("TEST", "\uE000"); - String supplementaryKey = "TEST:\uD83D\uDE00"; - String bmpKey = "TEST:\uE000"; + SourceEvidence supplementaryEvidence = + new SourceEvidence( + SourceKind.ISSUER, + "\uD83D\uDE00", + "1", + "1", + "test-only-source-checkpoint", + "1", + utf8("synthetic supplementary issuer evidence")); + SourceEvidence bmpEvidence = + new SourceEvidence( + SourceKind.ISSUER, + "\uE000", + "1", + "1", + "test-only-source-checkpoint", + "1", + utf8("synthetic BMP issuer evidence")); + byte[] supplementarySource = supplementaryEvidence.canonicalBytes(); + byte[] bmpSource = bmpEvidence.canonicalBytes(); + String supplementaryKey = supplementaryEvidence.key(); + String bmpKey = bmpEvidence.key(); List sourceVector = List.of(supplementarySource, bmpSource); + List sourceEvidenceVector = List.of(supplementaryEvidence, bmpEvidence); String sourcePayload = publicationSourcePayload(identity, true, true, sourceJsonArray(sourceVector)); String bundlePayload = publicationBundle(true); + byte[] sourcePayloadBytes = sourcePayload.getBytes(StandardCharsets.UTF_8); + byte[] bundlePayloadBytes = bundlePayload.getBytes(StandardCharsets.UTF_8); ControlUiIssuance issuance = - insertCommittedControlUiIssuance( - context, - identity, - sourcePayload.getBytes(StandardCharsets.UTF_8), - bundlePayload.getBytes(StandardCharsets.UTF_8)); - String bindingJson = - "{\"canonicalTenantId\":\"" - + identity.tenantUuid() - + "\",\"canonicalVersionId\":\"" - + versionUuid - + "\"}"; + insertCommittedControlUiIssuance(context, identity, sourcePayloadBytes, bundlePayloadBytes); + DraftCommitBinding selectedCommit = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + identity.tenantUuid(), + versionUuid, + 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"))); + DraftAuthorizationFenceBinding originalDraftBinding = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + selectedCommit.requestId(), + selectedCommit.commitId(), + UUID.randomUUID(), + identity.accountUuid(), + identity.tenantUuid(), + versionUuid, + selectedCommit.baseCommitId(), + "0", + selectedCommit.canonicalBytes(), + selectedCommit.canonicalBytes(), + selectedCommit.digest(), + sourceEvidenceVector); + String bindingJson = selectedCommit.canonicalJson(); String snapshotJson = "{\"schema\":\"game-design-gameplay-rule-source-snapshot/v1\"," + "\"bindingJson\":\"" - + bindingJson.replace("\"", "\\\"") + + bindingJson.replace("\\", "\\\\").replace("\"", "\\\"") + "\",\"bindingDigest\":\"" + sha256(utf8(bindingJson)) + "\",\"manifestJson\":\"{}\"}"; @@ -439,6 +496,84 @@ void gameLogicSettlementAcceptsCompleteTerminalAndUsesCanonicalSourceLockOrder() .dsl() .execute( "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", bmpKey); + DraftAuthorizationFenceRepository draftFences = + new DraftAuthorizationFenceRepository(context.dsl()); + context + .transaction() + .executeWithoutResult( + status -> { + draftFences.reserve(originalDraftBinding); + draftFences.claimCommitOrder(originalDraftBinding); + for (Owner owner : originalDraftBinding.requiredOwners()) { + draftFences.recordOwnerReadback( + originalDraftBinding, + new OwnerReadback( + owner, + Outcome.COMMITTED, + originalDraftBinding.operationId(), + originalDraftBinding.commitId(), + originalDraftBinding.fenceId(), + originalDraftBinding.inputDigest(), + originalDraftBinding.canonicalBytes(), + utf8("test-only settled original owner fixture"))); + } + assertThat(draftFences.readSettlement(originalDraftBinding)) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.COMMITTED); + }); + + byte[] sourceReadScope = + encodeFrames( + List.of( + utf8("account-game-logic-intake-source-read/v1"), + utf8(namespace), + utf8(operationId.toString()), + utf8(fenceId.toString()), + utf8(requestId.toString()), + utf8(identity.accountUuid().toString()), + selectedCommit.canonicalBytes(), + utf8(sha256(selectedCommit.canonicalBytes())), + utf8("spiffe://firemud/ns/" + namespace + "/sa/account-service"), + utf8("GAME_LOGIC_INTAKE_SOURCE"))); + byte[] outboxCheckpoints = "[]".getBytes(StandardCharsets.UTF_8); + context + .transaction() + .executeWithoutResult( + status -> { + context + .dsl() + .execute( + "INSERT INTO account_game_logic_intake_source_read_reservations " + + "(operation_id, fence_id, intake_request_id, actor_account_uuid, " + + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, " + + "issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + fenceId, + requestId, + identity.accountUuid(), + identity.tenantUuid(), + versionUuid, + sourceReadScope, + sha256(sourceReadScope), + issuance.operationId(), + issuance.fence(), + sourcePayloadBytes, + bundlePayloadBytes, + outboxCheckpoints); + context + .dsl() + .execute( + "INSERT INTO account_game_logic_intake_source_read_sources " + + "(operation_id, source_key, source_evidence) " + + "VALUES (?, ?, ?), (?, ?, ?)", + operationId, + supplementaryKey, + supplementarySource, + operationId, + bmpKey, + bmpSource); + }); context .transaction() .executeWithoutResult( @@ -461,9 +596,9 @@ void gameLogicSettlementAcceptsCompleteTerminalAndUsesCanonicalSourceLockOrder() intakeBinding, issuance.operationId(), issuance.fence(), - sourcePayload.getBytes(StandardCharsets.UTF_8), - bundlePayload.getBytes(StandardCharsets.UTF_8), - "[]".getBytes(StandardCharsets.UTF_8)); + sourcePayloadBytes, + bundlePayloadBytes, + outboxCheckpoints); context .dsl() .execute( 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 d02e361f69..7761ea72a4 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 @@ -16,6 +16,7 @@ import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -5768,6 +5769,53 @@ void missingRetainedSourceDeniesPasswordResetBeforeTokenConsumption() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anyString()); } + @Test + void candidatePasswordVerifierIsPreparedBeforeWritableOwnerTransactionBegins() { + AtomicBoolean candidateVerifierPrepared = new AtomicBoolean(); + Argon2 argon2 = org.mockito.Mockito.mock(Argon2.class); + when(argon2.hash( + org.mockito.ArgumentMatchers.eq(2), + org.mockito.ArgumentMatchers.eq(65536), + org.mockito.ArgumentMatchers.eq(1), + org.mockito.ArgumentMatchers.any(char[].class))) + .thenAnswer( + invocation -> { + candidateVerifierPrepared.set(true); + return "prepared-candidate-verifier"; + }); + org.mockito.Mockito.doAnswer( + invocation -> { + assertTrue( + candidateVerifierPrepared.get(), + "Password hashing must complete before the owner transaction starts"); + return new SimpleTransactionStatus(); + }) + .when(transactionManager) + .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); + when(accountPasswordResetOperationRepository.findByTokenHash( + org.mockito.ArgumentMatchers.anyString())) + .thenReturn(Optional.empty()); + when(accountPasswordResetDraftSourceChangeRepository.findAccountIdByTokenHash( + org.mockito.ArgumentMatchers.anyString())) + .thenReturn(Optional.empty()); + when(passwordResetTokenRepository.findByToken(org.mockito.ArgumentMatchers.anyString())) + .thenReturn(Optional.empty()); + + try (org.mockito.MockedStatic argon2Factory = + org.mockito.Mockito.mockStatic(Argon2Factory.class)) { + argon2Factory.when(Argon2Factory::create).thenReturn(argon2); + + assertThrows( + IllegalArgumentException.class, + () -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + "invalid-reset-token", "candidate-password"))); + } + + assertTrue(candidateVerifierPrepared.get()); + } + @Test void passwordResetIssuanceFenceOverflowStopsBeforeTokenPasswordOrEventMutation() { UUID accountUuid = UUID.randomUUID(); From f1ed94a42dfdcb1f63bf52c95c60e9e5744af4b7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:48:10 +1300 Subject: [PATCH 09/10] Fix Account inspection lock order and immutable source evidence guards --- .../microservices/account-service/README.md | 2 +- .../account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 8 +- .../DraftAuthorizationFenceRepository.java | 24 +- ...ountAuthoritySourceEvidenceRepository.java | 5 +- ...ount_password_reset_operation_receipts.sql | 5 +- ..._account_logout_all_operation_receipts.sql | 5 +- ...V83__account_tenant_creation_bootstrap.sql | 5 +- ...count_hosted_terms_acceptance_workflow.sql | 12 + ...count_hosted_terms_environment_binding.sql | 6 + ...count_hosted_terms_disclosure_handoffs.sql | 4 +- ...horityProducerPostgresIntegrationTest.java | 26 +- ...wardMigrationsPostgresIntegrationTest.java | 543 ++++++++++++++++++ ...eMembershipAuthorityEvidenceValidator.java | 153 ++--- ...bershipAuthorityEvidenceValidatorTest.java | 31 + 15 files changed, 729 insertions(+), 102 deletions(-) diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 1033909e2a..96e297a857 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -6,7 +6,7 @@ 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. The latest replacement physical PostgreSQL execution remains pending; the earlier bounded execution provides partial evidence, with selected cases passing and failures outstanding. See the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) for exact proof scope and status. 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). +- The current Account source/currentness cut adds local persistence and writer-fencing consequences to the existing Account ownership boundary. The corrected-fixture Account CI job passed on the published snapshot; subsequent SQL and inspection fixes still need their own physical validation. Focused checks and integration-source compilation pass. See the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) for exact proof scope and status. 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). - 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. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index f384d01b10..a1830fd72c 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -10,7 +10,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn 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. V90–V97 add persistence relations and guards for source-currentness work across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds durable hosted-terms disclosure handoff and immutable source-evidence relations with database transition guards. These DDL stages establish persistence and source-writer fence relationships; they do not activate owner writers, legal authority verification, dispatch, or consumers. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion 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 remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Exact physical and local proof limits are recorded in 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. -Proof qualification: at `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2`, physical PostgreSQL execution established partial evidence: fresh installation through V97, V73 upgrade, and selected V80/V86 cases passed, while other cases failed. V98 and its disclosure persistence proof remain unrun. See the tracker for exact counts, failures, and local results; this evidence does not establish activation or playable closure. +Proof qualification: the earlier `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` run is historical. The corrected-fixture Account CI job passed on the later published snapshot, but subsequent SQL and inspection fixes require new physical validation. See the [player-access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) for the canonical proof inventory and exact limits. These results do not establish activation or playable closure. 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. 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 8edd3ad8c6..8ee288ea59 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,9 +6,9 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -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. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. 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. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. The 7a physical and local proof scopes, failures, and V98 limitation are detailed below and 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. Hosted-terms acceptance, 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). +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. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. 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. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. Historical and current bounded proof, failures, and pending physical validation are recorded below. 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. Hosted-terms acceptance, 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). -Proof qualification for the Account source/currentness cut: the historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` physical Account suite ran 92 cases with zero skips. Fresh installation through V97, V73 upgrade, the closed reset/logout V80 case, and the terms-binding V86 case passed. Three other cases failed: a fixture supplied `varchar` where `timestamptz` was expected, a schema identifier exceeded PostgreSQL's 63-character limit, and a rejection-message expectation differed. A subsequent historical post-7a local-repair snapshot passed the consolidated Account check in 28 seconds; the unchanged 636 Account unit outputs and 245 Common unit outputs were reused. Its local integration run executed two cases and skipped 83 without Docker; those historical counts are not the corrected V98 batch or current-head proof. The corrected V98 batch at `3123c3d883cb025eb28149bd62c99ec389c9f5fb` reported 86 local integration cases, with two executed and 84 skipped, and made no physical PostgreSQL claim. Smoke run `37983056841` passed against 7a in 15m36s. On current head `c69fa3645f3ddf16d2eaafd3838a29a52141736f`, Account job `114042562197`, run `37996096606`, artifact `11647735581` executed 98 physical integration cases with zero skips and one failure. Fresh V98 and V73 coverage, reset-overlap and unrelated-SQL-rollback cases, and V84 creator TRUNCATE/disclosure guards passed. The canonical-order Game Logic settlement fixture failed at commit because V97's terminal guard could not find its required preliminary source-read reservation (`SELECT INTO STRICT` returned no row). A fixture correction has since been prepared locally but has not been physically rerun, so this is not a green Account gate and does not prove the unpublished correction. These bounded results do not establish whole-suite Account readiness or activation. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for exact scope and limitations. +Proof qualification for the Account source/currentness cut: historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` physical and local results are superseded for current proof status; they remain historical evidence only. On `c69fa3645f3ddf16d2eaafd3838a29a52141736f`, physical Account job `114042562197`, run `37996096606`, artifact `11647735581` executed 98 integration cases, with zero skips and one fixture failure. Fresh V98 and V73 upgrade coverage, reset-overlap and unrelated-SQL-rollback cases, and V84 TRUNCATE/disclosure guards passed. The canonical-order Game Logic settlement fixture failed at commit because V97's terminal guard could not find its required preliminary source-read reservation (`SELECT INTO STRICT` returned no row). The correction is published at `fb6ca4dd29fa3f39407f7f2cc32a016fab155403`; exact-head Account job `114050124577` in run `37998363630` passed, including its integration task, with a successful 8m19s check. The overall required Validation Gate is still pending. Subsequent TRUNCATE, exact disclosure-source and inspection-lock changes are not covered by that earlier passing job and require replacement physical CI. This bounded evidence does not establish runtime activation or playable closure. 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. @@ -34,9 +34,9 @@ SEC-04 does not move player session ownership into Logging & Admin. Game Session 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 or an earlier source intent remains `WAITING`, the owner transaction rolls back and returns retryable `AUTH_UNAVAILABLE`; the handler does not wait for source settlement on a thread. An exact retry preserves the original intent and may proceed after its owner-fence outcome is known. The `WAITING` intent retains the Argon2 password verifier required for that retry; terminal source commit or abort clears the verifier while retaining its digest and immutable source binding and receipt. No finite receipt lifetime is selected; receipt retention remains an owning-policy gap. Retained pre-V40 rows remain denied and are neither backfilled nor admitted; unrelated transaction or database failures are not converted by this handler. -For AA-1.3 source-currentness, [AccountAuthoritySourceEventReadback](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java) and the source-fenced reset path in [AccountServiceImpl](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) are production anchors; [AccountAuthoritySourceEventReadbackTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java), [AccountServiceImplTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java), [PasswordResetAuthorityProducerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java), and [AccountAuthoritySourceEvidencePersistenceIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) are focused proof anchors. The Account authority-event reader still rejects generic source events that lack a supported exact closed-operation receipt as `AUTH_UNAVAILABLE`, so this does not claim complete LOGIN/currentness closure. The selected V80 closed reset/logout PostgreSQL case passed at 7a, but physical-suite proof remains incomplete and V98 disclosure persistence proof is unrun. Reset-driven revocation and the broader recovery/session/logout family remain incomplete. +For AA-1.3 source-currentness, [AccountAuthoritySourceEventReadback](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java) and the source-fenced reset path in [AccountServiceImpl](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java) are production anchors; [AccountAuthoritySourceEventReadbackTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java), [AccountServiceImplTest](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java), [PasswordResetAuthorityProducerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java), and [AccountAuthoritySourceEvidencePersistenceIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) are focused proof anchors. The Account authority-event reader still rejects generic source events that lack a supported exact closed-operation receipt as `AUTH_UNAVAILABLE`, so this does not claim complete LOGIN/currentness closure. Physical PostgreSQL results and the pending corrected-fixture CI validation are summarized in the [current proof qualification](#current-status). Reset-driven revocation and the broader recovery/session/logout family remain incomplete. -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. Physical fresh-install-through-V97/V73-upgrade and selected V80/V86 cases passed on 7a, but three other physical cases failed and V98 remains unexecuted; see the proof qualification above. 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. Physical PostgreSQL status and pending current-head validation are summarized in the [current proof qualification](#current-status). 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 index 7be192d55e..f8b9c063fd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -568,13 +568,13 @@ public void recordOwnerReadback(DraftAuthorizationFenceBinding binding, OwnerRea public FenceSnapshot read(DraftAuthorizationFenceBinding binding) { requireTransaction(); - return snapshot(requireExact(readOperation(binding.operationId()), binding)); + return snapshot(requireExact(inspectOperation(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); + Record row = requireExact(inspectOperation(binding.operationId()), binding); return settlement(originalBinding(row), Ordering.valueOf(row.get("ordering", String.class))); } @@ -582,7 +582,7 @@ public Settlement readSettlement(DraftAuthorizationFenceBinding binding) { public Optional readOriginalBinding(UUID operationId) { requireTransaction(); DraftAuthorizationFenceBinding.requireUuid(operationId); - Record row = readOperation(operationId); + Record row = inspectOperation(operationId); return row == null ? Optional.empty() : Optional.of(originalBinding(row)); } @@ -598,10 +598,11 @@ 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. + * Bounded non-locking 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(); @@ -617,7 +618,7 @@ public List readUnresolvedOperations(RecoveryCursor after, 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"; + sql += " ORDER BY f.reserved_at, f.operation_id LIMIT ?"; return dsl.fetch(sql, parameters).stream() .map( row -> @@ -641,7 +642,7 @@ private DraftAuthorizationFenceBinding originalBinding(Record row) { public Optional readOwnerResult( DraftAuthorizationFenceBinding binding, Owner owner) { requireTransaction(); - requireExact(readOperation(binding.operationId()), binding); + requireExact(inspectOperation(binding.operationId()), binding); Record row = dsl.fetchOne( "SELECT owner, outcome, readback, recorded_at FROM " @@ -875,6 +876,11 @@ private Record readOperation(UUID operation) { "SELECT * FROM " + FENCES + " WHERE operation_id = ? FOR UPDATE", operation); } + /** Exact immutable inspection without acquiring the operation row lock. */ + private Record inspectOperation(UUID operation) { + return dsl.fetchOne("SELECT * FROM " + FENCES + " WHERE operation_id = ?", operation); + } + private Record readChange(UUID change) { return dsl.fetchOne("SELECT * FROM " + CHANGES + " WHERE change_id = ? FOR UPDATE", change); } 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 5aab9a1d92..b10734de8a 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 @@ -766,6 +766,8 @@ private VerifiedSourceHistory verifyEventHistory( scope.kind() == ScopeKind.ACCOUNT ? readAccountIdentityForClosedReadback(scope.accountId()) : null; + AccountAuthoritySourceEventReadback eventReadback = + scope.kind() == ScopeKind.ACCOUNT ? closedEventReadback() : null; for (long current = 1L; current <= sequence; current++) { Event stored = outbox @@ -813,8 +815,7 @@ private VerifiedSourceHistory verifyEventHistory( } else if (scope.kind() == ScopeKind.ACCOUNT) { final RetainedEventEvidence receiptEvidence; try { - receiptEvidence = - closedEventReadback().requireRetainedEvent(sourceAccount, stored, authority); + receiptEvidence = eventReadback.requireRetainedEvent(sourceAccount, stored, authority); } catch (RuntimeException missingOrInvalidReceipt) { throw new SourceEvidenceUnavailableException(); } 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 index 718850abf2..bf506f0fa2 100644 --- 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 @@ -81,11 +81,14 @@ AS $$ BEGIN RAISE EXCEPTION 'Password-reset operation receipts are immutable' USING ERRCODE = '23514', CONSTRAINT = 'account_password_reset_operation_immutable'; - RETURN OLD; + RETURN NULL; 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(); +CREATE TRIGGER account_password_reset_operation_no_truncate + BEFORE TRUNCATE ON account_password_reset_operation_receipts + FOR EACH STATEMENT EXECUTE FUNCTION account_password_reset_operation_immutable_guard(); -- [jooq ignore stop] 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 index 00ab9cc390..2a2e13dcf6 100644 --- 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 @@ -80,11 +80,14 @@ AS $$ BEGIN RAISE EXCEPTION 'Logout-all operation receipts are immutable' USING ERRCODE = '23514', CONSTRAINT = 'account_logout_all_operation_immutable'; - RETURN OLD; + RETURN NULL; 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(); +CREATE TRIGGER account_logout_all_operation_no_truncate + BEFORE TRUNCATE ON account_logout_all_operation_receipts + FOR EACH STATEMENT EXECUTE FUNCTION account_logout_all_operation_immutable_guard(); -- [jooq ignore stop] 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 index 662c0252a7..22c8b8548d 100644 --- 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 @@ -171,7 +171,7 @@ BEGIN RAISE EXCEPTION 'Account creator-bootstrap history cannot be deleted' USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_creation_bootstrap_no_delete'; - RETURN OLD; + RETURN NULL; END; $$; @@ -186,4 +186,7 @@ CREATE TRIGGER account_tenant_creation_bootstrap_update 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(); +CREATE TRIGGER account_tenant_creation_bootstrap_no_truncate + BEFORE TRUNCATE ON account_tenant_creation_bootstrap_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_creation_bootstrap_no_delete(); -- [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 index bf01e873c1..4215797d43 100644 --- 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 @@ -127,6 +127,15 @@ CREATE TRIGGER account_hosted_terms_catalog_immutable 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 TRIGGER account_hosted_terms_catalog_no_truncate + BEFORE TRUNCATE ON account_hosted_terms_catalog_versions + FOR EACH STATEMENT EXECUTE FUNCTION account_hosted_terms_immutable_guard(); +CREATE TRIGGER account_hosted_terms_acceptance_no_truncate + BEFORE TRUNCATE ON account_individual_hosted_terms_acceptances + FOR EACH STATEMENT EXECUTE FUNCTION account_hosted_terms_immutable_guard(); +CREATE TRIGGER account_hosted_terms_scope_no_truncate + BEFORE TRUNCATE ON account_hosted_terms_scopes + FOR EACH STATEMENT 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; @@ -299,6 +308,9 @@ $$; 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 TRIGGER account_hosted_terms_publication_no_truncate + BEFORE TRUNCATE ON account_hosted_terms_publication_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_hosted_terms_immutable_guard(); CREATE FUNCTION account_hosted_terms_publication_fence_complete_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ 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 index 7b2862e2b7..a202028110 100644 --- 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 @@ -105,6 +105,9 @@ $$; 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 TRIGGER account_hosted_terms_environment_binding_no_truncate + BEFORE TRUNCATE ON account_hosted_terms_environment_bindings + FOR EACH STATEMENT EXECUTE FUNCTION account_hosted_terms_environment_binding_immutable_guard(); CREATE FUNCTION account_hosted_terms_environment_binding_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ @@ -267,6 +270,9 @@ $$; 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 TRIGGER account_hosted_terms_environment_binding_publication_no_truncate + BEFORE TRUNCATE ON account_hosted_terms_environment_binding_publications + FOR EACH STATEMENT EXECUTE FUNCTION account_hosted_terms_environment_binding_immutable_guard(); CREATE FUNCTION account_hosted_terms_environment_binding_complete_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ diff --git a/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql index 42942353d8..d69854cbec 100644 --- a/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql +++ b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql @@ -101,7 +101,9 @@ BEGIN IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED' AND OLD.dispatch_attempts = 0 AND NEW.dispatch_attempts = 1 AND NEW.result_outcome IS NULL AND NEW.result_payload IS NULL - AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL THEN + AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL + AND EXISTS (SELECT 1 FROM account_hosted_terms_disclosure_sources s + WHERE s.handoff_id = NEW.handoff_id AND s.source_key = NEW.source_key) THEN RETURN NEW; ELSIF OLD.status = 'DISPATCH_AUTHORIZED' AND NEW.status = 'AMBIGUOUS' AND NEW.dispatch_attempts = OLD.dispatch_attempts diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java index f370fbc4f3..706cd84e0c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -53,25 +54,32 @@ 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.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:"; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); - @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } @Test void commitsPasswordTokenAuthorityFenceClosedEventAndImmutableReceiptTogether() { @@ -690,11 +698,7 @@ private boolean concurrentReset( 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()); + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); Flyway.configure() .dataSource(dataSource) .schemas(schema) 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 index 1a7ced2fcd..0a29d27571 100644 --- 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 @@ -9,6 +9,7 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.sql.Connection; import java.sql.SQLException; import java.time.Instant; import java.time.OffsetDateTime; @@ -165,6 +166,33 @@ void freshInstallAppliesEveryForwardMigrationThroughV98() { "ORDER BY account_publication_authorization_source_sort_key(l.source_key) FOR UPDATE OF l"); for (String[] trigger : new String[][] { + { + "account_password_reset_operation_no_truncate", + "account_password_reset_operation_receipts" + }, + {"account_logout_all_operation_no_truncate", "account_logout_all_operation_receipts"}, + { + "account_tenant_creation_bootstrap_no_truncate", + "account_tenant_creation_bootstrap_operations" + }, + {"account_hosted_terms_catalog_no_truncate", "account_hosted_terms_catalog_versions"}, + { + "account_hosted_terms_acceptance_no_truncate", + "account_individual_hosted_terms_acceptances" + }, + {"account_hosted_terms_scope_no_truncate", "account_hosted_terms_scopes"}, + { + "account_hosted_terms_publication_no_truncate", + "account_hosted_terms_publication_operations" + }, + { + "account_hosted_terms_environment_binding_no_truncate", + "account_hosted_terms_environment_bindings" + }, + { + "account_hosted_terms_environment_binding_publication_no_truncate", + "account_hosted_terms_environment_binding_publications" + }, { "account_hosted_terms_disclosure_handoffs_no_truncate", "account_hosted_terms_disclosure_handoffs" @@ -920,6 +948,104 @@ private static byte[] utf8(String value) { return value.getBytes(StandardCharsets.UTF_8); } + @Test + void draftFenceInspectionDoesNotLockOperationRowsAndOwnerWriteKeepsSourceLocks() { + TestContext context = context(null); + SourceEvidence source = + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + UUID.randomUUID().toString(), + "1", + "1", + null, + null, + utf8("test-only draft fence inspection source")); + DraftAuthorizationFenceBinding binding = draftBinding(source); + DraftAuthorizationFenceRepository fences = new DraftAuthorizationFenceRepository(context.dsl()); + context.transaction().executeWithoutResult(status -> fences.reserve(binding)); + + SourceEvidence changedSource = + new SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + utf8("changed test-only source evidence")); + DraftAuthorizationFenceBinding changedBinding = + new DraftAuthorizationFenceBinding( + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.actorAccountId(), + binding.tenantId(), + binding.versionId(), + binding.baseCommitId(), + binding.expectedDraftEpoch(), + binding.gameDesignBinding(), + binding.normalizedInput(), + binding.inputDigest(), + List.of(changedSource), + binding.schemaVersion(), + binding.requiredOwners()); + + context + .transaction() + .executeWithoutResult( + status -> { + assertThat(fences.read(binding).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.RESERVED); + assertThat(fences.readSettlement(binding)) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.PENDING); + assertThat(fences.readOriginalBinding(binding.operationId())).contains(binding); + assertThat(fences.readOwnerResult(binding, Owner.GAME_DESIGN)).isEmpty(); + assertThat(fences.readUnresolvedOperations(null, 10)) + .extracting(DraftAuthorizationFenceRepository.UnresolvedOperation::binding) + .containsExactly(binding); + assertThatThrownBy(() -> fences.read(changedBinding)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed immutable Draft operation"); + + // This separate connection can take the operation row while every inspection above + // remains in its caller transaction; no timing or thread scheduling is involved. + assertThat(lockFenceNowait(context, binding.operationId())) + .isEqualTo(binding.operationId()); + }); + + context + .transaction() + .executeWithoutResult( + status -> + assertThat(fences.claimCommitOrder(binding).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER)); + + OwnerReadback ownerReadback = + new OwnerReadback( + Owner.GAME_DESIGN, + Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + utf8("test-only exact owner result")); + context + .transaction() + .executeWithoutResult( + status -> { + fences.recordOwnerReadback(binding, ownerReadback); + assertThat(fences.readOwnerResult(binding, Owner.GAME_DESIGN)) + .hasValueSatisfying( + result -> assertThat(result.outcome()).isEqualTo(Outcome.COMMITTED)); + assertThatThrownBy(() -> lockSourceNowait(context, source.key())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> lockFenceNowait(context, binding.operationId())) + .isInstanceOf(DataAccessException.class); + }); + } + @Test void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { TestContext context = context(null); @@ -1046,6 +1172,72 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { handoffBinding, sha256(handoffBinding))) .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs " + + "SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 " + + "WHERE handoff_id = ?", + handoffId)) + .isInstanceOf(DataAccessException.class); + assertThat( + context + .dsl() + .resultQuery( + "SELECT status FROM account_hosted_terms_disclosure_handoffs " + + "WHERE handoff_id = ?", + handoffId) + .fetchOne(0, String.class)) + .isEqualTo("PREPARED"); + + UUID unrelatedHandoffId = UUID.randomUUID(); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_disclosure_handoffs " + + "(handoff_id, request_id, kind, source_key, predecessor_digest, " + + "candidate_digest, effective_at, binding, binding_digest, status, " + + "dispatch_attempts) VALUES (?, ?, 'CATALOG', ?, ?, ?, ?::timestamptz, ?, ?, " + + "'PREPARED', 0)", + unrelatedHandoffId, + UUID.randomUUID(), + exactSource.key(), + sha256("unrelated predecessor".getBytes(StandardCharsets.UTF_8)), + HostedTermsEncoding.digest(document), + effectiveAt, + handoffBinding, + sha256(handoffBinding)); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_disclosure_sources " + + "(handoff_id, source_key, source_evidence, source_evidence_digest) " + + "VALUES (?, ?, ?, ?)", + unrelatedHandoffId, + exactSource.key(), + exactSourceEvidence, + sha256(exactSourceEvidence)); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs " + + "SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 " + + "WHERE handoff_id = ?", + handoffId)) + .isInstanceOf(DataAccessException.class); + assertThat( + context + .dsl() + .resultQuery( + "SELECT status FROM account_hosted_terms_disclosure_handoffs " + + "WHERE handoff_id = ?", + handoffId) + .fetchOne(0, String.class)) + .isEqualTo("PREPARED"); context .dsl() @@ -1781,6 +1973,243 @@ void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradic .isZero(); } + @Test + void syntheticHostedTermsAndEnvironmentEvidenceSurvivesTruncateAttempts() { + TestContext context = context(null); + TestIdentity identity = testIdentity(context); + UUID hostedScopeId = UUID.randomUUID(); + UUID termsVersionId = UUID.randomUUID(); + UUID termsPublicationRequestId = UUID.randomUUID(); + UUID creatorPartyId = UUID.randomUUID(); + UUID acceptanceEvidenceId = UUID.randomUUID(); + UUID acceptanceActionRequestId = UUID.randomUUID(); + String environmentBoundary = "test-only/environment-boundary"; + UUID bindingPublicationRequestId = UUID.randomUUID(); + UUID bindingId = UUID.randomUUID(); + byte[] document = + "synthetic test fixture only; not legal terms".getBytes(StandardCharsets.UTF_8); + byte[] versionPayload = + "synthetic hosted terms catalog payload".getBytes(StandardCharsets.UTF_8); + byte[] termsPublicationPayload = + "synthetic initial catalog publication request".getBytes(StandardCharsets.UTF_8); + byte[] creatorSource = + "synthetic verified creator-party evidence".getBytes(StandardCharsets.UTF_8); + byte[] bindingPayload = + "synthetic environment binding payload".getBytes(StandardCharsets.UTF_8); + byte[] bindingPublicationPayload = + "synthetic environment binding publication request".getBytes(StandardCharsets.UTF_8); + OffsetDateTime effectiveAt = OffsetDateTime.now(ZoneOffset.UTC).minusMinutes(1); + String affirmativeActionJson = + "{\"schema\":\"account-hosted-terms-affirmative-action/v1\"," + + "\"actionRequestId\":\"" + + acceptanceActionRequestId + + "\",\"affirmative\":true,\"accountId\":\"" + + identity.accountUuid() + + "\",\"creatorPartyId\":\"" + + creatorPartyId + + "\",\"hostedScopeId\":\"" + + hostedScopeId + + "\",\"shownVersionId\":\"" + + termsVersionId + + "\",\"shownDocumentDigest\":\"" + + sha256(document) + + "\",\"shownOperatorLegalIdentity\":\"TEST FIXTURE ONLY\"," + + "\"shownOperatorIdentityVersion\":\"1\"}"; + byte[] affirmativeAction = affirmativeActionJson.getBytes(StandardCharsets.UTF_8); + + // These isolated synthetic rows exercise the persisted guards only; no production writer or + // runtime activation is involved. + context + .transaction() + .executeWithoutResult( + status -> { + 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', " + + "'test-only/publication', 1, 'test-only/notice', 1, ?::timestamptz, ?, ?)", + termsVersionId, + hostedScopeId, + document, + sha256(document), + effectiveAt, + versionPayload, + sha256(versionPayload)); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_publication_operations " + + "(request_id, hosted_scope_id, request_payload, request_digest, status) " + + "VALUES (?, ?, ?, ?, 'RECEIVED')", + termsPublicationRequestId, + hostedScopeId, + termsPublicationPayload, + sha256(termsPublicationPayload)); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_publication_operations " + + "SET status = 'SCHEDULED', candidate_version_id = ? " + + "WHERE request_id = ?", + termsVersionId, + termsPublicationRequestId); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_scopes SET current_version_id = ?, " + + "current_source_version = 1, current_material_generation = 1 " + + "WHERE hosted_scope_id = ?", + termsVersionId, + hostedScopeId); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_publication_operations SET status = 'COMMITTED', " + + "result_payload = ?, result_digest = ?, committed_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ?", + versionPayload, + sha256(versionPayload), + termsPublicationRequestId); + context + .dsl() + .execute( + "INSERT INTO account_individual_creator_party_sources " + + "(creator_party_id, account_uuid, verification_status, identity_version, " + + "policy_reference, policy_version, verification_evidence_reference, " + + "verification_evidence_version, source_version, source_payload, source_digest) " + + "VALUES (?, ?, 'VERIFIED', 1, 'test-only/policy', 1, " + + "'test-only/verification', 1, 1, ?, ?)", + creatorPartyId, + identity.accountUuid(), + creatorSource, + sha256(creatorSource)); + 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)", + acceptanceEvidenceId, + acceptanceActionRequestId, + creatorPartyId, + identity.accountUuid(), + hostedScopeId, + termsVersionId, + sha256(document), + creatorSource, + sha256(creatorSource), + affirmativeAction, + sha256(affirmativeAction)); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_environment_binding_heads " + + "(environment_boundary) VALUES (?)", + environmentBoundary); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_environment_binding_publications " + + "(request_id, environment_boundary, request_payload, request_digest, status) " + + "VALUES (?, ?, ?, ?, 'RECEIVED')", + bindingPublicationRequestId, + environmentBoundary, + bindingPublicationPayload, + sha256(bindingPublicationPayload)); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_environment_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 (?, ?, ?, ?, 'TEST FIXTURE ONLY', 1, ?, 1, 'test-only/publisher', " + + "'test-only/event', ?, NULL, NULL, 1, ?, ?)", + bindingId, + bindingPublicationRequestId, + environmentBoundary, + hostedScopeId, + termsVersionId, + sha256(bindingPublicationPayload), + bindingPayload, + sha256(bindingPayload)); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_environment_binding_publications " + + "SET status = 'COMMITTED', candidate_binding_id = ?, result_payload = ?, " + + "result_digest = ?, committed_at = CURRENT_TIMESTAMP WHERE request_id = ?", + bindingId, + bindingPayload, + sha256(bindingPayload), + bindingPublicationRequestId); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_environment_binding_heads " + + "SET current_binding_id = ?, current_source_version = 1 " + + "WHERE environment_boundary = ?", + bindingId, + environmentBoundary); + }); + + assertTruncateRejected(context, "account_hosted_terms_catalog_versions"); + assertTruncateRejected(context, "account_hosted_terms_scopes"); + assertTruncateRejected(context, "account_individual_hosted_terms_acceptances"); + assertTruncateRejected(context, "account_hosted_terms_publication_operations"); + assertTruncateRejected(context, "account_hosted_terms_environment_bindings"); + assertTruncateRejected(context, "account_hosted_terms_environment_binding_publications"); + assertThat(count(context, "account_hosted_terms_scopes", "hosted_scope_id", hostedScopeId)) + .isEqualTo(1L); + assertThat( + count(context, "account_hosted_terms_catalog_versions", "version_id", termsVersionId)) + .isEqualTo(1L); + assertThat( + count( + context, + "account_individual_hosted_terms_acceptances", + "evidence_id", + acceptanceEvidenceId)) + .isEqualTo(1L); + assertThat( + count( + context, + "account_hosted_terms_publication_operations", + "request_id", + termsPublicationRequestId)) + .isEqualTo(1L); + assertThat(count(context, "account_hosted_terms_environment_bindings", "binding_id", bindingId)) + .isEqualTo(1L); + assertThat( + count( + context, + "account_hosted_terms_environment_binding_publications", + "request_id", + bindingPublicationRequestId)) + .isEqualTo(1L); + } + @Test void creatorBootstrapWithoutAuthorizationSourceDeniesBeforeAnyOwnerWrite() { TestContext context = context(null); @@ -1830,6 +2259,71 @@ void creatorBootstrapWithoutAuthorizationSourceDeniesBeforeAnyOwnerWrite() { .isZero(); } + @Test + void statementTruncateCannotRemovePasswordResetLogoutOrBootstrapEvidence() { + TestContext context = context(null); + TestIdentity identity = testIdentity(context); + + assertTruncateRejected(context, "account_password_reset_operation_receipts"); + assertTruncateRejected(context, "account_logout_all_operation_receipts"); + assertThat( + context + .dsl() + .resultQuery("SELECT count(*) FROM account_password_reset_operation_receipts") + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + context + .dsl() + .resultQuery("SELECT count(*) FROM account_logout_all_operation_receipts") + .fetchOne(0, Long.class)) + .isZero(); + + UUID requestId = UUID.randomUUID(); + UUID tenantUuid = UUID.randomUUID(); + UUID creationRequestId = UUID.randomUUID(); + UUID creationOperationId = UUID.randomUUID(); + byte[] creatorEvidence = + "synthetic creator-bootstrap evidence".getBytes(StandardCharsets.UTF_8); + byte[] sourceSnapshot = "synthetic tenant source snapshot".getBytes(StandardCharsets.UTF_8); + byte[] requestPayload = "synthetic bootstrap request".getBytes(StandardCharsets.UTF_8); + context + .dsl() + .execute( + "INSERT INTO account_tenant_creation_bootstrap_operations " + + "(request_id, schema_version, initiating_account_uuid, tenant_uuid, " + + "creation_request_id, creation_operation_id, account_authorization_operation_id, " + + "account_authorization_digest, creator_evidence_digest, creator_evidence_payload, " + + "source_snapshot_payload, source_snapshot_digest, request_payload, request_digest, " + + "baseline_membership_version, baseline_membership_authority_generation, " + + "baseline_event_sequence, status) " + + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 0, 'IN_PROGRESS')", + requestId, + identity.accountUuid(), + tenantUuid, + creationRequestId, + creationOperationId, + requestId, + sha256("synthetic authorization".getBytes(StandardCharsets.UTF_8)), + sha256(creatorEvidence), + creatorEvidence, + sourceSnapshot, + sha256(sourceSnapshot), + requestPayload, + sha256(requestPayload)); + + assertTruncateRejected(context, "account_tenant_creation_bootstrap_operations"); + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM account_tenant_creation_bootstrap_operations " + + "WHERE request_id = ?", + requestId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } + private static FreshTenantCreatorEvidence creatorEvidence(UUID accountUuid) { UUID creationRequestId = UUID.randomUUID(); UUID creationOperationId = UUID.randomUUID(); @@ -1935,6 +2429,55 @@ private static long count(TestContext context, String table, String column, UUID .fetchOne(0, Long.class)); } + private static void assertTruncateRejected(TestContext context, String relation) { + assertThatThrownBy(() -> context.dsl().execute("TRUNCATE " + relation + " CASCADE")) + .as("TRUNCATE of immutable evidence relation %s", relation) + .isInstanceOf(DataAccessException.class); + } + + private static UUID lockFenceNowait(TestContext context, UUID operationId) { + return independentTransaction( + context, + dsl -> + dsl.resultQuery( + "SELECT operation_id FROM account_draft_authorization_fences " + + "WHERE operation_id = ? FOR UPDATE NOWAIT", + operationId) + .fetchSingle(0, UUID.class)); + } + + private static String lockSourceNowait(TestContext context, String sourceKey) { + return independentTransaction( + context, + dsl -> + dsl.resultQuery( + "SELECT source_key FROM account_draft_authorization_source_locks " + + "WHERE source_key = ? FOR UPDATE NOWAIT", + sourceKey) + .fetchSingle(0, String.class)); + } + + private static T independentTransaction( + TestContext context, java.util.function.Function work) { + try (Connection connection = POSTGRES.dataSource(context.schema()).getConnection()) { + connection.setAutoCommit(false); + try { + T result = work.apply(DSL.using(connection, SQLDialect.POSTGRES)); + connection.commit(); + return result; + } catch (RuntimeException | Error failure) { + try { + connection.rollback(); + } catch (SQLException rollbackFailure) { + failure.addSuppressed(rollbackFailure); + } + throw failure; + } + } catch (SQLException failure) { + throw new IllegalStateException("Independent PostgreSQL lock probe failed", failure); + } + } + private static String sha256(byte[] value) { try { return "sha256:" 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 index 41c80248d2..beebe35a1f 100644 --- 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 @@ -9,6 +9,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.function.Function; 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; @@ -214,79 +215,28 @@ private static AccountSource verifyAccountSource( return null; } - AccountSource event; - try { - var verified = AccountAuthoritySourceEventV1Codec.verify(supplied.canonicalEventJson()); - if (!(verified instanceof AccountAuthoritySourceEventV1Codec.AccountEvent account)) { - throw invalid("account source", "must be an Account event"); - } - event = - new AccountSource( - account.eventId(), - account.eventDigest(), - account.canonicalJson(), - account.outboxStreamKey(), - account.outboxSequence(), - account.accountId(), - account.accountAuthorityGeneration(), - account.accountSecurityCutoff().accountAuthorityGeneration(), - account.accountSecurityCutoff().outboxStreamKey(), - account.accountSecurityCutoff().outboxSequence()); - } catch (IllegalArgumentException currentSchemaMismatch) { + List> decoders = + List.of( + RuntimeMembershipAuthorityEvidenceValidator::decodeCurrentAccountSource, + RuntimeMembershipAuthorityEvidenceValidator::decodePasswordResetAccountSource, + RuntimeMembershipAuthorityEvidenceValidator::decodeLogoutAllAccountSource, + RuntimeMembershipAuthorityEvidenceValidator::decodeSecurityStateAccountSource); + List failures = new ArrayList<>(decoders.size()); + AccountSource event = null; + for (Function decoder : decoders) { try { - var reset = PasswordResetAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); - event = - new AccountSource( - reset.eventId(), - reset.eventDigest(), - reset.canonicalJson(), - reset.outboxStreamKey(), - reset.outboxSequence(), - reset.accountId(), - reset.accountAuthorityGeneration(), - reset.accountSecurityCutoff().accountAuthorityGeneration(), - reset.accountSecurityCutoff().outboxStreamKey(), - reset.accountSecurityCutoff().outboxSequence()); - } catch (IllegalArgumentException resetFailure) { - try { - var logout = AccountLogoutAllAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); - event = - new AccountSource( - logout.eventId(), - logout.eventDigest(), - logout.canonicalJson(), - logout.outboxStreamKey(), - logout.outboxSequence(), - logout.accountId(), - logout.accountAuthorityGeneration(), - logout.accountSecurityCutoff().accountAuthorityGeneration(), - logout.accountSecurityCutoff().outboxStreamKey(), - logout.accountSecurityCutoff().outboxSequence()); - } catch (IllegalArgumentException logoutFailure) { - try { - var security = - AccountSecurityStateAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); - event = - new AccountSource( - security.eventId(), - security.eventDigest(), - security.canonicalJson(), - security.outboxStreamKey(), - security.outboxSequence(), - security.accountId(), - security.accountAuthorityGeneration(), - security.accountSecurityCutoff().accountAuthorityGeneration(), - security.accountSecurityCutoff().outboxStreamKey(), - security.accountSecurityCutoff().outboxSequence()); - } catch (IllegalArgumentException securityFailure) { - securityFailure.addSuppressed(currentSchemaMismatch); - securityFailure.addSuppressed(resetFailure); - securityFailure.addSuppressed(logoutFailure); - throw securityFailure; - } - } + event = decoder.apply(supplied.canonicalEventJson()); + break; + } catch (IllegalArgumentException unsupportedSchema) { + failures.add(unsupportedSchema); } } + if (event == null) { + IllegalArgumentException failure = + invalid("account source", "does not match any supported Account event schema"); + failures.forEach(failure::addSuppressed); + throw failure; + } requireSourceIdentity( supplied, checkpoint, @@ -305,6 +255,69 @@ private static AccountSource verifyAccountSource( return event; } + private static AccountSource decodeCurrentAccountSource(String canonicalJson) { + var verified = AccountAuthoritySourceEventV1Codec.verify(canonicalJson); + if (!(verified instanceof AccountAuthoritySourceEventV1Codec.AccountEvent account)) { + throw invalid("account source", "must be an Account event"); + } + return new AccountSource( + account.eventId(), + account.eventDigest(), + account.canonicalJson(), + account.outboxStreamKey(), + account.outboxSequence(), + account.accountId(), + account.accountAuthorityGeneration(), + account.accountSecurityCutoff().accountAuthorityGeneration(), + account.accountSecurityCutoff().outboxStreamKey(), + account.accountSecurityCutoff().outboxSequence()); + } + + private static AccountSource decodePasswordResetAccountSource(String canonicalJson) { + var reset = PasswordResetAuthorityEventV1Codec.verify(canonicalJson); + return new AccountSource( + reset.eventId(), + reset.eventDigest(), + reset.canonicalJson(), + reset.outboxStreamKey(), + reset.outboxSequence(), + reset.accountId(), + reset.accountAuthorityGeneration(), + reset.accountSecurityCutoff().accountAuthorityGeneration(), + reset.accountSecurityCutoff().outboxStreamKey(), + reset.accountSecurityCutoff().outboxSequence()); + } + + private static AccountSource decodeLogoutAllAccountSource(String canonicalJson) { + var logout = AccountLogoutAllAuthorityEventV1Codec.verify(canonicalJson); + return new AccountSource( + logout.eventId(), + logout.eventDigest(), + logout.canonicalJson(), + logout.outboxStreamKey(), + logout.outboxSequence(), + logout.accountId(), + logout.accountAuthorityGeneration(), + logout.accountSecurityCutoff().accountAuthorityGeneration(), + logout.accountSecurityCutoff().outboxStreamKey(), + logout.accountSecurityCutoff().outboxSequence()); + } + + private static AccountSource decodeSecurityStateAccountSource(String canonicalJson) { + var security = AccountSecurityStateAuthorityEventV1Codec.verify(canonicalJson); + return new AccountSource( + security.eventId(), + security.eventDigest(), + security.canonicalJson(), + security.outboxStreamKey(), + security.outboxSequence(), + security.accountId(), + security.accountAuthorityGeneration(), + security.accountSecurityCutoff().accountAuthorityGeneration(), + security.accountSecurityCutoff().outboxStreamKey(), + security.accountSecurityCutoff().outboxSequence()); + } + private static MembershipEvent verifyMembershipSource( SourceEvidence supplied, Checkpoint checkpoint, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java index e50b64b3c4..5d97cc27d3 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java @@ -178,6 +178,37 @@ void preservesMalformedResetDigestDiagnosticWhenSecurityStateVerificationFails() .contains("canonical event preimage"))); } + @Test + void reportsAccountSourceFailureWithEverySupportedDecoderDiagnostic() { + var valid = currentSnapshot(); + var accountSource = valid.sourceEvidence().get(0); + var malformedSource = + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + accountSource.outboxStreamKey(), + accountSource.outboxSequence(), + accountSource.eventId(), + accountSource.eventDigest(), + "{\"unsupported\":true}"); + + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith( + valid, + valid.checkpoints(), + List.of(malformedSource, valid.sourceEvidence().get(1))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("account source") + .hasMessageContaining("supported Account event schema") + .satisfies( + failure -> { + assertThat(failure.getSuppressed()).hasSize(4); + assertThat(failure.getSuppressed()) + .allSatisfy( + diagnostic -> assertThat(diagnostic.getMessage()).isNotNull().isNotBlank()); + }); + } + @Test void requiresSortedExactCheckpointAndSourceInventories() { var valid = currentSnapshot(); From 14eaa6c9568928f0079830159ac66f37ead2c146 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:16:50 +1300 Subject: [PATCH 10/10] fix(account): prove optional inventory settlement and complete source vectors --- .../microservices/account-service/README.md | 2 +- .../account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 2 +- ...V94__selected_publication_inventory_v2.sql | 4 +- ...e_logic_intake_source_read_reservation.sql | 4 +- ...wardMigrationsPostgresIntegrationTest.java | 508 +++++++++++++++++- .../service/impl/AccountServiceImplTest.java | 2 + 7 files changed, 515 insertions(+), 9 deletions(-) diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 96e297a857..d6765b92f3 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -6,7 +6,7 @@ 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. The corrected-fixture Account CI job passed on the published snapshot; subsequent SQL and inspection fixes still need their own physical validation. Focused checks and integration-source compilation pass. See the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) for exact proof scope and status. 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). +- The current Account source/currentness cut adds local persistence and writer-fencing consequences to the existing Account ownership boundary. Physical CI executed the inspection-lock, TRUNCATE and disclosure-source regressions successfully; its trigger-catalog fixture failed and is corrected. Final optional-inventory settlement and malformed source-vector corrections require replacement physical CI. See the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) for exact proof scope and status. 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). - 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. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index a1830fd72c..b181153c1f 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -10,7 +10,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn 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. V90–V97 add persistence relations and guards for source-currentness work across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds durable hosted-terms disclosure handoff and immutable source-evidence relations with database transition guards. These DDL stages establish persistence and source-writer fence relationships; they do not activate owner writers, legal authority verification, dispatch, or consumers. New repository-created Accounts receive the V40 source baseline; retained pre-V40 rows are neither backfilled nor admitted. Password-reset completion 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 remains `WAITING`, the request returns retryable `AUTH_UNAVAILABLE`; it does not wait on a thread for settlement, and an exact retry retains the original operation identity. A `WAITING` reset intent retains the Argon2 password verifier needed by that retry; terminal source commit or abort clears the verifier while preserving its digest and immutable source binding and receipt. Finite receipt retention remains unresolved under the owning retention policy; no lifetime is selected here. Logout-all production remains unregistered and unwired. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime activation. Exact physical and local proof limits are recorded in 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. -Proof qualification: the earlier `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` run is historical. The corrected-fixture Account CI job passed on the later published snapshot, but subsequent SQL and inspection fixes require new physical validation. See the [player-access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) for the canonical proof inventory and exact limits. These results do not establish activation or playable closure. +Proof qualification: the earlier `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` run is historical. Later physical CI executed the inspection-lock, TRUNCATE and disclosure-source regressions successfully but failed a trigger-catalog fixture. That fixture and the final optional-inventory settlement and malformed source-vector corrections require replacement physical CI. See the [player-access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) for the canonical proof inventory and exact limits. These results do not establish activation or playable closure. 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. 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 8ee288ea59..8cd9cda7af 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca 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. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. 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. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. Historical and current bounded proof, failures, and pending physical validation are recorded below. 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. Hosted-terms acceptance, 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). -Proof qualification for the Account source/currentness cut: historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` physical and local results are superseded for current proof status; they remain historical evidence only. On `c69fa3645f3ddf16d2eaafd3838a29a52141736f`, physical Account job `114042562197`, run `37996096606`, artifact `11647735581` executed 98 integration cases, with zero skips and one fixture failure. Fresh V98 and V73 upgrade coverage, reset-overlap and unrelated-SQL-rollback cases, and V84 TRUNCATE/disclosure guards passed. The canonical-order Game Logic settlement fixture failed at commit because V97's terminal guard could not find its required preliminary source-read reservation (`SELECT INTO STRICT` returned no row). The correction is published at `fb6ca4dd29fa3f39407f7f2cc32a016fab155403`; exact-head Account job `114050124577` in run `37998363630` passed, including its integration task, with a successful 8m19s check. The overall required Validation Gate is still pending. Subsequent TRUNCATE, exact disclosure-source and inspection-lock changes are not covered by that earlier passing job and require replacement physical CI. This bounded evidence does not establish runtime activation or playable closure. +Proof qualification for the Account source/currentness cut: historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` results remain historical evidence only. Physical Account job `114042562197` on `c69fa3645f3ddf16d2eaafd3838a29a52141736f` executed 98 integration cases with zero skips and one canonical-order Game Logic fixture failure; its correction passed Account job `114050124577` on `fb6ca4dd29fa3f39407f7f2cc32a016fab155403`. The subsequent `f1ed94a42dfdcb1f63bf52c95c60e9e5744af4b7` Account job `114059401680` in run `38001172632`, artifact `11648894382`, executed 101 PostgreSQL integration cases with zero skips and one trigger-catalog fixture failure. The new inspection-lock, immutable TRUNCATE and exact disclosure-source regressions passed. PostgreSQL truncates identifiers to its `name` type's capacity; the catalog assertion now compares through `?::name` while retaining enabled statement-level TRUNCATE checks and actual rejection tests. Final V94 empty optional region/spawn inventory settlement and V97 malformed/missing source-vector rejection regressions require replacement physical CI. The required Validation Gate remains red until that corrected candidate passes. This bounded evidence does not establish runtime activation or playable closure. 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. diff --git a/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql b/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql index 3a61bd3ef4..2def145a6a 100644 --- a/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql +++ b/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql @@ -275,7 +275,7 @@ BEGIN OR NOT (entry ?& ARRAY['family', 'rowCount']) OR jsonb_typeof(entry->'rowCount') IS DISTINCT FROM 'number' OR (entry->>'rowCount')::NUMERIC < 0) - OR (SELECT jsonb_agg(entry ORDER BY entry->>'regionTemplateId') FROM + OR (SELECT coalesce(jsonb_agg(entry ORDER BY entry->>'regionTemplateId'), '[]'::JSONB) FROM jsonb_array_elements(model->'regionGeneratorInputs') entry) IS DISTINCT FROM model->'regionGeneratorInputs' OR EXISTS (SELECT 1 FROM jsonb_array_elements(model->'regionGeneratorInputs') entry @@ -284,7 +284,7 @@ BEGIN OR NOT (entry ?& ARRAY['regionTemplateId', 'generatorType', 'generatorParams']) OR entry->>'generatorType' IS DISTINCT FROM '' OR entry->>'generatorParams' IS DISTINCT FROM '') - OR (SELECT jsonb_agg(entry ORDER BY entry->>'bindingTemplateId') FROM + OR (SELECT coalesce(jsonb_agg(entry ORDER BY entry->>'bindingTemplateId'), '[]'::JSONB) FROM jsonb_array_elements(model->'spawnBindingInputs') entry) IS DISTINCT FROM model->'spawnBindingInputs' OR EXISTS (SELECT 1 FROM jsonb_array_elements(model->'spawnBindingInputs') entry diff --git a/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql b/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql index 3564861a6d..b5eb4a4175 100644 --- a/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql +++ b/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql @@ -115,7 +115,9 @@ BEGIN RAISE EXCEPTION 'Exact original author must have committed settlement before source scope' USING ERRCODE = '23514'; END IF; vector := convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'; - IF jsonb_array_length(vector) < 1 OR jsonb_array_length(vector) <> + IF jsonb_typeof(vector) IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'Incomplete preliminary source participation' USING ERRCODE = '23514'; END IF; + IF jsonb_array_length(vector) < 1 OR jsonb_array_length(vector) IS DISTINCT FROM (SELECT count(*) FROM account_game_logic_intake_source_read_sources WHERE operation_id = NEW.operation_id) THEN RAISE EXCEPTION 'Incomplete preliminary source participation' USING ERRCODE = '23514'; END IF; FOR source_bytes IN SELECT decode(value, 'base64') FROM jsonb_array_elements_text(vector) LOOP 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 index 0a29d27571..d88b6f4378 100644 --- 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 @@ -200,14 +200,28 @@ void freshInstallAppliesEveryForwardMigrationThroughV98() { { "account_hosted_terms_disclosure_sources_no_truncate", "account_hosted_terms_disclosure_sources" + }, + { + "account_game_logic_intake_source_read_no_truncate", + "account_game_logic_intake_source_read_reservations" + }, + { + "account_game_logic_intake_source_read_sources_no_truncate", + "account_game_logic_intake_source_read_sources" + }, + { + "account_game_logic_intake_source_read_aborts_no_truncate", + "account_game_logic_intake_source_read_aborts" } }) { assertThat( context .dsl() .resultQuery( - "SELECT count(*) FROM pg_trigger WHERE tgname = ? " - + "AND tgrelid = ?::regclass AND NOT tgisinternal", + "SELECT count(*) FROM pg_trigger WHERE tgname = ?::name " + + "AND tgrelid = ?::regclass AND NOT tgisinternal " + + "AND (tgtype::INTEGER & 32) <> 0 " + + "AND (tgtype::INTEGER & 1) = 0 AND tgenabled <> 'D'", trigger[0], trigger[1]) .fetchOne(0, Long.class)) @@ -411,6 +425,14 @@ void publicationCompletenessRejectsMissingJsonValuesAndAcceptsMaximumHostedSourc false); } + @Test + void v2PublicationSettlementAcceptsEmptyOptionalInputsButRequiresRoomInventory() { + TestContext context = context(null); + exerciseSelectedPublicationV2Settlement(context, testIdentity(context), 0, 1, true); + exerciseSelectedPublicationV2Settlement(context, testIdentity(context), 0, 0, false); + exerciseSelectedPublicationV2Settlement(context, testIdentity(context), 1, 1, false); + } + @Test void gameLogicSettlementAcceptsCompleteTerminalAndUsesCanonicalSourceLockOrder() { TestContext context = context(null); @@ -689,6 +711,485 @@ void gameLogicSettlementAcceptsCompleteTerminalAndUsesCanonicalSourceLockOrder() operationId) .fetchOne(0, String.class)) .isEqualTo("RETAINED"); + + for (String invalidSourcePayload : + List.of( + publicationSourcePayload(identity, true, true, null), + publicationSourcePayload(identity, true, true, "null"), + publicationSourcePayload(identity, true, true, "{}"), + publicationSourcePayload(identity, true, true, "[]"), + publicationSourcePayload( + identity, + true, + true, + sourceJsonArray(List.of(sourceEvidence("ISSUER", "mismatch")))))) { + assertGameLogicSourceParticipationRejected( + context, identity, versionUuid, selectedCommit, namespace, invalidSourcePayload); + } + } + + private static void exerciseSelectedPublicationV2Settlement( + TestContext context, + TestIdentity identity, + int regionRowCount, + int roomRowCount, + boolean accepted) { + UUID versionUuid = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID fenceId = UUID.randomUUID(); + UUID publishRequestId = UUID.randomUUID(); + UUID intakeRequestId = UUID.randomUUID(); + UUID applicationOperationId = operationId; + UUID workflowId = UUID.randomUUID(); + DraftCommitBinding selectedCommit = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + identity.tenantUuid(), + versionUuid, + 1, + "test-tenant", + 2, + "test-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 revision")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "test-region", + "aggregate", + "test-region", + "0"))); + String expectedTuples = + "[{\"owner\":\"WORLD_MANAGEMENT\",\"aggregateType\":\"region\"," + + "\"aggregateId\":\"test-region\",\"scopeType\":\"aggregate\"," + + "\"scopeId\":\"test-region\",\"expectedEpoch\":\"0\"}]"; + String expectedEpochs = + "[{\"aggregateType\":\"region\",\"aggregateId\":\"test-region\"," + + "\"scopeType\":\"aggregate\",\"scopeId\":\"test-region\"," + + "\"expectedEpoch\":\"0\",\"resultingEpoch\":\"1\"}]"; + String selectedIntent = + jsonObject( + "canonicalTenantId", jsonString(identity.tenantUuid().toString()), + "canonicalVersionId", jsonString(versionUuid.toString()), + "publishRequestId", jsonString(publishRequestId.toString()), + "expectedVersionStateEpoch", jsonString("1"), + "notes", jsonString(""), + "selectedCommitRequestId", jsonString(selectedCommit.requestId().toString()), + "selectedCommitId", jsonString(selectedCommit.commitId().toString()), + "selectedCommitDigest", jsonString(selectedCommit.digest())); + String selectedTarget = + jsonObject( + "canonicalTenantId", jsonString(identity.tenantUuid().toString()), + "canonicalVersionId", jsonString(versionUuid.toString()), + "gameDesignVersionRowId", jsonString("1"), + "gameDesignVersionTenantKey", jsonString("test-tenant"), + "sourceGameRowId", jsonString("2"), + "sourceGameTenantKey", jsonString("test-tenant"), + "sourceProvenanceKind", jsonString("NEW_GAME_ROW")); + String synchronizedFence = + jsonObject( + "requestId", jsonString(selectedCommit.requestId().toString()), + "commitId", jsonString(selectedCommit.commitId().toString()), + "inputDigest", jsonString(selectedCommit.digest()), + "resultVectorJson", jsonString("[]"), + "createdAt", jsonString("test-only")); + String selectedJson = + jsonObject( + "schemaVersion", + jsonString("1"), + "intent", + selectedIntent, + "target", + selectedTarget, + "selectedCommitBindingJson", + jsonString(selectedCommit.canonicalJson()), + "selectedCommitDigest", + jsonString(selectedCommit.digest()), + "synchronizedFence", + synchronizedFence); + byte[] selectedBytes = utf8(selectedJson); + byte[] inputBytes = + encodeFrames( + List.of( + utf8("account-publication-input/v1"), + utf8(identity.accountUuid().toString()), + selectedBytes, + utf8(sha256(selectedBytes)))); + byte[] source = sourceEvidence("HOSTED_TERMS", "test-v2-publication/" + operationId); + String sourceKey = "HOSTED_TERMS:test-v2-publication/" + operationId; + String sourcePayload = + publicationSourcePayload(identity, true, true, sourceJsonArray(List.of(source))); + byte[] sourcePayloadBytes = utf8(sourcePayload); + byte[] bundlePayloadBytes = utf8(publicationBundle(true)); + byte[] outboxCheckpoints = utf8("[]"); + byte[] accountBinding = + encodeFrames( + List.of( + utf8("account-publication-authorization/v1"), + utf8(operationId.toString()), + utf8(fenceId.toString()), + inputBytes, + utf8("1"), + source)); + ControlUiIssuance issuance = + insertCommittedControlUiIssuance(context, identity, sourcePayloadBytes, bundlePayloadBytes); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) " + + "ON CONFLICT DO NOTHING", + sourceKey); + context + .transaction() + .executeWithoutResult( + status -> { + context + .dsl() + .execute( + "INSERT INTO account_selected_publication_authorizations " + + "(operation_id, fence_id, actor_account_uuid, tenant_uuid, " + + "publish_request_id, input_digest, binding, world_evidence, " + + "issuance_operation_id, issuance_fence, " + + "source_payload, issuance_bundle, " + + "outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + fenceId, + identity.accountUuid(), + identity.tenantUuid(), + publishRequestId.toString(), + sha256(inputBytes), + accountBinding, + null, + issuance.operationId(), + issuance.fence(), + sourcePayloadBytes, + bundlePayloadBytes, + outboxCheckpoints); + context + .dsl() + .execute( + "INSERT INTO account_selected_publication_sources " + + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + operationId, + sourceKey, + source); + }); + + String requestDigest = sha256(selectedBytes).substring("sha256:".length()); + String contentDigest = sha256(utf8("test-only content digest")).substring("sha256:".length()); + String graphDigest = sha256(utf8("test-only applied graph digest")); + byte[] appliedOperation = + encodeFrames( + List.of( + utf8("test-world-applied-operation/v1"), utf8(applicationOperationId.toString()))); + byte[] appliedBytes = + utf8( + jsonObject( + "status", + jsonString("APPLIED"), + "operationBytesBase64", + jsonString(Base64.getEncoder().encodeToString(appliedOperation)), + "graphDigest", + jsonString(graphDigest))); + String selectorRequest = + jsonObject( + "targetNamespace", jsonString("test"), + "canonicalTenantId", jsonString(identity.tenantUuid().toString()), + "canonicalVersionId", jsonString(versionUuid.toString()), + "intakeRequestId", jsonString(intakeRequestId.toString()), + "publicationFence", jsonString(fenceId.toString()), + "publicationRequestId", jsonString(publishRequestId.toString()), + "requestDigest", jsonString(requestDigest), + "versionStateEpoch", jsonString("1"), + "publishWorkflowId", jsonString(workflowId.toString()), + "appliedCommitId", jsonString(selectedCommit.commitId().toString()), + "contentDigest", jsonString(contentDigest), + "digestSchemaVersion", "1", + "worldAffectedTuples", expectedTuples); + String selectorJson = + jsonObject( + "schema", jsonString("world-published-start-location-evidence/v1"), + "request", selectorRequest, + "selectorReceiptBytesBase64", + jsonString(Base64.getEncoder().encodeToString(utf8("test-only selector receipt"))), + "originalAccountBindingBytesBase64", + jsonString(Base64.getEncoder().encodeToString(accountBinding)), + "appliedResultBytesBase64", + jsonString(Base64.getEncoder().encodeToString(appliedBytes))); + byte[] selectorBytes = utf8(selectorJson); + String regionFamilyCount = familyCount("REGION", regionRowCount); + String modelJson = + jsonObject( + "modelId", + jsonString("WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1"), + "graphSchemaVersion", + "2", + "graphDigest", + jsonString(graphDigest), + "topologyResultDigest", + jsonString(sha256(utf8("test-only topology digest"))), + "familyCounts", + "[" + + String.join( + ",", + List.of( + regionFamilyCount, + familyCount("ZONE", 0), + familyCount("ROOM", roomRowCount), + familyCount("ROOM_EXIT", 0), + familyCount("GENERATION_RULE", 0), + familyCount("WORLD_ENTITY_SPAWN_BINDING", 0))) + + "]", + "regionGeneratorInputs", + "[]", + "generationRuleFields", + "[\"id\",\"name\",\"scopeType\",\"scopeId\",\"value\"]", + "regionFields", + "[\"id\",\"shardId\",\"name\",\"weather\",\"generationSeed\"," + + "\"generatorType\",\"generatorParams\",\"spacingMultiplier\"]", + "zoneFields", + "[\"id\",\"regionId\",\"name\"]", + "roomFields", + "[\"id\",\"zoneId\",\"name\",\"description\"," + + "\"nameLocalizedVariantsJson\",\"descriptionLocalizedVariantsJson\"]", + "roomExitFields", + "[\"id\",\"fromRoomId\",\"toRoomId\",\"direction\",\"cost\"]", + "spawnBindingFields", + "[\"id\",\"roomId\",\"entityTemplateType\",\"entityReference.kind\"," + + "\"entityReference.tenantId\",\"entityReference.versionId\"," + + "\"entityReference.templateId\",\"spawnCount\",\"respawnDelaySeconds\"]", + "spawnBindingInputs", + "[]", + "generationRuleInputCount", + "0", + "spawnBindingCount", + "0", + "appliedEpochs", + expectedEpochs); + String inventoryJson = + jsonObject( + "schema", jsonString("world-selected-publication-artifact-inventory/v1"), + "schemaVersion", "1", + "completeness", jsonString("COMPLETE"), + "ownerScope", + jsonObject( + "targetNamespace", jsonString("test"), + "canonicalTenantId", jsonString(identity.tenantUuid().toString()), + "canonicalVersionId", jsonString(versionUuid.toString()), + "versionIdentityOperationId", jsonString(UUID.randomUUID().toString()), + "intakeRequestId", jsonString(intakeRequestId.toString()), + "intakeOperationId", jsonString(UUID.randomUUID().toString()), + "intakeRequestDigest", jsonString(sha256(utf8("intake request"))), + "sourceOperationId", jsonString(UUID.randomUUID().toString()), + "sourceEvidenceDigest", jsonString(sha256(utf8("source evidence"))), + "intakeReceiptDigest", jsonString(sha256(utf8("intake receipt")))), + "selectedApplication", + jsonObject( + "applicationOperationId", jsonString(applicationOperationId.toString()), + "applicationRequestId", jsonString(selectedCommit.requestId().toString()), + "appliedCommitId", jsonString(selectedCommit.commitId().toString()), + "bindingDigest", jsonString(selectedCommit.digest()), + "appliedResultDigest", jsonString(sha256(appliedBytes))), + "accountOrder", + jsonObject( + "operationId", jsonString(operationId.toString()), + "fenceId", jsonString(fenceId.toString()), + "actorAccountId", jsonString(identity.accountUuid().toString()), + "publicationRequestId", jsonString(publishRequestId.toString()), + "selectionDigest", jsonString(sha256(selectedBytes)), + "selectedCommitId", jsonString(selectedCommit.commitId().toString()), + "bindingDigest", jsonString(sha256(accountBinding))), + "freeze", + jsonObject( + "publicationFence", jsonString(fenceId.toString()), + "publicationRequestId", jsonString(publishRequestId.toString()), + "requestDigest", jsonString(requestDigest), + "versionStateEpoch", jsonString("1"), + "publishWorkflowId", jsonString(workflowId.toString())), + "checkpoint", + jsonObject( + "appliedCommitId", jsonString(selectedCommit.commitId().toString()), + "contentDigest", jsonString(contentDigest), + "digestSchemaVersion", "1"), + "sourceModel", modelJson, + "artifactDecisions", + "[{\"artifactKind\":\"NAVMESH\",\"state\":\"NOT_REQUIRED\"," + + "\"rule\":\"ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT\"}," + + "{\"artifactKind\":\"PATH_GRAPH\",\"state\":\"NOT_REQUIRED\"," + + "\"rule\":\"AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH\"}]"); + byte[] inventoryBytes = utf8(inventoryJson); + byte[] publicationOperation = + encodeFrames( + List.of( + utf8("game-design-publication-operation/v2"), + accountBinding, + selectorBytes, + inventoryBytes, + utf8(sha256(inventoryBytes)))); + byte[] terminal = + encodeFrames( + List.of( + utf8("game-design-publication-terminal/v1"), + publicationOperation, + utf8("PUBLISHED"), + utf8("test-only complete release content"), + utf8("2"))); + byte[] receipt = + encodeFrames( + List.of( + utf8("account-selected-publication-settlement/v1"), + accountBinding, + publicationOperation, + terminal, + utf8("PUBLISHED"), + terminal)); + + RuntimeException settlementFailure = null; + try { + context + .dsl() + .execute( + "INSERT INTO account_selected_publication_settlements " + + "(operation_id, fence_id, account_binding, publication_operation, " + + "game_design_outcome, game_design_terminal, world_outcome, " + + "world_terminal, receipt) " + + "VALUES (?, ?, ?, ?, 'PUBLISHED', ?, 'PUBLISHED', ?, ?)", + operationId, + fenceId, + accountBinding, + publicationOperation, + terminal, + terminal, + receipt); + } catch (RuntimeException failure) { + settlementFailure = failure; + } + if (accepted) { + if (settlementFailure != null) { + throw settlementFailure; + } + assertThat( + context + .dsl() + .resultQuery( + "SELECT count(*) FROM account_selected_publication_settlements " + + "WHERE operation_id = ?", + operationId) + .fetchOne(0, Long.class)) + .isEqualTo(1L); + } else { + assertPostgresCheckViolation( + settlementFailure, "invalid required family count must fail selected settlement"); + } + } + + private static String familyCount(String family, int count) { + return jsonObject("family", jsonString(family), "rowCount", Integer.toString(count)); + } + + private static void assertGameLogicSourceParticipationRejected( + TestContext context, + TestIdentity identity, + UUID versionUuid, + DraftCommitBinding selectedCommit, + String namespace, + String sourcePayload) { + UUID operationId = UUID.randomUUID(); + UUID fenceId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + byte[] sourcePayloadBytes = utf8(sourcePayload); + byte[] bundlePayloadBytes = utf8(publicationBundle(true)); + ControlUiIssuance issuance = + insertCommittedControlUiIssuance(context, identity, sourcePayloadBytes, bundlePayloadBytes); + byte[] scopeBytes = + encodeFrames( + List.of( + utf8("account-game-logic-intake-source-read/v1"), + utf8(namespace), + utf8(operationId.toString()), + utf8(fenceId.toString()), + utf8(requestId.toString()), + utf8(identity.accountUuid().toString()), + selectedCommit.canonicalBytes(), + utf8(sha256(selectedCommit.canonicalBytes())), + utf8("spiffe://firemud/ns/" + namespace + "/sa/account-service"), + utf8("GAME_LOGIC_INTAKE_SOURCE"))); + RuntimeException reservationFailure = null; + try { + context + .transaction() + .executeWithoutResult( + status -> + context + .dsl() + .execute( + "INSERT INTO account_game_logic_intake_source_read_reservations " + + "(operation_id, fence_id, intake_request_id, actor_account_uuid, " + + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, " + + "issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + fenceId, + requestId, + identity.accountUuid(), + identity.tenantUuid(), + versionUuid, + scopeBytes, + sha256(scopeBytes), + issuance.operationId(), + issuance.fence(), + sourcePayloadBytes, + bundlePayloadBytes, + utf8("[]"))); + } catch (RuntimeException failure) { + reservationFailure = failure; + } + assertPostgresCheckViolation( + reservationFailure, "invalid preliminary source vector must fail at PostgreSQL commit"); + } + + private static void assertPostgresCheckViolation(RuntimeException failure, String reason) { + assertThat(failure).as(reason).isNotNull(); + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause).as(reason).isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause).getSQLState()).as(reason).isEqualTo("23514"); + } + + private static String jsonObject(String... fields) { + if (fields.length % 2 != 0) { + throw new IllegalArgumentException("JSON object fields must be key/value pairs"); + } + List members = new ArrayList<>(); + for (int index = 0; index < fields.length; index += 2) { + members.add(jsonString(fields[index]) + ":" + fields[index + 1]); + } + return "{" + String.join(",", members) + "}"; + } + + private static String jsonString(String value) { + return "\"" + + value + .replace("\\", "\\\\") + .replace("\"", "\\\"") + .replace("\b", "\\b") + .replace("\f", "\\f") + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t") + + "\""; } private static TestIdentity testIdentity(TestContext context) { @@ -845,7 +1346,8 @@ private static void exerciseSelectedPublication( "INSERT INTO account_selected_publication_authorizations " + "(operation_id, fence_id, actor_account_uuid, tenant_uuid, " + "publish_request_id, input_digest, binding, world_evidence, " - + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, " + + "issuance_operation_id, issuance_fence, " + + "source_payload, issuance_bundle, " + "outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", operationId, fenceId, 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 7761ea72a4..4928bef0b8 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 @@ -5813,6 +5813,8 @@ void candidatePasswordVerifierIsPreparedBeforeWritableOwnerTransactionBegins() { "invalid-reset-token", "candidate-password"))); } + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.atLeastOnce()) + .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); assertTrue(candidateVerifierPrepared.get()); }