diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 87c35f30a7..4512143b38 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2574,7 +2574,7 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#revokeBeforeCommitDeniesDelayedRequestsUntilBothDefinitiveAborts()' \ --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBothReadbacks()' \ --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReopening()' \ - --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#bothMixedDirectionsFailNonpublicationAndReleaseOnlyAfterBothExactReadbacks()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#bothMixedDirectionsRemainPendingAndPreserveOriginalReadbacks()' \ --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#revokeOrderWithEitherMixedDirectionCannotAuthorizeSourceMutation()' \ --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#changedCompleteBindingsConflictWithoutRewritingOriginal()' \ --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#inconsistentOrMalformedCompleteBindingsFailBeforeReservationStorage()' \ @@ -2587,9 +2587,16 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#originalRecoveryRejectsMalformedBytesAndEveryConflictingIdentityColumn()' \ --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#ownerRecoveryRejectsReadbackThatContradictsItsOutcomeColumn()' \ --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#twoOwnerConsumerPersistsWorldOnceAndRecoversMissingGameDesignOnRetry()' \ - --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#mixedCommitOrderPreservesOriginalWorldCommitAndTerminalConsumerRetry()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#mixedCommitOrderPreservesOriginalWorldCommitAndHoldsSourceFence()' \ --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#concurrentExactConsumerRetriesReturnTheSameOriginalSettlement()' \ --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#concurrentConflictingOwnerEvidenceRejectsRetryAndPreservesWinningBytes()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#v2WorldEntityAndCoordinatorRequireAllThreeExactOriginalResults()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#v2FreshDraftEpochZeroAcceptsExactRequiredOwnerReadback()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#rawSqlCannotRecordOwnerProofWithMissingChangedOrExtraSourceParticipation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#v2RequiredOwnerDecoderRejectsMissingExtraDuplicateAndReorderedOwners()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#v2AllRequiredAbortsSettleBothCommitAndRevokeOrdering()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#v2MixedResultsHoldBothSourceTransitionsAndPreserveAppliedBytes()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#forwardMigrationRetainsV1BindingReadbackAndFlywayChecksumsExactly()' \ account-service - name: Verify Game Design authored-draft publication PostgreSQL proof @@ -2752,7 +2759,7 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#invalidHistoricalSelectorsFailWithoutChangingAnyAccountSourceEvidence()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#historicalReaderHoldsAccountFenceThroughSelectedAndCurrentSourceReadback()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#revokeOrderWaitsForBothExactAbortsBeforeOneLogoutAdvanceAndNeverAdmitsDelayedCommit()' \ - --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#commitOrderWaitsForBothExactOutcomesIncludingMixedFailureBeforeLogoutAdvance()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#mixedCommitOrderHoldsLogoutAuthorityAndPreservesOriginalOwnerResult()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#pendingRetryKeepsOriginalCaptureAndConflictsOnlyOnChangedCallerBindings()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#lateDatabaseFailureAfterReceiptEventAndBothJournalTransitionsRollsBackLogoutOnly()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountLogoutAllAuthorityProducerPostgresIntegrationTest#v59ToV60PreservesImmutableLogoutResetSourceOutboxAndFenceHistoryWithoutBackfill()' \ @@ -3452,6 +3459,43 @@ jobs: --require-case 'integration.net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyPostgresIntegrationTest#databaseRejectsSourceAndReceiptRewritesAndOrphanInitialHistory()' \ account-service + # Run after creator-party XML is captured: integrationTest replaces reports. + - name: Run Account hosted-terms PostgreSQL proof cases + if: ${{ matrix.module == 'account-service' }} + run: | + ./gradlew :account-service:integrationTest \ + --tests integration.net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsPostgresIntegrationTest \ + --tests integration.net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingPostgresIntegrationTest \ + -PfullCheck --no-build-cache --no-configuration-cache + + - name: Capture Account hosted-terms PostgreSQL raw XML + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: account-hosted-terms-postgresql-proof-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + services/account-service/build/test-results/integrationTest/TEST-*AccountHostedTermsPostgresIntegrationTest.xml + services/account-service/build/test-results/integrationTest/TEST-*HostedTermsEnvironmentBindingPostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: Verify Account hosted-terms PostgreSQL proof cases + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsPostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsPostgresIntegrationTest#migrationRetainsExistingPartyAndBackfillsNoCatalogOrAcceptance()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsPostgresIntegrationTest#realServicePublishesAffirmativelyAcceptsReadsBackAndAdvancesMateriality()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsPostgresIntegrationTest#acceptanceRejectsWrongSignerNegativeActionChangedShownTermsAndUnavailableIdentity()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsPostgresIntegrationTest#futureTermsCarryDeadlineWithoutFreezingPriorTermsEarly()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsPostgresIntegrationTest#ownerTransactionRollbackRemovesUncommittedCatalogAndPublicationIntent()' \ + --require-suite integration.net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingPostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingPostgresIntegrationTest#realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersions()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingPostgresIntegrationTest#bindingUpdateWaitsForExactTerminalSettlementOfAffectedDraftOperation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingPostgresIntegrationTest#boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline()' \ + account-service + - name: Verify Game Session LOGIN fixture isolation proof if: ${{ !cancelled() && matrix.module == 'game-session-service' }} run: | diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index b4bcee2920..db5bbf1853 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -40,6 +40,14 @@ Recovery reads the original immutable results and never remints permission or re Account is the sole target authority for the identified hosted Creator Party, operator/legal-party and terms-version catalog, and acceptance/currentness evidence under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md). Acceptance is an explicit party-level decision for an identified operator and hosted-terms scope; tenant roles, billing ownership, payment, caller-supplied fields, or a copied Game Design flag do not establish party, signer, or acceptance authority. Organization and other unsupported party/signer paths remain disabled until their target contract is implemented and reviewed. +Account selects the official hosted-terms scope from the existing canonical environment boundary through the [authenticated environment-owner publication contract](../../infrastructure/environment-and-secrets-overview.md#secret-governance-tiers); neither a caller-selected scope, the latest acceptance, a tenant role nor a Git manifest authenticates that selection. Account owns an immutable binding receipt and its current head, binding that environment boundary to the exact hosted scope, legal operator, catalogue source version, authenticated publisher identity, publication event, evidence digest and predecessor. This reuses the environment authority rather than introducing another environment UUID registry; an operator credential binding is not itself legal-party evidence. An exact retry reads back the original receipt, while changed evidence under the same publication identity conflicts. A binding update preserves history and atomically fences the affected source and outstanding captures. Account validates the binding, current catalogue and exact party acceptance together in its owner transaction; absent, contradictory or unproved publication authority denies the capture. The binding implementation does not establish production publisher custody or channel readiness, and isolated test-owner publication evidence is not production authority. + +The binding head participates as a separate `HOSTED_TERMS` source with scope `environment-boundary/`, distinct from the catalogue's canonical hosted-scope UUID. Its positive source version is independent of the catalogue source version and material-acceptance generation; the binding source has no fabricated material generation. Both exact sources and their evidence must accompany a bound capture and its source-change ordering. The namespace is part of the Account-owned source identity, not a new environment registry or permission inferred from arbitrary scope text. + +Currentness evidence retains the exact operative catalogue and affirmative acceptance together with the immutable scheduled catalogue receipt and its disclosed effective date, or explicit absence proved by the same locked Account snapshot. A detached deadline or missing receipt is not complete source evidence. Capturing that history does not enforce an owner's physical commit deadline; the consumer must still prove current authority through its commit boundary. + +**Implementation boundary:** the unregistered Account workflow adds immutable catalog publication, affirmative individual acceptance, exact retained result recovery and currentness evaluation. Its trusted operator and individual-action collaborators are not public request authority, and its isolated test policy and identity evidence are not operative legal publication or live identity verification. A scheduled version retains its disclosed effective date independently of unresolved owner settlement; currentness must use fresh database time after source locks and cannot extend the earlier acceptance beyond that date. The protected Draft authorization producer, complete source-writer participation and through-commit consumer checks remain required. The existing deny-only authoring gate is not enabled by these storage and service components; executed proof and live launch prerequisites belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). + For a fresh tenant with no prior creator-party association or association history, Account may record an explicit initial association requested by the authenticated initiator of that exact committed Game Design tenant-creation operation. Account independently verifies the initiator's own individual creator party and the complete committed creation evidence, binding the canonical tenant, initiating Account and original creation operation/evidence to the immutable association result. Account proves the absence of any prior association or history at its commit boundary; missing or contradictory creation, individual-party or history evidence denies the association. A `tenantAdmin` role alone is insufficient. Exact retries recover the original operation and association without choosing another party or rewriting the creation evidence. Retained tenant associations require separate, owner-approved audited evidence and do not use this fresh-only path. The initial association is neither hosted-terms acceptance nor authority to create content, transfer parties or admit gameplay. Independently verified individual identity, legally reviewed terms and verification policy, and retention/launch gates remain required; recording a tenant-party link does not satisfy or waive them. @@ -58,17 +66,19 @@ Decline or missing reacceptance does not itself cancel a subscription, delete co ### Account-Owned Authored-Draft Authorization Fence -Account owns the exact-operation authorization fence for the multi-owner Draft commit in [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md). It binds the authenticated acting Account, canonical tenant and Version, stable operation and commit identities, complete mutation/input digest, expected Draft and base commit, and each applicable current role, party, terms and authority source with its independent version and checkpoint. Game Design and World remain the mutation owners. A capture, reservation, source receipt or finalization response is not reusable permission for a later owner commit. +Account owns the exact-operation authorization fence for the multi-owner Draft commit in [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md). It binds the authenticated acting Account, canonical tenant and Version, stable operation and commit identities, complete mutation/input digest, expected Draft and base commit, and each applicable current role, party, terms and authority source with its independent version and checkpoint. Game Design coordinates the complete commit; every affected service remains the owner of its local mutation. A capture, reservation, source receipt or finalization response is not reusable permission for a later owner commit. + +The forward-versioned `account-draft-authorization-fence/v2` binds a closed, ordered required-owner set derived from the complete authenticated Game Design `DraftCommitBinding`. It always includes Game Design coordinator completion and includes each applicable independent mutation owner, including World and Entity; Game Design's own control-plane work is covered by its coordinator result. A syntactically valid owner list is not authenticated or semantically complete source evidence. Missing, extra, duplicate, substituted or unsupported owners deny authorization. Retained v1 bindings and readbacks keep their original bytes and identities; they are not rewritten or promoted to v2 proof. -Account durably orders the exact operation against changes to every applicable authority source before either owner may commit. If the authority change wins, owner work must be rejected and the source mutation may finish only after definitive, exact no-commit/abort readback from both participants. If the operation wins, Account waits for every participant's definitive outcome. Both commits establish success; both definitive aborts or a definitive mixed vector establish terminal failure/nonpublication and may release the authorization fence without advancing synchronized Draft visibility. World's original applied result remains immutable even when Game Design definitively did not commit. An unknown Game Design result is not no-commit proof: recovery must first recover any valid committed result or obtain durable no-commit evidence that fences delayed attempts for the exact operation. Conflicting, missing or unavailable evidence remains pending. The operation ordering, all original participant results and source-change intent remain durable and immutable; they are not reopened or rewritten to manufacture matching outcomes. The prior synchronized version remains authoritative, and any compensation is a separate freshly authorized operation rather than a rewrite of original apply evidence. +Account durably orders the exact operation against changes to every applicable authority source before any required owner may commit. If the authority change wins, owner work must be rejected and the source mutation may finish only after definitive, exact no-commit/abort readback from the entire required set. If the operation wins, Account waits for every required participant's definitive outcome. All exact commits, including coordinator completion, establish success; all exact definitive aborts may establish terminal nonpublication. A mixed vector remains held and non-authorizing: it does not release the source fence or advance synchronized Draft visibility. Original applied results remain immutable when another owner did not commit. An unknown result is not no-commit proof: recovery must first recover any valid committed result or obtain durable no-commit evidence that fences delayed attempts for the exact operation. Conflicting, missing or unavailable evidence remains pending. The operation ordering, all original participant results and source-change intent remain durable and immutable; they are not reopened or rewritten to manufacture matching outcomes. The prior synchronized version remains authoritative, and any compensation is a separate freshly authorized operation rather than a rewrite of original apply evidence. Each local transition uses a short owner transaction; no database lock spans a remote call and this is not a distributed database transaction. The source writer must participate in this ordering at its own commit, including issuer/account-wide changes when applicable. An Account-local reservation table alone does not prove that integration. The fence cannot extend authorization past a disclosed hosted-terms effective date or replace Account's required currentness check; the [hosted-terms contract](#account-owned-hosted-terms-and-creator-party) remains authoritative. Expiry, a lease, an operator acknowledgement, absence of an outcome, or a previously returned authorization result cannot bypass recovery or create permission. -A disclosed terms effective date is never delayed by unresolved owner work and never grandfathers a later Game Design commit. Recovery may recognize an exact valid pre-deadline commit; otherwise Game Design must provide the durable final no-commit proof before the definitive mixed failure can settle. Staged or partially applied content remains non-authoritative and cannot satisfy publication or admission. +A disclosed terms effective date is never delayed by unresolved owner work and never grandfathers a later Game Design commit. Recovery may recognize an exact valid pre-deadline commit; otherwise each required owner must provide its exact durable terminal evidence, and a partial or mixed result remains held. Staged or partially applied content remains non-authoritative and cannot satisfy publication or admission. -**Implementation boundary:** the internal durable fence and participant readback storage are preparation, not an authenticated authorization producer or enabled writer. The unwired logout-all source producer now retains an immutable pending caller binding and original Account capture, waits for both definitive participant outcomes, and commits its source advance, event, receipt and linked journals in one Account transaction. Pending readback grants no authorization. Complete participation by the remaining source writers, current role/party/terms proof, authenticated participant verification and executed commit-versus-revocation proof remain required before canonical writes may be enabled. No public route or wire schema is selected by this section. Current proof and remaining gates belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). +**Implementation boundary:** the internal durable fence and participant readback storage are preparation, not an authenticated authorization producer or enabled writer. The unwired logout-all source producer retains an immutable pending caller binding and original Account capture, waits for the complete original required-owner set to satisfy the settlement predicate, and commits its source advance, event, receipt and linked journals in one Account transaction. Pending readback grants no authorization. Complete participation by the remaining source writers, current role/party/terms proof, authenticated participant verification and executed commit-versus-revocation proof remain required before canonical writes may be enabled. No public route or wire schema is selected by this section. Current proof and remaining gates belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). -Account recovery reads the original durable operation rather than recapturing sources or replacing its binding. The [World terminal readback](../world-management-service/api-contracts.md#exact-authored-draft-terminal-readback) and [Game Design terminal readback](../game-design-service/api-contracts.md#exact-authored-draft-terminal-readback) run outside the Account transaction; only independently authenticated, exact terminal results may be recorded in a subsequent short owner transaction. Recovery rechecks the original operation and ordering at that transaction boundary. A stored World-only result must not skip the missing Game Design read, and `UNKNOWN` stores no invented outcome. This readback grants no authorization or source-mutation permission beyond the definitive settlement predicate above. +Account recovery reads the original durable operation rather than recapturing sources or replacing its binding. The [World terminal readback](../world-management-service/api-contracts.md#exact-authored-draft-terminal-readback), [Game Design coordinator readback](../game-design-service/api-contracts.md#exact-authored-draft-terminal-readback) and each other required owner's independent readback run outside the Account transaction; only independently authenticated, exact terminal results may be recorded in a subsequent short owner transaction. Each result binds its owner, original operation/commit/fence, complete binding and input digest, and exact owner result bytes. Game Design's aggregate status cannot substitute for an independent Entity or World outcome. Recovery rechecks the original operation, required-owner set and ordering at that transaction boundary. A stored subset must not skip any missing owner read, and `UNKNOWN` stores no invented outcome. This readback grants no authorization or source-mutation permission beyond the definitive settlement predicate above. ### Account-Owned Publication Authorization Fence 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 9759c1e824..acbc87deaa 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,24 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The V95 hosted-environment continuation adds an unregistered immutable binding receipt, predecessor history and current head selected through trusted environment-owner collaborators. Its binding source counter and namespaced participation key remain independent of the hosted catalogue and material-acceptance generation. Currentness captures exact operative catalogue, affirmative acceptance and scheduled catalogue/deadline evidence together; pending binding changes deny currentness until the original required owners settle. Five new unit cases execute, and three new PostgreSQL cases compile and discover but skip locally. R23 full Account checks, formatting, schema generation, analyzers, integration compilation, packaging, links and Markdown pass in 2m47s: 1,114 unit and three non-database integration executions, zero failures, and 526 PostgreSQL skips without Docker. The CI selector, raw artifact and strict gate retain all five existing hosted-terms cases and add all three binding cases. Trusted publisher custody, the production publication/current-environment channel, complete protected Draft producer and held commit-time enforcement remain open; neither these collaborators nor isolated policy fixtures authenticate production authority or enable canonical writes. + +At exact historical source `b432e8a693a04b40d09dce64cf28f2e59399f929`, [CI37733635593](https://github.com/benhook1013/FireMUD/actions/runs/37733635593) physically executes all twenty-six Draft-fence PostgreSQL cases cleanly, including retained checksum/binding proof. All five hosted-terms PostgreSQL cases execute and fail: four share the plain-SQL `effective_at` varchar binding, and one compares byte-array identity inside a retained-row map. Published `edf0e879dc63e6ab61bebbdf42ca91a97de9892e` fixes the timestamp cast and exact byte comparison without relaxing assertions; its corrected physical CI is pending. Raw XML proves the historical execution, not the V95 continuation or a green current aggregate. Local R20 at that exact published head passes the full Account gate with 1,109 unit and three non-database integration executions and 523 PostgreSQL skips. + +The existing-only fresh creator-party reader derives the initial association operation, creator qualification and party from persisted canonical tenant and bootstrap rows, then validates the exact immutable receipt and single-entry history. Its tenant-first lock order matches the initial-association writer; it does not provision a party, infer a retained association or authorize a caller. Parent inspection corrected the mock fixture's missing no-argument SQL and untyped-record overloads before accepting its negative proof. All six focused reader cases execute cleanly; corrected R18 full Account checks, formatting, analyzers, integration compilation, packaging, links and Markdown pass in 2m7s, with 1,109 unit and three non-database integration executions, zero failures, and 523 PostgreSQL skips without Docker. The [Account-owned hosted-scope binding contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party) now has the bounded V95 receipt/head continuation above; production owner-publication proof, complete Draft capture and runtime activation remain denied. + +The V94 hosted-terms continuation implements an unregistered Account catalog, affirmative individual acceptance and currentness workflow, rather than seeding an acceptance flag. Explicitly isolated test-only operator, policy and identity collaborators drive that workflow; they neither publish an operative agreement nor prove a production signer or identity provider. Immutable catalog and acceptance bytes, stable request recovery, independent source/material-generation advancement, scheduled effective dates and pending source-fence settlement are the bounded proof targets. Corrected R14 full Account checks, formatting, Checkstyle, SpotBugs, JaCoCo, integration compilation, packaging, links and Markdown pass in 55 seconds. The unchanged production/unit candidate retains R13's 1,103 clean executed unit cases, including all ten new hosted-terms cases; three non-database integration cases execute and all 523 PostgreSQL definitions skip locally without Docker. All five new hosted-terms PostgreSQL cases compile and discover but remain unexecuted locally; their dedicated CI run, raw XML capture and strict required-case gate preserve that proof obligation. A lock/deadline barrier case requires fresh database time after acquiring the scope lock. R12's missing test parenthesis and R13's unused test overload were corrected without weakening assertions or suppressing analysis. PostgreSQL execution, the protected authenticated Draft producer, complete current role/party/authority composition and consumer commit-time checks remain open, and canonical writes and runtime activation remain denied under the [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-hosted-terms-and-creator-party). + +At exact corrected required-owner source `df39581f9881f5f5072228825db34d00547599d7`, [CI37729668224](https://github.com/benhook1013/FireMUD/actions/runs/37729668224) executes 1,093 clean unit tests and 525 integration tests with one failure and zero skips. All seven earlier non-Draft owner-settlement failures now pass. The twenty-six-case Draft fence suite has one remaining migration-fixture failure: its unbounded upgrade includes test-only V1000–V1002 history rows. Inspection of the complete captured HTML assertion proves the null-version schema marker and all original V1–V80 checksum rows are retained unchanged. The correction targets V81 explicitly for this V80→V81 preservation test and retains its new-V81-row, complete checksum, exact binding/readback and pending-settlement assertions. Corrected PostgreSQL execution remains required; no production migration or guard is relaxed. The runner merge has the exact parent/source pair and a source-identical tree. Raw Draft XML was unavailable, so the failure diagnosis rests on captured per-method HTML rather than a claimed raw-XML result. + +At exact required-owner source `8e5370bc9a9974b60f99e4d103f582ae0bb75a7b`, [CI37726485230](https://github.com/benhook1013/FireMUD/actions/runs/37726485230) executes all twenty-six Draft-fence PostgreSQL cases without skips: twenty-five pass, including six of the seven additive V81 cases. The retained-history case fails because its comparison query excludes Flyway's existing null-version schema marker, not because the reported migration checksum changed. The correction uses null-safe exclusion of only V81 and explicitly requires its new history row, retaining every original checksum and binding/readback assertion. Corrected Account full checks, formatting, analyzers, integration compilation and packaging pass in R7 (43s); the unchanged unit task retains 1,093 clean executed results, three non-database integrations execute, and all 518 PostgreSQL definitions skip locally without Docker. Corrected PostgreSQL execution and the remaining Account CI failures are still open; these component results do not establish authenticated current source authority or runtime activation. + +The complete same-head Account report contains 1,093 clean unit executions and 525 integration executions with eight distinct failures and zero skips. Repeated strict verification steps inspect the same reports, not additional executions. The other seven failures are owned by the required-owner convergence even though their fixture paths were unchanged: three send newly added enum owners into retained v1 bindings, and four still expect mixed outcomes to release password-reset, issuer, tenant or admin-transfer source intents. Their correction iterates each exact binding's required-owner vector, retains uniform all-commit/all-abort positive cases, and proves that mixed evidence preserves source counters, events, pending intents and original owner outcomes. Existing strict selector names are retained. R9 exposed five generic transaction-result inference sites in the added JOIN assertions; explicit result types correct compilation without relaxing proof. R10 full Account checks, formatting, analyzers, integration compilation and packaging pass in 45s; local PostgreSQL execution remains unavailable. All eight corrected physical cases and aggregate CI still require confirmation; no production guard, migration or v2 wire bytes are weakened by the fixture corrections. + +The forward-only Account Draft authorization continuation versions the existing family to `account-draft-authorization-fence/v2`, deriving its exact required-owner vector from the complete Game Design binding and always including coordinator completion. V81 preserves retained v1 bindings, readbacks and migration checksums; it validates full owner/readback framing and complete original source participation before accepting terminal evidence. Repository and database settlement now keep mixed outcomes pending, including the existing logout-all source writer; an aggregate coordinator result cannot replace Entity or World proof. Shared codec cases and seven additive PostgreSQL definitions cover missing, extra, duplicate, reordered, changed and mixed evidence, fresh Draft epoch zero, and retained-history migration. Corrected R4 full Core/Account checks, formatting, Checkstyle, SpotBugs, coverage, Account packaging and documentation validation pass in 2m13s. Account executes 1,093 clean unit cases, including fourteen subset-recovery cases; Core retains 358 clean executed unit outcomes from the preceding affected gate. Three non-database integrations execute, while all 518 PostgreSQL cases skip locally without Docker, including the entire twenty-six-case Draft fence suite. The strict workflow preserves nineteen inherited Draft cases and requires all seven new ones; workflow lint, twenty-five scope contracts and Flyway sanity (twelve sets/230 files) pass. The existing recovery consumer has only Game Design and World clients, skips World when it is not an original required owner, and cannot settle missing Entity proof. Complete additional-owner recovery, authenticated held-order production, current role/creator/terms sources and their commit-bound proof remain open. Storage is not permission, and canonical writes remain denied under the [Account fence contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-authored-draft-authorization-fence). + +The required-owner shared-binding continuation also passes Game Design and World full checks, formatting, analyzers, integration compilation and documentation validation in R5 (3m1s). Game Design executes 609 unit cases with one object-store skip; World executes 392 unit cases without skips. All 196 Game Design and 172 World PostgreSQL definitions skip locally without Docker. This checks their existing shared-binding consumers; it does not supply Entity terminal transport, authenticated current creator/terms production or enabled owner writes. + The fresh Game Session launch-owner receiving candidate adds a separately authenticated Game Design tenant association, a Game Session-owned private key, and complete v2 launch association capture/read. It retains V15/V16 source/transaction guards, same-namespace World-only transport, genuine SHARED/public-production catalog evidence and exact immutable selector echoes. The explicit, unregistered STARTING producer allocates or exactly retries a real Game Session instance and captures its full descriptor/attestation association in the same owner transaction, with independent committed readback. The source-qualified complete binding read validates the committed preparation before network I/O; no flat numeric launch fallback or runtime activation is supplied. Consolidated jOOQ, main/unit/integration-source compilation, boot JAR, formatting and documentation checks pass; 36 focused Game Session and five shared policy cases pass without failures or skips. PostgreSQL producer, retry, changed-pair rollback and migration definitions compile but have not executed locally. Physical PostgreSQL proof, runtime coordinator wiring, authenticated World preparation/through-commit/lifecycle readback and fresh-image playable proof remain open. Existing numeric capability fields are not canonical tenant association evidence, and Game Session status is not World lifecycle authority. The current #3029 local candidate adds unwired Account V79 publication participation and the shared exact selected-Draft codec. The existing Game Design adapter preserves its original eight-input selection bytes/digest. Publication reservations and immutable publication/revocation orders share the existing source locks and WAITING journal; source changes cannot finish while any affected publication lacks its own authenticated terminal results. Earlier Draft outcomes cannot satisfy this predicate. Twelve new PostgreSQL definitions cover replay/restart, source races, rollback, direct-SQL guards and retained V78 history, but have not executed locally without Docker. The current authority producer, Game Design no-publication seal, both-owner terminal verification and settlement remain required; nothing here enables publication or creator authority. See [Account's publication authorization owner contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-publication-authorization-fence). @@ -18,7 +36,7 @@ At exact Account source `1fcac809c159f5c05261cb3bb4fd4b444f0fb5d7`, [CI374412507 The distinct existing-only creator-control capture reads an already committed bootstrap through its owner and retains the exact immutable creation qualification, membership event, audit and result receipt alongside current locked authority sources, pair, role snapshot and complete checkpoints. Its typed source carrier preserves `ACTIVE`/`tenantAdmin` control-only state without gameplay admission; runtime first-JOIN and player guards remain unchanged. This is source evidence, not authoring permission, a new authenticated producer or a new route. The local working-tree Account full check and boot JAR pass in 2m16s; the five new PostgreSQL definitions compile but remain unexecuted because local database cases skip without Docker. Strict CI selects and captures those five methods after earlier Account report captures. Missing and corrupt receipt-read cases explicitly overlay real committed fixtures with synthetic owner reads rather than disabling database immutability guards. Complete authenticated creator authorization, party/terms sources and runtime activation remain open. -The authored-Draft recovery candidate reads the original immutable V57 operation and discovers unresolved operations through stable timestamp/UUID pagination. It strictly decodes stored participant readbacks and rejects contradictory identity or outcome columns. Its unregistered Account consumer now requires both typed Game Design and World clients: a short owner snapshot identifies missing results, remote authenticated reads run outside every Account transaction, and a second short transaction rechecks original bytes and ordering before retaining exact results. A stored World outcome cannot skip missing Game Design proof. `UNKNOWN`, absence and transient failure create no abort; definitive mixed outcomes preserve World's original commit and settle nonpublication under the [Account fence contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-authored-draft-authorization-fence). Synthetic consumer tests define transaction placement, binding/order rejection, lost-response and exact terminal recovery. The physical Account-client tests use transport doubles, and Account PostgreSQL consumer fixtures stipulate remote owner evidence; neither establishes genuine owner persistence or protected authorization. Original restart, pagination, corrupted-original and contradictory-outcome cases remain intact. Executed database and complete producer/consumer composition remain required. No new authorization, source writer, public commit or runtime activation is enabled; terminal API contracts belong to [Game Design](../../architecture/microservices/game-design-service/api-contracts.md#exact-authored-draft-terminal-readback) and [World](../../architecture/microservices/world-management-service/api-contracts.md#exact-authored-draft-terminal-readback). +The authored-Draft recovery candidate reads the original immutable V57 operation and discovers unresolved operations through stable timestamp/UUID pagination. It strictly decodes stored participant readbacks and rejects contradictory identity or outcome columns. Its unregistered Account consumer has typed Game Design and World clients: a short owner snapshot identifies missing results, remote authenticated reads run outside every Account transaction, and a second short transaction rechecks original bytes and ordering before retaining exact results. A stored World outcome cannot skip missing Game Design proof. `UNKNOWN`, absence and transient failure create no abort; mixed outcomes preserve World's original commit and remain pending under the [Account fence contract](../../architecture/microservices/account-service/api-contracts.md#account-owned-authored-draft-authorization-fence). Synthetic consumer tests define transaction placement, binding/order rejection, lost-response and exact terminal recovery. The physical Account-client tests use transport doubles, and Account PostgreSQL consumer fixtures stipulate remote owner evidence; neither establishes genuine owner persistence or protected authorization. Original restart, pagination, corrupted-original and contradictory-outcome cases remain intact. Executed database and complete required-owner producer/consumer composition remain required. No new authorization, source writer, public commit or runtime activation is enabled; terminal API contracts belong to [Game Design](../../architecture/microservices/game-design-service/api-contracts.md#exact-authored-draft-terminal-readback) and [World](../../architecture/microservices/world-management-service/api-contracts.md#exact-authored-draft-terminal-readback). Exact composed source `2ac634ff209309341c43ff79bb7f02455e2099b9` [CI37435549047](https://github.com/benhook1013/FireMUD/actions/runs/37435549047) provides clean raw XML for all nine pre-sign intent, seven credential-authentication and five actual credential-producer PostgreSQL/Redis cases. The six creator-provenance/bootstrap cases have HTML reports only: five pass and the historical-bootstrap service case fails because its decoded canonical event sequence string was compared with a Java `Long`. The fixture now expects the exact string while preserving numeric owner-row assertions; a dedicated run captures and strictly requires raw XML for all six cases before later report overwrite. Corrected database execution remains required. This does not prove initial authenticated capture, creator authorization, a protected signer or public credential release. @@ -89,7 +107,7 @@ The next candidate extends that ordering to the existing unwired issuer and tena The corrected combined Account/World check, boot JAR, jOOQ schema generation, formatting, Checkstyle, SpotBugs, coverage and documentation gate passes. Parsed local unit results are Account 954 and World 256, all clean; the final gate reused those unchanged unit results from the preceding affected checks. All 381 Account and 65 World PostgreSQL methods compile but skip locally without Docker. Flyway sanity passes for twelve sets/190 files, and workflow/proof tooling and 230 architecture-contract tests pass. The narrow independent source/migration fix audit returned no new obligation; it is not broad corpus closure or authenticated producer proof. -The authored-publication candidate adds internal V57 durable exact-operation authorization ordering and immutable World/Game Design outcome storage. Source-change intent survives unresolved outcomes and commit-versus-revoke ordering is immutable. The approved definitive mixed failure/nonpublication rule is implemented in the repository and matching database guard: commit order settles only after both definitive outcomes, revoke order requires both definitive aborts, and one result or an unknown participant remains insufficient. Original applied evidence and the prior synchronized version are not rewritten. The shared complete Game Design binding, canonical target and exact input bytes are verified before storage. The consolidated four-module checks/JAR/schema/docs gate passes; Account records 950 clean unit results and all 360 PostgreSQL methods compile but skip locally without Docker, including nine fence methods. Independently parsed raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054), dispatched for source `c5fd96e935028b72182d58a611152bee6a8e533b`, records all nine fence methods passing once without skips, errors or failures. Account's Gradle Checks passed, but the job was cancelled at post-Gradle setup; the observer could not retrieve checkout logs while the aggregate remained active, and Game Design and World proof failed separately. These are executed Account storage cases, not a green composed boundary or proof of an authenticated actor/role/party/terms producer, actual source-writer participation, authenticated participant readback, creator bootstrap, RPC activation or completed commit-time authority. +The earlier V57 checkpoint added durable exact-operation authorization ordering and immutable World/Game Design outcome storage. Source-change intent survives unresolved outcomes and commit-versus-revoke ordering is immutable. Its original mixed-failure settlement policy is superseded by the current required-owner continuation above: mixed outcomes remain held rather than releasing the source fence. Original applied evidence and the prior synchronized version are not rewritten. The shared complete Game Design binding, canonical target and exact input bytes are verified before storage. The historical consolidated four-module checks/JAR/schema/docs gate passed; Account recorded 950 clean unit results and all 360 PostgreSQL methods compiled but skipped locally without Docker, including nine fence methods. Independently parsed raw XML from [CI37310255054](https://github.com/benhook1013/FireMUD/actions/runs/37310255054), dispatched for source `c5fd96e935028b72182d58a611152bee6a8e533b`, records all nine then-existing fence methods passing once without skips, errors or failures. Account's Gradle Checks passed, but the job was cancelled at post-Gradle setup; the observer could not retrieve checkout logs while the aggregate remained active, and Game Design and World proof failed separately. That historical execution does not prove the corrected V81 settlement, a green composed boundary, an authenticated actor/role/party/terms producer, actual source-writer participation, authenticated participant readback, creator bootstrap, RPC activation or completed commit-time authority. Exact corrected Account head `3440d4d646414c2c7244e5e0cc1b650cd9e242d8` has executed [CI37290103027](https://github.com/benhook1013/FireMUD/actions/runs/37290103027) proof. Account job `111698347142` succeeded; the strict log records all fourteen `AccountAuthenticationUuidIntegrationTest` cases passing without skips, including one execution of the repaired email-OTP method. No separate OTP XML artifact was uploaded, so that method's attribution rests on the strict job log. All twenty required role/journal/fresh-JOIN/physical-mTLS methods also passed: independently parsed raw suites record JOIN 51/51, journal 2/2, reconciliation 11/11 and scope 4/4. The actual Game Session client PostgreSQL/mTLS suite passed 3/3 without skips before its later full check was cancelled; Game Session job `111698347041` and aggregate CI therefore did not pass. The cancellation log supplies no causal explanation. Verified checkout merge `c82c0262d55106fcbea0ed2329adfb1ff19098f1` has the exact World `f968b46adf12570e870b17e17fe0d4382e7078b4` and Account source parents and the same source tree `d39693e551631ed21fb1a6751eb4c4c6658a0e8c`. This closes the OTP fixture execution gap and repeats the physical component proof on that composed tree; upstream caller/policy, current-parent alignment, complete authorization, fresh images, live readiness and activation remain independent gates. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java index 4a0bece342..a2ed5db9ac 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java @@ -21,8 +21,9 @@ import org.springframework.transaction.support.TransactionTemplate; /** - * Unregistered two-owner recovery consumer. Exact authenticated owner readbacks recover only the - * original V57 settlement; this component creates no authorization, source mutation or activation. + * Unregistered Game Design/World subset recovery consumer. It reads only required owners supported + * by these clients; other missing v2 owners remain pending under the repository's complete-set + * settlement predicate. This component creates no authorization, source mutation or activation. */ public final class AccountDraftTerminalReconciliationService { private final DraftAuthorizationFenceRepository repository; @@ -75,9 +76,14 @@ public Optional reconcile(UUID operationId) { } Optional gameDesignReadback = - before.gameDesignReadback().isEmpty() ? readGameDesign(before.binding()) : Optional.empty(); + before.binding().requiredOwners().contains(Owner.GAME_DESIGN) + && before.gameDesignReadback().isEmpty() + ? readGameDesign(before.binding()) + : Optional.empty(); Optional worldReadback = - before.worldReadback().isEmpty() ? readWorld(before.binding()) : Optional.empty(); + before.binding().requiredOwners().contains(Owner.WORLD) && before.worldReadback().isEmpty() + ? readWorld(before.binding()) + : Optional.empty(); Settlement settled = ownerTransaction.execute( @@ -134,6 +140,7 @@ private Snapshot snapshot(DraftAuthorizationFenceBinding binding) { private Optional readStoredOwnerResult( DraftAuthorizationFenceBinding binding, Owner owner) { + if (!binding.requiredOwners().contains(owner)) return Optional.empty(); return repository .readOwnerResult(binding, owner) .map( @@ -170,7 +177,7 @@ private void retainExactMissing( Owner owner, Optional candidate, Snapshot after) { - if (candidate.isEmpty()) return; + if (!binding.requiredOwners().contains(owner) || candidate.isEmpty()) return; OwnerReadback verified = verifyOwnerReadback(binding, owner, candidate.orElseThrow()); Optional existing = owner == Owner.GAME_DESIGN ? after.gameDesignReadback() : after.worldReadback(); 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 1b4138fcb1..57b83af8e3 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 @@ -340,8 +340,8 @@ 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. + * source commit applies: every original required owner must report the same terminal outcome; + * revoke order requires definitive aborts. */ public void markSourceAborted(SourceChange change, SourceChangeAbortReason reason) { requireTransaction(); @@ -382,6 +382,10 @@ public void markSourceAborted(SourceChange change, SourceChangeAbortReason reaso 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"); @@ -442,15 +446,7 @@ public List readUnresolvedOperations(RecoveryCursor after, if (limit < 1 || limit > 100) { throw new IllegalArgumentException("Recovery page limit must be between 1 and 100"); } - String pending = - " (f.ordering = 'RESERVED' OR (f.ordering = 'COMMIT_ORDER' AND" - + " (SELECT count(*) FROM " - + READBACKS - + " r WHERE r.operation_id = f.operation_id) < 2) OR" - + " (f.ordering = 'REVOKE_ORDER' AND (SELECT count(*) FROM " - + READBACKS - + " r WHERE r.operation_id = f.operation_id AND" - + " r.outcome = 'DEFINITIVELY_ABORTED') < 2))"; + 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) { @@ -483,7 +479,7 @@ private DraftAuthorizationFenceBinding originalBinding(Record row) { public Settlement readSettlement(DraftAuthorizationFenceBinding binding) { requireTransaction(); Record row = requireExact(readOperation(binding.operationId()), binding); - return settlement(binding.operationId(), Ordering.valueOf(row.get("ordering", String.class))); + return settlement(binding, Ordering.valueOf(row.get("ordering", String.class))); } /** Absence means UNKNOWN, never no-commit proof. */ @@ -501,7 +497,8 @@ public Optional readOwnerResult( if (row != null) { OwnerReadback readback = OwnerReadback.fromStored(row.get("readback", byte[].class)); readback.requireBinding(binding); - if (readback.owner() != owner + if (!binding.requiredOwners().contains(owner) + || readback.owner() != owner || !readback.outcome().name().equals(row.get("outcome", String.class))) { throw new IllegalStateException("Owner readback differs from persisted columns"); } @@ -613,13 +610,13 @@ private List affectedOperations(List sources) { } /** - * Commit order settles only after both exact definitive outcomes, including mixed failure. Revoke - * order requires both definitive aborts. Missing evidence always remains pending. + * Every original required owner must report one uniform exact terminal outcome. Missing or mixed + * evidence always remains pending. */ private boolean allAffectedSettled(List sources) { for (UUID operation : affectedOperations(sources)) { Record row = readOperation(operation); - if (settlement(operation, Ordering.valueOf(row.get("ordering", String.class))) + if (settlement(originalBinding(row), Ordering.valueOf(row.get("ordering", String.class))) == Settlement.PENDING) { return false; } @@ -628,28 +625,42 @@ private boolean allAffectedSettled(List sources) { && new PublicationAuthorizationFenceRepository(dsl).allAffectedSettled(sources); } - private Settlement settlement(UUID operation, Ordering ordering) { + private Settlement settlement(DraftAuthorizationFenceBinding binding, Ordering ordering) { if (ordering == Ordering.RESERVED) { return Settlement.PENDING; } - List outcomes = - dsl - .fetch("SELECT outcome FROM " + READBACKS + " WHERE operation_id = ?", operation) - .getValues("outcome", String.class) - .stream() - .map(Outcome::valueOf) - .toList(); - // The owner CHECK and (operation_id, owner) primary key admit exactly these two owners. - if (outcomes.size() != 2) { + 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; } - return outcomes.stream().allMatch(o -> o == Outcome.COMMITTED) - ? Settlement.COMMITTED - : Settlement.FAILED_NONPUBLICATION; + if (outcomes.stream().allMatch(o -> o == Outcome.COMMITTED)) { + return Settlement.COMMITTED; + } + return bothAborted ? Settlement.FAILED_NONPUBLICATION : Settlement.PENDING; } private Record readOperation(UUID operation) { 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 index 7ba739989c..c8bc8618f1 100644 --- 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 @@ -8,6 +8,7 @@ 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; @@ -165,6 +166,90 @@ public AssociationReceipt readInitialAssociation( 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); + } + /** This slice never provides commit-bound party/terms authorization. */ public void requireHostedAuthoringCurrentness() { throw new IllegalStateException( @@ -300,6 +385,25 @@ private static void requireTransaction() { 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/hostedterms/AccountHostedTermsService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java new file mode 100644 index 0000000000..200b8cdd35 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java @@ -0,0 +1,1075 @@ +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.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) { + requireCurrentEnvironmentBoundaryAuthority(); + HostedTermsEncoding.requireUuid(creatorPartyId, "creator party"); + HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment = + Objects.requireNonNull( + currentEnvironmentBoundaryAuthority.currentBoundary(), + "authenticated current environment boundary"); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> currentnessForEnvironmentInTransaction(environment, creatorPartyId)), + "Account environment-bound currentness result"); + } + + /** 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()); + + 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) { + 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 new DraftAuthorizationFenceRepository.SourceChange( + changeId, + List.copyOf(sources.values()), + HostedTermsEnvironmentBindingEncoding.receipt(candidate)); + } + + 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 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()); + repository.insertCandidate(candidate); + if (candidate.effectiveAt().isAfter(scope.databaseNow().toInstant())) { + repository.markScheduled(requestId, candidate); + return result(HostedTermsRepository.PublicationStatus.SCHEDULED, 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..27d949819c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java @@ -0,0 +1,418 @@ +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); + 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..7e13ce38a8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java @@ -0,0 +1,547 @@ +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"); + 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/resources/db/migration/V81__draft_authorization_required_owner_set.sql b/services/account-service/src/main/resources/db/migration/V81__draft_authorization_required_owner_set.sql new file mode 100644 index 0000000000..dc312785f7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V81__draft_authorization_required_owner_set.sql @@ -0,0 +1,283 @@ +-- Forward-only structural validation. Retained bindings and owner evidence are never rewritten. +-- [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')); + +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/V94__account_hosted_terms_acceptance_workflow.sql b/services/account-service/src/main/resources/db/migration/V94__account_hosted_terms_acceptance_workflow.sql new file mode 100644 index 0000000000..bf01e873c1 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V94__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/V95__account_hosted_terms_environment_binding.sql b/services/account-service/src/main/resources/db/migration/V95__account_hosted_terms_environment_binding.sql new file mode 100644 index 0000000000..35c21bb8a9 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V95__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/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index 28893357d3..34083c61fb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -31,6 +31,7 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; @@ -2117,7 +2118,7 @@ void tenantRoleTransferParticipatesInBothMembershipsAndAccountIssuanceScope() { "ACCOUNT:" + fixture.admin().accountUuid()); for (DraftAuthorizationFenceBinding binding : List.of(actor, target)) { syntheticVerifiedOwnerReadback(binding, Owner.WORLD, Outcome.COMMITTED); - syntheticVerifiedOwnerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + syntheticVerifiedOwnerReadback(binding, Owner.GAME_DESIGN, Outcome.COMMITTED); assertPendingRoleIntent(tenantRoleMutationService.mutate(request)); } syntheticVerifiedOwnerReadback(issuance, Owner.WORLD, Outcome.COMMITTED); @@ -2125,12 +2126,91 @@ void tenantRoleTransferParticipatesInBothMembershipsAndAccountIssuanceScope() { assertThat(committedRoles(fixture.admin())).contains("tenantAdmin"); assertThat(committedRoles(fixture.target())).doesNotContain("tenantAdmin"); syntheticVerifiedOwnerReadback(issuance, Owner.GAME_DESIGN, Outcome.COMMITTED); + for (DraftAuthorizationFenceBinding binding : List.of(actor, target, issuance)) { + assertThat( + new TransactionTemplate(transactionManager) + .execute( + status -> new DraftAuthorizationFenceRepository(dsl).readSettlement(binding))) + .isEqualTo(Settlement.COMMITTED); + } OperationEvidence transfer = tenantRoleMutationService.mutate(request); assertThat(transfer.status()).isEqualTo("COMMITTED"); assertThat(transfer.members()).hasSize(2); assertCurrentRoleMutationState(fixture.admin(), 3L, 2L, 2L, 2L, List.of("player"), true); assertCurrentRoleMutationState( fixture.target(), 3L, 1L, 2L, 1L, List.of("player", "tenantAdmin"), false); + + TenantRoleFixture mixedFixture = syntheticRetainedAdminFixture(); + Request mixedRequest = roleRequest(mixedFixture, Action.TRANSFER_TENANT_ADMIN, 2L); + DraftAuthorizationFenceBinding mixedActor = + syntheticVerifiedRoleFence(mixedFixture.admin(), SourceKind.MEMBERSHIP); + DraftAuthorizationFenceBinding mixedTarget = + syntheticVerifiedRoleFence(mixedFixture.target(), SourceKind.MEMBERSHIP); + DraftAuthorizationFenceBinding mixedIssuance = + syntheticVerifiedRoleFence(mixedFixture.admin(), SourceKind.ACCOUNT); + for (DraftAuthorizationFenceBinding binding : List.of(mixedActor, mixedTarget, mixedIssuance)) { + reserveRoleFence(binding, true); + } + assertPendingRoleIntent(tenantRoleMutationService.mutate(mixedRequest)); + SourceChange mixedOriginal = originalRoleSourceChange(mixedRequest); + Map mixedAdminBefore = + membershipAuthorityReadEvidenceSnapshot(mixedFixture.admin()); + Map mixedTargetBefore = + membershipAuthorityReadEvidenceSnapshot(mixedFixture.target()); + long mixedAuditRowsBefore = countAuditOutboxRows(mixedFixture.admin()); + + for (DraftAuthorizationFenceBinding binding : List.of(mixedActor, mixedTarget)) { + syntheticVerifiedOwnerReadback(binding, Owner.WORLD, Outcome.COMMITTED); + syntheticVerifiedOwnerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + } + syntheticVerifiedOwnerReadback(mixedIssuance, Owner.WORLD, Outcome.COMMITTED); + syntheticVerifiedOwnerReadback(mixedIssuance, Owner.GAME_DESIGN, Outcome.COMMITTED); + + DraftAuthorizationFenceRepository mixedFences = new DraftAuthorizationFenceRepository(dsl); + for (DraftAuthorizationFenceBinding binding : List.of(mixedActor, mixedTarget)) { + assertThat( + new TransactionTemplate(transactionManager) + .execute(status -> mixedFences.readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + } + assertThat( + new TransactionTemplate(transactionManager) + .execute(status -> mixedFences.readSettlement(mixedIssuance))) + .isEqualTo(Settlement.COMMITTED); + assertPendingRoleIntent(tenantRoleMutationService.mutate(mixedRequest)); + assertThat(membershipAuthorityReadEvidenceSnapshot(mixedFixture.admin())) + .isEqualTo(mixedAdminBefore); + assertThat(membershipAuthorityReadEvidenceSnapshot(mixedFixture.target())) + .isEqualTo(mixedTargetBefore); + assertThat(countAuditOutboxRows(mixedFixture.admin())).isEqualTo(mixedAuditRowsBefore); + assertThat(committedRoles(mixedFixture.admin())).containsExactly("player", "tenantAdmin"); + assertThat(committedRoles(mixedFixture.target())).containsExactly("player"); + assertThat(originalRoleSourceChange(mixedRequest).canonicalBytes()) + .containsExactly(mixedOriginal.canonicalBytes()); + assertThat( + new TransactionTemplate(transactionManager) + .execute(status -> mixedFences.readSourceChange(mixedOriginal).status())) + .isEqualTo("WAITING"); + for (DraftAuthorizationFenceBinding binding : List.of(mixedActor, mixedTarget)) { + assertThat( + new TransactionTemplate(transactionManager) + .execute( + status -> + mixedFences + .readOwnerResult(binding, Owner.WORLD) + .orElseThrow() + .outcome())) + .isEqualTo(Outcome.COMMITTED); + assertThat( + new TransactionTemplate(transactionManager) + .execute( + status -> + mixedFences + .readOwnerResult(binding, Owner.GAME_DESIGN) + .orElseThrow() + .outcome())) + .isEqualTo(Outcome.DEFINITIVELY_ABORTED); + } } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java index 5220ee9855..bf61a503a0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLogoutAllAuthorityProducerPostgresIntegrationTest.java @@ -310,7 +310,7 @@ void revokeOrderWaitsForBothExactAbortsBeforeOneLogoutAdvanceAndNeverAdmitsDelay } @Test - void commitOrderWaitsForBothExactOutcomesIncludingMixedFailureBeforeLogoutAdvance() { + void mixedCommitOrderHoldsLogoutAuthorityAndPreservesOriginalOwnerResult() { Fixture fixture = newFixture(); Seed seed = seedAccount(fixture); DraftAuthorizationFenceBinding binding = @@ -347,7 +347,7 @@ void commitOrderWaitsForBothExactOutcomesIncludingMixedFailureBeforeLogoutAdvanc fixture, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {42}); assertThat( transaction(fixture.transaction(), () -> draftFences(fixture).readSettlement(binding))) - .isEqualTo(Settlement.FAILED_NONPUBLICATION); + .isEqualTo(Settlement.PENDING); var originalWorldResult = transaction( fixture.transaction(), @@ -356,18 +356,14 @@ void commitOrderWaitsForBothExactOutcomesIncludingMixedFailureBeforeLogoutAdvanc assertThat(originalWorldResult.outcome()).isEqualTo(Outcome.COMMITTED); assertThat(originalWorldResult.readback()).containsExactly(expectedWorldReadbackBytes); - assertThat(commit(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState())) - .isEqualTo(LogoutAllResult.LOGOUT_ALL_COMMITTED); - assertThat(authority(fixture, seed).generation()).isEqualTo(2L); - assertThat(logoutReceipt(fixture, requestId).outboxSequence()).isEqualTo(1L); - assertThat(event(fixture, seed, 1L).requestId()).isEqualTo(requestId.toString()); - assertThat(pendingIntent(fixture, requestId).orElseThrow().status()) - .isEqualTo("SOURCE_COMMITTED"); + assertPending(fixture, seed, requestId, requestDigest, tokenHash, seed.initialState()); + assertThat(snapshot(fixture, seed)).isEqualTo(before); + assertThat(pendingIntent(fixture, requestId).orElseThrow().status()).isEqualTo("WAITING"); assertThat( transaction( fixture.transaction(), () -> draftFences(fixture).readSourceChange(sourceChange).status())) - .isEqualTo("SOURCE_COMMITTED"); + .isEqualTo("WAITING"); var replayedWorldResult = transaction( fixture.transaction(), @@ -376,8 +372,8 @@ void commitOrderWaitsForBothExactOutcomesIncludingMixedFailureBeforeLogoutAdvanc assertThat(replayedWorldResult.outcome()).isEqualTo(originalWorldResult.outcome()); assertThat(replayedWorldResult.readback()).containsExactly(expectedWorldReadbackBytes); assertThat(replayedWorldResult.recordedAt()).isEqualTo(originalWorldResult.recordedAt()); - assertThat(count(fixture, "account_authority_outbox_events")).isEqualTo(1L); - assertThat(count(fixture, "account_logout_all_operation_receipts")).isEqualTo(1L); + assertThat(count(fixture, "account_authority_outbox_events")).isZero(); + assertThat(count(fixture, "account_logout_all_operation_receipts")).isZero(); } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountPasswordResetDraftSourceChangePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountPasswordResetDraftSourceChangePostgresIntegrationTest.java index 9265d8afbc..692e070e2b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountPasswordResetDraftSourceChangePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountPasswordResetDraftSourceChangePostgresIntegrationTest.java @@ -281,8 +281,36 @@ void commitAndRevokeOrderingRequireTheirExactDefinitiveOwnerOutcomesBeforeSource recordOwner( commitFixture, commitPending.binding(), Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); assertThat(readSettlement(commitFixture, commitPending.binding())) - .isEqualTo(Settlement.FAILED_NONPUBLICATION); - assertThat(abort(commitFixture, commitSnapshot, AbortReason.DEFINITIVE_ABORT)).isTrue(); + .isEqualTo(Settlement.PENDING); + StoredState mixedEvidence = storedState(commitFixture, commitSeed, commitPending); + assertThat(abort(commitFixture, commitSnapshot, AbortReason.DEFINITIVE_ABORT)).isFalse(); + assertThat(readSettlement(commitFixture, commitPending.binding())) + .isEqualTo(Settlement.PENDING); + assertThat(readSourceStatus(commitFixture, commitPending.intent().sourceChange())) + .isEqualTo("WAITING"); + assertThat(durableSnapshot(commitFixture, commitSeed, commitPending.intent()).status()) + .isEqualTo("WAITING"); + assertThat(storedState(commitFixture, commitSeed, commitPending)).isEqualTo(mixedEvidence); + assertThat( + transaction( + commitFixture.transaction(), + () -> + commitFixture + .fences() + .readOwnerResult(commitPending.binding(), Owner.WORLD) + .orElseThrow() + .outcome())) + .isEqualTo(Outcome.COMMITTED); + assertThat( + transaction( + commitFixture.transaction(), + () -> + commitFixture + .fences() + .readOwnerResult(commitPending.binding(), Owner.GAME_DESIGN) + .orElseThrow() + .outcome())) + .isEqualTo(Outcome.DEFINITIVELY_ABORTED); } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java index b6bf7a0433..c6919733da 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/IssuerAuthorityProducerPostgresIntegrationTest.java @@ -17,6 +17,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.Settlement; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; @@ -67,7 +68,6 @@ void issuerCommitOrderWaitsForEveryOriginalOwnerOutcomeBeforeAtomicSourceComplet for (List outcomes : List.of( List.of(Outcome.COMMITTED, Outcome.COMMITTED), - List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED), List.of(Outcome.DEFINITIVELY_ABORTED, Outcome.DEFINITIVELY_ABORTED))) { Fixture fixture = newFixture(); seedIssuer(fixture); @@ -99,6 +99,11 @@ void issuerCommitOrderWaitsForEveryOriginalOwnerOutcomeBeforeAtomicSourceComplet assertThat(readAuthority(fixture).generation()).isEqualTo(1); assertThat(countEvents(fixture, STREAM_KEY)).isZero(); recordOwner(fixture, binding, Owner.GAME_DESIGN, outcomes.get(1)); + assertThat(transaction(fixture.transaction(), () -> fences.readSettlement(binding))) + .isEqualTo( + outcomes.getFirst() == Outcome.COMMITTED + ? Settlement.COMMITTED + : Settlement.FAILED_NONPUBLICATION); IssuerGenerationAuthorityEvent event = fixture.producer().advance(ISSUER_ID, request, 1, 1); assertThat(event.issuerAuthGeneration()).isEqualTo("2"); assertThat( @@ -119,7 +124,76 @@ void issuerCommitOrderWaitsForEveryOriginalOwnerOutcomeBeforeAtomicSourceComplet fixture.transaction(), () -> fences.readOwnerResult(binding, Owner.WORLD).orElseThrow().outcome())) .isEqualTo(outcomes.get(0)); + assertThat( + transaction( + fixture.transaction(), + () -> fences.readOwnerResult(binding, Owner.GAME_DESIGN).orElseThrow().outcome())) + .isEqualTo(outcomes.get(1)); } + + Fixture mixedFixture = newFixture(); + seedIssuer(mixedFixture); + DraftAuthorizationFenceBinding mixedBinding = + issuerBinding(ISSUER_ID, "1", "1", "0", new byte[] {1}); + DraftAuthorizationFenceRepository mixedFences = + new DraftAuthorizationFenceRepository(mixedFixture.transactionDsl()); + transaction( + mixedFixture.transaction(), + () -> { + mixedFences.reserve(mixedBinding); + mixedFences.claimCommitOrder(mixedBinding); + return null; + }); + StoredState beforeMixed = snapshot(mixedFixture); + UUID mixedRequest = UUID.randomUUID(); + assertThatThrownBy(() -> mixedFixture.producer().advance(ISSUER_ID, mixedRequest, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + SourceChange mixedOriginal = pendingIssuerChange(mixedFixture, ISSUER_ID, mixedRequest); + recordOwner(mixedFixture, mixedBinding, Owner.WORLD, Outcome.COMMITTED); + recordOwner(mixedFixture, mixedBinding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + + assertThat( + transaction(mixedFixture.transaction(), () -> mixedFences.readSettlement(mixedBinding))) + .isEqualTo(Settlement.PENDING); + assertThatThrownBy(() -> mixedFixture.producer().advance(ISSUER_ID, mixedRequest, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class) + .satisfies( + error -> + assertThat(((PendingSourceChangeException) error).sourceChangeId()) + .isEqualTo(mixedOriginal.changeId())); + assertThat(snapshot(mixedFixture)).isEqualTo(beforeMixed); + assertThat(pendingIssuerChange(mixedFixture, ISSUER_ID, mixedRequest).canonicalBytes()) + .containsExactly(mixedOriginal.canonicalBytes()); + assertThat( + transaction( + mixedFixture.transaction(), + () -> mixedFences.readSourceChange(mixedOriginal).status())) + .isEqualTo("WAITING"); + assertThat( + Objects.requireNonNull( + mixedFixture + .setupDsl() + .fetchOne( + "SELECT status FROM account_issuer_tenant_draft_source_changes WHERE request_id = ?", + mixedRequest), + "Mixed issuer source intent disappeared") + .get("status", String.class)) + .isEqualTo("WAITING"); + assertThat( + transaction( + mixedFixture.transaction(), + () -> + mixedFences.readOwnerResult(mixedBinding, Owner.WORLD).orElseThrow().outcome())) + .isEqualTo(Outcome.COMMITTED); + assertThat( + transaction( + mixedFixture.transaction(), + () -> + mixedFences + .readOwnerResult(mixedBinding, Owner.GAME_DESIGN) + .orElseThrow() + .outcome())) + .isEqualTo(Outcome.DEFINITIVELY_ABORTED); } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java index 056a57d368..a4c959a220 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/TenantAuthorityProducerPostgresIntegrationTest.java @@ -17,6 +17,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.Settlement; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; @@ -76,7 +77,6 @@ void tenantCommitOrderWaitsForBothOriginalOwnerOutcomesBeforeAtomicSourceComplet for (List outcomes : List.of( List.of(Outcome.COMMITTED, Outcome.COMMITTED), - List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED), List.of(Outcome.DEFINITIVELY_ABORTED, Outcome.DEFINITIVELY_ABORTED))) { Fixture fixture = newFixture(); seed(fixture); @@ -111,6 +111,11 @@ void tenantCommitOrderWaitsForBothOriginalOwnerOutcomesBeforeAtomicSourceComplet assertThat(readTenantState(fixture).generation()).isEqualTo(1); assertThat(countEvents(fixture, STREAM_KEY)).isZero(); recordOwner(fixture, binding, Owner.GAME_DESIGN, outcomes.get(1)); + assertThat(transaction(fixture.transaction(), () -> fences.readSettlement(binding))) + .isEqualTo( + outcomes.getFirst() == Outcome.COMMITTED + ? Settlement.COMMITTED + : Settlement.FAILED_NONPUBLICATION); assertThat(fixture.producer().advance(TENANT_ID, request, 1, 1).tenantAuthorityGeneration()) .isEqualTo("2"); assertThat( @@ -121,7 +126,75 @@ void tenantCommitOrderWaitsForBothOriginalOwnerOutcomesBeforeAtomicSourceComplet fixture.transaction(), () -> fences.readOwnerResult(binding, Owner.WORLD).orElseThrow().outcome())) .isEqualTo(outcomes.get(0)); + assertThat( + transaction( + fixture.transaction(), + () -> fences.readOwnerResult(binding, Owner.GAME_DESIGN).orElseThrow().outcome())) + .isEqualTo(outcomes.get(1)); } + + Fixture mixedFixture = newFixture(); + seed(mixedFixture); + DraftAuthorizationFenceBinding mixedBinding = tenantBinding(mixedFixture); + DraftAuthorizationFenceRepository mixedFences = + new DraftAuthorizationFenceRepository(mixedFixture.transactionDsl()); + transaction( + mixedFixture.transaction(), + () -> { + mixedFences.reserve(mixedBinding); + mixedFences.claimCommitOrder(mixedBinding); + return null; + }); + StoredState beforeMixed = snapshot(mixedFixture); + UUID mixedRequest = UUID.randomUUID(); + assertThatThrownBy(() -> mixedFixture.producer().advance(TENANT_ID, mixedRequest, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class); + SourceChange mixedOriginal = pendingTenantChange(mixedFixture, mixedRequest); + recordOwner(mixedFixture, mixedBinding, Owner.WORLD, Outcome.COMMITTED); + recordOwner(mixedFixture, mixedBinding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + + assertThat( + transaction(mixedFixture.transaction(), () -> mixedFences.readSettlement(mixedBinding))) + .isEqualTo(Settlement.PENDING); + assertThatThrownBy(() -> mixedFixture.producer().advance(TENANT_ID, mixedRequest, 1, 1)) + .isInstanceOf(PendingSourceChangeException.class) + .satisfies( + error -> + assertThat(((PendingSourceChangeException) error).sourceChangeId()) + .isEqualTo(mixedOriginal.changeId())); + assertThat(snapshot(mixedFixture)).isEqualTo(beforeMixed); + assertThat(pendingTenantChange(mixedFixture, mixedRequest).canonicalBytes()) + .containsExactly(mixedOriginal.canonicalBytes()); + assertThat( + transaction( + mixedFixture.transaction(), + () -> mixedFences.readSourceChange(mixedOriginal).status())) + .isEqualTo("WAITING"); + assertThat( + Objects.requireNonNull( + mixedFixture + .setupDsl() + .fetchOne( + "SELECT status FROM account_issuer_tenant_draft_source_changes WHERE request_id = ?", + mixedRequest), + "Mixed tenant source intent disappeared") + .get("status", String.class)) + .isEqualTo("WAITING"); + assertThat( + transaction( + mixedFixture.transaction(), + () -> + mixedFences.readOwnerResult(mixedBinding, Owner.WORLD).orElseThrow().outcome())) + .isEqualTo(Outcome.COMMITTED); + assertThat( + transaction( + mixedFixture.transaction(), + () -> + mixedFences + .readOwnerResult(mixedBinding, Owner.GAME_DESIGN) + .orElseThrow() + .outcome())) + .isEqualTo(Outcome.DEFINITIVELY_ABORTED); } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java index afb7f25f8a..22f53a493a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -11,6 +11,7 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -138,7 +139,7 @@ void twoOwnerConsumerPersistsWorldOnceAndRecoversMissingGameDesignOnRetry() { } @Test - void mixedCommitOrderPreservesOriginalWorldCommitAndTerminalConsumerRetry() { + void mixedCommitOrderPreservesOriginalWorldCommitAndHoldsSourceFence() { Context context = context(); DraftAuthorizationFenceBinding binding = binding(); tx(context, () -> context.repository().reserve(binding)); @@ -174,15 +175,16 @@ void mixedCommitOrderPreservesOriginalWorldCommitAndTerminalConsumerRetry() { worldClient, "firemud-test"); - assertThat(service.reconcile(binding.operationId())).contains(Settlement.FAILED_NONPUBLICATION); + assertThat(service.reconcile(binding.operationId())).contains(Settlement.PENDING); assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD))) .get() .satisfies( stored -> assertThat(stored.readback()) .containsExactly(originalWorldCommit.canonicalBytes())); - assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); - assertThat(service.reconcile(binding.operationId())).contains(Settlement.FAILED_NONPUBLICATION); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + assertThat(service.reconcile(binding.operationId())).contains(Settlement.PENDING); verify(gameDesignClient).read(any()); verify(worldClient).read(any()); } @@ -440,7 +442,7 @@ void commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReop } @Test - void bothMixedDirectionsFailNonpublicationAndReleaseOnlyAfterBothExactReadbacks() { + void bothMixedDirectionsRemainPendingAndPreserveOriginalReadbacks() { for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { Context context = context(); DraftAuthorizationFenceBinding binding = binding(); @@ -461,20 +463,15 @@ void bothMixedDirectionsFailNonpublicationAndReleaseOnlyAfterBothExactReadbacks( worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED; owner(context, binding, Owner.GAME_DESIGN, gameDesignOutcome, new byte[] {2}); assertThat(tx(context, () -> context.repository().readSettlement(binding))) - .isEqualTo(Settlement.FAILED_NONPUBLICATION); - assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isTrue(); - assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); - tx( - context, - () -> { - context.repository().markSourceCommitted(change); - return null; - }); - var committed = tx(context, () -> context.repository().readSourceChange(change)); - assertThat(committed.status()).isEqualTo("SOURCE_COMMITTED"); - assertThat(committed.binding()).containsExactly(waiting.binding()); - assertThat(committed.requestedAt()).isEqualTo(waiting.requestedAt()); + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThat(tx(context, () -> context.repository().sourceAbortPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + var held = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(held.status()).isEqualTo("WAITING"); + assertThat(held.binding()).containsExactly(waiting.binding()); + assertThat(held.requestedAt()).isEqualTo(waiting.requestedAt()); assertThat(tx(context, () -> context.repository().read(binding)).ordering()) .isEqualTo(Ordering.COMMIT_ORDER); assertThat(tx(context, () -> context.repository().read(binding)).orderedAt()) @@ -841,16 +838,16 @@ void discoveryPagesOriginalPendingOperationsAndExcludesEverySettledVector() { new byte[] {2}); } var expected = - List.of(reserved, committedUnknown, revokedUnknown, revokedContradiction).stream() + List.of(reserved, committedUnknown, revokedUnknown, revokedContradiction, mixed).stream() .sorted(java.util.Comparator.comparing(b -> b.operationId().toString())) .toList(); var first = tx(context, () -> context.repository().readUnresolvedOperations(null, 2)); var second = tx( context, - () -> context.repository().readUnresolvedOperations(first.getLast().cursor(), 2)); + () -> context.repository().readUnresolvedOperations(first.getLast().cursor(), 3)); assertThat(first).hasSize(2); - assertThat(second).hasSize(2); + assertThat(second).hasSize(3); var combined = java.util.stream.Stream.concat(first.stream(), second.stream()).toList(); assertThat(combined.stream().map(item -> item.binding().operationId()).toList()) .containsExactlyElementsOf( @@ -920,19 +917,321 @@ void ownerRecoveryRejectsReadbackThatContradictsItsOutcomeColumn() { b.inputDigest(), b.canonicalBytes(), new byte[] {1}); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_owner_readbacks" + + " (operation_id, owner, outcome, readback) VALUES (?, 'WORLD', 'DEFINITIVELY_ABORTED', ?)", + b.operationId(), + readback.canonicalBytes()))) + .isInstanceOf(DataAccessException.class); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))).isEmpty(); + } + + @Test + void v2WorldEntityAndCoordinatorRequireAllThreeExactOriginalResults() { + Context context = context(); + var b = multiOwnerBinding(); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var change = change(b); + tx(context, () -> context.repository().requestSourceChange(change)); + owner(context, b, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {1}); + owner(context, b, Owner.WORLD, Outcome.COMMITTED, new byte[] {2}); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + assertThat(tx(context, () -> context.repository().readUnresolvedOperations(null, 100))) + .extracting(item -> item.binding().operationId()) + .contains(b.operationId()); + var entity = ownerReadback(b, Owner.ENTITY, Outcome.COMMITTED, new byte[] {3}); + // Structurally substituted owner, digest, full binding, result and trailing frames all fail. + for (byte[] invalid : + List.of( + java.util.Arrays.copyOf(entity.canonicalBytes(), entity.canonicalBytes().length - 1), + java.util.Arrays.copyOf(entity.canonicalBytes(), entity.canonicalBytes().length + 1), + ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {3}).canonicalBytes(), + ownerReadback(binding(), Owner.WORLD, Outcome.COMMITTED, new byte[] {3}) + .canonicalBytes())) { + assertThatThrownBy(() -> insertOwner(context, b, "ENTITY", "COMMITTED", invalid)) + .isInstanceOf(DataAccessException.class); + } + assertThatThrownBy( + () -> insertOwner(context, b, "AUTOMATION", "COMMITTED", entity.canonicalBytes())) + .isInstanceOf(DataAccessException.class); + owner(context, b, Owner.ENTITY, Outcome.COMMITTED, new byte[] {3}); + assertThatThrownBy( + () -> insertOwner(context, b, "ENTITY", "COMMITTED", entity.canonicalBytes())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> owner(context, b, Owner.ENTITY, Outcome.COMMITTED, new byte[] {4})) + .isInstanceOf(IllegalArgumentException.class); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.COMMITTED); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + } + + @Test + void v2FreshDraftEpochZeroAcceptsExactRequiredOwnerReadback() { + Context context = context(); + var prior = multiOwnerBinding(); + var b = + new DraftAuthorizationFenceBinding( + prior.operationId(), + prior.requestId(), + prior.commitId(), + prior.fenceId(), + prior.actorAccountId(), + prior.tenantId(), + prior.versionId(), + prior.baseCommitId(), + "0", + prior.gameDesignBinding(), + prior.normalizedInput(), + prior.inputDigest(), + prior.sources()) + .withRequiredOwners(); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var readback = ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + insertOwner(context, b, "WORLD", "COMMITTED", readback.canonicalBytes()); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))) + .get() + .satisfies( + result -> assertThat(result.readback()).containsExactly(readback.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + } + + @Test + void rawSqlCannotRecordOwnerProofWithMissingChangedOrExtraSourceParticipation() { + for (int sourceShape = 0; sourceShape < 4; sourceShape++) { + Context context = context(); + var b = multiOwnerBinding(); + var source = b.sources().getFirst(); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_fences" + + " (operation_id, request_id, commit_id, fence_id, binding, ordering)" + + " VALUES (?, ?, ?, ?, ?, 'RESERVED')", + b.operationId(), + b.requestId(), + b.commitId(), + b.fenceId(), + b.canonicalBytes()); + if (sourceShape != 0) { + String key = sourceShape == 2 ? source.key() + "/changed" : source.key(); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + key); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + b.operationId(), + key, + sourceShape == 1 ? new byte[] {99} : source.canonicalBytes()); + if (sourceShape == 3) { + String extraKey = source.key() + "/extra"; + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + extraKey); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + b.operationId(), + extraKey, + source.canonicalBytes()); + } + } + context + .dsl() + .execute( + "UPDATE account_draft_authorization_fences SET ordering = 'COMMIT_ORDER'," + + " ordered_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + b.operationId()); + var readback = ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + assertThatThrownBy( + () -> insertOwner(context, b, "WORLD", "COMMITTED", readback.canonicalBytes())) + .isInstanceOf(DataAccessException.class); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(*) FROM account_draft_authorization_owner_readbacks WHERE operation_id = ?", + b.operationId())) + .get(0, Integer.class)) + .isZero(); + } + } + + @Test + void v2RequiredOwnerDecoderRejectsMissingExtraDuplicateAndReorderedOwners() { + Context context = context(); + var b = multiOwnerBinding(); + for (var labels : + List.of( + List.of("GAME_DESIGN", "WORLD"), + List.of("GAME_DESIGN", "WORLD", "ENTITY", "AUTOMATION"), + List.of("GAME_DESIGN", "WORLD", "WORLD"), + List.of("GAME_DESIGN", "ENTITY", "WORLD"))) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(b.canonicalBytes()); + var output = new java.io.ByteArrayOutputStream(); + for (int i = 0; i < 15 + b.sources().size(); i++) { + DraftAuthorizationFenceBinding.frame(output, reader.bytes()); + } + DraftAuthorizationFenceBinding.frame(output, Integer.toString(labels.size())); + labels.forEach(label -> DraftAuthorizationFenceBinding.frame(output, label)); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .fetch( + "SELECT account_draft_authorization_required_owners(?::bytea)", + output.toByteArray()))) + .isInstanceOf(DataAccessException.class); + } + } + + @Test + void v2AllRequiredAbortsSettleBothCommitAndRevokeOrdering() { + for (boolean commitOrder : List.of(true, false)) { + Context context = context(); + var b = multiOwnerBinding(); + tx(context, () -> context.repository().reserve(b)); + if (commitOrder) tx(context, () -> context.repository().claimCommitOrder(b)); + var change = change(b); + tx(context, () -> context.repository().requestSourceChange(change)); + owner(context, b, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {1}); + owner(context, b, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {2}); + assertSourceGuardBlocked(context, change); + owner(context, b, Owner.ENTITY, Outcome.DEFINITIVELY_ABORTED, new byte[] {3}); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + assertThat(tx(context, () -> context.repository().readSourceChange(change)).status()) + .isEqualTo("SOURCE_COMMITTED"); + } + } + + @Test + void v2MixedResultsHoldBothSourceTransitionsAndPreserveAppliedBytes() { + Context context = context(); + var b = multiOwnerBinding(); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var change = change(b); + tx(context, () -> context.repository().requestSourceChange(change)); + owner(context, b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + owner(context, b, Owner.ENTITY, Outcome.DEFINITIVELY_ABORTED, new byte[] {2}); + owner(context, b, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {3}); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + assertSourceGuardBlocked(context, change); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes SET status = 'SOURCE_ABORTED'," + + " aborted_at = CURRENT_TIMESTAMP, abort_reason = 'DEFINITIVE_ABORT' WHERE change_id = ?", + change.changeId()))) + .isInstanceOf(DataAccessException.class); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))) + .get() + .satisfies( + result -> + assertThat(result.readback()) + .containsExactly( + ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}) + .canonicalBytes())); + } + + @Test + void forwardMigrationRetainsV1BindingReadbackAndFlywayChecksumsExactly() { + Context context = context("80"); + var b = binding(); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var original = ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {8}); + owner(context, b, Owner.WORLD, Outcome.COMMITTED, new byte[] {8}); + var checksums = + context + .dsl() + .fetch("SELECT version, checksum FROM flyway_schema_history ORDER BY installed_rank"); + String schema = + Objects.requireNonNull(context.dsl().fetchOne("SELECT current_schema()")) + .get(0, String.class); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("81") + .load() + .migrate(); + assertThat( + context + .dsl() + .fetch("SELECT version, checksum FROM flyway_schema_history WHERE version = '81'")) + .hasSize(1); + assertThat( + context + .dsl() + .fetch( + "SELECT version, checksum FROM flyway_schema_history WHERE version IS DISTINCT FROM '81' ORDER BY installed_rank")) + .isEqualTo(checksums); + assertThat(tx(context, () -> context.repository().read(b)).binding()) + .containsExactly(b.canonicalBytes()); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))) + .get() + .satisfies( + result -> assertThat(result.readback()).containsExactly(original.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + } + + private void insertOwner( + Context context, + DraftAuthorizationFenceBinding binding, + String owner, + String outcome, + byte[] bytes) { tx( context, () -> context .dsl() .execute( - "INSERT INTO account_draft_authorization_owner_readbacks" - + " (operation_id, owner, outcome, readback) VALUES (?, 'WORLD', 'DEFINITIVELY_ABORTED', ?)", - b.operationId(), - readback.canonicalBytes())); - assertThatThrownBy( - () -> tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))) - .isInstanceOf(IllegalStateException.class); + "INSERT INTO account_draft_authorization_owner_readbacks (operation_id, owner, outcome, readback) VALUES (?, ?, ?, ?)", + binding.operationId(), + owner, + outcome, + bytes)); } private void assertSourceGuardBlocked(Context context, SourceChange change) { @@ -952,6 +1251,10 @@ private void assertSourceGuardBlocked(Context context, SourceChange change) { } private Context context() { + return context("latest"); + } + + private Context context(String target) { String schema = "draft_fence_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource source = new DriverManagerDataSource(); source.setUrl(postgres.getJdbcUrl()); @@ -964,6 +1267,7 @@ private Context context() { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") + .target(target) .load() .migrate(); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); @@ -1009,6 +1313,41 @@ private DraftAuthorizationFenceBinding binding() { List.of(source)); } + private DraftAuthorizationFenceBinding multiOwnerBinding() { + var prior = binding(); + var complete = + DraftCommitBinding.fromStored( + new String(prior.gameDesignBinding(), StandardCharsets.UTF_8), prior.inputDigest()); + var entity = DraftCommitBinding.Owner.ENTITY_MANAGEMENT; + var multi = + DraftCommitBinding.create( + complete.target(), + complete.requestId(), + complete.commitId(), + complete.baseCommitId(), + List.of( + complete.revisions().getFirst(), + new RevisionPayload("1", UUID.randomUUID(), entity, "entity-payload")), + List.of( + complete.affectedUnits().getFirst(), + new AffectedUnit(entity, "entity", "entity-1", "aggregate", "entity-1", "0"))); + return new DraftAuthorizationFenceBinding( + prior.operationId(), + prior.requestId(), + prior.commitId(), + prior.fenceId(), + prior.actorAccountId(), + prior.tenantId(), + prior.versionId(), + prior.baseCommitId(), + prior.expectedDraftEpoch(), + multi.canonicalBytes(), + multi.canonicalBytes(), + multi.digest(), + prior.sources()) + .withRequiredOwners(); + } + private DraftAuthorizationFenceBinding changed(DraftAuthorizationFenceBinding b, int field) { SourceEvidence prior = b.sources().getFirst(); SourceEvidence changedSource = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFencePostgresIntegrationTest.java index d3e0955a7b..579a6e2586 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authorpublication/PublicationAuthorizationFencePostgresIntegrationTest.java @@ -203,7 +203,7 @@ void publicationOrderRemainsUnresolvedAfterOriginalDraftTerminalResults() { () -> { context.draft().reserve(draft); context.draft().claimCommitOrder(draft); - for (var owner : DraftAuthorizationFenceBinding.Owner.values()) { + for (var owner : draft.requiredOwners()) { context .draft() .recordOwnerReadback( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java new file mode 100644 index 0000000000..1c532676de --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java @@ -0,0 +1,722 @@ +package integration.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.Statement; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.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.accountservice.hostedterms.AccountHostedTermsService; +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.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.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; + +/** + * PostgreSQL workflow proof. Operator publication and authenticated identity rows are explicit + * test-only upstream fixtures; these tests do not prove live legal publication or identity. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountHostedTermsPostgresIntegrationTest { + private static final String TEST_NAMESPACE = "account-hosted-terms-isolated-test"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void migrationRetainsExistingPartyAndBackfillsNoCatalogOrAcceptance() throws Exception { + Database db = database("81"); + UUID accountId = insertAccount(db); + IndividualCreatorPartySource party = + party(UUID.randomUUID(), accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map accountBefore = + Objects.requireNonNull( + db.dsl().fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", accountId)) + .intoMap(); + Map partyBefore = + new HashMap<>( + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT * FROM account_individual_creator_party_sources WHERE creator_party_id = ?", + party.creatorPartyId())) + .intoMap()); + byte[] partySourceBefore = (byte[]) partyBefore.remove("source_payload"); + + migrate(db, "94"); + + assertThat( + Objects.requireNonNull( + db.dsl().fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", accountId)) + .intoMap()) + .isEqualTo(accountBefore); + Map partyAfter = + new HashMap<>( + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT * FROM account_individual_creator_party_sources WHERE creator_party_id = ?", + party.creatorPartyId())) + .intoMap()); + byte[] partySourceAfter = (byte[]) partyAfter.remove("source_payload"); + assertThat(partyAfter).isEqualTo(partyBefore); + assertThat(partySourceAfter).containsExactly(partySourceBefore); + assertThat(count(db, "account_hosted_terms_scopes")).isZero(); + assertThat(count(db, "account_hosted_terms_catalog_versions")).isZero(); + assertThat(count(db, "account_hosted_terms_publication_operations")).isZero(); + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isZero(); + } + + @Test + void realServicePublishesAffirmativelyAcceptsReadsBackAndAdvancesMateriality() throws Exception { + Database db = database("94"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + AccountHostedTermsService service = service(db, publications, actions); + + UUID firstRequest = UUID.randomUUID(); + byte[] originalDocument = new byte[] {0, 1, 2, (byte) 0xff, 13, 10}; + publications.put( + firstRequest, + publication( + scopeId, + originalDocument, + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(5))); + AccountHostedTermsService.PublicationResult first = service.publish(firstRequest); + assertThat(first.status()).isEqualTo(HostedTermsRepository.PublicationStatus.COMMITTED); + assertThat(first.candidate().documentBytes()).containsExactly(originalDocument); + assertThat(first.candidate().documentDigest()) + .isEqualTo(HostedTermsEncoding.digest(originalDocument)); + assertThat(service.publish(firstRequest)).isEqualTo(first); // lost-result exact recovery + publications.put( + firstRequest, + publication( + scopeId, + "changed request payload".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(5))); + assertThatThrownBy(() -> service.publish(firstRequest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + publications.put( + firstRequest, + publication( + scopeId, + originalDocument, + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + first.candidate().effectiveAt())); + assertThat(count(db, "account_hosted_terms_catalog_versions")).isEqualTo(1); + + UUID firstActionId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction firstAction = + action(firstActionId, accountId, partyId, scopeId, first.candidate(), true); + actions.put(firstActionId, firstAction); + var accepted = service.accept(firstActionId); + assertThat(accepted.evidenceId()).isNotNull(); + assertThat(accepted.termsVersionId()).isEqualTo(first.candidate().versionId()); + assertThat(accepted.acceptedAt()).isNotNull(); // generated by PostgreSQL, not the caller action + assertThat(service.accept(firstActionId)).isEqualTo(accepted); + actions.put( + firstActionId, + new AccountHostedTermsService.AcceptanceAction( + firstAction.actionRequestId(), + true, + firstAction.accountId(), + firstAction.creatorPartyId(), + firstAction.hostedScopeId(), + firstAction.shownVersionId(), + HostedTermsEncoding.digest("changed shown document".getBytes()), + firstAction.shownOperatorLegalIdentity(), + firstAction.shownOperatorIdentityVersion(), + firstAction.authenticatedActionReference(), + firstAction.authenticatedActionVersion(), + firstAction.actionCreatedAt())); + assertThatThrownBy(() -> service.accept(firstActionId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isEqualTo(1); + var current = service.requireCurrentness(scopeId, partyId); + assertThat(current.acceptanceEvidenceId()).isEqualTo(accepted.evidenceId()); + assertThat(current.materialGeneration()).isEqualTo(1); + + UUID secondRequest = UUID.randomUUID(); + publications.put( + secondRequest, + publication( + scopeId, + "material-v2".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.MATERIAL, + now().minusSeconds(3))); + AccountHostedTermsService.PublicationResult material = service.publish(secondRequest); + assertThat(material.candidate().sourceVersion()).isEqualTo(2); + assertThat(material.candidate().materialGeneration()).isEqualTo(2); + assertThatThrownBy(() -> service.requireCurrentness(scopeId, partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("affirmative party-wide"); + + UUID secondActionId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction secondAction = + action(secondActionId, accountId, partyId, scopeId, material.candidate(), true); + actions.put(secondActionId, secondAction); + var reaccepted = service.accept(secondActionId); + assertThat(service.requireCurrentness(scopeId, partyId).acceptanceEvidenceId()) + .isEqualTo(reaccepted.evidenceId()); + + UUID thirdRequest = UUID.randomUUID(); + publications.put( + thirdRequest, + publication( + scopeId, + "nonmaterial-v3".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + now().minusSeconds(2))); + AccountHostedTermsService.PublicationResult nonmaterial = service.publish(thirdRequest); + assertThat(nonmaterial.candidate().sourceVersion()).isEqualTo(3); + assertThat(nonmaterial.candidate().materialGeneration()).isEqualTo(2); + assertThat(service.requireCurrentness(scopeId, partyId).acceptanceEvidenceId()) + .isEqualTo(reaccepted.evidenceId()); // prior exact acceptance remains in active ancestry + + UUID operatorChangeRequest = UUID.randomUUID(); + publications.put( + operatorChangeRequest, + publication( + scopeId, + "operator-change-v4".getBytes(), + "Replacement Test Operator", + 2, + HostedTermsCatalogVersion.Materiality.MATERIAL, + now().minusSeconds(1))); + AccountHostedTermsService.PublicationResult operatorChange = + service.publish(operatorChangeRequest); + assertThat(operatorChange.candidate().sourceVersion()).isEqualTo(4); + assertThat(operatorChange.candidate().materialGeneration()).isEqualTo(3); + assertThat(operatorChange.candidate().operatorLegalIdentity()) + .isEqualTo("Replacement Test Operator"); + assertThatThrownBy(() -> service.requireCurrentness(scopeId, partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("affirmative party-wide"); + } + + @Test + void acceptanceRejectsWrongSignerNegativeActionChangedShownTermsAndUnavailableIdentity() + throws Exception { + Database db = database("94"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + AccountHostedTermsService service = service(db, publications, actions); + UUID publicationId = UUID.randomUUID(); + publications.put( + publicationId, + publication( + scopeId, + "test-terms".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(1))); + HostedTermsCatalogVersion terms = service.publish(publicationId).candidate(); + + UUID negativeId = UUID.randomUUID(); + actions.put(negativeId, action(negativeId, accountId, partyId, scopeId, terms, false)); + assertThatThrownBy(() -> service.accept(negativeId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Affirmative"); + + UUID wrongAccountId = UUID.randomUUID(); + UUID wrongSignerId = UUID.randomUUID(); + actions.put( + wrongSignerId, action(wrongSignerId, wrongAccountId, partyId, scopeId, terms, true)); + assertThatThrownBy(() -> service.accept(wrongSignerId)) + .isInstanceOf(IllegalStateException.class); + + UUID wrongPartyId = UUID.randomUUID(); + actions.put( + wrongPartyId, action(wrongPartyId, accountId, UUID.randomUUID(), scopeId, terms, true)); + assertThatThrownBy(() -> service.accept(wrongPartyId)) + .isInstanceOf(IllegalStateException.class); + + UUID mismatchId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction correct = + action(mismatchId, accountId, partyId, scopeId, terms, true); + actions.put( + mismatchId, + new AccountHostedTermsService.AcceptanceAction( + correct.actionRequestId(), + true, + correct.accountId(), + correct.creatorPartyId(), + correct.hostedScopeId(), + correct.shownVersionId(), + HostedTermsEncoding.digest("different document".getBytes()), + correct.shownOperatorLegalIdentity(), + correct.shownOperatorIdentityVersion(), + correct.authenticatedActionReference(), + correct.authenticatedActionVersion(), + correct.actionCreatedAt())); + assertThatThrownBy(() -> service.accept(mismatchId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isZero(); + } + + @Test + void futureTermsCarryDeadlineWithoutFreezingPriorTermsEarly() throws Exception { + Database db = database("94"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + AccountHostedTermsService service = service(db, publications, actions); + UUID initialRequest = UUID.randomUUID(); + publications.put( + initialRequest, + publication( + scopeId, + "test-terms-v1".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(1))); + HostedTermsCatalogVersion initial = service.publish(initialRequest).candidate(); + UUID actionId = UUID.randomUUID(); + actions.put(actionId, action(actionId, accountId, partyId, scopeId, initial, true)); + var accepted = service.accept(actionId); + + UUID futureRequest = UUID.randomUUID(); + Instant deadline = databaseNow(db).plusSeconds(5).truncatedTo(ChronoUnit.MICROS); + publications.put( + futureRequest, + publication( + scopeId, + "test-terms-v2".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.MATERIAL, + deadline)); + AccountHostedTermsService.PublicationResult scheduled = service.publish(futureRequest); + assertThat(scheduled.status()).isEqualTo(HostedTermsRepository.PublicationStatus.SCHEDULED); + UUID advanceAcceptanceId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction advanceAcceptance = + action(advanceAcceptanceId, accountId, partyId, scopeId, scheduled.candidate(), true); + actions.put(advanceAcceptanceId, advanceAcceptance); + var acceptedInAdvance = service.accept(advanceAcceptanceId); + assertThat(acceptedInAdvance.termsVersionId()).isEqualTo(scheduled.candidate().versionId()); + var beforeDeadline = service.requireCurrentness(scopeId, partyId); + assertThat(beforeDeadline.acceptanceEvidenceId()).isEqualTo(accepted.evidenceId()); + assertThat(beforeDeadline.validUntil()).isEqualTo(deadline); + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isEqualTo(2); + assertThat(service.resumePublication(futureRequest).status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.SCHEDULED); + + assertThat( + currentnessBlockedAcrossEffectiveDateIsDenied(db, service, scopeId, partyId, deadline)) + .isTrue(); + } + + private static boolean currentnessBlockedAcrossEffectiveDateIsDenied( + Database db, AccountHostedTermsService service, UUID scopeId, UUID partyId, Instant deadline) + throws Exception { + CountDownLatch scopeLocked = new CountDownLatch(1); + CountDownLatch releaseScope = new CountDownLatch(1); + AtomicInteger blockerPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + Future blocker = + executor.submit( + () -> + db.transactions() + .executeWithoutResult( + ignored -> { + blockerPid.set( + Objects.requireNonNull( + db.dsl().fetchOne("SELECT pg_backend_pid() AS pid")) + .get("pid", Integer.class)); + db.dsl() + .fetchOne( + "SELECT hosted_scope_id FROM account_hosted_terms_scopes " + + "WHERE hosted_scope_id = ? FOR UPDATE", + scopeId); + scopeLocked.countDown(); + awaitLatch(releaseScope, "Hosted scope blocker was not released"); + })); + try { + assertThat(scopeLocked.await(5, TimeUnit.SECONDS)).isTrue(); + Future waiter = + executor.submit(() -> service.requireCurrentness(scopeId, partyId)); + Record waiting = awaitHostedScopeLockWait(db, blockerPid.get(), deadline); + assertThat(waiting.get("query_start", OffsetDateTime.class).toInstant()) + .as("currentness lock wait must begin before the disclosed effective date") + .isBefore(deadline); + + awaitDatabaseTime(db, deadline); + releaseScope.countDown(); + try { + waiter.get(5, TimeUnit.SECONDS); + throw new AssertionError("Currentness returned after the disclosed terms deadline"); + } catch (ExecutionException failure) { + assertThat(failure.getCause()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("effective date has arrived"); + } + blocker.get(5, TimeUnit.SECONDS); + return true; + } finally { + releaseScope.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static Record awaitHostedScopeLockWait(Database db, int blockerPid, Instant deadline) + throws InterruptedException { + long timeoutAt = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < timeoutAt) { + Record waiting = + db.dsl() + .fetchOne( + "SELECT waiting.pid, waiting.query_start, waiting.xact_start " + + "FROM pg_stat_activity waiting " + + "WHERE waiting.wait_event_type = 'Lock' " + + "AND waiting.query ILIKE '%account_hosted_terms_scopes%' " + + "AND waiting.query ILIKE '%for update%' " + + "AND ? = ANY(pg_blocking_pids(waiting.pid)) LIMIT 1", + blockerPid); + if (waiting != null) { + assertThat(waiting.get("xact_start", OffsetDateTime.class).toInstant()) + .as("currentness transaction must also have begun before the deadline") + .isBefore(deadline); + return waiting; + } + Thread.sleep(10L); + } + throw new AssertionError("Currentness did not reach the hosted-scope lock wait"); + } + + private static void awaitDatabaseTime(Database db, Instant deadline) throws InterruptedException { + long timeoutAt = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < timeoutAt) { + Instant databaseTime = databaseNow(db); + if (!databaseTime.isBefore(deadline)) { + return; + } + Thread.sleep(10L); + } + throw new AssertionError("PostgreSQL clock did not reach the disclosed effective date"); + } + + private static Instant databaseNow(Database db) { + return Objects.requireNonNull(db.dsl().fetchOne("SELECT clock_timestamp() AS database_now")) + .get("database_now", OffsetDateTime.class) + .toInstant(); + } + + private static void awaitLatch(CountDownLatch latch, String message) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException(message); + } + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(message, failure); + } + } + + @Test + void ownerTransactionRollbackRemovesUncommittedCatalogAndPublicationIntent() throws Exception { + Database db = database("94"); + HostedTermsRepository repository = new HostedTermsRepository(db.dsl()); + UUID scopeId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + byte[] request = "test-only publication".getBytes(); + HostedTermsCatalogVersion candidate = + catalogCandidate( + scopeId, + "test-only terms".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(1), + UUID.randomUUID()); + + assertThatThrownBy( + () -> + tx( + db, + () -> + db.transactions() + .executeWithoutResult( + status -> { + repository.ensureScope(scopeId); + repository.claimPublication(requestId, scopeId, request); + repository.lockScope(scopeId); + repository.insertCandidate(candidate); + throw new IllegalStateException("test-only rollback"); + }))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("rollback"); + + assertThat(count(db, "account_hosted_terms_scopes")).isZero(); + assertThat(count(db, "account_hosted_terms_catalog_versions")).isZero(); + assertThat(count(db, "account_hosted_terms_publication_operations")).isZero(); + } + + private static AccountHostedTermsService service( + Database db, + Map publications, + Map actions) { + IndividualCreatorPartyRepository individualParties = + new IndividualCreatorPartyRepository( + db.dsl(), + new FreshTenantIdentityAssociationRepository(db.dsl(), TEST_NAMESPACE), + new AccountTenantCreationBootstrapOperationRepository(db.dsl())); + return new AccountHostedTermsService( + db.transactionManager(), + new HostedTermsRepository(db.dsl()), + individualParties, + new DraftAuthorizationFenceRepository(db.dsl()), + requestId -> + Objects.requireNonNull(publications.get(requestId), "test-only operator fixture"), + actionId -> + Objects.requireNonNull(actions.get(actionId), "test-only identity/action fixture")); + } + + private static AccountHostedTermsService.PublicationEvidence publication( + UUID scope, + byte[] document, + String operator, + long operatorVersion, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt) { + return new AccountHostedTermsService.PublicationEvidence( + scope, + operator, + operatorVersion, + document, + materiality, + materiality == HostedTermsCatalogVersion.Materiality.INITIAL + ? null + : "test-only-materiality", + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : 1L, + "test-only-publication-evidence", + 1, + "test-only-notice-evidence", + 1, + effectiveAt.truncatedTo(ChronoUnit.MICROS)); + } + + private static HostedTermsCatalogVersion catalogCandidate( + UUID scope, + byte[] document, + String operator, + long operatorVersion, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt, + UUID versionId) { + return new HostedTermsCatalogVersion( + versionId, + scope, + null, + operator, + operatorVersion, + document, + HostedTermsEncoding.digest(document), + 1, + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-only-publication-evidence", + 1, + "test-only-notice-evidence", + 1, + effectiveAt.truncatedTo(ChronoUnit.MICROS)); + } + + private static AccountHostedTermsService.AcceptanceAction action( + UUID actionId, + UUID accountId, + UUID partyId, + UUID scopeId, + HostedTermsCatalogVersion terms, + boolean affirmative) { + return new AccountHostedTermsService.AcceptanceAction( + actionId, + affirmative, + accountId, + partyId, + scopeId, + terms.versionId(), + terms.documentDigest(), + terms.operatorLegalIdentity(), + terms.operatorIdentityVersion(), + "test-only-authenticated-action", + 1, + OffsetDateTime.ofInstant(now(), ZoneOffset.UTC)); + } + + private static IndividualCreatorPartySource party( + UUID partyId, UUID accountId, long identityVersion, String evidenceRef) { + return new IndividualCreatorPartySource( + partyId, + accountId, + VerificationStatus.VERIFIED, + identityVersion, + "test-only-verification-policy", + 1L, + evidenceRef, + 1L, + 1); + } + + private static void insertParty(Database db, IndividualCreatorPartySource party) { + byte[] source = CreatorPartyEncoding.party(party); + db.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + source, + CreatorPartyEncoding.digest(source)); + } + + private static UUID insertAccount(Database db) { + UUID accountId = UUID.randomUUID(); + db.dsl() + .execute( + "INSERT INTO accounts (account_uuid, username, email, password_hash) " + + "VALUES (?, ?, ?, 'test-only-password-hash')", + accountId, + "hosted-" + accountId.toString().substring(0, 8), + accountId + "@example.test"); + return accountId; + } + + private static Instant now() { + return Instant.now().truncatedTo(ChronoUnit.MICROS); + } + + private static long count(Database db, String table) { + return Objects.requireNonNull( + Objects.requireNonNull(db.dsl().fetchOne("SELECT count(*) AS count FROM " + table)) + .get("count", Long.class)); + } + + private static Database database(String target) throws Exception { + String schema = "hosted_terms_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema, + postgres.getUsername(), + postgres.getPassword()); + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + schema); + } + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(source); + Database db = + new Database( + schema, + source, + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), + transactionManager, + new TransactionTemplate(transactionManager)); + migrate(db, target); + return db; + } + + private static void migrate(Database db, String target) { + Flyway.configure() + .dataSource(db.source()) + .schemas(db.schema()) + .defaultSchema(db.schema()) + .placeholders(Map.of("serviceSchema", db.schema())) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + } + + private static void tx(Database db, Runnable work) { + db.transactions().executeWithoutResult(status -> work.run()); + } + + private record Database( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactions) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java new file mode 100644 index 0000000000..917e44db0e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java @@ -0,0 +1,646 @@ +package integration.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 java.sql.Connection; +import java.sql.Statement; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +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.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +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 net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof with explicitly test-only environment publisher and identity authorities. */ +@Testcontainers(disabledWithoutDocker = true) +class HostedTermsEnvironmentBindingPostgresIntegrationTest { + private static final String TEST_NAMESPACE = "hosted-terms-binding-isolated-test"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersions() + throws Exception { + Database db = database("95"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + AtomicReference boundary = + new AtomicReference<>(currentBoundary("production")); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary); + + assertThat(count(db, "account_hosted_terms_environment_binding_heads")).isZero(); + assertThat(count(db, "account_hosted_terms_environment_bindings")).isZero(); + assertThat(count(db, "account_hosted_terms_environment_binding_publications")).isZero(); + + UUID firstTermsRequest = UUID.randomUUID(); + catalogPublications.put( + firstTermsRequest, + publication( + scopeId, + "test-only terms version one".getBytes(), + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(10))); + HostedTermsCatalogVersion firstCatalog = service.publish(firstTermsRequest).candidate(); + UUID acceptanceRequest = UUID.randomUUID(); + actions.put(acceptanceRequest, action(acceptanceRequest, accountId, partyId, firstCatalog)); + var acceptance = service.accept(acceptanceRequest); + + UUID firstBindingRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence firstBindingEvidence = + bindingEvidence("production", firstCatalog, null, null, "test-only-publisher-v1"); + bindingPublications.put(firstBindingRequest, firstBindingEvidence); + var firstBinding = service.publishEnvironmentBinding(firstBindingRequest); + assertThat(firstBinding.status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + assertThat(firstBinding.candidate().sourceVersion()).isOne(); + assertThat(firstBinding.exactReceipt()) + .containsExactly(HostedTermsEnvironmentBindingEncoding.receipt(firstBinding.candidate())); + assertThat(service.publishEnvironmentBinding(firstBindingRequest)).isEqualTo(firstBinding); + assertThat( + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT current_binding_id FROM account_hosted_terms_environment_binding_heads " + + "WHERE environment_boundary = 'production'")) + .get("current_binding_id", UUID.class)) + .isEqualTo(firstBinding.candidate().bindingId()); + + HostedTermsEnvironmentBinding.PublicationEvidence changedRetry = + bindingEvidence("production", firstCatalog, null, null, "changed-test-publisher"); + bindingPublications.put(firstBindingRequest, changedRetry); + assertThatThrownBy(() -> service.publishEnvironmentBinding(firstBindingRequest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + bindingPublications.put(firstBindingRequest, firstBindingEvidence); + + var current = service.requireCurrentnessForCurrentEnvironment(partyId); + assertThat(current.environment().environmentBoundary()).isEqualTo("production"); + assertThat(current.binding()).isEqualTo(firstBinding.candidate()); + assertThat(current.terms().acceptanceEvidenceId()).isEqualTo(acceptance.evidenceId()); + assertThat(current.sourceEvidence()).hasSize(3); + assertThat(current.sourceEvidence()) + .anySatisfy( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.scopeId()).isEqualTo("environment-boundary/production"); + assertThat(source.generation()).isNull(); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(source.evidence()) + .containsExactly( + HostedTermsEnvironmentBindingEncoding.receipt(firstBinding.candidate())); + }) + .anySatisfy( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.scopeId()).isEqualTo(scopeId.toString()); + assertThat(source.generation()).isEqualTo("1"); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(new String(source.evidence(), StandardCharsets.UTF_8)) + .contains("account-hosted-terms-currentness-source/v2") + .contains(HostedTermsEncoding.digest(HostedTermsEncoding.acceptance(acceptance))); + }) + .anySatisfy( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.CREATOR_PARTY); + assertThat(source.scopeId()).isEqualTo(partyId.toString()); + assertThat(source.generation()).isEqualTo("1"); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(source.evidence()).containsExactly(CreatorPartyEncoding.party(party)); + }); + + UUID nextTermsRequest = UUID.randomUUID(); + catalogPublications.put( + nextTermsRequest, + publication( + scopeId, + "test-only nonmaterial terms version two".getBytes(), + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + now().minusSeconds(5))); + HostedTermsCatalogVersion secondCatalog = service.publish(nextTermsRequest).candidate(); + assertThat(secondCatalog.sourceVersion()).isEqualTo(2); + assertThat(secondCatalog.materialGeneration()).isEqualTo(1); + assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed catalog authority"); + + UUID secondBindingRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence secondBindingEvidence = + bindingEvidence( + "production", + secondCatalog, + firstBinding.candidate().bindingId(), + firstBinding.candidate().sourceVersion(), + "test-only-publisher-v2"); + bindingPublications.put(secondBindingRequest, secondBindingEvidence); + var secondBinding = service.publishEnvironmentBinding(secondBindingRequest); + assertThat(secondBinding.status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + assertThat(secondBinding.candidate().sourceVersion()).isEqualTo(2); + assertThat(secondBinding.candidate().catalogSourceVersion()).isEqualTo(2); + assertThat(secondBinding.candidate().predecessorBindingId()) + .isEqualTo(firstBinding.candidate().bindingId()); + assertThat(service.publishEnvironmentBinding(secondBindingRequest)).isEqualTo(secondBinding); + HostedTermsEnvironmentBindingRepository bindingRepository = + new HostedTermsEnvironmentBindingRepository(db.dsl()); + assertThat(count(db, "account_hosted_terms_environment_bindings")).isEqualTo(2); + HostedTermsEnvironmentBinding retainedBinding = + db.transactions() + .execute( + ignored -> + bindingRepository.readBinding( + "production", firstBinding.candidate().bindingId())); + assertThat(retainedBinding).isEqualTo(firstBinding.candidate()); + assertThat(service.requireCurrentnessForCurrentEnvironment(partyId).binding()) + .isEqualTo(secondBinding.candidate()); + + boundary.set(currentBoundary("unbound-test-environment")); + assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("head is unavailable"); + } + + @Test + void bindingUpdateWaitsForExactTerminalSettlementOfAffectedDraftOperation() throws Exception { + Database db = database("95"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + AtomicReference boundary = + new AtomicReference<>(currentBoundary("settlement-test-environment")); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary); + + UUID termsRequest = UUID.randomUUID(); + catalogPublications.put( + termsRequest, + publication( + scopeId, + "test-only terms for settlement proof".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(10))); + HostedTermsCatalogVersion catalog = service.publish(termsRequest).candidate(); + UUID acceptanceRequest = UUID.randomUUID(); + actions.put(acceptanceRequest, action(acceptanceRequest, accountId, partyId, catalog)); + service.accept(acceptanceRequest); + + UUID firstRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence firstEvidence = + bindingEvidence( + "settlement-test-environment", catalog, null, null, "test-only-publisher-v1"); + bindingPublications.put(firstRequest, firstEvidence); + var first = service.publishEnvironmentBinding(firstRequest); + var captured = service.requireCurrentnessForCurrentEnvironment(partyId); + + // This is an explicit isolated-test fence fixture, not proof of the missing authenticated + // Draft producer. The Account binding update still uses the real PostgreSQL owner/fence repos. + DraftAuthorizationFenceBinding pendingDraft = + testDraftBinding(accountId, captured.sourceEvidence()); + var draftFences = new DraftAuthorizationFenceRepository(db.dsl()); + tx(db, () -> draftFences.reserve(pendingDraft)); + + UUID secondRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence secondEvidence = + bindingEvidence( + "settlement-test-environment", + catalog, + first.candidate().bindingId(), + first.candidate().sourceVersion(), + "test-only-publisher-v2"); + bindingPublications.put(secondRequest, secondEvidence); + var pendingBinding = service.publishEnvironmentBinding(secondRequest); + assertThat(pendingBinding.status()) + .isEqualTo( + HostedTermsEnvironmentBindingRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT); + assertThat(pendingBinding.candidate().sourceVersion()).isEqualTo(2); + assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source change is unresolved"); + String pendingDraftOrdering = + db.transactions().execute(ignored -> draftFences.read(pendingDraft).ordering().name()); + assertThat(pendingDraftOrdering).isEqualTo("REVOKE_ORDER"); + DraftAuthorizationFenceRepository.Settlement pendingSettlement = + db.transactions().execute(ignored -> draftFences.readSettlement(pendingDraft)); + assertThat(pendingSettlement).isEqualTo(DraftAuthorizationFenceRepository.Settlement.PENDING); + + // Explicitly simulated terminal abort evidence satisfies both original required owners. + tx( + db, + () -> { + draftFences.recordOwnerReadback( + pendingDraft, testReadback(pendingDraft, Owner.WORLD, new byte[] {1})); + draftFences.recordOwnerReadback( + pendingDraft, testReadback(pendingDraft, Owner.GAME_DESIGN, new byte[] {2})); + }); + assertThat(service.resumeEnvironmentBinding(secondRequest).status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + DraftAuthorizationFenceRepository.Settlement completedSettlement = + db.transactions().execute(ignored -> draftFences.readSettlement(pendingDraft)); + assertThat(completedSettlement) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.FAILED_NONPUBLICATION); + assertThat(service.requireCurrentnessForCurrentEnvironment(partyId).binding().sourceVersion()) + .isEqualTo(2); + } + + @Test + void boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline() throws Exception { + Database db = database("95"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + AtomicReference boundary = + new AtomicReference<>(currentBoundary("deadline-test-environment")); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary); + + UUID initialRequest = UUID.randomUUID(); + catalogPublications.put( + initialRequest, + publication( + scopeId, + "test-only current terms".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.INITIAL, + databaseNow(db).minusSeconds(10))); + HostedTermsCatalogVersion currentCatalog = service.publish(initialRequest).candidate(); + UUID acceptanceRequest = UUID.randomUUID(); + actions.put(acceptanceRequest, action(acceptanceRequest, accountId, partyId, currentCatalog)); + var acceptance = service.accept(acceptanceRequest); + + UUID bindingRequest = UUID.randomUUID(); + bindingPublications.put( + bindingRequest, + bindingEvidence( + "deadline-test-environment", currentCatalog, null, null, "test-only-publisher")); + service.publishEnvironmentBinding(bindingRequest); + + Instant deadline = databaseNow(db).plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.MICROS); + UUID scheduledRequest = UUID.randomUUID(); + catalogPublications.put( + scheduledRequest, + publication( + scopeId, + "test-only scheduled terms".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.MATERIAL, + deadline)); + HostedTermsCatalogVersion scheduled = service.publish(scheduledRequest).candidate(); + + var currentness = service.requireCurrentnessForCurrentEnvironment(partyId); + assertThat(currentness.terms().acceptanceEvidenceId()).isEqualTo(acceptance.evidenceId()); + assertThat(currentness.terms().validUntil()).isEqualTo(scheduled.effectiveAt()); + assertThat(currentness.terms().disclosedDeadline()).isEqualTo(scheduled); + byte[] exactTermsSource = + HostedTermsEncoding.currentnessSource(currentCatalog, acceptance, scheduled); + assertThat(currentness.terms().exactCurrentnessSource()).containsExactly(exactTermsSource); + assertThat(currentness.sourceEvidence()) + .filteredOn(source -> source.scopeId().equals(scopeId.toString())) + .singleElement() + .satisfies( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.generation()).isEqualTo("1"); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(source.evidence()).containsExactly(exactTermsSource); + assertThat(new String(source.evidence(), StandardCharsets.UTF_8)) + .contains(HostedTermsEncoding.digest(HostedTermsEncoding.catalog(scheduled))); + }); + } + + private static DraftAuthorizationFenceBinding testDraftBinding( + UUID actorAccountId, List sources) { + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof(tenantId, versionId, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + requestId, + commitId, + "opaque/base:1", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-only")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "test-region", + "aggregate", + "test-region", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + requestId, + commitId, + UUID.randomUUID(), + actorAccountId, + tenantId, + versionId, + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + sources) + .withRequiredOwners(); + } + + private static OwnerReadback testReadback( + DraftAuthorizationFenceBinding binding, Owner owner, byte[] exactTestResult) { + return new OwnerReadback( + owner, + Outcome.DEFINITIVELY_ABORTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + exactTestResult); + } + + private static AccountHostedTermsService service( + Database db, + Map catalogPublications, + Map actions, + Map bindingPublications, + AtomicReference boundary) { + IndividualCreatorPartyRepository parties = + new IndividualCreatorPartyRepository( + db.dsl(), + new FreshTenantIdentityAssociationRepository(db.dsl(), TEST_NAMESPACE), + new AccountTenantCreationBootstrapOperationRepository(db.dsl())); + return new AccountHostedTermsService( + db.transactionManager(), + new HostedTermsRepository(db.dsl()), + parties, + new DraftAuthorizationFenceRepository(db.dsl()), + request -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull( + catalogPublications.get(request), "test-only catalog fixture"); + }, + request -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull( + actions.get(request), "test-only affirmative action fixture"); + }, + new HostedTermsEnvironmentBindingRepository(db.dsl()), + request -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull( + bindingPublications.get(request), "test-only owner fixture"); + }, + () -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull(boundary.get()); + }); + } + + private static void assertOutsideOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Owner authority must be resolved outside Account locks"); + } + } + + private static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary currentBoundary( + String boundary) { + byte[] ownerEvidence = ("test-only-boundary:" + boundary).getBytes(); + return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + boundary, + "test-only-environment-owner/" + boundary, + "test-only-current-boundary-observation/" + boundary, + ownerEvidence, + HostedTermsEncoding.digest(ownerEvidence)); + } + + private static HostedTermsEnvironmentBinding.PublicationEvidence bindingEvidence( + String boundary, + HostedTermsCatalogVersion catalog, + UUID predecessorBindingId, + Long predecessorSourceVersion, + String publisher) { + return new HostedTermsEnvironmentBinding.PublicationEvidence( + boundary, + catalog.hostedScopeId(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + catalog.versionId(), + catalog.sourceVersion(), + publisher, + "test-only-publication-event/" + UUID.randomUUID(), + predecessorBindingId, + predecessorSourceVersion); + } + + private static AccountHostedTermsService.PublicationEvidence publication( + UUID scope, + byte[] document, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt) { + return new AccountHostedTermsService.PublicationEvidence( + scope, + "Test Operator Legal Name", + 1, + document, + materiality, + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : "test-materiality", + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : 1L, + "test-only-legal-publication", + 1, + "test-only-notice", + 1, + effectiveAt.truncatedTo(ChronoUnit.MICROS)); + } + + private static AccountHostedTermsService.AcceptanceAction action( + UUID requestId, UUID accountId, UUID partyId, HostedTermsCatalogVersion catalog) { + return new AccountHostedTermsService.AcceptanceAction( + requestId, + true, + accountId, + partyId, + catalog.hostedScopeId(), + catalog.versionId(), + catalog.documentDigest(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + "test-only-authenticated-individual-action", + 1, + OffsetDateTime.ofInstant(now(), ZoneOffset.UTC)); + } + + private static IndividualCreatorPartySource party(UUID partyId, UUID accountId) { + return new IndividualCreatorPartySource( + partyId, + accountId, + VerificationStatus.VERIFIED, + 1, + "test-only-identity-policy", + 1L, + "test-only-verified-identity-evidence", + 1L, + 1); + } + + private static void insertParty(Database db, IndividualCreatorPartySource party) { + byte[] payload = CreatorPartyEncoding.party(party); + db.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + payload, + CreatorPartyEncoding.digest(payload)); + } + + private static UUID insertAccount(Database db) { + UUID id = UUID.randomUUID(); + db.dsl() + .execute( + "INSERT INTO accounts (account_uuid, username, email, password_hash) " + + "VALUES (?, ?, ?, 'test-only-password-hash')", + id, + "hosted-binding-" + id.toString().substring(0, 8), + id + "@example.test"); + return id; + } + + private static Instant now() { + return Instant.now().truncatedTo(ChronoUnit.MICROS); + } + + private static Instant databaseNow(Database db) { + return Objects.requireNonNull(db.dsl().fetchOne("SELECT clock_timestamp() AS database_now")) + .get("database_now", OffsetDateTime.class) + .toInstant() + .truncatedTo(ChronoUnit.MICROS); + } + + private static long count(Database db, String table) { + return Objects.requireNonNull(db.dsl().fetchOne("SELECT count(*) AS count FROM " + table)) + .get("count", Long.class); + } + + private static Database database(String target) throws Exception { + String schema = "terms_binding_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema, + postgres.getUsername(), + postgres.getPassword()); + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + schema); + } + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(source); + Database db = + new Database( + schema, + source, + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), + transactionManager, + new TransactionTemplate(transactionManager)); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + return db; + } + + private static void tx(Database db, Runnable work) { + db.transactions().executeWithoutResult(ignored -> work.run()); + } + + private record Database( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactions) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java index 1fd76a48ec..2e7efc0259 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/tenantcreation/TenantCreationAuthorizationFencePostgresIntegrationTest.java @@ -414,7 +414,7 @@ private void owner( } private void draftOwners(Context c, DraftAuthorizationFenceBinding b) { - for (var owner : DraftAuthorizationFenceBinding.Owner.values()) { + for (var owner : b.requiredOwners()) { tx( c, () -> { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java index b913398def..c5c6195c2a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java @@ -398,12 +398,15 @@ void mixedCommitOrderPreservesOriginalWorldCommitAndTerminalRetry() { return worldEvidence(request, originalWorld); }); - assertThat(f.service().reconcile(f.binding().operationId())) - .contains(Settlement.FAILED_NONPUBLICATION); + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); assertThat(f.stored().get(Owner.WORLD).canonicalBytes()) .containsExactly(originalWorld.canonicalBytes()); - assertThat(f.service().reconcile(f.binding().operationId())) - .contains(Settlement.FAILED_NONPUBLICATION); + byte[] originalGameDesignBytes = f.stored().get(Owner.GAME_DESIGN).canonicalBytes(); + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); + assertThat(f.stored().get(Owner.WORLD).canonicalBytes()) + .containsExactly(originalWorld.canonicalBytes()); + assertThat(f.stored().get(Owner.GAME_DESIGN).canonicalBytes()) + .containsExactly(originalGameDesignBytes); verify(f.gameDesignClient()).read(any()); verify(f.worldClient()).read(any()); } @@ -503,13 +506,134 @@ void absentReservedTerminalAndAmbientCasesNeverCallOwners() { }); } + @Test + void v2WithoutWorldNeverReadsLooksUpOrRetainsWorldEvidence() { + Fixture f = + fixture( + Ordering.COMMIT_ORDER, + requiredBinding(List.of(DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE))); + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {31}))); + }); + + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.COMMITTED); + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.COMMITTED); + verifyNoInteractions(f.worldClient()); + verify(f.repository(), never()).readOwnerResult(any(), eq(Owner.WORLD)); + verify(f.repository()).recordOwnerReadback(eq(f.binding()), any()); + assertThat(f.stored()).containsOnlyKeys(Owner.GAME_DESIGN); + verify(f.gameDesignClient()).read(any()); + } + + @Test + void v2WorldAndGameDesignResultsCannotSettleMissingIndependentEntity() { + Fixture f = + fixture( + Ordering.COMMIT_ORDER, + requiredBinding( + List.of( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitBinding.Owner.ENTITY_MANAGEMENT))); + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {32}))); + }); + when(f.worldClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return worldEvidence( + request, readback(f.binding(), Owner.WORLD, Outcome.COMMITTED, new byte[] {33})); + }); + + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); + byte[] originalWorld = f.stored().get(Owner.WORLD).canonicalBytes(); + byte[] originalGameDesign = f.stored().get(Owner.GAME_DESIGN).canonicalBytes(); + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); + assertThat(f.stored()).containsOnlyKeys(Owner.GAME_DESIGN, Owner.WORLD); + assertThat(f.stored().get(Owner.WORLD).canonicalBytes()).containsExactly(originalWorld); + assertThat(f.stored().get(Owner.GAME_DESIGN).canonicalBytes()) + .containsExactly(originalGameDesign); + verify(f.gameDesignClient()).read(any()); + verify(f.worldClient()).read(any()); + verify(f.repository(), never()).readOwnerResult(any(), eq(Owner.ENTITY)); + } + + private static DraftAuthorizationFenceBinding requiredBinding( + List owners) { + var original = binding(); + var prior = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), java.nio.charset.StandardCharsets.UTF_8), + original.inputDigest()); + var revisions = + java.util.stream.IntStream.range(0, owners.size()) + .mapToObj( + index -> + new DraftCommitBinding.RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + owners.get(index), + "payload-" + index)) + .toList(); + var affected = + owners.stream() + .map( + owner -> + new DraftCommitBinding.AffectedUnit( + owner, "aggregate", owner.name(), "aggregate", owner.name(), "0")) + .toList(); + var complete = + DraftCommitBinding.create( + prior.target(), + prior.requestId(), + prior.commitId(), + prior.baseCommitId(), + revisions, + affected); + return new DraftAuthorizationFenceBinding( + original.operationId(), + original.requestId(), + original.commitId(), + original.fenceId(), + original.actorAccountId(), + original.tenantId(), + original.versionId(), + original.baseCommitId(), + original.expectedDraftEpoch(), + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + original.sources()) + .withRequiredOwners(); + } + private static Fixture fixture(Ordering ordering) { + return fixture(ordering, binding()); + } + + private static Fixture fixture(Ordering ordering, DraftAuthorizationFenceBinding binding) { DraftAuthorizationFenceRepository repository = mock(DraftAuthorizationFenceRepository.class); GameDesignDraftTerminalReadClient gameDesignClient = mock(GameDesignDraftTerminalReadClient.class); WorldDraftTerminalReadClient worldClient = mock(WorldDraftTerminalReadClient.class); TestTransactionManager manager = new TestTransactionManager(); - DraftAuthorizationFenceBinding binding = binding(); Map stored = new EnumMap<>(Owner.class); when(repository.readOriginalBinding(any())).thenReturn(Optional.of(binding)); when(repository.read(any())).thenAnswer(invocation -> fenceSnapshot(binding, ordering)); @@ -527,21 +651,19 @@ private static Fixture fixture(Ordering ordering) { when(repository.readSettlement(any())) .thenAnswer( invocation -> { - OwnerReadback gameDesign = stored.get(Owner.GAME_DESIGN); - OwnerReadback world = stored.get(Owner.WORLD); - if (ordering == Ordering.RESERVED || gameDesign == null || world == null) { + if (ordering == Ordering.RESERVED + || !stored.keySet().equals(java.util.Set.copyOf(binding.requiredOwners()))) { return Settlement.PENDING; } - if (ordering == Ordering.REVOKE_ORDER) { - return gameDesign.outcome() == Outcome.DEFINITIVELY_ABORTED - && world.outcome() == Outcome.DEFINITIVELY_ABORTED - ? Settlement.FAILED_NONPUBLICATION - : Settlement.PENDING; + if (ordering == Ordering.COMMIT_ORDER + && stored.values().stream() + .allMatch(value -> value.outcome() == Outcome.COMMITTED)) { + return Settlement.COMMITTED; } - return gameDesign.outcome() == Outcome.COMMITTED - && world.outcome() == Outcome.COMMITTED - ? Settlement.COMMITTED - : Settlement.FAILED_NONPUBLICATION; + return stored.values().stream() + .allMatch(value -> value.outcome() == Outcome.DEFINITIVELY_ABORTED) + ? Settlement.FAILED_NONPUBLICATION + : Settlement.PENDING; }); doAnswer( invocation -> { 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..0367e93183 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java @@ -0,0 +1,384 @@ +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.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 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("WHERE tenant_uuid = ? FOR UPDATE")) { + 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/AccountHostedTermsServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java new file mode 100644 index 0000000000..44f8772a00 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java @@ -0,0 +1,567 @@ +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.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +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.accountservice.hostedterms.AccountHostedTermsService; +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.hostedterms.IndividualHostedTermsAcceptance; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; + +/** + * Unit proof uses explicit typed upstream authority fixtures, not caller-supplied authority DTOs. + */ +class AccountHostedTermsServiceTest { + private static final Instant NOW = Instant.parse("2026-10-08T00:00:00Z"); + + @Test + void affirmativeAcceptancePersistsExactShownCatalogAndReturnsOriginalReceipt() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion terms = + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(60)); + AccountHostedTermsService.AcceptanceAction action = action(fixture, terms, true); + IndividualHostedTermsAcceptance expected = acceptance(action, party, terms); + fixture.acceptanceAuthority(action); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, terms, NOW, null)); + when(fixture.repository.readCatalog(fixture.scopeId, terms.versionId())).thenReturn(terms); + when(fixture.repository.readAcceptanceByRequest(action.actionRequestId())) + .thenReturn(Optional.empty()); + when(fixture.repository.insertAcceptance( + any(UUID.class), any(), any(), any(), any(byte[].class))) + .thenReturn(expected); + + assertThat(fixture.service.accept(action.actionRequestId())).isEqualTo(expected); + verify(fixture.repository) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void nonaffirmativeOrUnverifiedForeignPartyCannotWriteAcceptance() { + Fixture fixture = new Fixture(); + HostedTermsCatalogVersion terms = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + AccountHostedTermsService.AcceptanceAction no = action(fixture, terms, false); + fixture.acceptanceAuthority(no); + assertThatThrownBy(() -> fixture.service.accept(no.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Affirmative"); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + + AccountHostedTermsService.AcceptanceAction foreign = action(fixture, terms, true); + fixture.acceptanceAuthority(foreign); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party(fixture.partyId, UUID.randomUUID())); + assertThatThrownBy(() -> fixture.service.accept(foreign.actionRequestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("own locally verified"); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void changedShownDigestOperatorOrVersionIsDenied() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion stored = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + HostedTermsCatalogVersion other = terms(fixture.scopeId, null, 1, 1, "other-terms", NOW); + AccountHostedTermsService.AcceptanceAction action = action(fixture, stored, true); + fixture.acceptanceAuthority(action); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, stored, NOW, null)); + when(fixture.repository.readCatalog(fixture.scopeId, stored.versionId())).thenReturn(other); + + assertThatThrownBy(() -> fixture.service.accept(action.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void changedOperatorIdentityOrVersionCannotBeAcceptedAsTheShownTerms() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion terms = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + AccountHostedTermsService.AcceptanceAction base = action(fixture, terms, true); + AccountHostedTermsService.AcceptanceAction changedName = + new AccountHostedTermsService.AcceptanceAction( + base.actionRequestId(), + true, + base.accountId(), + base.creatorPartyId(), + base.hostedScopeId(), + base.shownVersionId(), + base.shownDocumentDigest(), + "Different Operator", + base.shownOperatorIdentityVersion(), + base.authenticatedActionReference(), + base.authenticatedActionVersion(), + base.actionCreatedAt()); + fixture.acceptanceAuthority(changedName); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, terms, NOW, null)); + when(fixture.repository.readCatalog(fixture.scopeId, terms.versionId())).thenReturn(terms); + when(fixture.repository.readAcceptanceByRequest(base.actionRequestId())) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> fixture.service.accept(base.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + + AccountHostedTermsService.AcceptanceAction changedVersion = + new AccountHostedTermsService.AcceptanceAction( + UUID.randomUUID(), + true, + base.accountId(), + base.creatorPartyId(), + base.hostedScopeId(), + base.shownVersionId(), + base.shownDocumentDigest(), + base.shownOperatorLegalIdentity(), + 2, + base.authenticatedActionReference(), + base.authenticatedActionVersion(), + base.actionCreatedAt()); + fixture.acceptanceAuthority(changedVersion); + when(fixture.repository.readAcceptanceByRequest(changedVersion.actionRequestId())) + .thenReturn(Optional.empty()); + assertThatThrownBy(() -> fixture.service.accept(changedVersion.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + } + + @Test + void exactRetryRecoversOriginalEvidenceWithoutRewritingOrReplacingIt() { + Fixture fixture = new Fixture(); + HostedTermsCatalogVersion terms = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + AccountHostedTermsService.AcceptanceAction action = action(fixture, terms, true); + IndividualHostedTermsAcceptance receipt = + acceptance(action, party(fixture.partyId, fixture.accountId), terms); + fixture.acceptanceAuthority(action); + when(fixture.repository.readAcceptanceByRequest(action.actionRequestId())) + .thenReturn(Optional.of(receipt)); + + assertThat(fixture.service.accept(action.actionRequestId())).isEqualTo(receipt); + verify(fixture.parties, never()).readIndividualSource(any(), any()); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void materialityAdvancesOnlyItsIndependentGenerationAndNonmaterialityPreservesIt() { + Fixture material = new Fixture(); + HostedTermsCatalogVersion oldMaterial = + terms(material.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(1)); + HostedTermsRepository.PublicationOperation materialOperation = + operation( + material.requestId, + material.scopeId, + "intent", + HostedTermsRepository.PublicationStatus.RECEIVED); + when(material.repository.claimPublication(any(), any(), any())).thenReturn(materialOperation); + when(material.repository.lockScope(material.scopeId)) + .thenReturn(scope(material.scopeId, oldMaterial, NOW, null)); + when(material.fences.requestSourceChange(any())).thenReturn(true); + when(material.fences.sourceMutationPermitted(any())).thenReturn(true); + material.publicationAuthority( + publication( + material.scopeId, + "terms-v2", + HostedTermsCatalogVersion.Materiality.MATERIAL, + NOW.minusSeconds(1))); + AccountHostedTermsService.PublicationResult materialResult = + material.service.publish(material.requestId); + assertThat(materialResult.status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.COMMITTED); + assertThat(materialResult.candidate().sourceVersion()).isEqualTo(2); + assertThat(materialResult.candidate().materialGeneration()).isEqualTo(2); + + Fixture nonmaterial = new Fixture(); + HostedTermsCatalogVersion oldNonmaterial = + terms(nonmaterial.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(1)); + HostedTermsRepository.PublicationOperation nonmaterialOperation = + operation( + nonmaterial.requestId, + nonmaterial.scopeId, + "intent", + HostedTermsRepository.PublicationStatus.RECEIVED); + when(nonmaterial.repository.claimPublication(any(), any(), any())) + .thenReturn(nonmaterialOperation); + when(nonmaterial.repository.lockScope(nonmaterial.scopeId)) + .thenReturn(scope(nonmaterial.scopeId, oldNonmaterial, NOW, null)); + when(nonmaterial.fences.requestSourceChange(any())).thenReturn(true); + when(nonmaterial.fences.sourceMutationPermitted(any())).thenReturn(true); + nonmaterial.publicationAuthority( + publication( + nonmaterial.scopeId, + "terms-v2", + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + NOW.minusSeconds(1))); + AccountHostedTermsService.PublicationResult nonmaterialResult = + nonmaterial.service.publish(nonmaterial.requestId); + assertThat(nonmaterialResult.candidate().sourceVersion()).isEqualTo(2); + assertThat(nonmaterialResult.candidate().materialGeneration()).isEqualTo(1); + } + + @Test + void unresolvedOwnerSettlementKeepsPublicationPendingWithoutAdvancingCatalogHead() { + Fixture fixture = new Fixture(); + HostedTermsCatalogVersion current = + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(1)); + when(fixture.repository.claimPublication(any(), any(), any())) + .thenReturn( + operation( + fixture.requestId, + fixture.scopeId, + "intent", + HostedTermsRepository.PublicationStatus.RECEIVED)); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, current, NOW, null)); + when(fixture.fences.requestSourceChange(any())).thenReturn(false); + fixture.publicationAuthority( + publication( + fixture.scopeId, + "terms-v2", + HostedTermsCatalogVersion.Materiality.MATERIAL, + NOW.minusSeconds(1))); + + AccountHostedTermsService.PublicationResult result = fixture.service.publish(fixture.requestId); + assertThat(result.status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT); + verify(fixture.repository).markOwnerSettlementPending(any(), any(), any(byte[].class)); + verify(fixture.repository, never()).completePublication(any(), any(), any(), any()); + } + + @Test + void dueDisclosedDeadlineDeniesOldCurrentnessWhileSourceSettlementIsPending() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion current = + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(10)); + HostedTermsCatalogVersion next = + terms(fixture.scopeId, current.versionId(), 2, 2, "terms-v2", NOW.minusSeconds(1)); + HostedTermsRepository.PublicationOperation pending = + new HostedTermsRepository.PublicationOperation( + fixture.requestId, + fixture.scopeId, + new byte[] {1}, + HostedTermsEncoding.digest(new byte[] {1}), + HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT, + next.versionId(), + new byte[] {2}, + null, + null, + null); + when(fixture.repository.lockPartyAccount(fixture.partyId)).thenReturn(fixture.accountId); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, current, NOW, pending)); + when(fixture.repository.readCandidate(pending)).thenReturn(next); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("effective date has arrived"); + } + + @Test + void staleGenerationAndChangedOrUnavailableIdentityNeverReturnCurrentness() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource acceptedParty = party(fixture.partyId, fixture.accountId); + IndividualCreatorPartySource changedParty = + new IndividualCreatorPartySource( + fixture.partyId, + fixture.accountId, + VerificationStatus.VERIFIED, + 2, + "test-policy-v2", + 2L, + "test-verification-v2", + 2L, + 1); + HostedTermsCatalogVersion current = + terms(fixture.scopeId, UUID.randomUUID(), 2, 2, "terms-v2", NOW); + IndividualHostedTermsAcceptance stale = + acceptance( + action(fixture, terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW), true), + acceptedParty, + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW)); + IndividualHostedTermsAcceptance currentAcceptance = + acceptance(action(fixture, current, true), acceptedParty, current); + when(fixture.repository.lockPartyAccount(fixture.partyId)).thenReturn(fixture.accountId); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(acceptedParty, acceptedParty, changedParty) + .thenThrow(new IllegalStateException("source unavailable")); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, current, NOW, null)); + when(fixture.repository.readCurrentAcceptance(fixture.partyId, fixture.scopeId, current)) + .thenReturn(Optional.empty(), Optional.of(stale), Optional.of(currentAcceptance)); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No current affirmative"); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or changed"); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or changed"); + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source unavailable"); + } + + @Test + void catalogAndAcceptanceEncodingsBindExactBytesWithoutCallerTimeAuthority() { + Fixture fixture = new Fixture(); + byte[] document = new byte[] {0, 1, (byte) 0xff, 13, 10}; + HostedTermsCatalogVersion version = terms(fixture.scopeId, null, 1, 1, document, NOW); + byte[] original = version.documentBytes(); + original[0] = 9; + assertThat(version.documentBytes()).containsExactly(document); + assertThat(version.documentDigest()).isEqualTo(HostedTermsEncoding.digest(document)); + assertThat(HostedTermsEncoding.catalog(version)) + .isEqualTo(HostedTermsEncoding.catalog(version)); + assertThatThrownBy( + () -> + new HostedTermsCatalogVersion( + UUID.randomUUID(), + fixture.scopeId, + null, + "Test Operator", + 1, + document, + HostedTermsEncoding.digest("different".getBytes()), + 1, + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-publication", + 1, + "test-notice", + 1, + NOW)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Document digest"); + } + + private static HostedTermsRepository.ScopeSnapshot scope( + UUID id, + HostedTermsCatalogVersion current, + Instant now, + HostedTermsRepository.PublicationOperation pending) { + return new HostedTermsRepository.ScopeSnapshot( + id, current, OffsetDateTime.ofInstant(now, ZoneOffset.UTC), pending); + } + + private static HostedTermsRepository.PublicationOperation operation( + UUID requestId, + UUID scopeId, + String request, + HostedTermsRepository.PublicationStatus status) { + byte[] payload = request.getBytes(); + return new HostedTermsRepository.PublicationOperation( + requestId, + scopeId, + payload, + HostedTermsEncoding.digest(payload), + status, + null, + null, + null, + null, + null); + } + + private static HostedTermsCatalogVersion terms( + UUID scope, + UUID predecessor, + long source, + long generation, + String document, + Instant effectiveAt) { + return terms(scope, predecessor, source, generation, document.getBytes(), effectiveAt); + } + + private static HostedTermsCatalogVersion terms( + UUID scope, + UUID predecessor, + long source, + long generation, + byte[] document, + Instant effectiveAt) { + return new HostedTermsCatalogVersion( + UUID.randomUUID(), + scope, + predecessor, + "Test Operator", + 1, + document, + HostedTermsEncoding.digest(document), + source, + generation, + predecessor == null + ? HostedTermsCatalogVersion.Materiality.INITIAL + : generation == 2 + ? HostedTermsCatalogVersion.Materiality.MATERIAL + : HostedTermsCatalogVersion.Materiality.NONMATERIAL, + predecessor == null ? null : "test-materiality", + predecessor == null ? null : 1L, + "test-publication", + 1, + "test-notice", + 1, + effectiveAt); + } + + private static IndividualCreatorPartySource party(UUID partyId, UUID accountId) { + return new IndividualCreatorPartySource( + partyId, + accountId, + VerificationStatus.VERIFIED, + 1, + "test-policy", + 1L, + "test-verification", + 1L, + 1); + } + + private static AccountHostedTermsService.AcceptanceAction action( + Fixture fixture, HostedTermsCatalogVersion terms, boolean affirmative) { + return new AccountHostedTermsService.AcceptanceAction( + UUID.randomUUID(), + affirmative, + fixture.accountId, + fixture.partyId, + fixture.scopeId, + terms.versionId(), + terms.documentDigest(), + terms.operatorLegalIdentity(), + terms.operatorIdentityVersion(), + "test-authenticated-action", + 1, + OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC)); + } + + private static AccountHostedTermsService.PublicationEvidence publication( + UUID scope, + String document, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt) { + return new AccountHostedTermsService.PublicationEvidence( + scope, + "Test Operator", + 1, + document.getBytes(), + materiality, + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : "test-materiality", + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : 1L, + "test-publication", + 1, + "test-notice", + 1, + effectiveAt); + } + + private static IndividualHostedTermsAcceptance acceptance( + AccountHostedTermsService.AcceptanceAction action, + IndividualCreatorPartySource party, + HostedTermsCatalogVersion terms) { + byte[] source = HostedTermsEncoding.individualParty(party); + byte[] actionBytes = HostedTermsEncoding.affirmativeAction(action); + return new IndividualHostedTermsAcceptance( + UUID.randomUUID(), + action.actionRequestId(), + party.creatorPartyId(), + party.accountId(), + terms.hostedScopeId(), + terms.versionId(), + terms.documentDigest(), + terms.operatorLegalIdentity(), + terms.operatorIdentityVersion(), + terms.sourceVersion(), + terms.materialGeneration(), + source, + HostedTermsEncoding.digest(source), + actionBytes, + HostedTermsEncoding.digest(actionBytes), + OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC)); + } + + private static final class Fixture { + private final UUID requestId = UUID.randomUUID(); + private final UUID scopeId = UUID.randomUUID(); + private final UUID accountId = UUID.randomUUID(); + private final UUID partyId = UUID.randomUUID(); + private final HostedTermsRepository repository = mock(HostedTermsRepository.class); + private final IndividualCreatorPartyRepository parties = + mock(IndividualCreatorPartyRepository.class); + private final DraftAuthorizationFenceRepository fences = + mock(DraftAuthorizationFenceRepository.class); + private final AccountHostedTermsService.OperatorPublicationAuthority publicationAuthority = + mock(AccountHostedTermsService.OperatorPublicationAuthority.class); + private final AccountHostedTermsService.IndividualAcceptanceAuthority acceptanceAuthority = + mock(AccountHostedTermsService.IndividualAcceptanceAuthority.class); + private final AccountHostedTermsService service = + new AccountHostedTermsService( + new NoopTransactionManager(), + repository, + parties, + fences, + publicationAuthority, + acceptanceAuthority); + + private void acceptanceAuthority(AccountHostedTermsService.AcceptanceAction action) { + when(acceptanceAuthority.resolve(action.actionRequestId())).thenReturn(action); + } + + private void publicationAuthority(AccountHostedTermsService.PublicationEvidence evidence) { + when(publicationAuthority.resolve(requestId)).thenReturn(evidence); + } + } + + private static final class NoopTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingTest.java new file mode 100644 index 0000000000..4080386540 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingTest.java @@ -0,0 +1,307 @@ +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 java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding.PublicationEvidence; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingEncoding; +import net.firedevops.firemud.accountservice.hostedterms.IndividualHostedTermsAcceptance; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.junit.jupiter.api.Test; + +class HostedTermsEnvironmentBindingTest { + @Test + void canonicalPublicationBindsBoundaryScopeOperatorCatalogPublisherEventAndPredecessor() { + UUID requestId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + UUID catalogVersionId = UUID.randomUUID(); + UUID priorBinding = UUID.randomUUID(); + PublicationEvidence evidence = + new PublicationEvidence( + "official/production-cluster-a", + scopeId, + "Test Operator Legal Name", + 4, + catalogVersionId, + 9, + "environment-secrets-owner@production", + "deployment-ref:event-37:traffic-open-12", + priorBinding, + 2L); + + byte[] original = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence); + assertThat(HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence)) + .containsExactly(original); + assertThat(HostedTermsEnvironmentBindingEncoding.publicationDigest(requestId, evidence)) + .isEqualTo(HostedTermsEncoding.digest(original)); + + PublicationEvidence changed = + new PublicationEvidence( + evidence.environmentBoundary(), + evidence.hostedScopeId(), + evidence.operatorLegalIdentity(), + evidence.operatorIdentityVersion(), + evidence.catalogVersionId(), + evidence.catalogSourceVersion(), + evidence.authenticatedPublisherIdentity(), + evidence.publicationEventIdentity(), + UUID.randomUUID(), + evidence.predecessorSourceVersion()); + assertThat(HostedTermsEnvironmentBindingEncoding.publication(requestId, changed)) + .isNotEqualTo(original); + assertThat(HostedTermsEnvironmentBindingEncoding.publication(UUID.randomUUID(), evidence)) + .isNotEqualTo(original); + } + + @Test + void independentBindingCounterAndExactReceiptUseNamespacedHostedTermsSourceKey() { + UUID requestId = UUID.randomUUID(); + PublicationEvidence evidence = + new PublicationEvidence( + "production", + UUID.randomUUID(), + "Test Operator", + 1, + UUID.randomUUID(), + 7, + "test-only-environment-owner", + "test-only-publication-event-17", + UUID.randomUUID(), + 8L); + byte[] publication = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence); + HostedTermsEnvironmentBinding binding = + new HostedTermsEnvironmentBinding( + UUID.randomUUID(), + requestId, + evidence.environmentBoundary(), + evidence.hostedScopeId(), + evidence.operatorLegalIdentity(), + evidence.operatorIdentityVersion(), + evidence.catalogVersionId(), + evidence.catalogSourceVersion(), + evidence.authenticatedPublisherIdentity(), + evidence.publicationEventIdentity(), + HostedTermsEncoding.digest(publication), + evidence.predecessorBindingId(), + evidence.predecessorSourceVersion(), + 9); + + var source = binding.sourceEvidence(); + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.scopeId()).isEqualTo("environment-boundary/production"); + assertThat(source.key()).isEqualTo("HOSTED_TERMS:environment-boundary/production"); + assertThat(source.scopeId()).isNotEqualTo(binding.hostedScopeId().toString()); + assertThat(source.generation()).isNull(); + assertThat(source.sourceVersion()).isEqualTo("9"); + assertThat(source.evidence()) + .containsExactly(HostedTermsEnvironmentBindingEncoding.receipt(binding)); + assertThat(HostedTermsEnvironmentBindingEncoding.receiptDigest(binding)) + .isEqualTo(HostedTermsEncoding.digest(source.evidence())); + assertThat(binding.catalogSourceVersion()).isEqualTo(7); + assertThat(binding.sourceVersion()).isEqualTo(9); + } + + @Test + void initialBindingCannotInventPredecessorAndUpdatesAdvanceExactlyOnce() { + UUID requestId = UUID.randomUUID(); + UUID priorBinding = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + UUID catalogId = UUID.randomUUID(); + assertThatThrownBy( + () -> + new PublicationEvidence( + "production", + scopeId, + "Test Operator", + 1, + catalogId, + 1, + "test-owner", + "event-1", + null, + 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("present together"); + + assertThatThrownBy( + () -> + new HostedTermsEnvironmentBinding( + UUID.randomUUID(), + requestId, + "production", + scopeId, + "Test Operator", + 1, + catalogId, + 1, + "test-owner", + "event-2", + HostedTermsEncoding.digest(new byte[] {1}), + priorBinding, + 4L, + 7)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact predecessor"); + } + + @Test + void currentEnvironmentEvidenceRequiresExactOwnerDigest() { + byte[] evidence = new byte[] {1, 2, 3}; + var current = + new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + "staging", + "test-only-environment-owner", + "test-only-current-boundary-read-1", + evidence, + HostedTermsEncoding.digest(evidence)); + byte[] returned = current.exactOwnerEvidence(); + returned[0] = 9; + assertThat(current.exactOwnerEvidence()).containsExactly(evidence); + + assertThatThrownBy( + () -> + new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + "staging", + "test-only-environment-owner", + "test-only-current-boundary-read-2", + evidence, + HostedTermsEncoding.digest(new byte[] {8}))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest conflicts"); + } + + @Test + void currentnessSourceRetainsExactScheduledCatalogAndDisclosedDeadline() { + Instant currentAt = Instant.parse("2026-10-08T00:00:00Z"); + byte[] currentDocument = "current terms".getBytes(StandardCharsets.UTF_8); + HostedTermsCatalogVersion current = + new HostedTermsCatalogVersion( + UUID.randomUUID(), + UUID.randomUUID(), + null, + "Test Operator", + 1, + currentDocument, + HostedTermsEncoding.digest(currentDocument), + 1, + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "current-publication", + 1, + "current-notice", + 1, + currentAt); + byte[] partySource = new byte[] {11, 12}; + byte[] affirmativeAction = new byte[] {21, 22}; + IndividualHostedTermsAcceptance acceptance = + new IndividualHostedTermsAcceptance( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + current.hostedScopeId(), + current.versionId(), + current.documentDigest(), + current.operatorLegalIdentity(), + current.operatorIdentityVersion(), + current.sourceVersion(), + current.materialGeneration(), + partySource, + HostedTermsEncoding.digest(partySource), + affirmativeAction, + HostedTermsEncoding.digest(affirmativeAction), + OffsetDateTime.ofInstant(currentAt, ZoneOffset.UTC)); + + Instant disclosedAt = Instant.parse("2026-10-09T00:00:00Z"); + byte[] nextDocument = "scheduled terms".getBytes(StandardCharsets.UTF_8); + HostedTermsCatalogVersion deadline = + new HostedTermsCatalogVersion( + UUID.randomUUID(), + current.hostedScopeId(), + current.versionId(), + current.operatorLegalIdentity(), + current.operatorIdentityVersion(), + nextDocument, + HostedTermsEncoding.digest(nextDocument), + 2, + 1, + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + "audited-nonmaterial-classification", + 1L, + "scheduled-publication", + 2, + "scheduled-notice", + 2, + disclosedAt); + + byte[] exactDeadline = HostedTermsEncoding.catalog(deadline); + byte[] source = HostedTermsEncoding.currentnessSource(current, acceptance, deadline); + String sourceJson = new String(source, StandardCharsets.UTF_8); + assertThat(sourceJson).contains("account-hosted-terms-currentness-source/v2"); + assertThat(sourceJson) + .contains(Base64.getEncoder().encodeToString(exactDeadline)) + .contains(HostedTermsEncoding.digest(exactDeadline)); + assertThat( + new String( + HostedTermsEncoding.currentnessSource(current, acceptance), StandardCharsets.UTF_8)) + .contains("\"disclosedDeadlineCatalog\":null") + .contains("\"disclosedDeadlineCatalogDigest\":null"); + + HostedTermsCatalogVersion changedDeadline = + new HostedTermsCatalogVersion( + deadline.versionId(), + deadline.hostedScopeId(), + deadline.predecessorVersionId(), + deadline.operatorLegalIdentity(), + deadline.operatorIdentityVersion(), + deadline.documentBytes(), + deadline.documentDigest(), + deadline.sourceVersion(), + deadline.materialGeneration(), + deadline.materiality(), + deadline.materialityEvidenceReference(), + deadline.materialityEvidenceVersion(), + deadline.publicationEvidenceReference(), + deadline.publicationEvidenceVersion(), + deadline.noticeEvidenceReference(), + deadline.noticeEvidenceVersion(), + disclosedAt.plusSeconds(1)); + assertThat(HostedTermsEncoding.currentnessSource(current, acceptance, changedDeadline)) + .isNotEqualTo(source); + + HostedTermsCatalogVersion changedOperator = + new HostedTermsCatalogVersion( + deadline.versionId(), + deadline.hostedScopeId(), + deadline.predecessorVersionId(), + "Different Operator", + deadline.operatorIdentityVersion(), + deadline.documentBytes(), + deadline.documentDigest(), + deadline.sourceVersion(), + deadline.materialGeneration(), + deadline.materiality(), + deadline.materialityEvidenceReference(), + deadline.materialityEvidenceVersion(), + deadline.publicationEvidenceReference(), + deadline.publicationEvidenceVersion(), + deadline.noticeEvidenceReference(), + deadline.noticeEvidenceVersion(), + deadline.effectiveAt()); + assertThatThrownBy( + () -> HostedTermsEncoding.currentnessSource(current, acceptance, changedOperator)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact immutable next catalog"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java index a5a8e37767..ece7e54a82 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java @@ -10,6 +10,7 @@ import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Comparator; +import java.util.EnumSet; import java.util.HexFormat; import java.util.List; import java.util.Objects; @@ -29,11 +30,51 @@ public record DraftAuthorizationFenceBinding( byte[] gameDesignBinding, byte[] normalizedInput, String inputDigest, - List sources) { + List sources, + String schemaVersion, + List requiredOwners) { public static final String SCHEMA = "account-draft-authorization-fence/v1"; + public static final String SCHEMA_V1 = SCHEMA; + public static final String SCHEMA_V2 = "account-draft-authorization-fence/v2"; + private static final List V1_OWNERS = List.of(Owner.GAME_DESIGN, Owner.WORLD); + + /** Retains the original producer's exact v1 frame and fixed owner vector. */ + public DraftAuthorizationFenceBinding( + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + UUID actorAccountId, + UUID tenantId, + UUID versionId, + String baseCommitId, + String expectedDraftEpoch, + byte[] gameDesignBinding, + byte[] normalizedInput, + String inputDigest, + List sources) { + this( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources, + SCHEMA_V1, + V1_OWNERS); + } public DraftAuthorizationFenceBinding { + Objects.requireNonNull(schemaVersion, "schemaVersion"); + requiredOwners = List.copyOf(Objects.requireNonNull(requiredOwners, "requiredOwners")); for (UUID id : List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { requireUuid(id); @@ -75,13 +116,72 @@ public record DraftAuthorizationFenceBinding( if (sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { throw new IllegalArgumentException("Duplicate Account source scope"); } + if (SCHEMA_V1.equals(schemaVersion)) { + if (!V1_OWNERS.equals(requiredOwners)) { + throw new IllegalArgumentException("V1 Draft authorization owners are fixed"); + } + } else if (SCHEMA_V2.equals(schemaVersion)) { + List canonicalOwners = requiredOwners(completeBinding); + if (!canonicalOwners.equals(requiredOwners)) { + throw new IllegalArgumentException( + "V2 Draft authorization owners must exactly match the complete binding"); + } + } else { + throw new IllegalArgumentException("Unsupported Draft authorization fence schema"); + } } - /** Reconstructs only the exact existing immutable V57 framing; this grants no authorization. */ + /** Converts this exact authorization input to v2 with its canonical complete owner set. */ + public DraftAuthorizationFenceBinding withRequiredOwners() { + DraftCommitBinding completeBinding = completeGameDesignBinding(); + return new DraftAuthorizationFenceBinding( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources, + SCHEMA_V2, + requiredOwners(completeBinding)); + } + + private DraftCommitBinding completeGameDesignBinding() { + return DraftCommitBinding.fromStored( + new String(gameDesignBinding, StandardCharsets.UTF_8), digest(gameDesignBinding)); + } + + private static List requiredOwners(DraftCommitBinding binding) { + EnumSet owners = EnumSet.of(Owner.GAME_DESIGN); + for (DraftCommitBinding.Owner owner : binding.requiredOwners()) { + owners.add( + switch (owner) { + case WORLD_MANAGEMENT -> Owner.WORLD; + case ENTITY_MANAGEMENT -> Owner.ENTITY; + case GAME_LOGIC -> Owner.GAME_LOGIC; + case AUTOMATION_SCRIPTING -> Owner.AUTOMATION; + case GAME_DESIGN_CONTROL_PLANE -> Owner.GAME_DESIGN; + }); + } + return Arrays.stream(Owner.values()).filter(owners::contains).toList(); + } + + /** + * Reconstructs only exact supported immutable Draft-fence framing; this grants no authorization. + */ public static DraftAuthorizationFenceBinding fromStored(byte[] original) { byte[] stored = bytes(original); FrameReader reader = new FrameReader(stored); - reader.expect(SCHEMA); + String schemaVersion = reader.text(); + if (!SCHEMA_V1.equals(schemaVersion) && !SCHEMA_V2.equals(schemaVersion)) { + throw new IllegalArgumentException("Unsupported immutable source schema"); + } UUID operationId = canonicalUuidValue(reader.text()); UUID requestId = canonicalUuidValue(reader.text()); UUID commitId = canonicalUuidValue(reader.text()); @@ -106,8 +206,26 @@ public static DraftAuthorizationFenceBinding fromStored(byte[] original) { for (int index = 0; index < sourceCountValue; index++) { sources.add(SourceEvidence.fromStored(reader.bytes())); } - reader.expect("GAME_DESIGN"); - reader.expect("WORLD"); + List requiredOwners; + if (SCHEMA_V1.equals(schemaVersion)) { + reader.expect("GAME_DESIGN"); + reader.expect("WORLD"); + requiredOwners = V1_OWNERS; + } else { + String ownerCountText = reader.text(); + decimal(ownerCountText, false); + BigInteger ownerCount = new BigInteger(ownerCountText); + if (ownerCount.compareTo(BigInteger.valueOf(Owner.values().length)) > 0 + || ownerCount.compareTo(BigInteger.valueOf(reader.remaining() / Integer.BYTES)) > 0) { + throw new IllegalArgumentException("Invalid stored required-owner vector"); + } + int ownerCountValue = ownerCount.intValueExact(); + java.util.ArrayList storedOwners = new java.util.ArrayList<>(); + for (int index = 0; index < ownerCountValue; index++) { + storedOwners.add(Owner.valueOf(reader.text())); + } + requiredOwners = List.copyOf(storedOwners); + } reader.requireEnd(); DraftAuthorizationFenceBinding binding = @@ -124,7 +242,9 @@ public static DraftAuthorizationFenceBinding fromStored(byte[] original) { gameDesignBinding, normalizedInput, inputDigest, - sources); + sources, + schemaVersion, + requiredOwners); if (!Arrays.equals(stored, binding.canonicalBytes())) { throw new IllegalArgumentException("Noncanonical stored authorization fence binding"); } @@ -136,6 +256,11 @@ public List sources() { return List.copyOf(sources); } + @Override + public List requiredOwners() { + return List.copyOf(requiredOwners); + } + @Override public byte[] gameDesignBinding() { return gameDesignBinding.clone(); @@ -149,7 +274,7 @@ public byte[] normalizedInput() { /** Closed, ordered UTF-8/binary length frames; counters are exact decimal strings. */ public byte[] canonicalBytes() { ByteArrayOutputStream output = new ByteArrayOutputStream(); - frame(output, SCHEMA); + frame(output, schemaVersion); for (UUID id : List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { frame(output, id.toString()); @@ -164,8 +289,15 @@ public byte[] canonicalBytes() { for (SourceEvidence source : sources) { frame(output, source.canonicalBytes()); } - frame(output, "GAME_DESIGN"); - frame(output, "WORLD"); + if (SCHEMA_V1.equals(schemaVersion)) { + frame(output, "GAME_DESIGN"); + frame(output, "WORLD"); + } else { + frame(output, Integer.toString(requiredOwners.size())); + for (Owner owner : requiredOwners) { + frame(output, owner.name()); + } + } return output.toByteArray(); } @@ -334,7 +466,10 @@ public void requireEnd() { public enum Owner { GAME_DESIGN, - WORLD + WORLD, + ENTITY, + GAME_LOGIC, + AUTOMATION } public enum Outcome { @@ -342,6 +477,9 @@ public enum Outcome { DEFINITIVELY_ABORTED } + private static final String OWNER_READBACK_SCHEMA_V1 = "account-draft-owner-readback/v1"; + private static final String OWNER_READBACK_SCHEMA_V2 = "account-draft-owner-readback/v2"; + /** Only a future authenticated owner verifier may supply this exact durable readback. */ public record OwnerReadback( Owner owner, @@ -369,7 +507,10 @@ public record OwnerReadback( public static OwnerReadback fromStored(byte[] original) { byte[] stored = bytes(original); FrameReader reader = new FrameReader(stored); - reader.expect("account-draft-owner-readback/v1"); + String schema = reader.text(); + if (!OWNER_READBACK_SCHEMA_V1.equals(schema) && !OWNER_READBACK_SCHEMA_V2.equals(schema)) { + throw new IllegalArgumentException("Unsupported stored owner readback schema"); + } OwnerReadback readback = new OwnerReadback( Owner.valueOf(reader.text()), @@ -381,7 +522,12 @@ public static OwnerReadback fromStored(byte[] original) { reader.bytes(), reader.bytes()); reader.requireEnd(); - readback.requireBinding(DraftAuthorizationFenceBinding.fromStored(readback.fullBinding())); + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(readback.fullBinding()); + if (!schema.equals(readbackSchema(binding))) { + throw new IllegalArgumentException("Owner readback schema differs from its full binding"); + } + readback.requireBinding(binding); if (!Arrays.equals(stored, readback.canonicalBytes())) { throw new IllegalArgumentException("Noncanonical stored owner readback"); } @@ -406,13 +552,22 @@ public void requireBinding(DraftAuthorizationFenceBinding binding) { || !Arrays.equals(fullBinding, binding.canonicalBytes())) { throw new IllegalArgumentException("Owner readback differs from complete Draft binding"); } + if (SCHEMA_V2.equals(binding.schemaVersion()) && !binding.requiredOwners().contains(owner)) { + throw new IllegalArgumentException("Owner readback owner is not required by Draft binding"); + } + if (SCHEMA_V1.equals(binding.schemaVersion()) && !V1_OWNERS.contains(owner)) { + throw new IllegalArgumentException("V1 owner readback owner is outside its closed schema"); + } } public byte[] canonicalBytes() { + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(fullBinding); + requireBinding(binding); ByteArrayOutputStream output = new ByteArrayOutputStream(); for (String value : List.of( - "account-draft-owner-readback/v1", + readbackSchema(binding), owner.name(), outcome.name(), operationId.toString(), @@ -425,6 +580,12 @@ public byte[] canonicalBytes() { frame(output, result); return output.toByteArray(); } + + private static String readbackSchema(DraftAuthorizationFenceBinding binding) { + return SCHEMA_V1.equals(binding.schemaVersion()) + ? OWNER_READBACK_SCHEMA_V1 + : OWNER_READBACK_SCHEMA_V2; + } } public static byte[] bytes(byte[] value) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java index 2d6044a0a3..c7cdff15e9 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java @@ -64,6 +64,171 @@ void preservesV57ProducerGoldenBytesAndDigestAndRoundTripsEveryField() { DraftAuthorizationFenceBinding restored = DraftAuthorizationFenceBinding.fromStored(golden); assertBindingValues(original, restored); assertThat(restored.canonicalBytes()).containsExactly(golden); + assertThat(restored.schemaVersion()).isEqualTo(DraftAuthorizationFenceBinding.SCHEMA_V1); + assertThat(restored.requiredOwners()) + .containsExactly( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD); + } + + @Test + void v2BindsWorldAndEntityAndRoundTripsTheCanonicalRequiredOwnerSet() { + DraftAuthorizationFenceBinding original = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + List expectedOwners = + List.of( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Owner.ENTITY); + + assertThat(original.schemaVersion()).isEqualTo(DraftAuthorizationFenceBinding.SCHEMA_V2); + assertThat(original.requiredOwners()).containsExactlyElementsOf(expectedOwners); + assertThat(original.canonicalBytes()).containsExactly(goldenV2Bytes(original, expectedOwners)); + + DraftAuthorizationFenceBinding restored = + DraftAuthorizationFenceBinding.fromStored(original.canonicalBytes()); + assertBindingValues(original, restored); + assertThat(restored.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(restored.requiredOwners()).containsExactlyElementsOf(expectedOwners); + } + + @Test + void v2MapsEveryCommitOwnerAndAlwaysIncludesTheGameDesignCoordinator() { + DraftAuthorizationFenceBinding multiOwner = + bindingForOwners(Arrays.asList(Owner.values())).withRequiredOwners(); + assertThat(multiOwner.requiredOwners()) + .containsExactly( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Owner.ENTITY, + DraftAuthorizationFenceBinding.Owner.GAME_LOGIC, + DraftAuthorizationFenceBinding.Owner.AUTOMATION); + assertBindingValues( + multiOwner, DraftAuthorizationFenceBinding.fromStored(multiOwner.canonicalBytes())); + + DraftAuthorizationFenceBinding controlPlaneOnly = + bindingForOwners(List.of(Owner.GAME_DESIGN_CONTROL_PLANE)).withRequiredOwners(); + assertThat(controlPlaneOnly.requiredOwners()) + .containsExactly(DraftAuthorizationFenceBinding.Owner.GAME_DESIGN); + assertBindingValues( + controlPlaneOnly, + DraftAuthorizationFenceBinding.fromStored(controlPlaneOnly.canonicalBytes())); + } + + @Test + void v2RejectsMissingExtraUnknownReorderedAndSubstitutedOwners() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + List canonicalFrames = readFrames(binding.canonicalBytes()); + + List missing = new ArrayList<>(canonicalFrames); + missing.set(16, utf8("2")); + missing.remove(missing.size() - 1); + assertInvalid(writeFrames(missing)); + + List extra = new ArrayList<>(canonicalFrames); + extra.set(16, utf8("4")); + extra.add(utf8("AUTOMATION")); + assertInvalid(writeFrames(extra)); + + List unknown = new ArrayList<>(canonicalFrames); + unknown.set(18, utf8("UNKNOWN_OWNER")); + assertInvalid(writeFrames(unknown)); + + List reordered = new ArrayList<>(canonicalFrames); + byte[] gameDesign = reordered.get(17); + reordered.set(17, reordered.get(18)); + reordered.set(18, gameDesign); + assertInvalid(writeFrames(reordered)); + + List substituted = new ArrayList<>(canonicalFrames); + substituted.set(18, utf8("GAME_LOGIC")); + assertInvalid(writeFrames(substituted)); + } + + @Test + void v2RejectsChangedCompleteBindingAndNoncanonicalOwnerCount() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + List changedInput = readFrames(binding.canonicalBytes()); + changedInput.set(11, utf8("{}")); + assertInvalid(writeFrames(changedInput)); + + List noncanonicalCount = readFrames(binding.canonicalBytes()); + noncanonicalCount.set(16, utf8("03")); + assertInvalid(writeFrames(noncanonicalCount)); + + List excessiveCount = readFrames(binding.canonicalBytes()); + excessiveCount.set(16, utf8("999999999999999999999999999999999999")); + assertInvalid(writeFrames(excessiveCount)); + } + + @Test + void v2OwnerReadbackUsesMatchingVersionAndOnlyAllowsRequiredOwners() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + var worldReadback = + ownerReadback(binding, DraftAuthorizationFenceBinding.Owner.WORLD, new byte[] {1}); + List frames = readFrames(worldReadback.canonicalBytes()); + assertThat(new String(frames.get(0), StandardCharsets.UTF_8)) + .isEqualTo("account-draft-owner-readback/v2"); + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(worldReadback.canonicalBytes()) + .requireBinding(binding); + + var wrongOwner = new ArrayList<>(frames); + wrongOwner.set(1, utf8("AUTOMATION")); + assertThatThrownBy( + () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(wrongOwner))) + .isInstanceOf(IllegalArgumentException.class); + + for (int field : List.of(3, 4, 5, 6, 7)) { + var changedBinding = new ArrayList<>(frames); + changedBinding.set( + field, + switch (field) { + case 3, 4, 5 -> utf8("99999999-9999-4999-8999-999999999999"); + case 6 -> utf8("sha256:" + "f".repeat(64)); + default -> binding(List.of(source())).canonicalBytes(); + }); + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + writeFrames(changedBinding))) + .isInstanceOf(IllegalArgumentException.class); + } + + var mismatchedVersion = new ArrayList<>(frames); + mismatchedVersion.set(0, utf8("account-draft-owner-readback/v1")); + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + writeFrames(mismatchedVersion))) + .isInstanceOf(IllegalArgumentException.class); + + var changedResult = new ArrayList<>(frames); + changedResult.set(changedResult.size() - 1, new byte[] {2}); + var changedReadback = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(changedResult)); + assertThat(changedReadback.result()).containsExactly((byte) 2); + assertThat(changedReadback.canonicalBytes()).containsExactly(writeFrames(changedResult)); + assertThat(changedReadback.canonicalBytes()).isNotEqualTo(worldReadback.canonicalBytes()); + } + + @Test + void v1OwnerReadbackSchemaCannotBeSubstitutedForV2Binding() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT)).withRequiredOwners(); + var readback = + ownerReadback(binding, DraftAuthorizationFenceBinding.Owner.WORLD, new byte[] {1}); + List frames = readFrames(readback.canonicalBytes()); + frames.set(0, utf8("account-draft-owner-readback/v1")); + assertThatThrownBy( + () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(frames))) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -155,7 +320,10 @@ void rejectsReorderedSourceVectorAndMalformedStoredFrames() { @Test void ownerReadbackRoundTripsExactBytesAndOriginalBindingForEveryOutcome() { var binding = binding(List.of(source())); - for (var owner : DraftAuthorizationFenceBinding.Owner.values()) { + for (var owner : + List.of( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD)) { for (var outcome : DraftAuthorizationFenceBinding.Outcome.values()) { var original = new DraftAuthorizationFenceBinding.OwnerReadback( @@ -174,6 +342,8 @@ void ownerReadbackRoundTripsExactBytesAndOriginalBindingForEveryOutcome() { assertThat(decoded.outcome()).isEqualTo(outcome); assertThat(decoded.result()).containsExactly(new byte[] {1, 2, 3}); assertThat(decoded.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(original.canonicalBytes()) + .containsExactly(goldenOwnerReadbackV1(binding, owner, outcome, new byte[] {1, 2, 3})); } } } @@ -229,6 +399,14 @@ void ownerReadbackRejectsCorruptFramingNoncanonicalFieldsAndContradictoryBinding assertThatThrownBy( () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(invalidUtf8))) .isInstanceOf(IllegalArgumentException.class); + + var expandedV1Owner = readFrames(bytes); + expandedV1Owner.set(1, utf8("ENTITY")); + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + writeFrames(expandedV1Owner))) + .isInstanceOf(IllegalArgumentException.class); } private static void assertBindingValues( @@ -245,6 +423,8 @@ private static void assertBindingValues( assertThat(actual.gameDesignBinding()).containsExactly(expected.gameDesignBinding()); assertThat(actual.normalizedInput()).containsExactly(expected.normalizedInput()); assertThat(actual.inputDigest()).isEqualTo(expected.inputDigest()); + assertThat(actual.schemaVersion()).isEqualTo(expected.schemaVersion()); + assertThat(actual.requiredOwners()).containsExactlyElementsOf(expected.requiredOwners()); assertThat(actual.sources()).hasSize(expected.sources().size()); for (int index = 0; index < expected.sources().size(); index++) { SourceEvidence expectedSource = expected.sources().get(index); @@ -291,6 +471,121 @@ private static DraftCommitBinding gameDesignBinding() { Owner.WORLD_MANAGEMENT, "WORLD_TEMPLATE", "world-1", "ROOM_SCOPE", "room-1", "0"))); } + private static DraftAuthorizationFenceBinding bindingForOwners(List owners) { + DraftCommitBinding gameDesign = gameDesignBinding(owners); + byte[] gameDesignBytes = gameDesign.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-source-1", + EXPECTED_DRAFT_EPOCH, + gameDesignBytes, + gameDesignBytes, + gameDesign.digest(), + List.of(source())); + } + + private static DraftCommitBinding gameDesignBinding(List owners) { + List revisions = new ArrayList<>(); + List affectedUnits = new ArrayList<>(); + for (int index = 0; index < owners.size(); index++) { + Owner owner = owners.get(index); + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.nameUUIDFromBytes(("revision-" + owner.name()).getBytes(StandardCharsets.UTF_8)), + owner, + "{}")); + affectedUnits.add( + new AffectedUnit( + owner, + "TEST_AGGREGATE", + owner.name().toLowerCase(java.util.Locale.ROOT), + "TEST_SCOPE", + "scope-" + owner.name().toLowerCase(java.util.Locale.ROOT), + "0")); + } + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-source-1", + revisions, + affectedUnits); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback ownerReadback( + DraftAuthorizationFenceBinding binding, + DraftAuthorizationFenceBinding.Owner owner, + byte[] result) { + return new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + result); + } + + private static byte[] goldenV2Bytes( + DraftAuthorizationFenceBinding binding, + List requiredOwners) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + appendFrame(output, DraftAuthorizationFenceBinding.SCHEMA_V2); + for (String value : + List.of( + binding.operationId().toString(), + binding.requestId().toString(), + binding.commitId().toString(), + binding.fenceId().toString(), + binding.actorAccountId().toString(), + binding.tenantId().toString(), + binding.versionId().toString(), + binding.baseCommitId(), + "DRAFT", + binding.expectedDraftEpoch())) { + appendFrame(output, value); + } + appendFrame(output, binding.gameDesignBinding()); + appendFrame(output, binding.normalizedInput()); + appendFrame(output, binding.inputDigest()); + appendFrame(output, Integer.toString(binding.sources().size())); + binding.sources().forEach(source -> appendFrame(output, source.canonicalBytes())); + appendFrame(output, Integer.toString(requiredOwners.size())); + requiredOwners.forEach(owner -> appendFrame(output, owner.name())); + return output.toByteArray(); + } + + private static byte[] goldenOwnerReadbackV1( + DraftAuthorizationFenceBinding binding, + DraftAuthorizationFenceBinding.Owner owner, + DraftAuthorizationFenceBinding.Outcome outcome, + byte[] result) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : + List.of( + "account-draft-owner-readback/v1", + owner.name(), + outcome.name(), + binding.operationId().toString(), + binding.commitId().toString(), + binding.fenceId().toString(), + binding.inputDigest())) { + appendFrame(output, value); + } + appendFrame(output, binding.canonicalBytes()); + appendFrame(output, result); + return output.toByteArray(); + } + private static SourceEvidence source() { return new SourceEvidence( SourceKind.GLOBAL_ROLES,